Add sanitize.js: secret-free copy under a new passphrase (Refs #19)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-24 07:26:27 -05:00
parent 78bf87c4e6
commit 05ffcc8561
6 changed files with 161 additions and 1 deletions

92
sanitize.js Normal file
View File

@@ -0,0 +1,92 @@
// Makes a copy of a Final Wishes file with every secret value erased, sealed under a NEW passphrase,
// so it can be kept somewhere less safe (a shared SSD, an online session) for working on the layout.
// The input file is only read. The copy carries the newest app code from src/.
//
// node sanitize.js --in real.html --out /path/copy.html
//
// Passphrases: FW_PASSPHRASE (current) and FW_NEW_PASSPHRASE (for the copy), else prompted for hidden.
// They are never accepted as arguments. Only values flagged `secret` are erased; the summary printed
// at the end lists what is still in the copy so you can judge whether it is safe to put where you plan to.
import { readFileSync, writeFileSync, mkdirSync, existsSync, realpathSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join, resolve } from 'node:path';
import { assemble } from './src/template.js';
import { encrypt, decrypt, passphraseProblem } from './src/crypto.js';
import { assertValid, isSequence } from './src/model.js';
import { clearSecrets } from './src/ops.js';
import { bundleJs, promptHidden } from './build.js';
const root = dirname(fileURLToPath(import.meta.url));
export function extractPayload(html) {
const m = html.match(/<script id="payload"[^>]*>([^<]*)<\/script>/);
if (!m || !m[1].trim()) throw new Error('That file has no encrypted data in it.');
return m[1].trim();
}
// What is left in the document after erasing: per section, counts of kept text values and images.
export function remaining(doc) {
return doc.sections.map((s) => {
let text = 0, images = 0, empty = 0;
const count = (v, isImage) => { if (!v || !String(v).trim()) empty++; else if (isImage) images++; else text++; };
const frames = (q) => { for (const f of q.frames) { count(f.text, false); if (f.image) images++; } };
for (const r of s.records || []) {
if (isSequence(r)) frames(r);
else for (const f of r.fields) count(f.value, f.kind === 'image' || /^data:image\//.test(f.value || ''));
}
for (const it of s.items || []) { if (isSequence(it)) frames(it); else count(it.text, false); }
for (const q of s.sequences || []) frames(q);
if (s.body && String(s.body).trim()) text++;
return { title: s.title, kind: s.kind, text, images };
});
}
// Pure core: encrypted file text in, sanitized file text out. `iterations` is for fast tests only.
export async function sanitize({ html, oldPass, newPass, css, js, iterations }) {
const problem = passphraseProblem(newPass);
if (problem) throw new Error('New passphrase: ' + problem);
if (newPass === oldPass) throw new Error('Choose a different passphrase for the sanitized copy.');
const doc = assertValid(JSON.parse(await decrypt(extractPayload(html), oldPass)));
const erased = clearSecrets(doc);
assertValid(doc);
const payload = await encrypt(JSON.stringify(doc), newPass, iterations);
return { html: assemble({ css, js, payload }), erased, left: remaining(doc) };
}
function parseArgs(argv) {
const a = {};
for (let i = 0; i < argv.length; i++) {
if (argv[i] === '--in') a.in = argv[++i];
else if (argv[i] === '--out') a.out = argv[++i];
else throw new Error(`Unknown argument: ${argv[i]}`);
}
if (!a.in || !a.out) throw new Error('Usage: node sanitize.js --in real.html --out copy.html');
return a;
}
async function main() {
const args = parseArgs(process.argv.slice(2));
const inPath = resolve(args.in), outPath = resolve(args.out);
if (!existsSync(inPath)) throw new Error(`Not found: ${inPath}`);
if (inPath === outPath || (existsSync(outPath) && realpathSync(inPath) === realpathSync(outPath))) {
throw new Error('--out must be a different file from --in.');
}
const oldPass = process.env.FW_PASSPHRASE || await promptHidden('Passphrase of the real file: ');
let newPass = process.env.FW_NEW_PASSPHRASE;
if (!newPass) {
newPass = await promptHidden('New passphrase for the sanitized copy: ');
if (newPass !== await promptHidden('Repeat new passphrase: ')) throw new Error('Passphrases did not match.');
}
const r = await sanitize({
html: readFileSync(inPath, 'utf8'), oldPass, newPass,
css: readFileSync(join(root, 'src', 'style.css'), 'utf8'), js: bundleJs(),
});
mkdirSync(dirname(outPath), { recursive: true });
writeFileSync(outPath, r.html);
console.log(`Wrote ${outPath} (${r.html.length} bytes). Erased ${r.erased} secret value${r.erased === 1 ? '' : 's'}.`);
console.log('\nStill in the copy (review before using it somewhere less safe):');
for (const s of r.left) console.log(` ${s.title} [${s.kind}]: ${s.text} text value${s.text === 1 ? '' : 's'}, ${s.images} image${s.images === 1 ? '' : 's'}`);
console.log(`\nThe real file was not changed. Do not Save the copy over it.`);
}
if (process.argv[1] === fileURLToPath(import.meta.url)) main().catch((e) => { console.error(e.message); process.exit(1); });