feat(pdf): @faunosteo/pdf engine — explicit inputs, envelope v1 attachment, layered reader, xmldom composition, allowlist SVG sanitiser, WinAnsi guard, rasterizer adapter; goldens reproduced

This commit is contained in:
bchanot committed 2026-10-11 13:09:17 +02:00
1 parent e7419cb4cb
commit c17956031d
46 files changed
+4396 -1

No files matched your search

+43
View File
@@ -0,0 +1,43 @@
/**
* Hard ceiling on an attachment, inflated or not: a report archive weighs a
* few hundred KB; anything bigger is a decompression bomb or corruption.
*/
export const MAX_ATTACHMENT_BYTES = 16 * 1024 * 1024
function concat(chunks: Uint8Array[], total: number): Uint8Array {
const out = new Uint8Array(total)
let offset = 0
for (const chunk of chunks) {
out.set(chunk, offset)
offset += chunk.byteLength
}
return out
}
/** FlateDecode under the cap. Null on failure or when the cap is exceeded. */
export async function inflateFlate(
bytes: Uint8Array,
): Promise<Uint8Array | null> {
if (typeof DecompressionStream === 'undefined') return null
try {
const stream = new Blob([bytes])
.stream()
.pipeThrough(new DecompressionStream('deflate'))
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_ATTACHMENT_BYTES) {
await reader.cancel()
return null
}
chunks.push(value)
}
return concat(chunks, total)
} catch {
return null
}
}
+105
View File
@@ -0,0 +1,105 @@
import {
PDFDict,
PDFHexString,
PDFName,
PDFRawStream,
PDFStream,
PDFString,
type PDFDocument,
} from 'pdf-lib'
import { ArchiveReadError } from '../errors'
import { inflateFlate, MAX_ATTACHMENT_BYTES } from './inflate'
/**
* Finds the Faunosteo attachment of a loaded PDF: the Filespec whose file
* name starts with `osteo-report` first, else the first embedded file
* (today's behaviour, kept as the fallback). pdf-lib 1.17 exposes no
* attachment API, so this walks the indirect objects.
*/
export const ATTACHMENT_NAME_PREFIX = 'osteo-report'
export const PDF_KEYWORD = 'faunosteo-archive/1'
const TYPE = PDFName.of('Type')
const F = PDFName.of('F')
function textOf(value: unknown): string | null {
if (value instanceof PDFString || value instanceof PDFHexString) {
return value.decodeText()
}
return null
}
/** The embedded stream of a `/Filespec` named for a Faunosteo report. */
function namedFilespecStream(dict: PDFDict): PDFStream | null {
if (dict.get(TYPE) !== PDFName.of('Filespec')) return null
const name = textOf(dict.lookup(F))
if (name === null || !name.startsWith(ATTACHMENT_NAME_PREFIX)) return null
const files = dict.lookup(PDFName.of('EF'))
if (!(files instanceof PDFDict)) return null
const stream = files.lookup(F)
return stream instanceof PDFStream ? stream : null
}
/** Today's heuristic: an `/EmbeddedFile` stream or a JSON-subtyped one. */
function looksLikeEmbeddedJson(stream: PDFStream): boolean {
const type = String(stream.dict.lookup(TYPE) ?? '')
const subtype = String(stream.dict.lookup(PDFName.of('Subtype')) ?? '')
return (
type.includes('EmbeddedFile') ||
subtype.includes('application/json') ||
subtype.includes('application#2Fjson')
)
}
function locateAttachment(pdfDoc: PDFDocument): PDFStream | null {
const objects = pdfDoc.context.enumerateIndirectObjects()
for (const [, object] of objects) {
if (!(object instanceof PDFDict)) continue
const stream = namedFilespecStream(object)
if (stream) return stream
}
for (const [, object] of objects) {
if (object instanceof PDFStream && looksLikeEmbeddedJson(object)) {
return object
}
}
return null
}
/** Stream bytes, inflated when Flate-encoded; null when unreadable or over the cap. */
async function attachmentBytes(stream: PDFStream): Promise<Uint8Array | null> {
const contents =
stream instanceof PDFRawStream ? stream.contents : stream.getContents()
if (contents.byteLength > MAX_ATTACHMENT_BYTES) return null
const filter = String(stream.dict.lookup(PDFName.of('Filter')) ?? '')
if (!filter.includes('FlateDecode')) return contents
return inflateFlate(contents)
}
/** A PDF stamped as an archive but holding no attachment lost it in a viewer. */
function missingAttachmentError(pdfDoc: PDFDocument): ArchiveReadError {
const stamped = (pdfDoc.getKeywords() ?? '').includes('faunosteo-archive')
return new ArchiveReadError(stamped ? 'attachment_stripped' : 'no_attachment')
}
/**
* The raw JSON carried by the PDF, whatever its shape (bare report of any
* version or archive envelope), before any validation: what the archive
* check tool shows next to the read result. Throws ArchiveReadError.
*/
export async function readAttachedDocument(
pdfDoc: PDFDocument,
): Promise<unknown> {
const stream = locateAttachment(pdfDoc)
if (!stream) throw missingAttachmentError(pdfDoc)
const bytes = await attachmentBytes(stream)
if (!bytes || bytes.byteLength > MAX_ATTACHMENT_BYTES) {
throw new ArchiveReadError('no_attachment')
}
try {
return JSON.parse(new TextDecoder().decode(bytes)) as unknown
} catch {
throw new ArchiveReadError('no_attachment')
}
}
+19
View File
@@ -0,0 +1,19 @@
import { AFRelationship, type PDFDocument } from 'pdf-lib'
export const ATTACHMENT_FILENAME = 'osteo-report.json'
export const ATTACHMENT_DESCRIPTION = 'Faunosteo report archive v1'
/** The envelope bytes as a native embedded file; every date is `exportedAt`. */
export async function attachEnvelope(
pdfDoc: PDFDocument,
bytes: Uint8Array,
exportedAt: Date,
): Promise<void> {
await pdfDoc.attach(bytes, ATTACHMENT_FILENAME, {
mimeType: 'application/json',
description: ATTACHMENT_DESCRIPTION,
creationDate: exportedAt,
modificationDate: exportedAt,
afRelationship: AFRelationship.Data,
})
}