Add encrypted build and save flow

build.js seals a JSON document into the single-file HTML (passphrase from
a hidden prompt or FW_PASSPHRASE, 12 character minimum). In the page,
Save writes via the File System Access API when available and downloads
otherwise; Backup copy downloads final-wishes-YYYYMMDD.html; Ctrl+S and
Change passphrase are supported. Build and Save share assemble() in
template.js, replacing src/index.html. Tests confirm the built file
holds no plaintext and that the payload round-trips.

Closes #6

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-09 08:17:20 -05:00
parent e291ee75b6
commit fec23c3e80
8 changed files with 293 additions and 32 deletions

View File

@@ -1,18 +1,82 @@
// Inlines src/ into a single self-contained dist/final-wishes.html.
// The encrypted payload is a placeholder until the crypto module exists (#2, #6).
// Builds the single self-contained final-wishes.html.
//
// node build.js app only, no data (open/import a JSON file in the page)
// node build.js --data data/seed.json also encrypt that JSON and embed it
// node build.js --data X --out /path/final-wishes.html
//
// The passphrase is read from the FW_PASSPHRASE environment variable, or
// prompted for (hidden, entered twice). It is never accepted as an argument.
import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import { dirname, join, resolve } from 'node:path';
import { assemble } from './src/template.js';
import { encrypt, passphraseProblem } from './src/crypto.js';
import { assertValid } from './src/model.js';
const root = dirname(fileURLToPath(import.meta.url));
const read = (p) => readFileSync(join(root, 'src', p), 'utf8');
// Function replacers avoid '$' pattern interpretation in replacement text.
const out = read('index.html')
.replace('/*__CSS__*/', () => read('style.css'))
// Plain-script bundle: drop ES `export` so modules concatenate into one scope.
.replace('/*__JS__*/', () => ['crypto.js', 'model.js', 'ops.js', 'print.js'].map((f) => read(f).replace(/^export /gm, '')).concat(read('app.js')).join('\n'))
.replace('/*__PAYLOAD__*/', () => '');
mkdirSync(join(root, 'dist'), { recursive: true });
writeFileSync(join(root, 'dist', 'final-wishes.html'), out);
console.log('Wrote dist/final-wishes.html (' + out.length + ' bytes)');
// Modules are concatenated (ES `export` dropped) ahead of app.js into one scope.
const MODULES = ['crypto.js', 'model.js', 'ops.js', 'print.js', 'template.js'];
export function bundleJs() {
return MODULES.map((f) => read(f).replace(/^export /gm, '')).concat(read('app.js')).join('\n');
}
function parseArgs(argv) {
const a = {};
for (let i = 0; i < argv.length; i++) {
if (argv[i] === '--data') a.data = argv[++i];
else if (argv[i] === '--out') a.out = argv[++i];
else throw new Error(`Unknown argument: ${argv[i]}`);
}
return a;
}
function promptHidden(question) {
return new Promise((res, rej) => {
if (!process.stdin.isTTY) return rej(new Error('No terminal to prompt on: set FW_PASSPHRASE instead.'));
process.stdout.write(question);
let buf = '';
process.stdin.setRawMode(true);
process.stdin.resume();
process.stdin.setEncoding('utf8');
const done = (fn, v) => { process.stdin.setRawMode(false); process.stdin.pause(); process.stdin.off('data', onData); process.stdout.write('\n'); fn(v); };
const onData = (chunk) => {
for (const ch of chunk) {
if (ch === '\r' || ch === '\n') return done(res, buf);
if (ch === '\u0003') return done(rej, new Error('Cancelled.'));
if (ch === '\u007f' || ch === '\b') buf = buf.slice(0, -1);
else buf += ch;
}
};
process.stdin.on('data', onData);
});
}
async function getPassphrase() {
if (process.env.FW_PASSPHRASE) return process.env.FW_PASSPHRASE;
const a = await promptHidden('Passphrase: ');
const b = await promptHidden('Repeat passphrase: ');
if (a !== b) throw new Error('Passphrases did not match.');
return a;
}
async function main() {
const args = parseArgs(process.argv.slice(2));
let payload = '';
if (args.data) {
const doc = assertValid(JSON.parse(readFileSync(args.data, 'utf8')));
const pass = await getPassphrase();
const problem = passphraseProblem(pass);
if (problem) throw new Error(problem);
payload = await encrypt(JSON.stringify(doc), pass);
}
const html = assemble({ css: read('style.css'), js: bundleJs(), payload });
const out = resolve(args.out || join(root, 'dist', 'final-wishes.html'));
mkdirSync(dirname(out), { recursive: true });
writeFileSync(out, html);
console.log(`Wrote ${out} (${html.length} bytes, ${payload ? 'encrypted data embedded' : 'no data embedded'})`);
if (args.data) console.log(`Note: ${args.data} is still plaintext. Keep it out of git and delete it when done.`);
}
main().catch((e) => { console.error(e.message); process.exit(1); });

View File

@@ -6,7 +6,10 @@
"type": "module",
"scripts": {
"build": "node build.js",
"test": "node --test"
"test": "node --test",
"seal": "node build.js --data data/seed.json"
},
"engines": { "node": ">=20" }
"engines": {
"node": ">=20"
}
}

View File

@@ -10,6 +10,8 @@
editing: false,
dirty: false,
revealed: new WeakSet(), // secret field objects currently shown
handle: null, // File System Access handle once the user picked a save location
status: '',
error: '',
};
@@ -35,6 +37,9 @@
state.dirty = true;
const d = document.getElementById('dirty');
if (d) d.hidden = false;
state.status = '';
const st = document.getElementById('status');
if (st) st.textContent = '';
}
function changed(record) {
touch(state.doc, record);
@@ -88,7 +93,7 @@
return h('div', { class: 'card start' },
h('h1', {}, 'Final Wishes'),
h('p', {}, 'No encrypted data is built into this file yet.'),
h('p', {}, 'Open a JSON file:'), file, msg,
h('p', {}, 'Import a plain JSON file (you will choose a passphrase when you save):'), file, msg,
h('p', {}, 'or'),
btn('Start a new document', () => {
state.doc = emptyDocument('');
@@ -258,6 +263,94 @@
dlg.showModal();
}
// ---------- save ----------
const byId = (id) => document.getElementById(id);
function downloadFile(html, name) {
const url = URL.createObjectURL(new Blob([html], { type: 'text/html' }));
const a = h('a', { href: url, download: name });
document.body.append(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 10000);
}
// Resolves to the chosen passphrase, or null if cancelled.
function askPassphrase(title, intro) {
return new Promise((resolve) => {
const p1 = h('input', { type: 'password', autocomplete: 'new-password', 'aria-label': 'New passphrase' });
const p2 = h('input', { type: 'password', autocomplete: 'new-password', 'aria-label': 'Repeat passphrase' });
const err = h('p', { class: 'error', role: 'alert' });
const finish = (v) => { dlg.close(); dlg.remove(); resolve(v); };
const dlg = h('dialog', { class: 'card', 'aria-label': title },
h('form', { onsubmit: (e) => {
e.preventDefault();
const problem = passphraseProblem(p1.value);
if (problem) err.textContent = problem;
else if (p1.value !== p2.value) err.textContent = 'The two entries do not match.';
else finish(p1.value);
} },
h('h3', {}, title), h('p', {}, intro), p1, p2, err,
h('div', { class: 'row' }, btn('Cancel', () => finish(null)), btn('Set passphrase', null, 'primary', { type: 'submit' }))));
dlg.addEventListener('cancel', () => resolve(null));
document.body.append(dlg);
dlg.showModal();
p1.focus();
});
}
// backup=true downloads final-wishes-YYYYMMDD.html; otherwise writes the main file.
async function save({ backup = false } = {}) {
try {
if (!state.passphrase) {
const p = await askPassphrase('Choose a passphrase', 'This passphrase encrypts the document. Without it nobody can open it, so store it where your executor can find it.');
if (!p) return;
state.passphrase = p;
}
assertValid(state.doc);
const html = assemble({
css: byId('fw-css').textContent,
js: byId('fw-js').textContent,
payload: await encrypt(JSON.stringify(state.doc), state.passphrase),
});
if (backup) {
const name = backupName(new Date());
downloadFile(html, name);
state.status = 'Backup copy downloaded as ' + name + '.';
} else if (window.showSaveFilePicker) {
if (!state.handle) {
state.handle = await window.showSaveFilePicker({ suggestedName: 'final-wishes.html', types: [{ description: 'Final Wishes', accept: { 'text/html': ['.html'] } }] });
}
const w = await state.handle.createWritable();
await w.write(html);
await w.close();
state.status = 'Saved to ' + state.handle.name + '.';
state.dirty = false;
} else {
downloadFile(html, 'final-wishes.html');
state.status = 'Downloaded final-wishes.html. Replace the old copy on the thumbdrive with it.';
state.dirty = false;
}
} catch (e) {
if (e && e.name === 'AbortError') return; // user closed the file picker
state.status = 'Save failed: ' + (e && e.message ? e.message : e);
}
render();
}
async function changePassphrase() {
const p = await askPassphrase('Change passphrase', 'The new passphrase takes effect when you next save. Until then the saved file still opens with the old one.');
if (!p) return;
state.passphrase = p;
markDirty();
state.status = 'Passphrase changed. Save to apply it.';
render();
}
document.addEventListener('keydown', (e) => {
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 's' && state.doc) { e.preventDefault(); save(); }
});
// ---------- shell ----------
function renderNav() {
const nav = h('nav', { 'aria-label': 'Sections' },
@@ -285,6 +378,10 @@
h('h1', {}, state.doc.meta.title || 'Final Wishes'),
h('span', { class: 'muted' }, 'Last update: ' + state.doc.meta.lastUpdated),
h('span', { id: 'dirty', class: 'badge tbd', hidden: !state.dirty }, 'Unsaved changes'),
h('span', { id: 'status', class: 'muted', role: 'status' }, state.status),
btn('Save', () => save(), state.dirty ? 'primary' : ''),
btn('Backup copy', () => save({ backup: true })),
btn('Change passphrase', changePassphrase),
btn('Print…', openPrintDialog),
btn(state.editing ? 'Done editing' : 'Edit', () => { state.editing = !state.editing; render(); }, state.editing ? 'primary' : '')),
h('div', { class: 'layout' }, renderNav(),

View File

@@ -92,3 +92,13 @@ export async function decrypt(blob, passphrase) {
throw new DecryptError('Wrong passphrase, or the file is damaged.');
}
}
export const MIN_PASSPHRASE_LENGTH = 12;
// Returns '' when acceptable, otherwise a message for the user.
export function passphraseProblem(p) {
if (!p || p.length < MIN_PASSPHRASE_LENGTH) {
return `Use at least ${MIN_PASSPHRASE_LENGTH} characters (a few random words works well).`;
}
return '';
}

View File

@@ -1,17 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Final Wishes</title>
<!-- build.js inlines CSS and JS here; no external requests (must work offline) -->
<style>/*__CSS__*/</style>
</head>
<body>
<div id="printdoc" aria-hidden="true"></div>
<main id="app"><noscript>This document needs JavaScript enabled.</noscript></main>
<!-- Encrypted data blob is injected by build.js (issue #6). -->
<script id="payload" type="application/octet-stream">/*__PAYLOAD__*/</script>
<script>/*__JS__*/</script>
</body>
</html>

View File

@@ -67,3 +67,9 @@ export function addItem(doc, section) {
touch(doc);
return it;
}
// final-wishes-YYYYMMDD.html (local date)
export function backupName(date) {
const p = (n) => String(n).padStart(2, '0');
return `final-wishes-${date.getFullYear()}${p(date.getMonth() + 1)}${p(date.getDate())}.html`;
}

22
src/template.js Normal file
View File

@@ -0,0 +1,22 @@
// The single-file HTML skeleton. Used by build.js (Node) and by Save in the
// browser, so a built file and a saved file are produced by the same code.
// NOTE: the closing script tag is written <\/script> inside the template
// literal so this source can itself be inlined into a <script> element.
export function assemble({ css, js, payload }) {
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Final Wishes</title>
<style id="fw-css">${css}</style>
</head>
<body>
<div id="printdoc" aria-hidden="true"></div>
<main id="app"><noscript>This document needs JavaScript enabled.</noscript></main>
<script id="payload" type="application/octet-stream">${payload}<\/script>
<script id="fw-js">${js}<\/script>
</body>
</html>
`;
}

76
test/build.test.js Normal file
View File

@@ -0,0 +1,76 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { execFileSync, spawnSync } from 'node:child_process';
import { mkdtempSync, writeFileSync, readFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { decrypt, passphraseProblem } from '../src/crypto.js';
import { validate } from '../src/model.js';
import { backupName } from '../src/ops.js';
import { assemble } from '../src/template.js';
const SECRET = 'hunter2-SENTINEL-9431';
const doc = {
schemaVersion: 1,
meta: { owner: 'Test Owner SENTINEL', 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 }] }] }],
};
const PASS = 'a long test passphrase';
function build(extraEnv = {}, args) {
const dir = mkdtempSync(join(tmpdir(), 'fw-'));
const data = join(dir, 'doc.json');
const out = join(dir, 'out.html');
writeFileSync(data, JSON.stringify(doc));
const r = spawnSync('node', ['build.js', '--data', data, '--out', out, ...(args || [])],
{ env: { ...process.env, FW_PASSPHRASE: PASS, ...extraEnv }, encoding: 'utf8' });
return { r, out };
}
test('built file embeds ciphertext only: no plaintext anywhere', () => {
const { r, out } = build();
assert.equal(r.status, 0, r.stderr);
const html = readFileSync(out, 'utf8');
assert.ok(!html.includes(SECRET), 'secret leaked');
assert.ok(!html.includes('Test Owner SENTINEL'), 'owner leaked');
assert.ok(!html.includes(PASS), 'passphrase leaked');
assert.doesNotMatch(html, /https?:\/\//, 'external URL present');
});
test('embedded payload decrypts back to the document', async () => {
const { out } = build();
const html = readFileSync(out, 'utf8');
const payload = html.match(/<script id="payload"[^>]*>([^<]*)<\/script>/)[1];
const back = JSON.parse(await decrypt(payload, PASS));
assert.deepEqual(back, doc);
assert.deepEqual(validate(back), []);
await assert.rejects(decrypt(payload, 'wrong passphrase!!'));
});
test('build refuses a weak passphrase and missing data', () => {
const weak = build({ FW_PASSPHRASE: 'short' });
assert.notEqual(weak.r.status, 0);
assert.match(weak.r.stderr, /at least 12/);
const bad = spawnSync('node', ['build.js', '--data', '/nonexistent.json'], { env: { ...process.env, FW_PASSPHRASE: PASS }, encoding: 'utf8' });
assert.notEqual(bad.status, 0);
});
test('assemble is reproducible from the pieces of a built file (what Save relies on)', () => {
const { out } = build();
const html = readFileSync(out, 'utf8');
const css = html.match(/<style id="fw-css">([\s\S]*?)<\/style>/)[1];
const js = html.match(/<script id="fw-js">([\s\S]*?)<\/script>\n<\/body>/)[1];
const payload = html.match(/<script id="payload"[^>]*>([^<]*)<\/script>/)[1];
assert.equal(assemble({ css, js, payload }), html);
assert.doesNotMatch(js, /<\/script/i, 'inline script would end early');
});
test('backupName and passphraseProblem', () => {
assert.equal(backupName(new Date(2026, 10, 9)), 'final-wishes-20261109.html');
assert.equal(backupName(new Date(2026, 0, 5)), 'final-wishes-20260105.html');
assert.ok(passphraseProblem(''));
assert.ok(passphraseProblem('elevenchars'));
assert.equal(passphraseProblem('twelve chars!'), '');
});