import { readFile, writeFile, mkdtemp, rm, access } from 'node:fs/promises'; import { createHash } from 'node:crypto'; import { execFileSync } from 'node:child_process'; import { tmpdir } from 'node:os'; import { join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { readReportIndex } from '../src/lib/report-index.ts'; const root = fileURLToPath(new URL('../', import.meta.url)); const recipient = '3374F5B7E65B8CDB7949E2EBBFB092454FAFECB4'; const encryptionSubkey = 'CA941D9D162F9278D0C61407B091C4B88C11FB95'; const input = process.argv[2]; if (!input || process.argv.length !== 3) throw new Error('Usage: node scripts/encrypt-report-index.mjs /private/path/report-index.json'); const source = resolve(input); if (source === root.replace(/\/$/, '') || source.startsWith(root)) throw new Error('Keep the decrypted index outside the checkout.'); const bytes = await readFile(source); const hash = data => createHash('sha256').update(data).digest('hex'); const plaintextSha256 = hash(bytes); const steps = await readReportIndex(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength), plaintextSha256, recipient); for (const step of steps) await access(join(root, 'src/content/sheets', `${step.sheetId}.md`)); const scratch = await mkdtemp(join(tmpdir(), 'daemon-report-index-')); try { const output = join(scratch, 'report-index.gpg'); // --no-options and --no-encrypt-to prevent a local encrypt-to-self setting adding another recipient. execFileSync('gpg', ['--no-options', '--batch', '--no-encrypt-to', '--trust-model', 'always', '--recipient', `${encryptionSubkey}!`, '--encrypt', '--output', output, source], { stdio: 'inherit' }); const ciphertext = await readFile(output); await writeFile(join(root, 'public/encrypted/report-index.gpg'), ciphertext); await writeFile(join(root, 'src/data/report-index-lock.json'), JSON.stringify({ recipient, encryptionSubkey, plaintextSha256, ciphertextSha256: hash(ciphertext) }, null, 2) + '\n'); await writeFile(join(root, 'src/data/report-guides.json'), JSON.stringify([...new Set(steps.map(step => step.sheetId))].sort(), null, 2) + '\n'); console.log(`Encrypted ${steps.length} steps to Main_Key; build the site to refresh the download and viewer.`); } finally { await rm(scratch, { recursive: true, force: true }); }