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:
@@ -23,6 +23,7 @@ There are no npm dependencies and no CDN or network calls at runtime.
|
|||||||
|
|
||||||
```
|
```
|
||||||
build.js builds dist/final-wishes.html (optionally encrypting a JSON file into it)
|
build.js builds dist/final-wishes.html (optionally encrypting a JSON file into it)
|
||||||
|
sanitize.js `node sanitize.js --in real.html --out copy.html`: re-seals a copy with secrets erased under a new passphrase
|
||||||
bump-version.js `npm run bump`, and the pre-commit hook's engine: advances src/version.js to today's date + next letter
|
bump-version.js `npm run bump`, and the pre-commit hook's engine: advances src/version.js to today's date + next letter
|
||||||
.githooks/pre-commit runs `bump-version.js --staged`; enable once per clone with `npm run hooks`
|
.githooks/pre-commit runs `bump-version.js --staged`; enable once per clone with `npm run hooks`
|
||||||
package.json scripts: build, seal, test
|
package.json scripts: build, seal, test
|
||||||
|
|||||||
2
build.js
2
build.js
@@ -32,7 +32,7 @@ function parseArgs(argv) {
|
|||||||
return a;
|
return a;
|
||||||
}
|
}
|
||||||
|
|
||||||
function promptHidden(question) {
|
export function promptHidden(question) {
|
||||||
return new Promise((res, rej) => {
|
return new Promise((res, rej) => {
|
||||||
if (!process.stdin.isTTY) return rej(new Error('No terminal to prompt on: set FW_PASSPHRASE instead.'));
|
if (!process.stdin.isTTY) return rej(new Error('No terminal to prompt on: set FW_PASSPHRASE instead.'));
|
||||||
process.stdout.write(question);
|
process.stdout.write(question);
|
||||||
|
|||||||
@@ -224,6 +224,10 @@ To work on the layout somewhere less safe (a shared or online machine), open the
|
|||||||
|
|
||||||
Nothing is written until you Save, and saving over the file removes the secrets for good. Use **Backup copy** first, or save under a new name, if you need them again. Choosing "Keep them" dismisses the banner and changes nothing.
|
Nothing is written until you Save, and saving over the file removes the secrets for good. Use **Backup copy** first, or save under a new name, if you need them again. Choosing "Keep them" dismisses the banner and changes nothing.
|
||||||
|
|
||||||
|
### Making a copy without secrets (the sanitize script)
|
||||||
|
|
||||||
|
`node sanitize.js --in /path/real.html --out /path/copy.html` reads your real file (it is never changed), asks for its passphrase and a **new** passphrase for the copy, erases every value marked secret, and writes the copy with the newest app code. It prints what is still in the copy, section by section, so you can judge whether it is safe where you plan to put it. It refuses to write over the input, and refuses to reuse the real passphrase. Set `FW_PASSPHRASE` and `FW_NEW_PASSPHRASE` to skip the prompts. Only values flagged secret are erased: review anything sensitive that is not flagged.
|
||||||
|
|
||||||
## Keep it current
|
## Keep it current
|
||||||
Nothing in the app reminds you to review. Set a yearly reminder. Things that
|
Nothing in the app reminds you to review. Set a yearly reminder. Things that
|
||||||
go stale: card expiry dates, account balances and metal values, advisors'
|
go stale: card expiry dates, account balances and metal values, advisors'
|
||||||
|
|||||||
@@ -8,6 +8,7 @@
|
|||||||
"build": "node build.js",
|
"build": "node build.js",
|
||||||
"test": "node --test",
|
"test": "node --test",
|
||||||
"seal": "node build.js --data data/seed.json",
|
"seal": "node build.js --data data/seed.json",
|
||||||
|
"sanitize": "node sanitize.js",
|
||||||
"bump": "node bump-version.js",
|
"bump": "node bump-version.js",
|
||||||
"hooks": "git config core.hooksPath .githooks"
|
"hooks": "git config core.hooksPath .githooks"
|
||||||
},
|
},
|
||||||
|
|||||||
92
sanitize.js
Normal file
92
sanitize.js
Normal 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); });
|
||||||
62
test/sanitize.test.js
Normal file
62
test/sanitize.test.js
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
import { test } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { spawnSync } from 'node:child_process';
|
||||||
|
import { mkdtempSync, writeFileSync, readFileSync, existsSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { encrypt, decrypt } from '../src/crypto.js';
|
||||||
|
import { assemble } from '../src/template.js';
|
||||||
|
import { sanitize, extractPayload } from '../sanitize.js';
|
||||||
|
|
||||||
|
const SECRET = 'hunter2-SENTINEL-9431';
|
||||||
|
const OLD = 'the real long passphrase';
|
||||||
|
const NEW = 'a throwaway passphrase';
|
||||||
|
const doc = {
|
||||||
|
schemaVersion: 1,
|
||||||
|
meta: { owner: 'O', title: 'T', lastUpdated: '2022-04-14' },
|
||||||
|
sections: [{ id: 's', title: 'S', kind: 'records', records: [
|
||||||
|
{ id: 'r', title: 'Acct', status: 'ok', updated: '2022-04-14',
|
||||||
|
fields: [{ label: 'PW', value: SECRET, secret: true }, { label: 'Bank', value: 'First Bank' }] }] }],
|
||||||
|
};
|
||||||
|
const fast = 1000; // PBKDF2 iterations, tests only
|
||||||
|
async function realFile() {
|
||||||
|
return assemble({ css: 'x', js: 'y', payload: await encrypt(JSON.stringify(doc), OLD, fast) });
|
||||||
|
}
|
||||||
|
|
||||||
|
test('erases secrets, keeps the rest, re-seals under the new passphrase', async () => {
|
||||||
|
const html = await realFile();
|
||||||
|
const r = await sanitize({ html, oldPass: OLD, newPass: NEW, css: 'newcss', js: 'newjs', iterations: fast });
|
||||||
|
assert.equal(r.erased, 1);
|
||||||
|
assert.ok(!r.html.includes(SECRET));
|
||||||
|
assert.ok(r.html.includes('newcss') && r.html.includes('newjs'));
|
||||||
|
const out = JSON.parse(await decrypt(extractPayload(r.html), NEW));
|
||||||
|
assert.equal(out.sections[0].records[0].fields[0].value, '');
|
||||||
|
assert.equal(out.sections[0].records[0].fields[0].secret, true);
|
||||||
|
assert.equal(out.sections[0].records[0].fields[1].value, 'First Bank');
|
||||||
|
assert.deepEqual(r.left.map((s) => [s.title, s.text]), [['S', 1]]);
|
||||||
|
await assert.rejects(decrypt(extractPayload(r.html), OLD));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('refuses the same passphrase, a weak one, or a wrong old one', async () => {
|
||||||
|
const html = await realFile();
|
||||||
|
await assert.rejects(sanitize({ html, oldPass: OLD, newPass: OLD, css: '', js: '', iterations: fast }), /different passphrase/);
|
||||||
|
await assert.rejects(sanitize({ html, oldPass: OLD, newPass: 'short', css: '', js: '', iterations: fast }), /New passphrase/);
|
||||||
|
await assert.rejects(sanitize({ html, oldPass: 'wrong wrong wrong', newPass: NEW, css: '', js: '', iterations: fast }), /Wrong passphrase/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('CLI: writes a new file, leaves the input alone, refuses in == out', async () => {
|
||||||
|
const dir = mkdtempSync(join(tmpdir(), 'fw-san-'));
|
||||||
|
const inp = join(dir, 'real.html'), out = join(dir, 'copy.html');
|
||||||
|
const html = await realFile();
|
||||||
|
writeFileSync(inp, html);
|
||||||
|
const env = { ...process.env, FW_PASSPHRASE: OLD, FW_NEW_PASSPHRASE: NEW };
|
||||||
|
const bad = spawnSync('node', ['sanitize.js', '--in', inp, '--out', inp], { env, encoding: 'utf8' });
|
||||||
|
assert.notEqual(bad.status, 0);
|
||||||
|
assert.match(bad.stderr, /different file/);
|
||||||
|
const ok = spawnSync('node', ['sanitize.js', '--in', inp, '--out', out], { env, encoding: 'utf8' });
|
||||||
|
assert.equal(ok.status, 0, ok.stderr);
|
||||||
|
assert.match(ok.stdout, /Erased 1 secret value/);
|
||||||
|
assert.ok(existsSync(out));
|
||||||
|
assert.equal(readFileSync(inp, 'utf8'), html);
|
||||||
|
assert.ok(!readFileSync(out, 'utf8').includes(SECRET));
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user