diff --git a/src/pdf/attachment.ts b/src/pdf/attachment.ts index b37e611d..dae64409 100644 --- a/src/pdf/attachment.ts +++ b/src/pdf/attachment.ts @@ -61,11 +61,37 @@ interface RawObj { dict?: { entries?: () => Array<[unknown, unknown]> } } -async function inflateFlate(bytes: Uint8Array): Promise { +/** + * Hard ceiling on inflated attachment size. A valid report JSON is far + * smaller; anything bigger is a decompression bomb or corruption. + */ +const MAX_INFLATED_BYTES = 16 * 1024 * 1024 + +/** Exported for tests. Returns null on failure or when the cap is exceeded. */ +export async function inflateFlate(bytes: Uint8Array): Promise { if (typeof DecompressionStream === 'undefined') return null try { const stream = new Blob([bytes as BlobPart]).stream().pipeThrough(new DecompressionStream('deflate')) - return new Uint8Array(await new Response(stream).arrayBuffer()) + const reader = stream.getReader() + const chunks: Uint8Array[] = [] + let total = 0 + for (;;) { + const { done, value } = await reader.read() + if (done) break + total += value.byteLength + if (total > MAX_INFLATED_BYTES) { + await reader.cancel() + return null + } + chunks.push(value) + } + const out = new Uint8Array(total) + let offset = 0 + for (const c of chunks) { + out.set(c, offset) + offset += c.byteLength + } + return out } catch { return null } diff --git a/tests/unit/pdf.attachment.inflate.test.ts b/tests/unit/pdf.attachment.inflate.test.ts new file mode 100644 index 00000000..a0332cd3 --- /dev/null +++ b/tests/unit/pdf.attachment.inflate.test.ts @@ -0,0 +1,26 @@ +import { describe, it, expect } from 'vitest' +import { inflateFlate } from '@/pdf/attachment' + +async function deflate(data: Uint8Array): Promise { + const stream = new Blob([data as BlobPart]) + .stream() + .pipeThrough(new CompressionStream('deflate')) + return new Uint8Array(await new Response(stream).arrayBuffer()) +} + +describe('inflateFlate decompression cap', () => { + it('inflates a normal-size payload', async () => { + const payload = new TextEncoder().encode(JSON.stringify({ version: 2, hello: 'world' })) + const out = await inflateFlate(await deflate(payload)) + expect(out).not.toBeNull() + expect(new TextDecoder().decode(out!)).toContain('hello') + }) + + it('returns null for a decompression bomb above the cap', async () => { + // 24 MB of zeros deflates to a few KB but inflates past the 16 MB cap + const bomb = await deflate(new Uint8Array(24 * 1024 * 1024)) + expect(bomb.byteLength).toBeLessThan(1024 * 1024) + const out = await inflateFlate(bomb) + expect(out).toBeNull() + }) +})