From 258a0be344ddd5d08e08e55b3e088212df0c409a Mon Sep 17 00:00:00 2001 From: Oli Evans Date: Tue, 17 Jan 2023 15:55:28 +0000 Subject: [PATCH] fix: throw on CID.parse v0 string with multibase prefix Add a check to CID.parse to throw on a CID v0 string with explict multibase, e.g. `zQmPr755CxWUwt39C2Yiw4UGKrv16uZhSgeZJmoHUUS9TSJ` We're seeing pinning service requests comming in from the wild with the undesriable multibase prefix, and the expectation was that CID.parse would have thrown and spared us from having to deal with them. Fixes: https://github.com/multiformats/js-multiformats/issues/240 See also: https://github.com/ipfs/kubo/issues/9556 License: MIT Signed-off-by: Oli Evans --- src/cid.js | 4 ++++ test/test-cid.spec.js | 6 ++++++ 2 files changed, 10 insertions(+) diff --git a/src/cid.js b/src/cid.js index a13d4ec8..852b3d53 100644 --- a/src/cid.js +++ b/src/cid.js @@ -484,6 +484,10 @@ export class CID { const cid = CID.decode(bytes) + if (cid.version === 0 && source[0] !== 'Q') { + throw Error('Version 0 CID string must not include multibase prefix') + } + // Cache string representation to avoid computing it on `this.toString()` baseCache(cid).set(prefix, source) diff --git a/test/test-cid.spec.js b/test/test-cid.spec.js index cf59103a..e6a6b806 100644 --- a/test/test-cid.spec.js +++ b/test/test-cid.spec.js @@ -85,6 +85,12 @@ describe('CID', () => { assert.throws(() => cid.toString(base32), msg) }) + it('throws on CIDv0 string with explicit multibase prefix', async () => { + const str = 'zQmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n' + const msg = 'Version 0 CID string must not include multibase prefix' + assert.throws(() => CID.parse(str), msg) + }) + it('.bytes', async () => { const hash = await sha256.digest(textEncoder.encode('abc')) const codec = 112