pdf-corruption-lab / generate.js
islam ayoub
Add gen_training.js (training-set generator)
70f2c87 verified
Raw History Blame Contribute Delete
5.12 kB
#!/usr/bin/env node
/**
* pdf-corruption-lab
* Generates a small, fully synthetic corpus of damaged PDF files with a known
* kind and severity of damage, plus a manifest.json describing each file.
* Intended for testing and benchmarking PDF repair / recovery tools.
*
* Usage: node generate.js [outputDir]
*/
const fs = require('fs');
const path = require('path');
const { PDFDocument, rgb, StandardFonts } = require('pdf-lib');
// 2x2 PNG used to make sure the base document contains an image stream.
const TEST_IMAGE_BASE64 =
'iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAAFElEQVQIW2NkwAJGDjACU2M4wAgAJu4BCHgB5hQAAAAASUVORK5CYII=';
const toLatin1 = (bytes) => new TextDecoder('latin1').decode(bytes);
const fromLatin1 = (str) => Uint8Array.from(str, (c) => c.charCodeAt(0) & 0xff);
async function buildBasePdf() {
const doc = await PDFDocument.create();
doc.setTitle('pdf-corruption-lab base document');
const font = await doc.embedFont(StandardFonts.Helvetica);
const p1 = doc.addPage([595, 842]);
p1.drawText('pdf-corruption-lab: base document', { x: 40, y: 780, size: 20, font, color: rgb(0.1, 0.3, 0.8) });
p1.drawText('Page 1 contains text and a vector rule.', { x: 40, y: 740, size: 11, font });
p1.drawRectangle({ x: 40, y: 760, width: 515, height: 3, color: rgb(0, 0.6, 0.6) });
const p2 = doc.addPage([595, 842]);
p2.drawText('Page 2 contains an embedded raster image.', { x: 40, y: 780, size: 14, font });
const png = await doc.embedPng(Buffer.from(TEST_IMAGE_BASE64, 'base64'));
p2.drawImage(png, { x: 100, y: 450, width: 120, height: 120 });
const p3 = doc.addPage([595, 842]);
p3.drawText('Page 3 contains text only.', { x: 40, y: 780, size: 14, font });
for (let i = 0; i < 20; i++) {
p3.drawText(`Line ${i + 1}: the quick brown fox jumps over the lazy dog.`, { x: 40, y: 740 - i * 18, size: 10, font });
}
return doc.save({ useObjectStreams: false });
}
// Each scenario receives (bytes, text) and returns damaged bytes.
const scenarios = [
{
id: 'missing_eof',
severity: 1,
description: 'The trailing %%EOF marker is removed. Structure is otherwise intact.',
apply: (_b, t) => fromLatin1(t.replace(/%%EOF\s*$/, '')),
},
{
id: 'invalid_startxref',
severity: 2,
description: 'startxref points to a non-numeric value; the xref table itself is valid.',
apply: (_b, t) => fromLatin1(t.replace(/startxref\s+\d+/, 'startxref\nINVALID')),
},
{
id: 'scrambled_xref',
severity: 3,
description: 'All xref offsets are replaced with bogus values and startxref is invalid.',
apply: (_b, t) => {
const pos = t.lastIndexOf('xref\n') !== -1 ? t.lastIndexOf('\nxref') + 1 : t.lastIndexOf('xref');
const head = t.substring(0, pos);
const count = (t.match(/\n\d{10} \d{5} n/g) || []).length + 1;
const rows = Array.from({ length: count - 1 }, (_, i) => `${String(99999 - i * 111).padStart(10, '0')} 00000 n \n`).join('');
return fromLatin1(`${head}xref\n0 ${count}\n0000000000 65535 f \n${rows}trailer\n<< /Size ${count} >>\nstartxref\nINVALID\n%%EOF\n`);
},
},
{
id: 'bad_root_reference',
severity: 3,
description: 'The trailer /Root points to a non-existent object and startxref is -1.',
apply: (_b, t) => {
let s = t.replace(/\/Root \d+ \d+ R/, '/Root 9999 0 R');
const pos = s.lastIndexOf('trailer');
if (pos !== -1) s = `${s.substring(0, pos)}trailer\n<< /Size 9999 >>\nstartxref\n-1\n%%EOF\n`;
return fromLatin1(s);
},
},
{
id: 'truncated_75',
severity: 4,
description: 'File cut at 75% of its length: xref, trailer and EOF are lost, last object is incomplete.',
apply: (b) => b.slice(0, Math.floor(b.length * 0.75)),
},
{
id: 'truncated_55',
severity: 5,
description: 'File cut at 55%: roughly half of the objects are lost; only partial content is recoverable.',
apply: (b) => b.slice(0, Math.floor(b.length * 0.55)),
},
];
async function main() {
const outDir = path.resolve(process.argv[2] || path.join(__dirname, 'output'));
fs.mkdirSync(outDir, { recursive: true });
const base = await buildBasePdf();
const baseText = toLatin1(base);
fs.writeFileSync(path.join(outDir, 'base_valid.pdf'), base);
const manifest = {
generator: 'pdf-corruption-lab',
base_file: 'base_valid.pdf',
base_pages: 3,
files: [],
};
for (const s of scenarios) {
const damaged = s.apply(base, baseText);
const name = `damaged_${s.id}.pdf`;
fs.writeFileSync(path.join(outDir, name), damaged);
manifest.files.push({ file: name, damage: s.id, severity: s.severity, description: s.description, bytes: damaged.length });
console.log(`ok ${name} (severity ${s.severity}, ${damaged.length} bytes)`);
}
fs.writeFileSync(path.join(outDir, 'manifest.json'), JSON.stringify(manifest, null, 2));
console.log(`\nWrote ${manifest.files.length + 1} PDFs and manifest.json to ${outDir}`);
}
module.exports = { scenarios, toLatin1, fromLatin1 };
if (require.main === module) {
main().catch((e) => {
console.error(e);
process.exit(1);
});
}