From 6d564e33dbc3e9760ad0d103d61beceafd1b9d6a Mon Sep 17 00:00:00 2001 From: tabcat Date: Tue, 23 Jun 2026 18:01:47 +0700 Subject: [PATCH] fix: verify CID hash before decoding in Block.create Block.create is the verifying block constructor, but it decoded bytes before checking they matched the CID, so the codec parser ran on unverified, potentially untrusted input. Hash and compare first, then delegate decoding to createUnsafe. Valid blocks are unchanged; bytes that do not match the CID are now rejected without ever being decoded, and such input always throws the hash mismatch error rather than possibly a codec error first. Adds a test asserting mismatched, codec-invalid bytes reject with the hash error. Closes #339 Signed-off-by: tabcat --- src/block.ts | 3 +-- test/test-block.spec.ts | 9 +++++++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/block.ts b/src/block.ts index 0383f99f..356a6c9e 100644 --- a/src/block.ts +++ b/src/block.ts @@ -224,7 +224,7 @@ interface CreateInput ({ bytes, cid, hasher, codec }: CreateInput): Promise> { if (bytes == null) { throw new Error('Missing required argument "bytes"') } if (hasher == null) { throw new Error('Missing required argument "hasher"') } - const value = codec.decode(bytes) + const hash = await hasher.digest(bytes) if (!binary.equals(cid.multihash.bytes, hash.bytes)) { throw new Error('CID hash does not match bytes') @@ -233,7 +233,6 @@ export async function create { await assert.isRejected(main.create({ bytes: block.bytes, cid: block2.cid, codec, hasher }), 'CID hash does not match bytes') }) + it('create verifies the cid hash before decoding the bytes', async () => { + const block = await main.encode({ value: fixture, codec, hasher }) + const badBytes = bytes.fromString('not valid json') + await assert.isRejected( + main.create({ bytes: badBytes, cid: block.cid, codec, hasher }), + 'CID hash does not match bytes' + ) + }) + it('get', async () => { const block = await main.encode({ value: fixture, codec, hasher }) assert.throws(() => block.get('/asd/fs/dfasd/f'), 'Object has no property at ["asd"]')