diff --git a/src/util/MMKVParser.ts b/src/util/MMKVParser.ts index 399184c..a413baf 100644 --- a/src/util/MMKVParser.ts +++ b/src/util/MMKVParser.ts @@ -7,7 +7,7 @@ export class MMKVParser { constructor(private view: DataView) { const payloadLength = view.getUint32(0, true); - this.length = 4 + payloadLength; + this.length = Math.min(4 + payloadLength, view.byteLength); // skip unused str this.readInt(); diff --git a/src/util/__tests__/MMKVParser.test.ts b/src/util/__tests__/MMKVParser.test.ts index 7a2f978..12b5c69 100644 --- a/src/util/__tests__/MMKVParser.test.ts +++ b/src/util/__tests__/MMKVParser.test.ts @@ -26,3 +26,58 @@ test('able to handle empty value', () => { expect(parser.readKey()).toEqual('1'); expect(parser.readStringValue()).toEqual('2'); }); + +describe('eof payload boundary', () => { + // Small string records: "a" -> "one" and "b" -> "two". + const firstRecord = Buffer.from([0x01, 0x61, 0x04, 0x03, 0x6f, 0x6e, 0x65]); + const secondRecord = Buffer.from([0x01, 0x62, 0x04, 0x03, 0x74, 0x77, 0x6f]); + const payload = Buffer.concat([Buffer.from([0x7f]), firstRecord, secondRecord]); + const allEntries = [ + ['a', 'one'], + ['b', 'two'], + ]; + + const makeView = (payloadLength: number) => { + const header = Buffer.alloc(4); + header.writeUInt32LE(payloadLength); + return makeViewFromBuffer(Buffer.concat([header, payload])); + }; + + const readEntries = (parser: MMKVParser) => { + const entries: [string, string | null][] = []; + while (!parser.eof) { + entries.push([parser.readKey(), parser.readStringValue()]); + } + return entries; + }; + + test.each([payload.byteLength + 4, 0xffffffff])('clamps oversized payload length %i to the view', (payloadLength) => { + const parser = new MMKVParser(makeView(payloadLength)); + + expect(readEntries(parser)).toEqual(allEntries); + expect(parser.eof).toBe(true); + }); + + test('reads all records when the payload length is exact', () => { + const parser = new MMKVParser(makeView(payload.byteLength)); + + expect(readEntries(parser)).toEqual(allEntries); + expect(parser.eof).toBe(true); + }); + + test('stops at the declared payload boundary with another valid record remaining', () => { + const parser = new MMKVParser(makeView(1 + firstRecord.byteLength)); + + expect(readEntries(parser)).toEqual([allEntries[0]]); + expect(parser.eof).toBe(true); + }); + + test('clamps to the DataView length with another valid record outside the view', () => { + const fullView = makeView(payload.byteLength + 4); + const view = new DataView(fullView.buffer, 0, 4 + 1 + firstRecord.byteLength); + const parser = new MMKVParser(view); + + expect(readEntries(parser)).toEqual([allEntries[0]]); + expect(parser.eof).toBe(true); + }); +});