From fec23c3e80f6790b92ea4c2afc8b47243bfa2d3b Mon Sep 17 00:00:00 2001 From: Eric Bell Date: Mon, 9 Nov 2026 08:17:20 -0500 Subject: [PATCH] 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 --- build.js | 88 +++++++++++++++++++++++++++++++++++------ package.json | 7 +++- src/app.js | 99 +++++++++++++++++++++++++++++++++++++++++++++- src/crypto.js | 10 +++++ src/index.html | 17 -------- src/ops.js | 6 +++ src/template.js | 22 +++++++++++ test/build.test.js | 76 +++++++++++++++++++++++++++++++++++ 8 files changed, 293 insertions(+), 32 deletions(-) delete mode 100644 src/index.html create mode 100644 src/template.js create mode 100644 test/build.test.js diff --git a/build.js b/build.js index 52528d7..4cadc8f 100644 --- a/build.js +++ b/build.js @@ -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); }); diff --git a/package.json b/package.json index d12f06f..a24c529 100644 --- a/package.json +++ b/package.json @@ -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" + } } diff --git a/src/app.js b/src/app.js index 3d1ff86..b79e449 100644 --- a/src/app.js +++ b/src/app.js @@ -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(), diff --git a/src/crypto.js b/src/crypto.js index e52786c..7721a11 100644 --- a/src/crypto.js +++ b/src/crypto.js @@ -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 ''; +} diff --git a/src/index.html b/src/index.html deleted file mode 100644 index d4ec584..0000000 --- a/src/index.html +++ /dev/null @@ -1,17 +0,0 @@ - - - - - -Final Wishes - - - - - -
- - - - - diff --git a/src/ops.js b/src/ops.js index 2470995..69d12c0 100644 --- a/src/ops.js +++ b/src/ops.js @@ -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`; +} diff --git a/src/template.js b/src/template.js new file mode 100644 index 0000000..2ea282b --- /dev/null +++ b/src/template.js @@ -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