Capture walkthroughs online in a separate tool, merge them in offline (Fixes #28)

build.js now also writes capture.html: no document, no payload, no storage.
It captures walkthroughs and exports an encrypted .fwcapture bundle (magic
FC, own passphrase). The main app's Import captures... opens a bundle and
places each walkthrough in a chosen section or sub-tab; nothing is written
until Save and the bundle is never modified.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-27 15:41:19 -05:00
parent 273c714fc4
commit 673560a249
12 changed files with 443 additions and 9 deletions

View File

@@ -915,6 +915,65 @@
});
}
// ---------- import captured walkthroughs (issue #28) ----------
// Open a bundle made by capture.html, then choose where each walkthrough goes. All or
// nothing per bundle: a wrong passphrase or damaged file imports nothing. The bundle file is
// never changed, so walkthroughs you skip can be imported from it later.
function importCaptures() {
const dests = destinations(state.doc);
const file = h('input', { type: 'file', accept: '.fwcapture,text/plain', 'aria-label': 'Capture bundle file' });
const pw = h('input', { type: 'password', autocomplete: 'off', placeholder: 'Bundle passphrase', 'aria-label': 'Bundle passphrase' });
const msg = h('p', { class: 'error', role: 'alert' });
const list = h('div', {});
const go = btn('Import selected', null, 'primary', { type: 'button', hidden: true });
let rows = [];
const close = () => { dlg.close(); dlg.remove(); };
const open = async () => {
msg.textContent = '';
try {
if (!file.files[0]) throw new Error('Choose the bundle file first.');
const bundle = await openBundle(await file.files[0].text(), pw.value);
if (!bundle.walkthroughs.length) throw new Error('That bundle has no walkthroughs.');
rows = bundle.walkthroughs.map((w) => {
const use = h('input', { type: 'checkbox', checked: true, 'aria-label': 'Import this walkthrough' });
const title = h('input', { value: w.title, 'aria-label': 'Walkthrough name' });
const where = h('select', { 'aria-label': 'Where to put it' }, dests.map((d) => h('option', { value: d.key }, d.label)));
const cur = state.doc.sections.find((x) => x.id === state.current);
if (cur) where.value = cur.id + '|';
return { w, use, title, where, el: h('div', { class: 'importrow' },
h('label', { class: 'check' }, use, ' ' + w.frames.length + ' step' + (w.frames.length === 1 ? '' : 's') + ', captured ' + w.captured),
h('div', { class: 'row' }, title, where)) };
});
list.replaceChildren(...rows.map((r) => r.el));
go.hidden = false;
if (!dests.length) msg.textContent = 'The document has no sections to put them in. Add one first.';
} catch (err) {
msg.textContent = err instanceof DecryptError ? err.message : err.message || 'Could not open that file.';
}
};
go.onclick = () => {
const picked = rows.filter((r) => r.use.checked);
if (!picked.length) { msg.textContent = 'Tick at least one walkthrough, or Cancel.'; return; }
for (const r of picked) {
const d = dests.find((x) => x.key === r.where.value);
const sec = state.doc.sections.find((x) => x.id === d.sid);
importWalkthrough(state.doc, sec, Object.assign({}, r.w, { title: r.title.value }), d.tab);
}
close();
markDirty();
state.status = 'Imported ' + picked.length + ' walkthrough' + (picked.length === 1 ? '' : 's') + '. Save to keep them, then delete the bundle file.';
render();
};
const dlg = h('dialog', { class: 'card', 'aria-label': 'Import captured walkthroughs' },
h('h3', {}, 'Import captured walkthroughs'),
h('p', {}, 'Choose the bundle file made by the capture tool and enter its passphrase. Nothing is saved until you Save.'),
file, pw, btn('Open bundle', open, 'small'), msg, list,
h('div', { class: 'row' }, btn('Cancel', close), go));
dlg.addEventListener('cancel', () => dlg.remove());
document.body.append(dlg);
dlg.showModal();
}
// backup=true downloads final-wishes-YYYYMMDD.html; otherwise writes the main file.
async function save({ backup = false } = {}) {
try {
@@ -1039,6 +1098,7 @@
btn('Backup copy', () => save({ backup: true })),
btn('Change passphrase', changePassphrase),
btn('Print…', openPrintDialog),
state.editing ? null : btn('Import captures…', importCaptures, '', { title: 'Merge walkthroughs captured with the separate capture tool' }),
state.editing ? null : btn('Search', openSearch, '', { id: 'searchopen', title: 'Find a word in the document' }),
btn(state.editing ? 'Done editing' : 'Edit', () => { state.editing = !state.editing; render(); }, state.editing ? 'primary' : '')])),
...(resetRequested() && !state.resetOffered ? [resetBanner()] : []), // never pass null: append() would print "null"

135
src/capture-app.js Normal file
View File

@@ -0,0 +1,135 @@
// The capture tool (issue #28): capture walkthroughs while online, then carry them to the
// offline Final Wishes file as an encrypted bundle. This page holds no document and has no
// way to read one. Nothing is stored in the browser: close the tab and unexported captures are gone.
// DOM is built with h() + textContent, never innerHTML.
(function () {
const root = document.getElementById('app');
const state = {
walks: [], // [{ title, captured, frames: [{ image }] }]
cur: -1, // index of the walkthrough being captured
unsaved: false, // captured something not yet exported
exporting: false,
status: '',
error: '',
};
let cap = null; // { stream, video } while the screen is shared
function h(tag, attrs, ...kids) {
const el = document.createElement(tag);
for (const [k, v] of Object.entries(attrs || {})) {
if (v === false || v == null) continue;
if (k.startsWith('on')) el.addEventListener(k.slice(2), v);
else if (k === 'class') el.className = v;
else if (k in el && k !== 'list') el[k] = v;
else el.setAttribute(k, v === true ? '' : v);
}
for (const kid of kids.flat(Infinity)) {
if (kid == null || kid === false) continue;
el.append(kid.nodeType ? kid : document.createTextNode(String(kid)));
}
return el;
}
const btn = (label, onclick, cls = '', extra = {}) =>
h('button', Object.assign({ type: 'button', class: 'btn ' + cls, onclick }, extra), label);
window.addEventListener('beforeunload', (e) => { if (state.unsaved) { e.preventDefault(); e.returnValue = ''; } });
const walk = () => state.walks[state.cur];
function endShare() { stopScreenCapture(cap); cap = null; }
async function startShare() {
endShare();
try {
const c = await startScreenCapture();
c.stream.getVideoTracks()[0].onended = () => { if (cap === c) { cap = null; state.status = 'Screen sharing ended.'; render(); } };
cap = c;
state.status = 'Sharing. Get the site to the screen you want, come back here and click Capture step.';
} catch (err) { state.status = err.message; }
render();
}
async function captureStep() {
try {
const image = await processImageFile(await grabScreenFrame(cap));
walk().frames.push({ image });
state.unsaved = true;
state.status = 'Step ' + walk().frames.length + ' captured.';
} catch (err) { state.status = err.message; }
render();
}
function newWalk() {
state.walks.push(newWalkthrough(''));
state.cur = state.walks.length - 1;
state.status = '';
render();
}
async function doExport(pass) {
const named = state.walks.filter((w) => w.frames.length);
const blob = await sealBundle(named, pass);
const a = h('a', { href: URL.createObjectURL(new Blob([blob], { type: 'text/plain' })), download: 'captures-' + new Date().toISOString().slice(0, 10) + '.fwcapture' });
document.body.append(a);
a.click();
a.remove();
state.unsaved = false;
state.exporting = false;
state.status = 'Exported ' + named.length + ' walkthrough' + (named.length === 1 ? '' : 's') + '. Copy the file to the thumbdrive, then delete it from this computer.';
}
function exportForm() {
const p1 = h('input', { type: 'password', autocomplete: 'new-password', placeholder: 'Passphrase for this bundle', 'aria-label': 'Bundle passphrase' });
const p2 = h('input', { type: 'password', autocomplete: 'new-password', placeholder: 'Repeat passphrase', 'aria-label': 'Repeat bundle passphrase' });
const err = h('p', { class: 'error', role: 'alert' });
return h('form', { class: 'card', onsubmit: async (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 { try { await doExport(p1.value); } catch (x) { err.textContent = x.message; return; } render(); }
} },
h('h3', {}, 'Export an encrypted bundle'),
h('p', {}, 'The pictures may show account numbers and balances, so the bundle is encrypted. You will type this passphrase again when you merge it into your Final Wishes file. It can differ from the passphrase of that file.'),
p1, p2, err,
h('div', { class: 'row' }, btn('Cancel', () => { state.exporting = false; render(); }), btn('Export', null, 'primary', { type: 'submit' })));
}
function render() {
root.replaceChildren();
const w = walk();
const total = state.walks.filter((x) => x.frames.length).length;
root.append(
h('header', { class: 'top' },
h('div', { class: 'titlerow' }, h('h1', {}, 'Final Wishes: capture walkthroughs'),
h('span', { class: 'muted', id: 'version', title: 'Version of this tool' }, 'Ver ' + APP_VERSION),
h('span', { class: 'badge tbd', hidden: !state.unsaved }, 'Not exported yet'),
h('span', { id: 'status', class: 'muted', role: 'status' }, state.status)),
h('p', { class: 'muted small' }, 'This page holds no document and no passwords. Capture here while online, export an encrypted bundle, then merge it into your Final Wishes file when you are offline. Nothing is kept in this browser, so export before you close the page.')),
h('div', { class: 'capwalks' },
state.walks.map((x, i) => btn((x.title || 'Untitled') + ' (' + x.frames.length + ')', () => { state.cur = i; state.status = ''; render(); }, i === state.cur ? 'primary' : '')),
btn('+ New walkthrough', newWalk)),
w ? h('div', { class: 'card' },
h('label', {}, 'Name of this walkthrough (for example "Log in to Chase")',
h('input', { value: w.title, 'aria-label': 'Walkthrough name', oninput: (e) => { w.title = e.target.value; state.unsaved = true; } })),
h('div', { class: 'row' },
cap ? [btn('Capture step', captureStep, 'primary'), btn('Stop sharing', () => { endShare(); state.status = 'Stopped sharing.'; render(); })]
: btn('Share screen…', startShare, 'primary', { title: 'Share the window with the site, then capture each screen you want as a step' }),
btn('Delete walkthrough', () => {
if (w.frames.length && !confirm('Delete this walkthrough and its ' + w.frames.length + ' step(s)?')) return;
state.walks.splice(state.cur, 1);
state.cur = state.walks.length ? Math.min(state.cur, state.walks.length - 1) : -1;
render();
}, 'danger')),
h('div', { class: 'capthumbs' }, w.frames.map((f, i) => h('div', { class: 'capthumb' },
h('img', { src: f.image, alt: 'Step ' + (i + 1) }),
h('div', { class: 'row' }, h('strong', {}, 'Step ' + (i + 1)),
btn('↑', () => { if (i > 0) { [w.frames[i - 1], w.frames[i]] = [w.frames[i], w.frames[i - 1]]; render(); } }, 'icon', { 'aria-label': 'Move step up', disabled: i === 0 }),
btn('↓', () => { if (i < w.frames.length - 1) { [w.frames[i + 1], w.frames[i]] = [w.frames[i], w.frames[i + 1]]; render(); } }, 'icon', { 'aria-label': 'Move step down', disabled: i === w.frames.length - 1 }),
btn('Delete', () => { w.frames.splice(i, 1); render(); }, 'small danger'))))))
: h('p', { class: 'muted' }, 'Start a walkthrough, name it, then share the screen and capture each step.'),
state.exporting ? exportForm() : h('div', { class: 'row' },
btn('Export bundle…', () => { state.exporting = true; state.status = ''; render(); }, total ? 'primary' : '', { disabled: !total, title: 'Save every walkthrough that has steps as one encrypted file' }),
h('span', { class: 'muted small' }, total ? total + ' walkthrough' + (total === 1 ? '' : 's') + ' with steps' : 'Capture at least one step to export.')));
}
render();
})();

68
src/capture.js Normal file
View File

@@ -0,0 +1,68 @@
import { encrypt, decrypt, CAPTURE_MAGIC } from './crypto.js';
import { isImageDataUrl } from './images.js';
// Capture bundles (issue #28): walkthroughs captured in the separate, online capture.html
// and carried to the offline main app. A bundle is JSON sealed like the main document
// (PBKDF2 -> AES-GCM) but with the "FC" magic bytes, so the two can never be mixed up.
//
// { format: 'fw-capture', version: 1, created: 'YYYY-MM-DD',
// walkthroughs: [{ title, captured: 'YYYY-MM-DD', frames: [{ image: <PNG/JPEG data URL> }] }] }
//
// Pure functions, no DOM. build.js strips `export` / `import` lines.
export const BUNDLE_FORMAT = 'fw-capture';
export const BUNDLE_VERSION = 1;
export const MAX_WALKTHROUGHS = 100;
export const MAX_FRAMES = 200;
const BUNDLE_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
export function newWalkthrough(title = '', date = new Date().toISOString().slice(0, 10)) {
return { title, captured: date, frames: [] };
}
// Problems with a bundle's contents, as strings; [] when it is fine to import.
export function validateBundle(b) {
const errs = [];
if (!b || typeof b !== 'object' || b.format !== BUNDLE_FORMAT) return ['This is not a capture bundle.'];
if (b.version !== BUNDLE_VERSION) return ['This bundle is from a different version of the capture tool (' + b.version + ').'];
if (!Array.isArray(b.walkthroughs) || b.walkthroughs.length > MAX_WALKTHROUGHS) return ['The bundle has no walkthroughs list.'];
b.walkthroughs.forEach((w, i) => {
const where = 'Walkthrough ' + (i + 1);
if (!w || typeof w !== 'object') return errs.push(where + ' is not valid.');
if (typeof w.title !== 'string') errs.push(where + ' has no title.');
if (typeof w.captured !== 'string' || !BUNDLE_DATE_RE.test(w.captured)) errs.push(where + ' has no capture date.');
if (!Array.isArray(w.frames) || w.frames.length > MAX_FRAMES) return errs.push(where + ' has no steps list.');
w.frames.forEach((f, j) => { if (!f || !isImageDataUrl(f.image)) errs.push(where + ', step ' + (j + 1) + ' has no valid picture.'); });
});
return errs;
}
// Walkthroughs with no steps are left out: there is nothing to carry over.
export async function sealBundle(walkthroughs, passphrase, iterations, date = new Date().toISOString().slice(0, 10)) {
const bundle = { format: BUNDLE_FORMAT, version: BUNDLE_VERSION, created: date, walkthroughs: walkthroughs.filter((w) => w.frames.length) };
const errs = validateBundle(bundle);
if (errs.length) throw new Error(errs[0]);
return encrypt(JSON.stringify(bundle), passphrase, iterations, CAPTURE_MAGIC);
}
// Returns the bundle; throws DecryptError (wrong passphrase / damaged / not a bundle) or Error (bad contents).
// Nothing is returned unless the whole bundle is valid, so a merge is all or nothing.
export async function openBundle(blob, passphrase) {
const bundle = JSON.parse(await decrypt(blob, passphrase, CAPTURE_MAGIC));
const errs = validateBundle(bundle);
if (errs.length) throw new Error(errs[0]);
return bundle;
}
// ---- where a walkthrough can go in the document ----
// [{ key, sid, tab, label }]: every section a sequence can live in, with one entry per sub-tab.
export function destinations(doc) {
const out = [];
for (const s of doc.sections) {
out.push({ key: s.id + '|', sid: s.id, tab: '', label: s.title });
if (s.kind === 'records') {
for (const t of s.subsections || []) out.push({ key: s.id + '|' + t.id, sid: s.id, tab: t.id, label: s.title + ' \u203a ' + t.title });
}
}
return out;
}

View File

@@ -7,6 +7,7 @@
// tampering with them fails authentication just like tampering with the ciphertext.
const MAGIC = [0x46, 0x57, 0x01]; // "FW" version 1
export const CAPTURE_MAGIC = [0x46, 0x43, 0x01]; // "FC" version 1: a capture bundle (issue #28)
const SALT_LEN = 16;
const IV_LEN = 12;
const HEADER_LEN = MAGIC.length + 4;
@@ -48,13 +49,13 @@ async function deriveKey(passphrase, salt, iterations) {
}
// Returns a base64 string. `iterations` is overridable for fast tests only.
export async function encrypt(plaintext, passphrase, iterations = DEFAULT_ITERATIONS) {
export async function encrypt(plaintext, passphrase, iterations = DEFAULT_ITERATIONS, magic = MAGIC) {
if (!passphrase) throw new Error('A passphrase is required.');
const salt = crypto.getRandomValues(new Uint8Array(SALT_LEN));
const iv = crypto.getRandomValues(new Uint8Array(IV_LEN));
const head = new Uint8Array(HEADER_LEN + SALT_LEN + IV_LEN);
head.set(MAGIC, 0);
new DataView(head.buffer).setUint32(MAGIC.length, iterations);
head.set(magic, 0);
new DataView(head.buffer).setUint32(magic.length, iterations);
head.set(salt, HEADER_LEN);
head.set(iv, HEADER_LEN + SALT_LEN);
@@ -70,13 +71,13 @@ export async function encrypt(plaintext, passphrase, iterations = DEFAULT_ITERAT
// Throws DecryptError for a wrong passphrase, corruption, or tampering
// (these are deliberately indistinguishable).
export async function decrypt(blob, passphrase) {
export async function decrypt(blob, passphrase, magic = MAGIC) {
const bytes = fromBase64(blob);
const preamble = HEADER_LEN + SALT_LEN + IV_LEN;
if (bytes.length < preamble + 16 || MAGIC.some((b, i) => bytes[i] !== b)) {
if (bytes.length < preamble + 16 || magic.some((b, i) => bytes[i] !== b)) {
throw new DecryptError('Not a valid encrypted file.');
}
const iterations = new DataView(bytes.buffer, bytes.byteOffset).getUint32(MAGIC.length);
const iterations = new DataView(bytes.buffer, bytes.byteOffset).getUint32(magic.length);
if (iterations < 1 || iterations > MAX_ITERATIONS) {
throw new DecryptError('Not a valid encrypted file.');
}

View File

@@ -262,6 +262,16 @@ export function addCapture(seq, image) {
return f;
}
// Merge a captured walkthrough ({ title, captured, frames: [{ image }] }) from a capture
// bundle (issue #28) into `section`, as a new visual sequence. Returns the sequence.
export function importWalkthrough(doc, section, wt, tabId = '') {
const q = addSequence(doc, section, tabId);
q.title = String(wt.title || '').trim() || 'Captured walkthrough';
q.captured = wt.captured;
for (const f of wt.frames) addFrame(q, f.image);
return q;
}
// ---- what a section holds (for the delete confirmation) ----
export function sectionContents(section) {
const c = { records: 0, items: 0, sequences: 0, images: 0, text: false };

View File

@@ -126,3 +126,12 @@ dialog.lightbox { max-width: 92vw; max-height: 92vh; overflow: auto; } .bigimg {
.pitem .pnotes { margin-left: 2.2em; }
.cb { display: inline-block; width: 11pt; height: 11pt; border: 1.2pt solid #000; margin: 0 7pt 0 4pt; vertical-align: -1.5pt; text-align: center; line-height: 10pt; font: 700 9pt system-ui, sans-serif; }
}
/* capture tool (issue #28) */
.capwalks { display: flex; flex-wrap: wrap; gap: .4rem; margin: 0 0 .75rem; }
.capthumbs { display: grid; grid-template-columns: repeat(auto-fill, minmax(11rem, 1fr)); gap: .75rem; margin: .75rem 0; }
.capthumb { border: 1px solid var(--line); border-radius: .4rem; padding: .4rem; }
.capthumb img { width: 100%; display: block; border-radius: .25rem; }
.capthumb .row { margin: .4rem 0 0; }
.importrow { border-top: 1px solid var(--line); padding: .6rem 0; }
.importrow:first-of-type { border-top: 0; }

View File

@@ -20,3 +20,22 @@ export function assemble({ css, js, payload }) {
</html>
`;
}
// The capture tool (issue #28): a separate page with no document, no payload and no
// way to read the main file. Built by build.js into capture.html.
export function assembleCapture({ css, js }) {
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Final Wishes: capture walkthroughs</title>
<style id="fw-css">${css}</style>
</head>
<body>
<main id="app"><noscript>This tool needs JavaScript enabled.</noscript></main>
<script id="fw-js">${js}<\/script>
</body>
</html>
`;
}

View File

@@ -2,7 +2,7 @@
// YYMMDD is the date, X the iteration that day (A first, B second, ...).
// Bump with `npm run bump` (see bump-version.js). build.js strips `export`.
export const APP_VERSION = '261124I';
export const APP_VERSION = '261127A';
const VERSION_RE = /^(\d{6})([A-Z])$/;
export const isVersion = (v) => typeof v === 'string' && VERSION_RE.test(v);