Compare commits

...

7 Commits

Author SHA1 Message Date
8d1e1846e6 Update OVERVIEW.md for the Masked print view (Refs #31)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-01 14:00:58 -05:00
90e8a3a850 Add Masked print view: secrets shown with every digit hidden
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-01 13:39:48 -05:00
4e2f343393 Add lawyer's summary print: records with lawyer-level fields only (Fixes #30)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-30 20:29:01 -05:00
eeba5d00db Add lawyer's view: a third field level and print mode (Fixes #29)
Fields and steps are Normal, Lawyer or Secret. Lawyer is stored as
secret: true plus lawyer: true, so older builds treat it as a plain secret.
Print offers masked, lawyer and complete views.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-30 20:15:47 -05:00
edb85d4f64 Regenerate null.html sanitized sample copy
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-30 19:14:59 -05:00
e4cfd0fd1c Refresh OVERVIEW.md: save fallback, HANDOFF.md, open issue #20
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-30 19:14:14 -05:00
673560a249 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>
2026-11-27 15:41:19 -05:00
19 changed files with 1618 additions and 105 deletions

View File

@@ -15,7 +15,7 @@ The owner keeps accounts, documents, contacts, wind-down steps and similar life-
| Crypto | WebCrypto: PBKDF2-SHA256 (600,000 iterations) into AES-256-GCM |
| Build | `build.js`: concatenates `src/*.js`, no bundler, no dependencies |
| Tests | `node --test` (built-in runner). Browser behavior was checked by hand with headless Chromium over CDP, which is not part of the repo. |
| Hosting / issues | Gitea (`gitea.ericthered.tech`), `gt` CLI. Issues #1–#19 track the work. |
| Hosting / issues | Gitea (`gitea.ericthered.tech`), `gt` CLI. Issues track the work (latest: #31). |
There are no npm dependencies and no CDN or network calls at runtime.
@@ -28,6 +28,8 @@ bump-version.js `npm run bump`, and the pre-commit hook's engine: advan
.githooks/pre-commit runs `bump-version.js --staged`; enable once per clone with `npm run hooks`
package.json scripts: build, seal, test
src/
capture.js capture-bundle format and merge destinations (pure)
capture-app.js the UI of the separate capture.html tool
crypto.js encrypt / decrypt / passphrase rules (blob format below)
model.js document schema, validate(), section/record/field/sequence kinds
ops.js pure edit helpers: add/move/remove, header, images, sequences, sub-tabs,
@@ -42,6 +44,8 @@ test/ one test file per src module, plus a build test
docs/
thumbdrive/README.txt executor's one-page instructions (copied to the drive)
PLAN.md original plan
HANDOFF.md notes on open issue #20 (save writes a 0-byte file) and the pending decision on download-by-default
null.html, null.withWorkflow.html committed sanitized sample copies (secrets erased via `sanitize.js`); null.withWorkflow.html includes a sample capture workflow
```
Git-ignored on purpose: `*.pdf`, `data/` (plaintext working copies with real secrets), `dist/`, `node_modules/`.
@@ -57,7 +61,7 @@ Git-ignored on purpose: `*.pdf`, `data/` (plaintext working copies with real sec
- `records` (records with labeled `fields`; a field is text or an image). It can optionally have sub-tabs: `subsections: [{id, title}]`, a `generalTitle` for the catch-all first tab (default "General"), and a `subsection` id on each record or sequence. No `subsection`, or one that matches no tab, means General.
- `steps` and `checklist` (ordered `items`)
A **visual sequence** (`kind: 'sequence'`, numbered `frames` of image + text with a layout of right / under / none) is an entry in the same ordered list as a section's records or items, or in a text section's `sequences` array. It is not a record or an item: no step number and no tick box. Ids are unique across the whole document. `secret` flags exist on fields and frames. Validation is `validate()` / `assertValid()`; the save path refuses an invalid document.
A **visual sequence** (`kind: 'sequence'`, numbered `frames` of image + text with a layout of right / under / none) is an entry in the same ordered list as a section's records or items, or in a text section's `sequences` array. It is not a record or an item: no step number and no tick box. Ids are unique across the whole document. `secret` flags exist on fields and frames; a `lawyer` flag (valid only with `secret: true`) makes a third level (see Print). Validation is `validate()` / `assertValid()`; the save path refuses an invalid document.
**UI** (`src/app.js`, a single IIFE): state lives in one `state` object (including `collapsed`, the folded record ids). Edits mutate `state.doc` in place and then call `markDirty()` or `changed(record)` (which also stamps `updated` and `meta.lastUpdated`). `render()` rebuilds the page. `changed` clears `state.status`, so set the status afterwards.
- **Editing and Cancel:** edit mode is global. **Cancel** reverts the section (or the print header) on screen to a deep-copy baseline taken at open and at each save, then leaves edit mode.
@@ -69,13 +73,14 @@ A **visual sequence** (`kind: 'sequence'`, numbered `frames` of image + text wit
- **Credential references (issue #24):** a frame's `uses: [{record, field}]` points at record fields by id. A field gets an `id` the first time it is referenced (`ensureFieldId`, `addUse`, `findFieldRef`, `allRecordsIn` in `ops.js`). A dangling reference is shown as removed, never a validation error. `viewUses` and `copyValue` (30 s clipboard wipe) are in `app.js`; `usesView` in `print.js` does the masked/included print text.
- **Annotation (issue #25):** a frame's `marks` are `{type:'marker',x,y}` or `{type:'box',x,y,w,h}` as fractions of the picture (`isMark`, `normRect` in `images.js`). `markedImage()` in `app.js` wraps a step's `<img>` in a `.marked` box and lays CSS overlays over it, so the same marks work in the list, player, lightbox and print. `openAnnotator()` is a canvas dialog; Blur out runs `pixelateRegion()` (pure, in `images.js`) on the pixels and `Apply` re-encodes the picture, so no unblurred copy is stored. Marks are dropped when the picture is replaced, removed or erased by `clearSecrets`.
- **Search (issue #27):** `src/search.js` has the pure `searchRanges()` (case-insensitive, plain text) and `stepSearchIndex()`. In `app.js` a toolbar **Search** button sets `state.searchOpen`, which swaps the toolbar's buttons for the search controls (same row); Cancel swaps them back. The controls are a persistent element re-attached on every `render()` (so the typed text and focus survive). `findAllHits()` builds a hidden copy of every section with `state.searchAll` set (all sub-tabs, nothing folded) using the normal view functions, then counts matches per entry (`data-eid` on record/item/sequence elements). `stepSearch()` navigates (section, sub-tab, unfold, `state.walk = null`); `highlightSearch()` runs at the end of `render()` and wraps the matches in `<mark class="hit">`. Text under `SEARCH_SKIP` (buttons, inputs, `.secret`, `.nosearch`) is never searched, so secrets stay out. New view-mode furniture such as dates and badges needs the `nosearch` class or it will be counted.
- **Capture online, merge offline (issue #28):** `build.js` also writes `capture.html` (modules `crypto, images, capture, version` + `src/capture-app.js`, no document, no payload, no storage). It captures walkthroughs and exports an encrypted bundle: `src/capture.js` (`sealBundle`, `openBundle`, `validateBundle`, `destinations`), the blob uses magic `"FC"` 0x01 via the `magic` argument of `encrypt`/`decrypt`, so bundles and documents can't be confused. The main app's **Import captures…** (`importCaptures()` in `app.js`) opens a bundle, lets the user choose a destination per walkthrough, and `importWalkthrough()` in `ops.js` adds each as a sequence. Nothing is written until Save; the bundle file is never modified. Annotation happens after import.
- **Reset (`?reset=1`):** opening the file with `?reset=1` or `#reset=1` shows a banner after unlock offering to erase every secret-flagged field value and secret frame (`clearSecrets()` in `ops.js`, count from `countSecrets`). Labels, structure and flags stay. It is read live (`resetRequested()`), with a `hashchange` listener to re-offer, and `state.resetOffered` dismisses it. Nothing is written until Save, so make a Backup copy first. It's meant for working on layout on a less safe machine.
**Save.** Uses the File System Access API (`showSaveFilePicker`, handle reused) where available, otherwise a Blob download. `assemble()` rebuilds the full HTML from the page's own CSS and JS plus a fresh encrypted payload. "Backup copy" downloads `final-wishes-YYYYMMDD.html`.
**Save.** Uses the File System Access API (`showSaveFilePicker`, handle reused) where available, otherwise a Blob download. `assemble()` rebuilds the full HTML from the page's own CSS and JS plus a fresh encrypted payload. If the write throws `NotAllowedError`/`SecurityError` (Chrome creates an empty file, then refuses the write; seen on a COSMIC/Wayland desktop with portal dialogs, issue #20), `save()` drops the handle and downloads `final-wishes.html` instead, with an explanatory status. "Backup copy" downloads `final-wishes-YYYYMMDD.html`.
**Upgrading app code, keeping data.** A file runs the code it was saved with. On the start screen, "Open your existing Final Wishes file" extracts the `#payload` from an older `.html`, unlocks it with the passphrase, and Save then writes it out with the newer code.
**Print.** Built only when Print is chosen and cleared on `afterprint`, so secrets don't linger in the DOM. It is a `<table>` whose `<thead>` holds the running header, which the browser repeats at the top of every page. Each section starts a new page (a section with sub-tabs gets a sub-heading per non-empty tab), records and sequence steps avoid page breaks inside them, and checklist items have tick boxes. The print dialog offers "withhold secrets" (default) or "include secrets". Images are decoded before `window.print()`.
**Print.** Built only when Print is chosen and cleared on `afterprint`, so secrets don't linger in the DOM. It is a `<table>` whose `<thead>` holds the running header, which the browser repeats at the top of every page. Each section starts a new page (a section with sub-tabs gets a sub-heading per non-empty tab), records and sequence steps avoid page breaks inside them, and checklist items have tick boxes. The print dialog offers five views (issues #29, #30, #31): "withhold secrets" (default, mode `masked`), "lawyer's view" (`lawyer`: shows secrets flagged `lawyer: true`, still withholds plain secrets), "lawyer's summary" (`summary`, issue #30: `summaryGroups()` in `print.js` lists only records with lawyer-level text fields, each with just those fields, built by `printSummary()` in `app.js`) "Masked" (`obscured`, issue #31: like complete, but `maskDigits()` in `print.js` turns every digit in a secret value, and in a secret frame's text and if-stuck note, into a bullet; secret images and secret frames with a picture are withheld, because a picture can't be masked) and "include secrets" (`complete`). Note the naming trap: the UI label "Masked" is mode `obscured`, because `masked` already meant withhold. `isHidden()`, `displayValue()`, `frameView()` and `usesView()` in `print.js` take the mode (a boolean still works: true is complete); `levelOf()`/`setLevel()` in `ops.js` keep the flags canonical and the edit UI uses a Normal/Lawyer/Secret select. Older builds read a lawyer-level item as a plain secret, which fails closed. `countByLevel()` feeds the dialog counts; `?reset=1` still erases lawyer-level values. Images are decoded before `window.print()`.
## Integrations
@@ -111,5 +116,5 @@ No database. The document is a JSON object, encrypted and embedded in the HTML f
- **Blob size:** images are embedded in the encrypted payload and make the file bigger and saves slower.
- **Skipped test:** one test in `test/model.test.js` is skipped unless the gitignored `data/seed.json` exists.
- **Browser coverage:** features were verified in headless Chromium only; Firefox and Safari drop and paste are untested.
- **Open work:** issue #8 (security clean-up) remains open. It is the owner's own tasks: rotating exposed secrets, refreshing stale data and keeping a second encrypted copy.
- **Open work:** issue #20 (in-place save refused by Chrome on one machine; see `HANDOFF.md`) is open, with a pending choice to make download the default save. Issue #8 (security clean-up) remains open. It is the owner's own tasks: rotating exposed secrets, refreshing stale data and keeping a second encrypted copy.
- **Git history:** commit `9fa6096` contains a PIN that matched a real one from the source material. It was removed from the code in `7a81637` but not from history, so treat it as exposed.

View File

@@ -26,7 +26,7 @@ The passphrase is prompted for (hidden) or read from `FW_PASSPHRASE`.
- `src/version.js` the version shown at the top (`Ver YYMMDDX`); `npm run bump` advances it by hand;
a pre-commit hook (`npm run hooks` once per clone) does it on every commit
that changes the app
- `src/print.js` print helpers (secret masking, header layout)
- `src/print.js` print helpers (secret masking in three views, header layout)
- `src/app.js` + `src/style.css` the UI, including the Print header panel
- `src/template.js` the HTML skeleton shared by `build.js` and in-page Save
- `docs/thumbdrive/` what goes on the drive alongside the HTML file
@@ -135,7 +135,7 @@ Standard, Online and Credit Union. Other kinds of section don't have them.
## Images
Any record can hold pictures (scans of documents, photos of a safe's
contents, a screenshot of where to click). They are another kind of field, so
they have a label, a **secret** checkbox, reorder arrows and a delete button
they have a label, a **Normal / Lawyer / Secret** choice, reorder arrows and a delete button
like any other field. In **Edit** mode, add one of three ways:
- **+ Add image...** in the record, then choose one or more files.
@@ -193,6 +193,20 @@ not part of a record or item, so it sits exactly where you put it.
Edit). Account numbers and balances in a screenshot are real data: mark the
step **secret**, or capture a screen before they appear. Works in Chrome,
Edge and Firefox opened from a file. Pasting a screenshot still works too.
- **Capture online, merge offline (issue #28):** capturing inside this file
means the unlocked document is open in a browser that is logged in to a
bank. Instead, `npm run build` also writes **`capture.html`** next to the
main file. It holds no document and no passwords. Open it while online,
**+ New walkthrough**, name it, **Share screen…**, **Capture step** for each
screen, and repeat for as many walkthroughs as you like. **Export bundle…**
asks for a passphrase (the pictures can show account numbers) and downloads
one encrypted `.fwcapture` file. Nothing is kept in the browser, so export
before closing the page. Later, offline, open your Final Wishes file and
choose **Import captures…**: pick the bundle, enter its passphrase, and for
each walkthrough tick it, rename it and choose the section (or sub-tab) it
goes in. Then **Save**, and delete the bundle file. The bundle is never
changed, so walkthroughs you skip can be imported from it later. Add the
step text, marks, blur and secret flags after importing.
- **If it looks different or fails:** each step has an optional note for what
to do when the screen is not what the picture shows (who to call, what to
say). Tick **Stop here** to tell the reader not to go further without help.
@@ -281,8 +295,18 @@ Documents made by older versions keep working: anything a newer version added
LastPass master password.
## Printing
**Print...** offers "Withhold secrets" (safe overview) and "Include
secrets" (full copy). Print on Letter paper with the browser's own
**Print...** offers "Withhold secrets" (safe overview), "Lawyer's view",
"Lawyer's summary" and "Include secrets" (full copy). Every field and step has a level in Edit mode:
**Normal** (always printed), **Lawyer** or **Secret**. Lawyer and Secret values
are both hidden on screen until **Show**. For a bank account, say, the name is
Normal, the account number Lawyer and the balance Secret: the overview prints
only the name, the lawyer's view adds the account number, and the full copy
prints all three. The **lawyer's summary** is a short list instead of a full copy: only the
records that have at least one Lawyer-level field, each with just its Lawyer
fields (so the account and its number, nothing else), in clear text. Text
sections, steps, walkthroughs, notes and Normal or Secret fields are left out.
Lawyer-level image fields are not listed. Both lawyer copies are still
sensitive, so store them too. Print on Letter paper with the browser's own
"Headers and footers" turned off (that is separate from the document header
below). A full copy is as sensitive as the passwords on it: store it in the
fire safe and shred superseded copies. Page layout was checked by rendering

View File

@@ -9,7 +9,7 @@
import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join, resolve } from 'node:path';
import { assemble } from './src/template.js';
import { assemble, assembleCapture } from './src/template.js';
import { encrypt, passphraseProblem } from './src/crypto.js';
import { assertValid } from './src/model.js';
@@ -17,11 +17,17 @@ const root = dirname(fileURLToPath(import.meta.url));
const read = (p) => readFileSync(join(root, 'src', p), 'utf8');
// Modules are concatenated (ES `import` lines and `export` keywords dropped) ahead of app.js into one scope.
const MODULES = ['crypto.js', 'images.js', 'model.js', 'ops.js', 'print.js', 'search.js', 'template.js', 'version.js'];
const MODULES = ['crypto.js', 'images.js', 'model.js', 'ops.js', 'capture.js', 'print.js', 'search.js', 'template.js', 'version.js'];
export function bundleJs() {
return MODULES.map((f) => read(f).replace(/^import .*$/gm, '').replace(/^export /gm, '')).concat(read('app.js')).join('\n');
}
// The separate online capture tool: only the modules it needs, and no document data.
const CAPTURE_MODULES = ['crypto.js', 'images.js', 'capture.js', 'version.js'];
export function captureJs() {
return CAPTURE_MODULES.map((f) => read(f).replace(/^import .*$/gm, '').replace(/^export /gm, '')).concat(read('capture-app.js')).join('\n');
}
function parseArgs(argv) {
const a = {};
for (let i = 0; i < argv.length; i++) {
@@ -75,6 +81,10 @@ async function main() {
const out = resolve(args.out || join(root, 'dist', 'final-wishes.html'));
mkdirSync(dirname(out), { recursive: true });
writeFileSync(out, html);
const capOut = join(dirname(out), 'capture.html');
const cap = assembleCapture({ css: read('style.css'), js: captureJs() });
writeFileSync(capOut, cap);
console.log(`Wrote ${capOut} (${cap.length} bytes, capture tool, no document)`);
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.`);
}

View File

@@ -22,6 +22,10 @@ You do not need internet access, and nothing you do here is sent anywhere.
TO PRINT IT
Click "Print..." at the top, then choose:
- "Withhold secrets": a safe overview with no passwords or PINs.
- "Lawyer's view": adds the details a lawyer needs (such as account
numbers) but still withholds the most private secrets.
- "Lawyer's summary": a short list of accounts and account numbers only,
with everything else left out.
- "Include secrets": the full copy. Keep it locked away and shred it
when you are finished.
In the browser's print window, set Paper size to Letter and turn OFF

860
null.html

File diff suppressed because one or more lines are too long

View File

@@ -583,22 +583,28 @@
return zone;
}
// Normal / Lawyer / Secret chooser for a field or step (replaces the old "secret" checkbox).
const LEVELS = [['normal', 'Normal'], ['lawyer', 'Lawyer'], ['secret', 'Secret']];
function levelSelect(x, label, onChange) {
const sel = h('select', { 'aria-label': label, onchange: () => { setLevel(x, sel.value); onChange(); } },
LEVELS.map(([v, t]) => h('option', { value: v, selected: levelOf(x) === v }, t)));
return h('label', { class: 'check' }, sel);
}
function editImageField(r, f, i) {
const secret = h('input', { type: 'checkbox', checked: !!f.secret, 'aria-label': 'Secret',
onchange: () => { f.secret = secret.checked || undefined; if (!f.secret) delete f.secret; changed(r); } });
const secret = levelSelect(f, 'Visibility of ' + (f.label || 'image field'), () => changed(r));
const zone = imageZone(f, 'value', f.label, { 'data-field': String(i) }, (files) => importFiles(r, files, { replace: f }), () => changed(r));
return h('div', { class: 'field imagefield' },
h('div', { class: 'row' }, input(f, 'label', { label: 'Field label' }, r), h('label', { class: 'check' }, secret, ' secret'), rowTools(r.fields, i, 'image field', r)),
h('div', { class: 'row' }, input(f, 'label', { label: 'Field label' }, r), secret, rowTools(r.fields, i, 'image field', r)),
zone);
}
function editField(r, f, i) {
if (f.kind === 'image') return editImageField(r, f, i);
const secret = h('input', { type: 'checkbox', checked: !!f.secret, 'aria-label': 'Secret',
onchange: () => { f.secret = secret.checked || undefined; if (!f.secret) delete f.secret; changed(r); } });
const secret = levelSelect(f, 'Visibility of ' + (f.label || 'field'), () => changed(r));
return h('div', { class: 'row field' },
input(f, 'label', { label: 'Field label' }, r), input(f, 'value', { label: 'Field value' }, r),
h('label', { class: 'check' }, secret, ' secret'), rowTools(r.fields, i, 'field', r));
secret, rowTools(r.fields, i, 'field', r));
}
// "Sub-tab: [select]" for a record or sequence; changing it moves the entry to that tab.
@@ -684,14 +690,13 @@
}
function editFrame(q, f, k) {
const secret = h('input', { type: 'checkbox', checked: !!f.secret, 'aria-label': 'Secret step',
onchange: () => { f.secret = secret.checked || undefined; if (!f.secret) delete f.secret; changed(q); } });
const secret = levelSelect(f, 'Visibility of step ' + (k + 1), () => changed(q));
const stop = h('input', { type: 'checkbox', checked: !!f.stop, 'aria-label': 'Stop here, step ' + (k + 1),
onchange: () => { f.stop = stop.checked || undefined; if (!f.stop) delete f.stop; changed(q); } });
const layout = h('select', { 'aria-label': 'Text position for step ' + (k + 1), onchange: () => { f.layout = layout.value; changed(q); render(); } },
LAYOUT_LABELS.map(([v, t]) => h('option', { value: v, selected: f.layout === v }, t)));
return h('div', { class: 'field imagefield frameedit' },
h('div', { class: 'row' }, h('strong', {}, 'Step ' + (k + 1)), layout, h('label', { class: 'check' }, secret, ' secret'), rowTools(q.frames, k, 'step', q)),
h('div', { class: 'row' }, h('strong', {}, 'Step ' + (k + 1)), layout, secret, rowTools(q.frames, k, 'step', q)),
imageZone(f, 'image', q.title + ', step ' + (k + 1), { 'data-frame': String(k) },
(files) => importFiles(q, files, { key: 'image', replace: f, add: addFrameFrom(q) }), () => { if (!f.image) delete f.marks; changed(q); }),
f.image ? h('div', { class: 'row' }, btn('Mark up picture\u2026', () => openAnnotator(q, f), 'small', { 'aria-label': 'Mark up the picture for step ' + (k + 1) }),
@@ -789,67 +794,91 @@
const box = (status) => h('span', { class: 'cb ' + status, 'aria-hidden': 'true' }, status === 'done' ? '✓' : '');
// Text, or the picture itself for a visible image field.
function printCell(f, includeSecrets) {
if (f.kind === 'image' && f.value && (!f.secret || includeSecrets)) return h('img', { class: 'pimg', src: f.value, alt: f.label });
return displayValue(f, includeSecrets);
function printCell(f, mode) {
if (f.kind === 'image' && f.value && !isHidden(f, mode)) return h('img', { class: 'pimg', src: f.value, alt: f.label });
return displayValue(f, mode);
}
function printFrame(f, k, includeSecrets) {
const v = frameView(f, includeSecrets);
function printFrame(f, k, mode) {
const v = frameView(f, mode);
return h('div', { class: 'pframe ' + v.layout },
h('div', { class: 'pfnum' }, 'Step ' + (k + 1)),
v.withheld ? h('p', { class: 'psecret' }, '[withheld]')
: v.image ? markedImage(h('img', { class: 'pimg', src: v.image, alt: 'Step ' + (k + 1) }), f.marks)
: h('p', {}, '(no image)'),
v.layout !== 'none' ? h('p', { class: 'pftext' }, v.text) : null,
v.withheld ? null : usesView(state.doc, f, includeSecrets).map((u) => h('p', { class: 'pftext' },
v.withheld ? null : usesView(state.doc, f, mode).map((u) => h('p', { class: 'pftext' },
u.missing ? '(a credential this step used has been removed)' : 'You will need: ' + u.record + ' \u203A ' + u.label + ': ' + u.value)),
v.stop ? h('p', { class: 'pstop' }, h('strong', {}, 'STOP HERE. Do not go further.')) : null,
v.ifStuck ? h('p', { class: 'pftext' }, h('strong', {}, 'If it looks different or fails: '), v.ifStuck) : null);
}
function printSequence(q, includeSecrets) {
function printSequence(q, mode) {
return h('div', { class: 'pseq' },
h('h3', {}, q.title),
q.captured ? h('p', { class: 'pftext' }, 'Captured ' + q.captured + '. The site may have changed since.') : null,
q.frames.map((f, k) => printFrame(f, k, includeSecrets)));
q.frames.map((f, k) => printFrame(f, k, mode)));
}
function printRecord(r, includeSecrets) {
function printRecord(r, mode) {
return h('div', { class: 'prec' + (r.status === 'tbd' ? ' tbd' : '') },
h('h3', {}, r.title, r.status === 'tbd' ? h('span', { class: 'ptag' }, 'TBD') : null),
r.fields.length ? h('table', {}, h('tbody', {}, r.fields.map((f) => h('tr', {},
h('th', {}, f.label), h('td', { class: f.secret ? 'psecret' : '' }, printCell(f, includeSecrets)))))) : null,
h('th', {}, f.label), h('td', { class: f.secret ? 'psecret' : '' }, printCell(f, mode)))))) : null,
r.notes ? h('p', { class: 'pnotes' }, r.notes) : null);
}
// The lawyer's summary: just the records with lawyer-level fields, as one compact list.
function printSummary(doc) {
const groups = summaryGroups(doc);
const list = groups.length ? groups.map((s) => h('section', { class: 'psumsec' },
h('h2', {}, s.section),
s.groups.map((g) => [g.title == null ? null : h('h3', { class: 'psubhead' }, g.title),
g.records.map((r) => h('div', { class: 'prec' }, h('h3', {}, r.title),
h('table', {}, h('tbody', {}, r.fields.map((f) => h('tr', {}, h('th', {}, f.label), h('td', { class: 'psecret' }, f.value || '(not set)')))))))])))
: h('p', {}, 'Nothing to list: no record has a lawyer-level field.');
printRoot.replaceChildren(h('table', { class: 'ptable' },
h('thead', {}, h('tr', {}, h('td', {}, headerEl(doc)))),
h('tbody', {}, h('tr', {}, h('td', {},
h('section', { class: 'pcover psumcover' },
h('h1', {}, (doc.meta.title || 'Final Wishes') + ": lawyer's summary"),
doc.meta.owner ? h('p', { class: 'powner' }, 'Prepared by ' + doc.meta.owner) : null,
h('p', {}, 'Last update: ' + doc.meta.lastUpdated),
h('p', { class: 'pnote warn' }, "This is the LAWYER'S SUMMARY. It lists only the accounts and details a lawyer needs, in clear text. Keep it locked away.")),
list)))));
}
function printItem(it, numbered) {
return h('li', { class: 'pitem ' + it.status },
box(it.status), h('strong', {}, it.text), it.status === 'tbd' ? h('span', { class: 'ptag' }, 'TBD') : null,
it.detail ? h('p', { class: 'pnotes' }, it.detail) : null);
}
function buildPrintDoc(includeSecrets) {
function buildPrintDoc(rawMode) {
const mode = normalizeMode(rawMode);
if (mode === 'summary') return printSummary(state.doc);
const doc = state.doc;
const kept = includeSecrets ? 'This copy INCLUDES passwords, PINs and other secrets. Keep it locked away (fire safe or sealed envelope).'
const kept = mode === 'complete' ? 'This copy INCLUDES passwords, PINs and other secrets. Keep it locked away (fire safe or sealed envelope).'
: mode === 'obscured' ? 'This is the MASKED copy. Secrets are shown, but every digit in them is replaced by \u2022. Pictures marked secret are withheld. Keep it locked away.'
: mode === 'lawyer' ? "This is the LAWYER'S VIEW. It includes account numbers and other details a lawyer needs, but the most private secrets (passwords, PINs, balances) are WITHHELD. Keep it locked away."
: 'Secrets (passwords, PINs, security answers) are WITHHELD from this copy. They are stored in the encrypted file.';
const content = [
h('section', { class: 'pcover' },
h('h1', {}, doc.meta.title || 'Final Wishes'),
doc.meta.owner ? h('p', { class: 'powner' }, 'Prepared by ' + doc.meta.owner) : null,
h('p', {}, 'Last update: ' + doc.meta.lastUpdated),
h('p', { class: 'pnote' + (includeSecrets ? ' warn' : '') }, kept),
h('p', { class: 'pnote' + (mode !== 'masked' ? ' warn' : '') }, kept),
h('p', {}, 'Items marked TBD are not yet filled in. A box beside an instruction is for ticking it off as it is done.'),
h('h2', {}, 'Contents'),
h('ol', { class: 'ptoc' }, doc.sections.map((s) => h('li', {}, s.title)))),
doc.sections.map((s) => h('section', { class: 'psec' },
h('h2', {}, s.title),
s.intro ? h('p', { class: 'pintro' }, s.intro) : null,
s.kind === 'text' ? [h('p', { class: 'pbody' }, s.body), (s.sequences || []).map((q) => printSequence(q, includeSecrets))] : null,
s.kind === 'text' ? [h('p', { class: 'pbody' }, s.body), (s.sequences || []).map((q) => printSequence(q, mode))] : null,
s.kind === 'records' ? printGroups(s).map((g) => [g.title == null ? null : h('h3', { class: 'psubhead' }, g.title),
g.entries.map((r) => (isSequence(r) ? printSequence(r, includeSecrets) : printRecord(r, includeSecrets)))]) : null,
s.kind === 'steps' ? h('ol', { class: 'pitems' }, s.items.map((i) => (isSequence(i) ? h('li', { class: 'pseqitem' }, printSequence(i, includeSecrets)) : printItem(i)))) : null,
s.kind === 'checklist' ? h('ul', { class: 'pitems' }, s.items.map((i) => (isSequence(i) ? h('li', { class: 'pseqitem' }, printSequence(i, includeSecrets)) : printItem(i)))) : null)),
g.entries.map((r) => (isSequence(r) ? printSequence(r, mode) : printRecord(r, mode)))]) : null,
s.kind === 'steps' ? h('ol', { class: 'pitems' }, s.items.map((i) => (isSequence(i) ? h('li', { class: 'pseqitem' }, printSequence(i, mode)) : printItem(i)))) : null,
s.kind === 'checklist' ? h('ul', { class: 'pitems' }, s.items.map((i) => (isSequence(i) ? h('li', { class: 'pseqitem' }, printSequence(i, mode)) : printItem(i)))) : null)),
].flat();
// The header sits in <thead> so the browser repeats it, in flow, at the top of every page.
printRoot.replaceChildren(h('table', { class: 'ptable' },
@@ -859,18 +888,23 @@
window.addEventListener('afterprint', () => printRoot.replaceChildren()); // don't leave secrets lingering in the DOM
function openPrintDialog() {
const n = countSecrets(state.doc);
const n = countByLevel(state.doc);
const sum = summaryCounts(state.doc);
const plural = (c) => c + ' secret value' + (c === 1 ? '' : 's');
const radio = (value, checked, text) => h('label', { class: 'radio' }, h('input', { type: 'radio', name: 'mode', value, checked }), ' ' + text);
const dlg = h('dialog', { class: 'card', 'aria-label': 'Print options' },
h('h3', {}, 'Print'),
radio('mask', true, 'Withhold secrets (safe overview; ' + n + ' secret value' + (n === 1 ? '' : 's') + ' hidden)'),
radio('include', false, 'Include secrets (full copy: store it securely)'),
radio('masked', true, 'Withhold secrets (safe overview; ' + plural(n.lawyer + n.secret) + ' hidden)'),
radio('lawyer', false, "Lawyer's view (shows " + n.lawyer + ' lawyer-level value' + (n.lawyer === 1 ? '' : 's') + '; ' + plural(n.secret) + ' hidden)'),
radio('summary', false, "Lawyer's summary (a short list of " + sum.records + ' record' + (sum.records === 1 ? '' : 's') + ' with lawyer-level values, ' + sum.values + ' value' + (sum.values === 1 ? '' : 's') + ')'),
radio('obscured', false, 'Masked (shows ' + plural(n.lawyer + n.secret) + ' with every number hidden)'),
radio('complete', false, 'Include secrets (full copy: store it securely)'),
h('div', { class: 'row' },
btn('Cancel', () => { dlg.close(); dlg.remove(); }),
btn('Print', async () => {
const include = dlg.querySelector('input[name=mode]:checked').value === 'include';
const chosen = dlg.querySelector('input[name=mode]:checked').value;
dlg.close(); dlg.remove();
buildPrintDoc(include);
buildPrintDoc(chosen);
// Pictures must be decoded before the browser lays out the pages.
await Promise.all([...printRoot.querySelectorAll('img')].map((img) => img.decode().catch(() => {})));
window.print();
@@ -915,6 +949,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 +1132,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

@@ -24,12 +24,16 @@ import { isImageDataUrl, MAX_IMAGE_DATA_CHARS, isMark } from './images.js';
//
// Record: { id, title, status: 'ok'|'tbd', updated: 'YYYY-MM-DD',
// fields: [Field], notes?: string }
// Field: { label, value, secret?: boolean, kind?: 'text'|'image' } (kind defaults to text)
// Field: { label, value, secret?: boolean, lawyer?: boolean, kind?: 'text'|'image' } (kind defaults to text)
// Three levels: normal (no flags), lawyer (`secret: true, lawyer: true`: masked on screen and
// in the masked print, shown in the lawyer's view) and secret (`secret: true`: shown only in
// the complete print). `lawyer` is only valid together with `secret: true`, so an older
// build that ignores it still treats the item as a secret.
// An image field's value is a PNG/JPEG data URL, or '' when no image is set yet.
// Item: { id, text, status: 'open'|'done'|'tbd', detail?: string }
// Sequence (visual sequence): { id, kind: 'sequence', title, updated: 'YYYY-MM-DD',
// frames: [Frame] } -- a numbered series of pictures with optional text.
// Frame: { image: PNG/JPEG data URL or '', text, layout: 'right'|'under'|'none', secret?: boolean,
// Frame: { image: PNG/JPEG data URL or '', text, layout: 'right'|'under'|'none', secret?: boolean, lawyer?: boolean,
// ifStuck?: string, what to do if the screen looks different or the step fails
// stop?: boolean, "stop here and call someone" marker; ifStuck says who/why
// marks?: [Mark] overlay on the picture: { type:'marker', x, y } or
@@ -182,6 +186,7 @@ export function validate(doc) {
if (!isStr(f.label) || !f.label) errs.push(`${fw}: missing label`);
if (!isStr(f.value)) errs.push(`${fw}: value must be a string`);
if (f.secret !== undefined && typeof f.secret !== 'boolean') errs.push(`${fw}: secret must be a boolean`);
checkLawyer(f, fw);
if (f.id !== undefined) {
if (!isStr(f.id) || !f.id) errs.push(`${fw}: id must be a non-empty string`);
else if (fieldIds.has(f.id)) errs.push(`${fw}: duplicate field id "${f.id}"`);
@@ -194,6 +199,12 @@ export function validate(doc) {
});
}
function checkLawyer(f, fw) {
if (f.lawyer === undefined) return;
if (typeof f.lawyer !== 'boolean') errs.push(`${fw}: lawyer must be a boolean`);
else if (f.lawyer && f.secret !== true) errs.push(`${fw}: lawyer needs secret: true`);
}
function checkSequence(q, where) {
if (!isObj(q)) return errs.push(`${where}: must be an object`);
checkId(q.id, where);
@@ -210,6 +221,7 @@ export function validate(doc) {
if (!isStr(f.text)) errs.push(`${fw}: text must be a string`);
if (!FRAME_LAYOUTS.includes(f.layout)) errs.push(`${fw}: bad layout "${f.layout}"`);
if (f.secret !== undefined && typeof f.secret !== 'boolean') errs.push(`${fw}: secret must be a boolean`);
checkLawyer(f, fw);
if (f.ifStuck !== undefined && !isStr(f.ifStuck)) errs.push(`${fw}: ifStuck must be a string`);
if (f.stop !== undefined && typeof f.stop !== 'boolean') errs.push(`${fw}: stop must be a boolean`);
if (f.marks !== undefined) {

View File

@@ -180,6 +180,19 @@ export function allSequences(doc) {
return out;
}
// The level of a field or frame: 'normal', 'lawyer' or 'secret' (see model.js).
export function levelOf(x) {
return !x.secret ? 'normal' : x.lawyer ? 'lawyer' : 'secret';
}
// Set the level, keeping the flags canonical: lawyer is stored only with secret: true,
// and an item with no flag has no keys at all.
export function setLevel(x, level) {
if (level === 'normal') { delete x.secret; delete x.lawyer; }
else if (level === 'lawyer') { x.secret = true; x.lawyer = true; }
else { x.secret = true; delete x.lawyer; }
}
// Erase the content of every secret field and secret frame (labels, structure
// and the secret flags stay). Returns how many values were erased.
export function clearSecrets(doc) {
@@ -262,6 +275,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

@@ -1,18 +1,44 @@
import { defaultHeaderFields, isSequence } from './model.js';
import { printGroups } from './ops.js';
// Pure helpers for the printed document. No DOM; tested in Node.
// build.js strips `export` when bundling.
// Print views: 'masked' (no secrets), 'lawyer' (lawyer-level secrets shown, the
// rest withheld) and 'complete' (everything). A boolean is accepted for older
// callers: true is 'complete', false is 'masked'. 'summary' is the lawyer's summary:
// it shows lawyer-level values like 'lawyer' does, but lists only those records (see summaryGroups).
// 'obscured' is the "Masked" view: like 'complete', but every digit in a secret value is replaced
// by a bullet, so the shape of an answer shows without the number. Pictures can't be masked, so a
// secret image (or a secret frame with a picture) is withheld.
export const PRINT_MODES = ['masked', 'lawyer', 'complete', 'summary', 'obscured'];
export const maskDigits = (text) => String(text == null ? '' : text).replace(/\p{Nd}/gu, '\u2022');
export function normalizeMode(mode) {
if (mode === true) return 'complete';
return PRINT_MODES.includes(mode) ? mode : 'masked';
}
// Is this field or frame withheld in this view? Normal items never are. A secret
// with `lawyer: true` is shown in the lawyer and complete views; a plain secret
// only in the complete view.
export function isHidden(item, mode) {
if (!item.secret) return false;
const m = normalizeMode(mode);
if (m === 'obscured') return item.kind === 'image' || !!item.image;
return m === 'complete' ? false : m === 'masked' ? true : !item.lawyer;
}
// What to print for a field. Secrets are either shown or withheld; an empty
// secret is always "(not set)" so a blank is never mistaken for a hidden value.
export function displayValue(field, includeSecrets) {
export function displayValue(field, mode) {
if (field.kind === 'image') {
if (!field.value) return '(no image)';
return field.secret && !includeSecrets ? '[withheld]' : '[image]';
return isHidden(field, mode) ? '[withheld]' : '[image]';
}
if (field.secret) {
if (!field.value) return '(not set)';
return includeSecrets ? field.value : '[withheld]';
if (isHidden(field, mode)) return '[withheld]';
return normalizeMode(mode) === 'obscured' ? maskDigits(field.value) : field.value;
}
return field.value || '(blank)';
}
@@ -45,41 +71,75 @@ export function frameLayout(frame) {
// What to show for a frame. A secret frame (picture and text) is withheld
// unless secrets are included; a frame with nothing in it is never "withheld".
export function frameView(frame, includeSecrets) {
export function frameView(frame, mode) {
const hasContent = !!(frame.image || String(frame.text || '').trim() || String(frame.ifStuck || '').trim());
const withheld = !!frame.secret && !includeSecrets && hasContent;
const withheld = isHidden(frame, mode) && hasContent;
const m = frame.secret && normalizeMode(mode) === 'obscured' ? maskDigits : (x) => x;
return {
withheld,
image: withheld ? '' : frame.image,
text: withheld ? '' : frame.text,
ifStuck: withheld ? '' : String(frame.ifStuck || '').trim(),
text: withheld ? '' : m(frame.text),
ifStuck: withheld ? '' : m(String(frame.ifStuck || '').trim()),
stop: withheld ? false : !!frame.stop,
layout: withheld ? 'none' : frameLayout(frame),
};
}
// What a step's credential references show: [{ label, record, value, secret, missing }].
// A secret value is a placeholder unless includeSecrets; a reference that no longer
// A secret value is a placeholder unless the view shows it; a reference that no longer
// resolves is marked missing. Uses displayValue so masking matches the rest of print.
export function usesView(doc, frame, includeSecrets) {
export function usesView(doc, frame, mode) {
return (frame.uses || []).map((u) => {
const rec = doc.sections.flatMap((s) => (s.records || []).filter((r) => !isSequence(r))).find((r) => r.id === u.record);
const f = rec && rec.fields.find((x) => x.id === u.field && x.kind !== 'image');
return f ? { label: f.label, record: rec.title, value: displayValue(f, includeSecrets), secret: !!f.secret, missing: false }
return f ? { label: f.label, record: rec.title, value: displayValue(f, mode), secret: !!f.secret, missing: false }
: { label: '', record: '', value: '', secret: false, missing: true };
});
}
export function countSecrets(doc) {
let n = 0;
const frames = (q) => { for (const f of q.frames) if (f.secret && (f.image || String(f.text || '').trim() || String(f.ifStuck || '').trim())) n++; };
// How many filled-in secret values the document holds: { lawyer, secret } where
// `lawyer` counts lawyer-level ones and `secret` the plain ones. Empty ones don't count.
// What the lawyer's summary lists: [{ section, groups: [{ title, records: [{ title, fields }] }] }].
// A record qualifies if it has a lawyer-level text field (secret + lawyer); only those fields are
// listed. Image fields, plain secrets and normal fields never are. Sections and sub-tabs with
// no qualifying record are left out; order is the document's.
export function summaryGroups(doc) {
const lawyerFields = (r) => r.fields.filter((f) => f.secret && f.lawyer && f.kind !== 'image');
const out = [];
for (const s of doc.sections) {
if (s.kind !== 'records') continue;
const groups = printGroups(s)
.map((g) => ({ title: g.title, records: g.entries.filter((r) => !isSequence(r)).map((r) => ({ title: r.title, fields: lawyerFields(r) })).filter((r) => r.fields.length) }))
.filter((g) => g.records.length);
if (groups.length) out.push({ section: s.title, groups });
}
return out;
}
// { records, values } the lawyer's summary would list, for the print dialog.
export function summaryCounts(doc) {
let records = 0, values = 0;
for (const s of summaryGroups(doc)) for (const g of s.groups) for (const r of g.records) { records++; values += r.fields.length; }
return { records, values };
}
export function countByLevel(doc) {
const n = { lawyer: 0, secret: 0 };
const add = (x) => { n[x.lawyer ? 'lawyer' : 'secret']++; };
const frames = (q) => { for (const f of q.frames) if (f.secret && (f.image || String(f.text || '').trim() || String(f.ifStuck || '').trim())) add(f); };
for (const s of doc.sections) {
for (const r of s.records || []) {
if (isSequence(r)) frames(r);
else for (const f of r.fields) if (f.secret && f.value) n++;
else for (const f of r.fields) if (f.secret && f.value) add(f);
}
for (const it of s.items || []) if (isSequence(it)) frames(it);
for (const q of s.sequences || []) frames(q);
}
return n;
}
// Total filled-in secret values, of every level.
export function countSecrets(doc) {
const n = countByLevel(doc);
return n.lawyer + n.secret;
}

View File

@@ -100,6 +100,9 @@ dialog.lightbox { max-width: 92vw; max-height: 92vh; overflow: auto; } .bigimg {
.pnote { border: 1.5pt solid #000; padding: 8pt 10pt; font: 600 10.5pt system-ui, sans-serif; }
.pnote.warn { border-width: 3pt; }
.ptoc { columns: 2; padding-left: 1.2em; }
.pcover.psumcover { break-after: auto; }
.pcover.psumcover h1 { font-size: 20pt; margin: 0 0 .1in; }
.psumsec h2 { break-after: avoid; }
.psec { break-before: page; }
.psec:first-of-type { break-before: auto; }
h2 { font-size: 17pt; border-bottom: 1pt solid #000; padding-bottom: 3pt; margin: 0 0 10pt; break-after: avoid; }
@@ -126,3 +129,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 = '261201A';
const VERSION_RE = /^(\d{6})([A-Z])$/;
export const isVersion = (v) => typeof v === 'string' && VERSION_RE.test(v);

105
test/capture.test.js Normal file
View File

@@ -0,0 +1,105 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
import { mkdtempSync, readFileSync, existsSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { encrypt, decrypt, DecryptError } from '../src/crypto.js';
import { newWalkthrough, sealBundle, openBundle, validateBundle, destinations } from '../src/capture.js';
import { emptyDocument, validate } from '../src/model.js';
import { addSection, addSubsection, importWalkthrough } from '../src/ops.js';
const FAST = 1000;
const PNG = 'data:image/png;base64,iVBORw0KGgo=';
const walk = (title = 'Log in to Chase', n = 2) => ({ ...newWalkthrough(title, '2026-11-24'), frames: Array.from({ length: n }, () => ({ image: PNG })) });
test('bundle round trip keeps walkthroughs and drops empty ones', async () => {
const blob = await sealBundle([walk('A'), walk('Empty', 0), walk('B', 1)], 'bundle passphrase', FAST);
const b = await openBundle(blob, 'bundle passphrase');
assert.deepEqual(b.walkthroughs.map((w) => w.title), ['A', 'B']);
assert.equal(b.walkthroughs[0].frames[0].image, PNG);
assert.deepEqual(validateBundle(b), []);
});
test('wrong passphrase and tampering are rejected', async () => {
const blob = await sealBundle([walk()], 'right passphrase', FAST);
await assert.rejects(openBundle(blob, 'wrong passphrase'), DecryptError);
const bytes = Buffer.from(blob, 'base64');
bytes[bytes.length - 3] ^= 1;
await assert.rejects(openBundle(bytes.toString('base64'), 'right passphrase'), DecryptError);
const hdr = Buffer.from(blob, 'base64');
hdr[5] ^= 1; // iteration count is authenticated header data
await assert.rejects(openBundle(hdr.toString('base64'), 'right passphrase'), DecryptError);
});
test('a bundle and a document cannot be mistaken for each other', async () => {
const bundle = await sealBundle([walk()], 'same passphrase!', FAST);
await assert.rejects(decrypt(bundle, 'same passphrase!'), DecryptError);
const docBlob = await encrypt('{}', 'same passphrase!', FAST);
await assert.rejects(openBundle(docBlob, 'same passphrase!'), DecryptError);
});
test('validateBundle rejects bad contents', () => {
const good = { format: 'fw-capture', version: 1, created: '2026-11-24', walkthroughs: [walk()] };
assert.deepEqual(validateBundle(good), []);
assert.ok(validateBundle({ ...good, format: 'x' }).length);
assert.ok(validateBundle({ ...good, version: 2 }).length);
assert.ok(validateBundle({ ...good, walkthroughs: [{ ...walk(), frames: [{ image: 'http://evil/x.png' }] }] }).length);
assert.ok(validateBundle({ ...good, walkthroughs: [{ ...walk(), captured: 'yesterday' }] }).length);
assert.ok(validateBundle(null).length);
});
test('importWalkthrough adds a valid sequence with unique ids, in a tab if asked', () => {
const doc = emptyDocument('Me');
const banks = addSection(doc, 'records', 'Banks');
const tab = addSubsection(doc, banks, 'Checking');
const text = addSection(doc, 'text', 'Intro');
const steps = addSection(doc, 'steps', 'Steps');
const a = importWalkthrough(doc, banks, walk('Chase'), tab.id);
const b = importWalkthrough(doc, banks, walk('Schwab', 3));
const c = importWalkthrough(doc, text, walk('Text one'));
const d = importWalkthrough(doc, steps, walk(' ', 1));
assert.deepEqual(validate(doc), []);
assert.equal(a.subsection, tab.id);
assert.equal(b.subsection, undefined);
assert.equal(a.captured, '2026-11-24');
assert.equal(b.frames.length, 3);
assert.equal(d.title, 'Captured walkthrough');
assert.equal(new Set([a.id, b.id, c.id, d.id]).size, 4);
assert.deepEqual(text.sequences.map((q) => q.title), ['Text one']);
});
test('destinations lists every section and each sub-tab', () => {
const doc = emptyDocument('Me');
const banks = addSection(doc, 'records', 'Banks');
addSection(doc, 'steps', 'Steps');
const tab = addSubsection(doc, banks, 'Checking');
const d = destinations(doc);
assert.deepEqual(d.map((x) => x.label), ['Banks', 'Banks › Checking', 'Steps']);
assert.equal(d[1].tab, tab.id);
});
test('build writes capture.html: no document, no payload, no network, no app code', () => {
const dir = mkdtempSync(join(tmpdir(), 'fw-cap-'));
const out = join(dir, 'final-wishes.html');
const r = spawnSync('node', ['build.js', '--out', out], { encoding: 'utf8' });
assert.equal(r.status, 0, r.stderr);
const capPath = join(dir, 'capture.html');
assert.ok(existsSync(capPath));
const html = readFileSync(capPath, 'utf8');
assert.doesNotMatch(html, /id="payload"/);
assert.doesNotMatch(html, /https?:\/\/(?!www\.w3\.org)/);
assert.doesNotMatch(html, /localStorage|indexedDB|sessionStorage/);
assert.doesNotMatch(html, /assertValid|showSaveFilePicker|clearSecrets/); // nothing of the main app
assert.match(html, /sealBundle/);
});
test('both built pages have scripts that parse (no name clashes across the shared scope)', () => {
const dir = mkdtempSync(join(tmpdir(), 'fw-parse-'));
const r = spawnSync('node', ['build.js', '--out', join(dir, 'final-wishes.html')], { encoding: 'utf8' });
assert.equal(r.status, 0, r.stderr);
for (const f of ['final-wishes.html', 'capture.html']) {
const js = readFileSync(join(dir, f), 'utf8').match(/<script id="fw-js">([\s\S]*)<\/script>/)[1];
assert.doesNotThrow(() => new Function(js), f);
}
});

View File

@@ -170,3 +170,14 @@ test('sub-tabs: valid shapes pass, bad ones are reported', () => {
d = good(); d.sections[1].records[0].subsection = 'x';
assert.match(validate(d).join('\n'), /not one of this section's sub-tabs/);
});
test('lawyer must be a boolean and needs secret: true, on fields and frames', () => {
const withField = (f) => { const d = good(); d.sections[1].records[0].fields = [{ label: 'A', value: 'x', ...f }]; return d; };
assert.deepEqual(validate(withField({ secret: true, lawyer: true })), []);
assert.deepEqual(validate(withField({ secret: true, lawyer: false })), []);
assert.match(validate(withField({ lawyer: true })).join('\n'), /lawyer needs secret: true/);
assert.match(validate(withField({ secret: true, lawyer: 'yes' })).join('\n'), /lawyer must be a boolean/);
const withFrame = (fr) => { const d = good(); d.sections[0].sequences = [{ id: 'q1', kind: 'sequence', title: 'Q', updated: '2022-04-14', frames: [{ image: '', text: 't', layout: 'none', ...fr }] }]; return d; };
assert.deepEqual(validate(withFrame({ secret: true, lawyer: true })), []);
assert.match(validate(withFrame({ lawyer: true })).join('\n'), /lawyer needs secret: true/);
});

View File

@@ -405,3 +405,26 @@ test('validation: uses and field ids', async () => {
bad((x) => { x.records[0].fields[0].id = 'f1'; x.records[0].fields[1].id = 'f1'; }, /duplicate field id/);
bad((x) => { x.records[0].fields[0].id = ''; }, /id must be a non-empty string/);
});
test('levelOf and setLevel keep lawyer/secret flags canonical', async () => {
const { levelOf, setLevel } = await import('../src/ops.js');
const f = { label: 'a', value: 'x' };
assert.equal(levelOf(f), 'normal');
setLevel(f, 'lawyer');
assert.deepEqual(f, { label: 'a', value: 'x', secret: true, lawyer: true });
assert.equal(levelOf(f), 'lawyer');
setLevel(f, 'secret');
assert.deepEqual(f, { label: 'a', value: 'x', secret: true });
assert.equal(levelOf(f), 'secret');
setLevel(f, 'lawyer'); setLevel(f, 'normal');
assert.deepEqual(f, { label: 'a', value: 'x' }); // no stray keys
assert.equal(levelOf({ lawyer: true }), 'normal'); // lawyer alone is not a secret
});
test('clearSecrets erases lawyer-level values too', async () => {
const { clearSecrets } = await import('../src/ops.js');
const doc = { sections: [{ records: [{ fields: [{ label: 'n', value: '12345', secret: true, lawyer: true }, { label: 'o', value: 'open' }] }] }] };
assert.equal(clearSecrets(doc), 1);
assert.equal(doc.sections[0].records[0].fields[0].value, '');
assert.equal(doc.sections[0].records[0].fields[1].value, 'open');
});

View File

@@ -44,3 +44,130 @@ test('header with only unaligned fields, and empty text dropped', () => {
assert.deepEqual(headerLayout(doc), { left: '', middle: ['A', '2026-11-09'], right: '' });
assert.deepEqual(headerLayout(D({ fields: [] })), { left: '', middle: [], right: '' });
});
import { isHidden, normalizeMode, frameView, usesView, countByLevel } from '../src/print.js';
// The bank account example: name normal, account number lawyer, amount secret.
const acct = {
name: { label: 'Name', value: 'First Bank' },
num: { label: 'Account', value: '12345', secret: true, lawyer: true },
amt: { label: 'Amount', value: '$900', secret: true },
};
test('displayValue: masked, lawyer and complete views of the three levels', () => {
const view = (m) => [acct.name, acct.num, acct.amt].map((f) => displayValue(f, m));
assert.deepEqual(view('masked'), ['First Bank', '[withheld]', '[withheld]']);
assert.deepEqual(view('lawyer'), ['First Bank', '12345', '[withheld]']);
assert.deepEqual(view('complete'), ['First Bank', '12345', '$900']);
});
test('booleans still work as modes: true is complete, false is masked', () => {
assert.equal(normalizeMode(true), 'complete');
assert.equal(normalizeMode(false), 'masked');
assert.equal(normalizeMode(undefined), 'masked');
assert.equal(normalizeMode('bogus'), 'masked'); // unknown fails closed
assert.equal(displayValue(acct.amt, true), '$900');
assert.equal(displayValue(acct.num, false), '[withheld]');
});
test('isHidden: normal never hidden; lawyer hidden only when masked; secret hidden unless complete', () => {
assert.equal(isHidden(acct.name, 'masked'), false);
assert.deepEqual(['masked', 'lawyer', 'complete'].map((m) => isHidden(acct.num, m)), [true, false, false]);
assert.deepEqual(['masked', 'lawyer', 'complete'].map((m) => isHidden(acct.amt, m)), [true, true, false]);
});
test('a lawyer flag without secret does not reveal or hide anything', () => {
assert.equal(isHidden({ lawyer: true }, 'masked'), false);
});
test('empty lawyer-level and image fields behave like other secrets', () => {
assert.equal(displayValue({ label: 'n', value: '', secret: true, lawyer: true }, 'masked'), '(not set)');
const img = { label: 'card', kind: 'image', value: 'data:image/png;base64,AAAA', secret: true, lawyer: true };
assert.deepEqual(['masked', 'lawyer', 'complete'].map((m) => displayValue(img, m)), ['[withheld]', '[image]', '[image]']);
});
test('frameView withholds a lawyer-level step only in the masked view', () => {
const fr = { image: '', text: 'Log in', layout: 'under', secret: true, lawyer: true };
assert.equal(frameView(fr, 'masked').withheld, true);
assert.equal(frameView(fr, 'lawyer').withheld, false);
assert.equal(frameView(fr, 'lawyer').text, 'Log in');
const plain = { ...fr, lawyer: undefined };
assert.equal(frameView(plain, 'lawyer').withheld, true);
assert.equal(frameView(plain, 'complete').withheld, false);
});
test('usesView masks a referenced credential per view', () => {
const doc = { sections: [{ records: [{ id: 'r', title: 'Bank', fields: [{ id: 'f1', ...acct.num }, { id: 'f2', ...acct.amt }] }] }] };
const val = (field, m) => usesView(doc, { uses: [{ record: 'r', field }] }, m)[0].value;
assert.deepEqual(['masked', 'lawyer', 'complete'].map((m) => val('f1', m)), ['[withheld]', '12345', '12345']);
assert.deepEqual(['masked', 'lawyer', 'complete'].map((m) => val('f2', m)), ['[withheld]', '[withheld]', '$900']);
});
test('countByLevel splits lawyer-level from plain secrets, and countSecrets totals them', () => {
const doc = { sections: [{ records: [{ fields: [acct.name, acct.num, acct.amt, { label: 'e', value: '', secret: true, lawyer: true }] }] },
{ sequences: [{ frames: [{ image: '', text: 'x', secret: true, lawyer: true }, { image: '', text: 'y', secret: true }] }] }] };
assert.deepEqual(countByLevel(doc), { lawyer: 2, secret: 2 });
assert.equal(countSecrets(doc), 4);
});
import { summaryGroups, summaryCounts } from '../src/print.js';
const rec = (title, fields) => ({ id: title, title, status: 'ok', updated: '2022-04-14', fields });
const lw = (label, value) => ({ label, value, secret: true, lawyer: true });
const summaryDoc = () => ({ sections: [
{ id: 'a', title: 'Intro', kind: 'text', body: 'hello' },
{ id: 'b', title: 'Bank', kind: 'records', records: [
rec('Chase', [{ label: 'Name', value: 'Chase' }, lw('Account', '123'), { label: 'Balance', value: '$9', secret: true }]),
rec('Only secret', [{ label: 'PIN', value: '1', secret: true }]),
rec('Only normal', [{ label: 'Phone', value: '555' }]),
rec('Empty acct', [lw('Account', '')]),
rec('Card scan', [{ label: 'Card', kind: 'image', value: '', secret: true, lawyer: true }]),
{ id: 'q', kind: 'sequence', title: 'Walk', updated: '2022-04-14', frames: [{ image: '', text: 'x', layout: 'none', secret: true, lawyer: true }] },
] },
{ id: 'c', title: 'Nothing here', kind: 'records', records: [rec('Plain', [{ label: 'x', value: 'y' }])] },
{ id: 'd', title: 'Steps', kind: 'steps', items: [] },
] });
test('summaryGroups keeps only records with lawyer-level text fields, and only those fields', () => {
const out = summaryGroups(summaryDoc());
assert.equal(out.length, 1);
assert.equal(out[0].section, 'Bank');
assert.deepEqual(out[0].groups[0].records.map((r) => r.title), ['Chase', 'Empty acct']);
assert.deepEqual(out[0].groups[0].records[0].fields.map((f) => f.label), ['Account']); // no Name, no Balance
assert.equal(out[0].groups[0].title, null);
});
test('summaryGroups follows sub-tabs and drops tabs with no match', () => {
const doc = summaryDoc();
const s = doc.sections[1];
s.subsections = [{ id: 't1', title: 'Savings' }, { id: 't2', title: 'Unused' }];
s.records[0].subsection = 't1';
const out = summaryGroups(doc);
assert.deepEqual(out[0].groups.map((g) => g.title), ['General', 'Savings']);
assert.deepEqual(out[0].groups[1].records.map((r) => r.title), ['Chase']);
});
test('summaryCounts counts records and values; an empty document lists nothing', () => {
assert.deepEqual(summaryCounts(summaryDoc()), { records: 2, values: 2 });
assert.deepEqual(summaryGroups({ sections: [] }), []);
assert.deepEqual(summaryCounts({ sections: [] }), { records: 0, values: 0 });
});
test("the summary mode shows lawyer values like the lawyer's view and keeps plain secrets hidden", () => {
assert.equal(normalizeMode('summary'), 'summary');
assert.equal(isHidden(acct.num, 'summary'), false);
assert.equal(isHidden(acct.amt, 'summary'), true);
});
test('obscured ("Masked") view shows secrets with every digit replaced; images are withheld', () => {
const pin = { label: 'PIN', value: 'ab 1234-x9', secret: true };
assert.equal(displayValue(pin, 'obscured'), 'ab ••••-x•');
assert.equal(displayValue({ label: 'n', value: 'Ann 5', secret: false }, 'obscured'), 'Ann 5');
assert.equal(displayValue({ label: 'p', value: '', secret: true }, 'obscured'), '(not set)');
assert.equal(displayValue({ label: 'c', kind: 'image', value: 'data:x', secret: true }, 'obscured'), '[withheld]');
const fr = frameView({ image: '', text: 'PIN 4321', ifStuck: 'call 555', layout: 'under', secret: true }, 'obscured');
assert.equal(fr.withheld, false);
assert.equal(fr.text, 'PIN ••••');
assert.equal(fr.ifStuck, 'call •••');
assert.equal(frameView({ image: 'data:x', text: 't', layout: 'under', secret: true }, 'obscured').withheld, true);
});