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

@@ -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>
`;
}