const fs = require('fs'); const os = require('os'); const path = require('path'); const cp = require('child_process'); const assert = (ok, message) => { if (!ok) throw Error(message); }; function run(command, args) { const result = cp.spawnSync(command, args, {encoding: 'utf8', timeout: 45000}); assert(result.status === 0, `${command} failed: ${result.stderr || result.stdout}`); return result.stdout; } function readPages(pdf) { const xml = run('pdftotext', ['-bbox', '-cropbox', pdf, '-']); return Array.from(xml.matchAll(/([\s\S]*?)<\/page>/g), ([, width, height, content]) => { const words = Array.from( content.matchAll(/([^<]*)<\/word>/g), ([, left, top, right, bottom, text]) => ({ left: Number(left), top: Number(top), right: Number(right), bottom: Number(bottom), text }) ); return {width: Number(width), height: Number(height), words}; }); } function checkWordBounds({width, height, words}) { for (const {left, top, right, bottom} of words) { assert(left >= -1 && top >= -1 && right <= width + 1 && bottom <= height + 1, 'text extends beyond the visible PDF page'); } } function checkEnglishBodyOverlap({words}, pageNumber) { // Compare ordinary multi-character English word boxes. This avoids applying // Latin font metrics to CJK punctuation and ignores small glyph overshoots. const body = words.filter(word => /[A-Za-z]{4}/.test(word.text) && word.right > word.left && word.bottom > word.top).sort((a, b) => a.top - b.top); for (const [index, word] of body.entries()) { for (let next = index + 1; next < body.length && body[next].top < word.bottom; next++) { const other = body[next]; const sharedWidth = Math.min(word.right, other.right) - Math.max(word.left, other.left); const sharedHeight = Math.min(word.bottom, other.bottom) - other.top; const widthThreshold = 0.7 * Math.min(word.right - word.left, other.right - other.left); const heightThreshold = 0.7 * Math.min(word.bottom - word.top, other.bottom - other.top); assert(sharedWidth <= widthThreshold || sharedHeight <= heightThreshold, `overlapping body words on page ${pageNumber}: ${word.text} / ${other.text}`); } } } function normalizeEnglishText(text) { return text.replace(/\u00ad|-(?=[\r\n])|\s/g, ''); } const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'ux008-readable-')); try { const input = path.join(scratch, 'input'); const output = path.join(scratch, 'output'); const evidence = '/logs/verifier/pdf-audit'; fs.mkdirSync(input); fs.mkdirSync(evidence, {recursive: true}); const markers = Array.from({length: 144}, (_, i) => `AUDITROW_${String(i).padStart(3, '0')}`); const repeats = 90; fs.writeFileSync(path.join(input, '中文报告.md'), '# 中文报告\n你好,离线批量转换。\n**完整内容**和`代码`必须保留。\n\\(\\sqrt{2}\\)\nUNIQUE_CHINESE_DOC'); fs.writeFileSync(path.join(input, 'long.md'), '# Long document\n\n' + markers.map(marker => `${marker} visible text must survive page breaks.`).join('\n\n') + '\n\n' + 'LongLineContent '.repeat(repeats) + 'UNIQUE_LONG_END'); run(process.execPath, [path.join(process.cwd(), 'convert.js'), input, output]); const chinese = path.join(output, '中文报告.pdf'); const long = path.join(output, 'long.pdf'); const chineseText = run('pdftotext', [chinese, '-']).replace(/\s/g, ''); assert(chineseText.includes('中文报告') && chineseText.includes('你好,离线批量转换。') && chineseText.includes('完整内容') && chineseText.includes('代码'), 'CJK text lost or replaced by missing glyphs'); assert(!chineseText.includes('AUDITROW_'), 'another document leaked into the Chinese PDF'); const longText = normalizeEnglishText(run('pdftotext', [long, '-'])); assert(markers.every(marker => longText.includes(marker)) && longText.includes('UNIQUE_LONG_END'), 'long document or wrapped-line content is missing'); assert(!longText.includes('UNIQUE_CHINESE_DOC'), 'batch documents were mixed together'); assert(longText.split('LongLineContent').length - 1 === repeats, 'long wrapped paragraph must retain every repeated word exactly once'); for (const pdf of [chinese, long]) { const pages = readPages(pdf); assert(pages.some(page => page.words.length), 'PDF has no extractable positioned text'); if (pdf === long) { const bodyPages = pages.filter(page => /AUDITROW_|LongLineContent/.test(page.words.map(word => word.text).join(''))); assert(bodyPages.length > 1, 'long document body must span multiple pages'); const visibleText = normalizeEnglishText(pages.flatMap(page => page.words.map(word => word.text)).join('\n')); assert(markers.every(marker => visibleText.includes(marker)) && visibleText.includes('UNIQUE_LONG_END'), 'long body must retain all paragraphs inside the visible pages'); assert(visibleText.split('LongLineContent').length - 1 === repeats, 'long wrapped paragraph must retain all repeated words inside the visible pages'); pages.forEach((page, index) => checkEnglishBodyOverlap(page, index + 1)); } pages.forEach(checkWordBounds); const name = path.basename(pdf, '.pdf'); fs.copyFileSync(pdf, path.join(evidence, name + '.pdf')); run('pdftoppm', ['-r', '80', '-png', pdf, path.join(evidence, name)]); } console.log('CJK, long-line wrapping, pagination, visible bounds and independent batch documents passed'); } finally { fs.rmSync(scratch, {recursive: true, force: true}); }