diff --git a/packages/json/src/index.ts b/packages/json/src/index.ts index 0578e8b3d..7cbcf2ae9 100644 --- a/packages/json/src/index.ts +++ b/packages/json/src/index.ts @@ -115,6 +115,10 @@ class DefaultJSON implements JSON { } async get (cid: CID, options: Partial = {}): Promise { + if (cid.code !== jsonCodec.code) { + throw new TypeError('The passed CID had an incorrect codec, it may correspond to a non-JSON block') + } + const buf = await this.components.blockstore.get(cid, options) return jsonCodec.decode(buf) diff --git a/packages/json/test/get.spec.ts b/packages/json/test/get.spec.ts index 42d472476..9a2575b96 100644 --- a/packages/json/test/get.spec.ts +++ b/packages/json/test/get.spec.ts @@ -2,10 +2,10 @@ import { expect } from 'aegir/chai' import { MemoryBlockstore } from 'blockstore-core' +import { CID } from 'multiformats/cid' import { identity } from 'multiformats/hashes/identity' import { json, type JSON } from '../src/index.js' import type { Blockstore } from 'interface-blockstore' -import type { CID } from 'multiformats/cid' describe('get', () => { let blockstore: Blockstore @@ -39,4 +39,10 @@ describe('get', () => { await expect(j.get(cid)).to.eventually.deep.equal(input) }) + + it('rejects if CID codec is not equal to JSON codec', async () => { + const rawCID = CID.createV1(0x55, cid.multihash) + await expect(j.get(rawCID)).to.eventually.be.rejected + .with.property('message', 'The passed CID had an incorrect codec, it may correspond to a non-JSON block') + }) })