Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/Decoder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -451,6 +451,10 @@ export class Decoder<ContextType = undefined> {
}
this.totalPos += this.pos;
}

if (arrayItemsLeft > 0 || this.headByte !== HEAD_BYTE_REQUIRED || this.stack.length > 0) {
throw new RangeError("Insufficient data in stream");
}
} finally {
this.entered = false;
}
Expand Down
20 changes: 20 additions & 0 deletions test/decodeArrayStream.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,4 +88,24 @@ describe("decodeArrayStream", () => {
}
}, /.*Unrecognized array type byte:.*/i);
});
for (const missingItem of [false, true]) {
it(`rejects an array stream ending ${missingItem ? "before" : "inside"} its last item`, async () => {
const first = encode({ id: 1 });
const second = encode({ label: "unfinished" });
const createTruncatedStream = async function* () {
yield Uint8Array.of(0x92);
yield first;
if (!missingItem) {
yield second.subarray(0, second.length - 1);
}
};
const items: Array<unknown> = [];
await assert.rejects(async () => {
for await (const item of decodeArrayStream(createTruncatedStream())) {
items.push(item);
}
}, RangeError);
assert.deepStrictEqual(items, [{ id: 1 }]);
});
}
});
16 changes: 16 additions & 0 deletions test/decodeMultiStream.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,4 +57,20 @@ describe("decodeStream", () => {

assert.deepStrictEqual(result, items);
});
for (const finalItem of ["unfinished", { nested: [1, 2] }]) {
it(`rejects a stream ending inside ${typeof finalItem}`, async () => {
const encoded = encode(finalItem);
const createTruncatedStream = async function* () {
yield encode({ id: 1 });
yield encoded.subarray(0, encoded.length - 1);
};
const items: Array<unknown> = [];
await assert.rejects(async () => {
for await (const item of decodeMultiStream(createTruncatedStream())) {
items.push(item);
}
}, RangeError);
assert.deepStrictEqual(items, [{ id: 1 }]);
});
}
});