// Last step of `npm run build`: refuses a release that carries things it
// should not. Two checks, both born from findings in the same audit.
//
// 1. The search index is this build's and nothing else.
// public/pagefind is a copy of the last build's index (kept so the dev
// server can search). Astro copies public/ into dist/, Pagefind then wrote
// the new index on top of the old one, and the union was copied back, so
// every build added to a pile: text of pages that had since been edited or
// deleted stayed downloadable for anyone holding an old fragment URL. The
// build now starts by deleting both copies (`npm run clean:search`); this
// check proves it, by matching what is on disk against what Pagefind's own
// entry file says this build produced.
//
// 2. No complete private key in first-party output.
// A working ledger with a live SSH key was once published as a sheet and
// indexed for search. The importer refuses such a note now
// (scripts/sync-pentest-workflow.py); this looks at the result anyway, in
// the three places it would surface: the source sheets, the rendered pages
// and the decompressed search fragments. The mirrored third-party
// collections are skipped: an example key in someone else's public
// documentation is not this site's secret, and failing the nightly sync
// over it would help nobody.
//
// Only a whole key block counts. A bare `-----BEGIN ... PRIVATE KEY-----`
// (a search dork, a grep pattern, a truncated sample) is ordinary content.
import { readFileSync, readdirSync, statSync, existsSync } from 'node:fs';
import { gunzipSync } from 'node:zlib';
import { join, relative, sep } from 'node:path';
import { pathToFileURL } from 'node:url';
const KEY_BLOCK = /-----BEGIN ((?:[A-Z0-9]+ )*PRIVATE KEY)-----[A-Za-z0-9+/=\s]{200,}?-----END \1-----/;
const MIRRORS = ['payloads', 'internal', 'hacktricks'];
const FRAGMENT_MAGIC = 'pagefind_dcd';
/** True when the text holds a complete PEM/OpenSSH private-key block. */
export function hasPrivateKey(text) {
return text.includes('PRIVATE KEY-----') && KEY_BLOCK.test(text);
}
/** Rendered HTML back to roughly the text a reader could copy out of it. */
export function htmlToText(html) {
return html
.replace(/<[^>]*>/g, '')
.replace(/&#x([0-9a-f]+);/gi, (_, hex) => String.fromCodePoint(parseInt(hex, 16)))
.replace(/&#(\d+);/g, (_, dec) => String.fromCodePoint(Number(dec)))
.replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/&/g, '&');
}
function* walk(dir) {
for (const name of readdirSync(dir)) {
const p = join(dir, name);
if (statSync(p).isDirectory()) yield* walk(p);
else yield p;
}
}
const isMirror = (rel) => MIRRORS.includes(rel.split(sep)[0]);
/** Decompressed text of one Pagefind fragment, with its magic prefix removed. */
export function readFragment(file) {
const text = gunzipSync(readFileSync(file)).toString('utf8');
return text.startsWith(FRAGMENT_MAGIC) ? text.slice(FRAGMENT_MAGIC.length) : text;
}
/** Problems with the Pagefind output in `dir`; empty when it is exactly one build's. */
export function checkSearchIndex(dir) {
const problems = [];
const entryFile = join(dir, 'pagefind-entry.json');
if (!existsSync(entryFile)) return [`${entryFile} is missing; did Pagefind run?`];
const languages = JSON.parse(readFileSync(entryFile, 'utf8')).languages ?? {};
const expectedPages = Object.values(languages).reduce((sum, lang) => sum + lang.page_count, 0);
const expectedMeta = new Set(Object.values(languages).map((lang) => `pagefind.${lang.hash}.pf_meta`));
const fragments = existsSync(join(dir, 'fragment')) ? readdirSync(join(dir, 'fragment')).filter((f) => f.endsWith('.pf_fragment')) : [];
if (fragments.length !== expectedPages) {
problems.push(`${fragments.length} search fragments on disk but this build indexed ${expectedPages} pages: ${Math.abs(fragments.length - expectedPages)} do not belong to it`);
}
const meta = readdirSync(dir).filter((f) => f.endsWith('.pf_meta'));
const strayMeta = meta.filter((f) => !expectedMeta.has(f));
if (strayMeta.length) problems.push(`${strayMeta.length} search metadata file(s) from another build: ${strayMeta.slice(0, 3).join(', ')}`);
for (const name of expectedMeta) if (!meta.includes(name)) problems.push(`search metadata ${name} is missing`);
return problems;
}
/** First-party places in the release that contain a complete private key. */
export function findPrivateKeys({ dist, sheets }) {
const hits = [];
if (sheets && existsSync(sheets)) {
for (const file of walk(sheets)) {
if (/\.mdx?$/.test(file) && hasPrivateKey(readFileSync(file, 'utf8'))) hits.push(`source sheet ${file}`);
}
}
if (dist && existsSync(dist)) {
for (const file of walk(dist)) {
const rel = relative(dist, file);
if (!file.endsWith('.html') || isMirror(rel)) continue;
const html = readFileSync(file, 'utf8');
if (html.includes('PRIVATE KEY-----') && hasPrivateKey(htmlToText(html))) hits.push(`page ${rel}`);
}
const fragmentDir = join(dist, 'pagefind', 'fragment');
if (existsSync(fragmentDir)) {
for (const name of readdirSync(fragmentDir)) {
if (!name.endsWith('.pf_fragment')) continue;
const text = readFragment(join(fragmentDir, name));
if (!text.includes('PRIVATE KEY-----')) continue;
let page;
try { page = JSON.parse(text); } catch { page = { url: '', content: text }; }
const url = String(page.url ?? '');
if (MIRRORS.some((m) => url.startsWith(`/${m}/`))) continue;
if (hasPrivateKey(String(page.content ?? text))) hits.push(`search fragment pagefind/fragment/${name} (${url || 'unknown page'})`);
}
}
}
return hits;
}
function main() {
const problems = [
...checkSearchIndex(join('dist', 'pagefind')),
...(existsSync(join('public', 'pagefind')) ? checkSearchIndex(join('public', 'pagefind')).map((p) => `public copy: ${p}`) : []),
...findPrivateKeys({ dist: 'dist', sheets: join('src', 'content', 'sheets') }).map((where) => `complete private key in ${where}`),
];
if (problems.length) {
console.error('check-release: this build must not be deployed:');
for (const problem of problems) console.error(` - ${problem}`);
process.exit(1);
}
console.log('check-release: search index matches this build; no private key in first-party output');
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) main();