Files
app/src/utils/html-to-pdf.ts
BOHA e11765bf0e fix: resolve all 28 findings from the 2026-06-12 full audit (TDD-pinned)
Critical (data integrity):
- warehouse inventory confirm: throw (not return) inside $transaction so a
  failed deficit line rolls back the surplus corrective receipt — retries
  no longer accumulate phantom stock
- warehouse issue confirm: validate batches against the COMBINED quantity
  of all lines (duplicate FIFO-resolved lines drove batches negative)
- attendance delete: restore vacation_used/sick_used for the deleted day
  (in-transaction, clamped at 0)

High:
- auth refresh: terminated sessions (replaced_at only) get a plain 401 —
  the theft branch (family revocation) now fires only on replaced_by_hash
- POST /users strips role_id for non-admin callers (mirrors PUT guard)
- issued-order transition flushes unsaved edits via the full save payload
  when dirty; server contract (items+status in one PUT) pinned
- received-invoices list: usePaginatedQuery + pager (rows 26+ unreachable)
- received-invoice dates: nullableIsoDateString + NaN guard before NAS save
  (Czech-format dates corrupted month/year, orphaned NAS files)
- leave approval skips Czech public holidays and books each calendar year's
  hours against its own balance (mirrors createLeave)

Medium/Low (classes):
- 52 Zod caps aligned to DB column widths across 7 schemas (over-cap input
  500ed at Prisma instead of a Czech 400)
- FK pre-validation: projects update + warehouse receipts/issues return
  Czech 400s instead of P2003 500s
- invoice PDF degrades gracefully when the CNB rate is unavailable
  (recap omitted instead of 500 + lost NAS archival)
- date boundaries: local-day filters (warehouse lists/reports, audit-log),
  @db.Date coercion on invoice dates
- plan updateEntry re-checks the per-cell cap (self-excluding)
- {id} tiebreaks on customers/received-invoices/warehouse-items sorts;
  /items honors the client sort param
- htmlToPdf relaunches once when the shared browser died mid-render
- offer number release parses the year from the document number (cross-year
  finalize+delete left permanent sequence gaps)
- trips/vehicles km fields integer-coerced; AI budget regated to
  settings.company|settings.system; Settings System tab no longer clobbers
  Firma numbering patterns; draft invoices hide the dead PDF button;
  dashboard quick-trip invalidates ["vehicles"]; TOTP secret cap 64;
  audit-log + invoice month buckets day-shift fixes

Docs: corrected the stale "Chromium has no CSS margin-box footers" claim
(html-to-pdf.ts + CLAUDE.md — margin boxes render since Chrome 131); audit
report M3 withdrawn accordingly.

~65 new pinning tests; every finding reproduced RED against the real test
DB before its fix. Suite: 58 files / 634 tests green.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-12 23:00:19 +02:00

165 lines
5.6 KiB
TypeScript

import fs from "fs";
import { Browser } from "puppeteer";
/**
* Pick the first Chromium executable that actually exists on disk.
* The previous `A || B || C` chain was dead: the second operand
* ("/usr/bin/chromium-browser") is always truthy, so the third
* ("/usr/bin/chromium") was never reached and launch failed on hosts
* that only ship the `chromium` binary. We now probe each candidate
* with fs.existsSync and fall through to the next.
*/
function resolveChromiumPath(): string | undefined {
const candidates = [
process.env.CHROMIUM_PATH,
"/usr/bin/chromium-browser",
"/usr/bin/chromium",
].filter((p): p is string => Boolean(p));
for (const candidate of candidates) {
try {
if (fs.existsSync(candidate)) return candidate;
} catch {
// existsSync should not throw, but if it does treat as "not found"
// and continue probing the next candidate.
}
}
// Nothing on disk matched — fall back to the configured env value (if any)
// so puppeteer-core surfaces a meaningful launch error instead of "undefined".
return process.env.CHROMIUM_PATH || undefined;
}
let browser: Browser | null = null;
let launching: Promise<Browser> | null = null;
async function getBrowser(): Promise<Browser> {
if (browser && browser.connected) return browser;
if (launching) return launching;
launching = (async () => {
// Try puppeteer (bundles Chromium), fall back to puppeteer-core (system Chromium)
try {
const puppeteer = await import("puppeteer");
browser = await puppeteer.default.launch({
headless: true,
args: ["--no-sandbox", "--disable-setuid-sandbox", "--disable-gpu"],
});
} catch {
const core = await import("puppeteer-core");
const executablePath = resolveChromiumPath();
browser = await core.default.launch({
headless: true,
executablePath,
args: ["--no-sandbox", "--disable-setuid-sandbox", "--disable-gpu"],
});
}
return browser!;
})();
try {
return await launching;
} finally {
launching = null;
}
}
export interface HtmlToPdfOptions {
/**
* Chromium footerTemplate HTML rendered in the bottom margin of EVERY page.
* Styles must be inline and the font-size explicit (Chromium defaults it
* to 0); `.pageNumber` / `.totalPages` spans are substituted by Chromium.
* When set, the bottom margin grows to make room and an empty
* headerTemplate suppresses Chromium's default date/title header.
* The other valid repeating-footer mechanism: CSS `@page` margin boxes
* (`@bottom-center` + `counter(page)`) render since Chrome 131 (Nov 2024)
* — the offer PDF uses that route and needs no footerTemplate.
*/
footerTemplate?: string;
/**
* Chromium headerTemplate HTML rendered in the top margin of EVERY page
* (same rules as footerTemplate: inline styles, explicit font-size; images
* must be data: URLs). When set, the top margin grows to 32mm to make room
* — the document body must NOT render its own header then, or page 1 shows
* it twice. NOTE: Chromium lays pages out by the document's CSS @page
* margins when present (they override this option) — keep them in sync.
*/
headerTemplate?: string;
}
export async function htmlToPdf(
html: string,
options: HtmlToPdfOptions = {},
): Promise<Buffer> {
try {
return await renderPdf(html, options);
} catch (err) {
// The shared browser can die (OOM-kill, crash) between getBrowser()'s
// point-in-time `connected` check and the render — every caller holding
// the stale handle then fails, even though an immediate relaunch would
// succeed. Retry ONCE, and only on the crash signature (browser gone or
// disconnected); a still-connected browser means a genuine render error.
if (browser && browser.connected) throw err;
console.error(
"[html-to-pdf] browser disconnected mid-render — relaunching once",
err,
);
browser = null;
return renderPdf(html, options);
}
}
async function renderPdf(
html: string,
options: HtmlToPdfOptions,
): Promise<Buffer> {
const b = await getBrowser();
const page = await b.newPage();
// Per-request timeouts so one stuck render (e.g. image tag pointing at a
// hung host) cannot starve every subsequent PDF request. networkidle0 is
// intentionally NOT used — it waits for 500ms of zero network connections
// and is the original source of the indefinite-hang bug.
try {
await page.setContent(html, {
waitUntil: "domcontentloaded",
timeout: 10_000,
});
const pdf = await page.pdf({
format: "A4",
printBackground: true,
margin: {
top: options.headerTemplate ? "32mm" : "10mm",
bottom: options.footerTemplate ? "18mm" : "10mm",
left: "10mm",
right: "10mm",
},
...(options.footerTemplate || options.headerTemplate
? {
displayHeaderFooter: true,
headerTemplate: options.headerTemplate || "<span></span>",
footerTemplate: options.footerTemplate || "<span></span>",
}
: {}),
timeout: 15_000,
});
return Buffer.from(pdf);
} finally {
try {
await page.close();
} catch {
// If a stuck page won't close, only close the whole browser if it
// is actually disconnected — otherwise we just spent 1-2s relaunching
// Chromium on every subsequent PDF request.
if (!browser?.connected) {
await closeBrowser();
}
}
}
}
export async function closeBrowser(): Promise<void> {
if (browser) {
await browser.close();
browser = null;
}
}