From eb3da7c4369714da5ecfe6be53d0ee2590808617 Mon Sep 17 00:00:00 2001 From: tabcat Date: Thu, 3 Oct 2024 15:31:29 +0700 Subject: [PATCH] fix: @helia/json.get throws if CID codec not JSON --- packages/json/src/index.ts | 4 ++++ packages/json/test/get.spec.ts | 8 +++++++- 2 files changed, 11 insertions(+), 1 deletion(-) 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') + }) })