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
38 changes: 28 additions & 10 deletions src/compiler.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,18 +93,36 @@ class CompiledProtodef {
}

createPacketBuffer (type, packet) {
const length = tryCatch(() => this.sizeOf(packet, type),
(e) => {
e.message = `SizeOf error for ${e.field} : ${e.message}`
throw e
})
const buffer = Buffer.allocUnsafe(length)
tryCatch(() => this.write(packet, buffer, 0, type),
(e) => {
// Fast path: write straight into a reusable scratch buffer and copy out the exact bytes, avoiding
// the separate sizeOf traversal (which re-walks the whole structure and re-encodes string lengths).
// Falls back to the exact sizeOf+alloc path if the packet overflows the scratch (then grows it).
let scratch = this._scratch
if (scratch === undefined) scratch = this._scratch = Buffer.allocUnsafe(65536)
try {
const end = this.write(packet, scratch, 0, type)
const buffer = Buffer.allocUnsafe(end)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Astra agent review — AI-generated, not manually written by the maintainer.

[P1] Detect writers that overrun the scratch without throwing

The compiled buffer writer uses value.copy(buffer, offset) and returns offset + value.length; Buffer.copy silently truncates when the destination is full. With payload: ['buffer', { countType: 'varint' }] and Buffer.alloc(80000, 0x5a), this call returns end = 80003 without entering the catch. The next allocation is 80,003 bytes, but only 65,536 bytes are copied from the scratch, leaving the suffix uninitialized. I executed the candidate: the round-trip first differs at payload byte 65,533, while restoring the exact-size allocation/write path preserves every byte. Large payloads can therefore be corrupted and include unrelated memory in returned packets.

Check the returned cursor against the scratch capacity before accepting the fast path and fall back/rewrite when it exceeds it. Cover a large buffer field (and other non-throwing writes, such as indexed bitfield writes), not just integer arrays whose Buffer methods throw.

Skills used: prismarine-protocol-data-review exposed the write/size mismatch; prismarine-architecture-review checked the shared codec's native-writer contract; prismarine-review checked the regression's actual coverage.

scratch.copy(buffer, 0, 0, end)
return buffer
} catch (e) {
if (e.code !== 'ERR_BUFFER_OUT_OF_BOUNDS' && e.code !== 'ERR_OUT_OF_RANGE') {
e.message = `Write error for ${e.field} : ${e.message}`
throw e
})
return buffer
}
// Scratch too small (or a value that didn't fit): take the exact path and grow the scratch.
const length = tryCatch(() => this.sizeOf(packet, type),
(er) => {
er.message = `SizeOf error for ${er.field} : ${er.message}`
throw er
})
const buffer = Buffer.allocUnsafe(length)
tryCatch(() => this.write(packet, buffer, 0, type),
(er) => {
er.message = `Write error for ${er.field} : ${er.message}`
throw er
})
if (length > this._scratch.length) this._scratch = Buffer.allocUnsafe(length)
return buffer
}
}

parsePacketBuffer (type, buffer, offset = 0) {
Expand Down
25 changes: 25 additions & 0 deletions test/misc.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,31 @@ describe('bitflags with a signed underlying type', () => {
}
})

describe('large packets exceeding the write scratch buffer', () => {
// createPacketBuffer writes into a reused 64 KiB scratch and only falls back to a sizeOf pass when that
// overflows. A packet larger than the scratch must still serialize correctly (fallback path), the scratch
// must then grow so a second large packet does not re-trigger the fallback, and small packets must keep working.
const type = ['array', { type: 'i32', countType: 'varint' }]
const compiler = new ProtoDefCompiler()
compiler.addTypesToCompile({ ints: type })
const compiled = compiler.compileProtoDefSync()

const big = Array.from({ length: 20000 }, (_, i) => i - 10000) // 20000 * 4 B = 80 KB > 64 KiB scratch
const bigger = Array.from({ length: 40000 }, (_, i) => i) // 160 KB, must also round-trip

it('round-trips a packet larger than the scratch (fallback path)', () => {
const buf = compiled.createPacketBuffer('ints', big)
assert.strictEqual(buf.length, 3 + big.length * 4) // 3-byte varint count + payload
assert.deepStrictEqual(compiled.parsePacketBuffer('ints', buf).data, big)
})

it('round-trips a second, larger packet and a small one after growing the scratch', () => {
assert.deepStrictEqual(compiled.parsePacketBuffer('ints', compiled.createPacketBuffer('ints', bigger)).data, bigger)
const small = [1, 2, 3]
assert.deepStrictEqual(compiled.parsePacketBuffer('ints', compiled.createPacketBuffer('ints', small)).data, small)
})
})

describe('FullPacketParser', () => {
const packet = ['container', [{ name: 'a', type: 'i32' }]]
const proto = new ProtoDef()
Expand Down
Loading