fix(pdf): bounded attachment extraction by byte scan — no pdf-lib parse on import, export without object streams (BLK-009)

This commit is contained in:
bchanot committed 2026-10-11 16:42:45 +02:00
1 parent 62b8a43e09
commit 60ee71208f
14 files changed
+1054 -198

No files matched your search

+23 -14
View File
@@ -1,17 +1,29 @@
import { AFRelationship, PDFDocument, PDFName, PDFRawStream } from 'pdf-lib'
import { AFRelationship, PDFDocument } from 'pdf-lib'
import { findEmbeddedFiles } from '../../src'
/**
* Crafted PDFs for the read tests, built with pdf-lib's own attach. Saved
* without object streams by default, like the export since BLK-009; pass
* `objectStreams: true` for the pre-BLK-009 layout (Filespec and Info
* packed into an `/ObjStm`, invisible to the byte scan).
*/
export interface CraftOptions {
keywords?: string[]
before?: [string, unknown]
objectStreams?: boolean
}
/** Crafted PDFs for the read tests, built with pdf-lib's own attach. */
export async function pdfWithAttachment(
name: string,
payload: unknown,
extra: { keywords?: string[]; before?: [string, unknown] } = {},
extra: CraftOptions = {},
): Promise<Uint8Array> {
const doc = await PDFDocument.create()
doc.addPage()
if (extra.keywords) doc.setKeywords(extra.keywords)
if (extra.before) await attachJson(doc, extra.before[0], extra.before[1])
await attachJson(doc, name, payload)
return doc.save()
return doc.save({ useObjectStreams: extra.objectStreams ?? false })
}
async function attachJson(
@@ -27,20 +39,17 @@ async function attachJson(
export async function pdfWithoutAttachment(
keywords?: string[],
objectStreams = false,
): Promise<Uint8Array> {
const doc = await PDFDocument.create()
doc.addPage()
if (keywords) doc.setKeywords(keywords)
return doc.save()
return doc.save({ useObjectStreams: objectStreams })
}
/** Stored (Flate) size of the first `/EmbeddedFile` stream of a saved PDF. */
export async function storedAttachmentSize(bytes: Uint8Array): Promise<number> {
const doc = await PDFDocument.load(bytes)
for (const [, object] of doc.context.enumerateIndirectObjects()) {
if (!(object instanceof PDFRawStream)) continue
const type = object.dict.lookup(PDFName.of('Type'))
if (type === PDFName.of('EmbeddedFile')) return object.contents.length
}
throw new Error('no EmbeddedFile stream')
/** Stored (Flate) size of the first `/EmbeddedFile` stream of a saved PDF, by the byte scan. */
export function storedAttachmentSize(bytes: Uint8Array): number {
const [first] = findEmbeddedFiles(bytes)
if (!first) throw new Error('no EmbeddedFile stream')
return first.length
}