Compare commits

..

23 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
273c714fc4 Add null.withWorkflow.html: sanitized copy with a sample capture workflow
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 14:36:40 -05:00
c51d289a7e Search controls replace the toolbar buttons instead of a permanent row (Refs #27)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 14:33:50 -05:00
2275889a86 Add a search bar: case-insensitive, steps through matches with Tab/Shift+Tab (Refs #27)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 14:27:48 -05:00
14a46abc63 Stop showing the word "null" above the menu (Fixes #26)
render() passed null to root.append(), which prints it as text. Only append
the reset banner when there is one.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 14:20:18 -05:00
1cdebcef85 Mark up step pictures: markers, boxes and burned-in blur (Refs #25)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 13:03:12 -05:00
eb988b96aa Add mark validation and pure blur/geometry helpers for step annotation (Refs #25)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 13:01:07 -05:00
6066aac6aa Show and copy referenced credentials in steps, view, player and print (Refs #24)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 12:36:25 -05:00
edb3e25e67 Add credential references for steps: field ids, addUse/findFieldRef, usesView (Refs #24)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 12:35:22 -05:00
f089a00b66 Capture steps from the screen and walk through a sequence one step at a time (Refs #23)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 12:26:04 -05:00
29f44440ca Add ifStuck/stop to frames and captured date to sequences (Refs #23)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 12:24:35 -05:00
32d4b06096 Fold docs/MAINTENANCE.md into README.md
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 07:53:30 -05:00
05ffcc8561 Add sanitize.js: secret-free copy under a new passphrase (Refs #19)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 07:26:27 -05:00
78bf87c4e6 Update HANDOFF.md with #20 findings and pending decision (Refs #20)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 07:10:28 -05:00
52ce84c579 Add HANDOFF.md for issue #20 (Refs #20)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 22:01:47 -05:00
613f03993a Fall back to download when Chrome refuses createWritable (Refs #20)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 21:49:07 -05:00
c480ff113a Refresh OVERVIEW.md: ?reset=1 route, issue range (Refs #19)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 21:41:02 -05:00
30 changed files with 7122 additions and 354 deletions

46
HANDOFF.md Normal file
View File

@@ -0,0 +1,46 @@
# Handoff: issue #20 (save writes a 0-byte file)
Written 2026-11-23, updated 2026-11-24. Read `OVERVIEW.md` first for the app itself. This file covers only the open problem.
## The problem
Issue #20 (https://gitea.ericthered.tech/eric/final-wishes/issues/20), a follow-up to #19 (`?reset=1`).
After unlocking, adding `#reset=1` and erasing the secrets, the Save button (Chrome) creates a 0-byte file. The status line shows:
> Save failed: Failed to execute 'createWritable' on 'FileSystemFileHandle': The request is not allowed by the user agent or the platform in the current context.
## What is established
- It is **not** caused by reset. Save after reset uses the same `save()` path as any edit (`src/app.js`, `async function save`). The user has not yet tried a plain save without `#reset=1` on the SSD.
- The picker succeeds and Chrome creates the empty file. Then `state.handle.createWritable()` throws `NotAllowedError`. Nothing is written.
- Headless Chrome with a stubbed `showSaveFilePicker` (OPFS) wrote a full file, so assemble/encrypt is fine. A real picker can't be driven headless.
- The user says **saving to a thumbdrive works fine**, while every SSD location tried fails. This contradicts the theory that Chrome blocks the `file://` site as a whole (`chrome://settings/content/filesystem`). Treat that theory as unlikely.
## What was changed (commit 613f039, pushed)
`save()` now catches `NotAllowedError`/`SecurityError` on the write, clears `state.handle`, downloads `final-wishes.html` as a fallback and sets an explanatory status. `README.md` (the owner's guide) has a matching line. Tests pass (63 pass, 1 skipped). This is a workaround, not a diagnosis. Issue #20 is still open.
Also committed this session: `c480ff1` (OVERVIEW.md refresh for `?reset=1`). Both are pushed to origin/master, along with the first version of this file (52ce84c).
## Findings since (the app is not at fault)
- Tried `~/Documents/final-wishes.html`: still a 0-byte file and the same error.
- A bare test page with no app code (a button calling `showSaveFilePicker`, then `createWritable`/`write`/`close`) **fails the same way on both `http://localhost` and `file://`**, even for a tiny text file. So Chrome or the desktop refuses the write; Final Wishes is not involved. (The test page lived in the session scratchpad and is gone; it is about 20 lines to rebuild.)
- Ruled out on this machine: file ownership and mounts (`~`, `~/Documents`, `~/Downloads` and the project folder are all owned by the user and writable; root is read-write ext4; no external drive was mounted), Chrome snap/flatpak sandboxing (it is the normal `.deb`, `/opt/google/chrome`, v157), enterprise policy (`/etc/opt/chrome/policies` does not exist), and stored Chrome settings (`file_system_write_guard` and `file_system_read_guard` are empty in both profiles).
- Unusual: the desktop is **COSMIC on Wayland**, and the save dialog goes through the COSMIC and GTK xdg-desktop-portal services. Best guess, **unconfirmed**: the portal-based dialog hands Chrome a file it will not let the page write to.
- Still unexplained: the user says saving to a thumbdrive works. It has not been checked how (same dialog? overwriting an existing file?) and no drive was mounted when checked.
## Decision pending (the user is thinking it over)
1. **Make download the default save.** Chrome writes the file itself, which works here. Cost: no silent overwrite, so the user replaces the old copy by hand. Chrome's "Ask where to save each file" (`chrome://settings/downloads`) lets them choose the SSD folder. Keep save-in-place only as an opt-in, so a failed in-place save does not leave a stray 0-byte file.
2. Keep the current behaviour: try in place, and on `NotAllowedError` fall back to a download (already shipped in 613f039). Cost: each failed save leaves an empty file behind.
3. Investigate more first: another browser (Firefox and Safari already use the download path), and repeat the test page on the thumbdrive with a new filename and with an existing file.
If option 1 is chosen: change `save()` in `src/app.js`, update `README.md` (the Chrome/Edge bullet in "Updating" and the "Backups" wording), update `OVERVIEW.md` (the Save paragraph), and add a test only if the logic can be isolated. Then close #20.
## Housekeeping
- Issue tooling: `gt` is not installed. Use `tea` (`tea issues create`, `tea comment N "..."`).
- Scratch files from this session are in the session scratchpad: `d.json` (plaintext test data), `fw.html` and `t.mjs` (the CDP test script). Delete `d.json` when done. None are in the repo.
- Close #20 only after the user confirms a real Chrome save works or the download fallback behaves.

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–#18 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.
@@ -23,14 +23,17 @@ There are no npm dependencies and no CDN or network calls at runtime.
```
build.js builds dist/final-wishes.html (optionally encrypting a JSON file into it)
sanitize.js `node sanitize.js --in real.html --out copy.html`: re-seals a copy with secrets erased under a new passphrase
bump-version.js `npm run bump`, and the pre-commit hook's engine: advances src/version.js to today's date + next letter
.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,
revert-to-saved (Cancel), delete-section message
revert-to-saved (Cancel), delete-section message, clearSecrets
print.js pure print helpers: secret masking, header layout, frame rules, secret count
images.js image helpers (PNG/JPEG sniffing, sizing, data URLs) + browser import pipeline
template.js assemble(): the HTML skeleton shared by build.js and in-page Save
@@ -39,9 +42,10 @@ src/
style.css screen styles, visual-sequence styles, @media print rules
test/ one test file per src module, plus a build test
docs/
MAINTENANCE.md owner's guide (updating, images, sequences, upgrading, backups, security clean-up)
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.
@@ -65,15 +69,22 @@ A **visual sequence** (`kind: 'sequence'`, numbered `frames` of image + text wit
- **Sub-tabs:** `ops.js` holds the pure logic (`tabsOf`, `entriesInTab`, `moveToTab`, `moveWithin`, `removeSubsection`, `printGroups`). The records stay in one array, and the tab bar filters them. The shown tab is in `state.tabs` (not saved). Up/down moves a record past its nearest neighbour in the same tab. Deleting a tab sends its records to General. Print writes one sub-heading per non-empty tab.
- **Images:** drag and drop, clipboard paste and file picker all feed `importFiles()`. Files are sniffed by their first bytes, downscaled to at most 1600 px and re-encoded, which strips metadata, and stored as data URLs with a limit of about 3 MB each.
**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`.
- **Walkthroughs (issue #23):** a sequence frame may carry `ifStuck` text and a `stop` flag, and a sequence a `captured` date. In Edit, "Capture from screen…" uses `getDisplayMedia` (`startScreenCapture`, `grabScreenFrame`, `stopScreenCapture` in `images.js`; the stream lives in a closure variable in `app.js`, ended when leaving edit mode) and adds frames via `addCapture()` in `ops.js`. In view mode `state.walk` (`{id, k}`, not saved) shows a sequence one step at a time (`walkSequence`).
- **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. 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
None at runtime. Development uses the Gitea remote and the `gt` CLI for issues; `PLAN.md` and `docs/MAINTENANCE.md` describe the process.
None at runtime. Development uses the Gitea remote and the `gt` CLI for issues; `PLAN.md` and `README.md` describe the process.
## Database & Data Layer
@@ -94,7 +105,7 @@ No database. The document is a JSON object, encrypted and embedded in the HTML f
- `src/app.js`: the start screen (`renderStart`), then `render()`, `save()`, `buildPrintDoc()`
- `src/model.js`: the data contract; read this first before changing stored data
- `src/crypto.js`: the encrypted format
- `docs/MAINTENANCE.md`: how the owner uses and updates it
- `README.md`: how the owner uses and updates it
## Notes & Gotchas
@@ -105,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.

348
README.md
View File

@@ -2,8 +2,9 @@
An encrypted, printable "in the event of my death or incapacity" guide that
lives on a thumbdrive as a single HTML file. No install and no network are
needed to use it. See `PLAN.md` for the design and `docs/MAINTENANCE.md` to
run it.
needed to use it. See `PLAN.md` for the design. This file is also the owner's
guide (updating, backups, printing and so on, below). The executor's
instructions are in `docs/thumbdrive/README.txt`.
## Develop
```
@@ -21,22 +22,347 @@ The passphrase is prompted for (hidden) or read from `FW_PASSPHRASE`.
- `src/images.js` image-field helpers and the import pipeline (PNG/JPEG only,
downscaled and re-encoded in the browser)
- Visual sequences (numbered pictures with optional text, in any section) are
described in `docs/MAINTENANCE.md`.
described under *Visual sequences* below.
- `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
## Upgrading a file to a newer build
The data lives in the encrypted payload of each `final-wishes.html`, not in
the app code, so a rebuild never changes an existing file. To move data into a
newer build: `npm run build`, open `dist/final-wishes.html`, choose
**Open your existing Final Wishes file**, unlock it, then Save under a *new*
file name and verify it before replacing the old one. Never point
`npm run seal --out` at a file you want to keep: it builds from `data/seed.json`.
## What you have
One file, `final-wishes.html`: the app plus your data, encrypted with a
passphrase (PBKDF2-SHA256, 600,000 iterations, AES-256-GCM). It runs in any
browser, offline. There is no recovery if the passphrase is lost.
## Thumbdrive layout
```
final-wishes.html the encrypted guide
README.txt copy of docs/thumbdrive/README.txt (fill in the blanks)
backups/ dated copies, final-wishes-YYYYMMDD.html
```
Fill in the two blanks in `README.txt` with *where* the passphrase and any
printed copy are kept, never the passphrase itself.
## First-time setup
Either route gives the same kind of file:
- **In a terminal:** `npm run seal` encrypts `data/seed.json` (prompts twice
for a passphrase, minimum 12 characters). To write straight to the drive:
`node build.js --data data/seed.json --out /mnt/f/final-wishes.html`
(WSL needs the drive mounted: `sudo mount -t drvfs F: /mnt/f`).
- **In the browser:** `npm run build`, open `dist/final-wishes.html`, import
a JSON file or start a new document, then Save. You will be asked to
choose a passphrase.
**Never write a seal over a file you want to keep.** `npm run seal` builds
from `data/seed.json`, not from your latest edits; use it only for the very
first file. After that, edit in the page and Save.
After sealing, `data/seed.json` is still plaintext. Delete it (and see
"Security clean-up" below). `data/` and `*.pdf` are git-ignored on purpose.
## Updating
1. Open `final-wishes.html` from the drive, unlock, click **Edit**.
2. Change things, **Done editing**, **Save** (or Ctrl/Cmd+S).
- Chrome/Edge: pick the drive file once; later saves overwrite silently.
- If Chrome refuses to write to the place you picked (a protected folder such as Downloads, Documents or your home folder), Save downloads the file instead and says so. Delete the empty file it left behind. Pick a subfolder you made, or the thumbdrive, to save in place.
- Firefox/Safari: a new `final-wishes.html` downloads. Copy it over the
old one on the drive.
- **Cancel** (next to Save, edit mode only) throws away the unsaved
changes to the section on screen, back to how it was at the last open
or save, and leaves edit mode. It asks first if anything changed. It
works on the Print header page too. Other sections keep their unsaved
edits. A section you added this session is removed. Deleting or moving
sections is not undone by Cancel, and neither is a passphrase change.
Deleting a section asks first and says what is in it (records, items,
visual sequences, images).
3. Saving updates "Last update" and the per-record dates. "Last update" is
what the printed header shows. Editing the header settings themselves does
not change it.
4. If you changed the passphrase, the old file still opens with the *old*
one until you save and replace it.
## Searching
Click **Search** in the toolbar (view mode only). The toolbar buttons are
replaced, in the same row, by a search box with **Search**, **← Previous**,
**Next →** and **Cancel** buttons. Type a word, press **Search** or Enter.
It ignores capitals and looks through the whole document: section titles, text,
record titles, field labels and values, notes, items and visual-sequence step
text. Every match on the page is highlighted and the current one is stronger;
the count shows as "2 of 6".
- **Tab** and **Shift+Tab** (with the cursor in the search box), the arrow
buttons, or Enter / Shift+Enter move to the next or previous match. They wrap
round at the ends and jump to the right section and sub-tab, unfolding a
collapsed record if the match is inside it.
- **Not found:** nothing is highlighted, the box says "Not found", the arrows
are greyed and Tab behaves normally (it moves on to the next control).
- **Cancel** (or Esc) clears the box and the highlights and puts the usual
toolbar buttons back. Typing a new word also clears the old results until you
search again.
- **Secrets are never searched or shown.** A word that only appears inside a
value marked secret is "Not found". Field labels are searched, values marked
secret are not. Image text is not searchable.
- Search is for reading: there is no Search button in Edit mode, and
starting to edit clears any results.
- The Print header page and dates such as "Updated" are not searched.
## Sub-tabs
A *records* section (Banking, say) can be split into **sub-tabs** such as
Standard, Online and Credit Union. Other kinds of section don't have them.
- **Create:** choose Edit, type a name under **Sub-tabs** and press
**+ Add sub-tab**. The first one makes a tab bar appear, with a catch-all
**General** tab first. Records you already had are in General. A section
with no sub-tabs looks exactly as before.
- **Add into a tab:** **+ Add record** and **+ Add visual sequence** add to the
tab you are on.
- **Fix a misplaced record:** each record (and visual sequence) has a
**Sub-tab** drop-down in edit mode. Pick the right tab and it moves there.
- **Order:** the up/down arrows reorder within the tab you are on. The
name box under Sub-tabs renames the selected tab (General too), and its
arrows move the tab left or right.
- **Delete a tab:** the ✕ asks first. Its records move to General, so
nothing is lost. Deleting the last tab turns the section back into a plain list.
- **Collapse all / Expand all** work on the tab you are on.
- **Print:** each tab prints as a sub-heading inside the section (tabs
with nothing in them are left out).
- **Older copies:** a file saved with sub-tabs can't be opened by an older
build of the app. Upgrade the app first (see *Upgrading*).
## 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 **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.
- **Drag and drop** a file onto the record (adds a new field) or onto an
existing image box (replaces that image).
- **Paste** (Ctrl/Cmd+V) with the cursor inside the record (adds a new field),
or with an image box selected (replaces it). Text pastes are unaffected.
What to expect:
- Only **PNG and JPEG** are accepted. The type is checked from the file's
contents, not its name. Anything else is refused with a message.
- Images are **shrunk** so the longest side is at most 1600 px and re-encoded.
This also removes camera metadata such as GPS location. A large PNG becomes a
JPEG (transparency is lost); small PNGs stay PNG so screenshots stay sharp.
Photos usually end up well under 1 MB; there is a hard limit of about 3 MB
per image.
- Pictures are stored inside the encrypted document, so they are protected by
the passphrase like everything else, but they make `final-wishes.html` bigger
and each save slower. Add what the executor needs, not everything you have.
- **Secret** images are hidden in the viewer behind **Show/Hide** and are
withheld ("[withheld]") from a masked print. A photo of an ID card is as
sensitive as a password: a full "Include secrets" print contains it.
- Click an image in the viewer to enlarge it. In print each image is scaled to
fit the page (at most about 4 inches tall).
- Dropping a file anywhere on the page never navigates away from unsaved work.
## Visual sequences
A **visual sequence** is a numbered series of pictures, each with optional
text, for things that are easier to show than to describe: how to log in to a
bank site, how to cancel a service that hides the button. It is its own block,
not part of a record or item, so it sits exactly where you put it.
- **Where:** in any section. In *records*, *steps* and *checklist* sections use
**+ Add visual sequence** next to the add-record / add-item button. It sits
in the same ordered list, so the up/down arrows place it between records or
items. In a *text* section sequences print after the text. A section can
hold as many as you like. A sequence is not a step: it has no number and no
tick box, and numbering of the items around it carries on unbroken.
- **Adding pictures:** **+ Add images…** (choose several files at once), drop
files on the sequence, or paste a screenshot while the cursor is inside it.
Each becomes a step. Dropping or pasting onto an existing step's box replaces
that step's picture. **+ Add step** adds an empty one. Same image rules as
Images above (PNG/JPEG, shrunk, about 3 MB limit).
- **Text:** each step has a text position, chosen per step: *right of image*,
*under image*, or *no text*. Text keeps its line breaks. Switching to *no
text* hides it but keeps what you typed. Empty text never takes room.
- **Secret** (per step) hides both the picture and the text behind Show/Hide
and withholds it from a masked print. Steps are numbered 1, 2, 3… in view
and in print, and a step is kept on one page.
- **Capture from the screen:** in Edit, **Capture from screen…** asks the
browser to share a window or tab (nothing is recorded or sent anywhere).
Log in to the site yourself, get to the screen you want, come back to this
page and click **Capture step**. Each click adds one step with that picture;
repeat for each screen, then **Stop sharing** (it also stops when you leave
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.
Both show in the list, the walkthrough and print, and are hidden with a
secret step.
- **Mark up a picture:** in Edit, **Mark up picture…** under a step's image
opens an editor. **Marker** (click) drops a numbered circle where the reader
should click; **Box** (drag) outlines something to look at; **Blur out**
(drag) pixelates anything private, such as account numbers and balances.
**Undo** steps back, **Apply** keeps it. Markers and boxes are overlays you can
change later (they show in the list, walkthrough, enlarged view and print).
**Blur is different: it is baked into the picture when you Apply**, so no
readable copy is kept, and it cannot be undone after you Save. Replacing or
removing a step's picture drops its markers and boxes, since they would no
longer line up.
- **Credentials a step needs:** in Edit, each step has **+ Use a field from a
record…**. Pick the login fields (say Santander's username and password) and
the step shows them beside the picture, live from the record, so there is one
copy to keep current. A secret stays masked until **Show**; **Copy** puts the
value on the clipboard without showing it (the clipboard is wiped after 30
seconds, which also replaces anything else copied in that time). Print shows
them too, masked unless you choose "Include secrets". If the record or field is
later deleted the step says the credential was removed. Renaming or
reordering fields is safe: the link is to the field itself.
- **Walkthrough:** in view mode, **Walk through, one step at a time** shows one
step with Back / Next. A sequence made from captures shows its capture date
and a reminder that the site may have changed since.
- Files saved with sequences cannot be opened by older builds; opening an
older file in a newer build (see below) still works. **Cancel** and the
other editing rules work the same as for records.
## Version number
The top of the page shows the app's version after the "Last update" date,
for example **Ver 261109B**: `261109` is the date (YY MM DD) and the letter is
the iteration that day (A first, B second, up to Z). It is the version of the
*app code*, not of your data, so a file saved from a newer build shows the
newer number. After upgrading an old file (below), check that it changed.
For the developer: the bump is automatic. A git pre-commit hook
(`.githooks/pre-commit`) moves `src/version.js` to today's date with the next
letter (or A on a new day) in any commit that changes `src/` or `build.js`.
Docs-only and test-only commits don't bump, and a commit that already changes
the version by hand is left alone. Past Z (26 in a day) it warns and keeps Z.
- Once per clone, switch the hook on: `npm run hooks` (sets
`core.hooksPath` to `.githooks`). Until then commits are not bumped.
- `npm run bump` still bumps by hand if you need it.
- The hook adds `src/version.js` to the commit being made. It works with
`git add ... && git commit` and `git commit -a`; with `git commit <paths>`
the bump is left out of that commit, so use the first form.
## Upgrading the app (new version, same data)
Your data is stored encrypted inside each `final-wishes.html`; the app code
sits beside it in the same file. A file therefore keeps running the version it
was saved with until you move its data into a newer build:
1. `npm run build` (or take a newer `final-wishes.html` build) and open
`dist/final-wishes.html`.
2. On the start screen choose **Open your existing Final Wishes file**, pick
your current file and unlock it with its passphrase. The old file is only
read, not changed.
3. Click **Save** and give the result a **new name** (for example
`final-wishes-new.html`) rather than the current one.
4. Open the new file, unlock it, and look through it. Only then replace the
old file (keep the old one in `backups/`).
Never point `npm run seal --out` at a file you want to keep: it builds from `data/seed.json`.
Documents made by older versions keep working: anything a newer version added
(such as the print header) falls back to a default until you set it.
## Backups
- **Backup copy** downloads `final-wishes-YYYYMMDD.html` to your Downloads
folder. Move it into `backups/`.
- Keep a second copy off the drive. The file is encrypted, so cloud storage
or a second drive is reasonable. Thumbdrives fail without warning.
- After any important change, open the *copy* once and unlock it to prove it
works.
## The passphrase (the real single point of failure)
- Do not store it on the drive or in the same place as the drive.
- Good options: a sealed envelope with your will in the fire safe, or with
your attorney, plus a second person who knows where it is.
- Make sure your executor knows the drive exists and where the passphrase
is kept. The blanks in `README.txt` exist for this.
- Use a few random words (12+ characters is enforced). Do not reuse the
LastPass master password.
## Printing
**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
pages in Chromium (Chrome/Edge); it has not been checked in Firefox or Safari,
so look at a test print the first time.
### The print header
Every printed page starts with a header line in larger bold type. It is part
of the document, so it is saved with the rest and is encrypted too. Open
**Print header** at the bottom of the sidebar to see a live preview, then
**Edit** to change it:
- Add as many fields as you like. Each is either **Text** (printed as
written) or **Last updated** (an optional label such as `Last update: `
followed by the document's last-update date).
- Each field's alignment is **Left**, **Right** or **Not aligned**. At most one
field can be left aligned and one right aligned; the other choice shows
"(in use)" and is disabled.
- Printed order is always: the left field, then the unaligned fields in the
order listed, then the right field. List order only matters between
unaligned fields. Use the arrows to reorder and the cross to remove.
- **Reset to default** restores the title on the left and "Last update: date"
on the right, which is also what a document with no header setting uses.
- Keep the left and middle text short. If the line gets crowded, the left
field wraps first; the right and middle fields never wrap.
## Reset: erase secrets before working online (issue #19)
To work on the layout somewhere less safe (a shared or online machine), open the file with `?reset=1` on the end of its address, for example `final-wishes.html?reset=1` (`#reset=1` works too). After you unlock it, a banner offers to erase every value marked secret: secret fields, secret images and secret steps. Labels, structure and everything else stay.
Nothing is written until you Save, and saving over the file removes the secrets for good. Use **Backup copy** first, or save under a new name, if you need them again. Choosing "Keep them" dismisses the banner and changes nothing.
### Making a copy without secrets (the sanitize script)
`node sanitize.js --in /path/real.html --out /path/copy.html` reads your real file (it is never changed), asks for its passphrase and a **new** passphrase for the copy, erases every value marked secret, and writes the copy with the newest app code. It prints what is still in the copy, section by section, so you can judge whether it is safe where you plan to put it. It refuses to write over the input, and refuses to reuse the real passphrase. Set `FW_PASSPHRASE` and `FW_NEW_PASSPHRASE` to skip the prompts. Only values flagged secret are erased: review anything sensitive that is not flagged.
## Keep it current
Nothing in the app reminds you to review. Set a yearly reminder. Things that
go stale: card expiry dates, account balances and metal values, advisors'
contact details, anything marked TBD. The "Still to add" section lists
known gaps.
## Security clean-up (issue #8)
- Destroy plaintext copies of the source material once the encrypted file is
verified: `abi-wishes.pdf`, the Word version, and `data/seed.json`.
- Rotate every password and PIN that appeared in the PDF (LastPass master
password, computer PIN, ATM PIN, bank logins), since it existed in
plaintext for years.
- Treat the encrypted file like any sensitive file: an attacker who gets it
can try passphrases offline forever, so the passphrase strength is all that
protects it.
## Limits
This is a guide, not a legal document. It does not replace a will, health
care directive or powers of attorney, and the executor may still need
those to be granted access to accounts.
## Never commit
`*.pdf` and `data/` hold real personal data and are git-ignored.

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', '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++) {
@@ -32,7 +38,7 @@ function parseArgs(argv) {
return a;
}
function promptHidden(question) {
export function promptHidden(question) {
return new Promise((res, rej) => {
if (!process.stdin.isTTY) return rej(new Error('No terminal to prompt on: set FW_PASSPHRASE instead.'));
process.stdout.write(question);
@@ -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

@@ -1,245 +0,0 @@
# Maintaining Final Wishes
For the owner. The executor's instructions are in `docs/thumbdrive/README.txt`.
## What you have
One file, `final-wishes.html`: the app plus your data, encrypted with a
passphrase (PBKDF2-SHA256, 600,000 iterations, AES-256-GCM). It runs in any
browser, offline. There is no recovery if the passphrase is lost.
## Thumbdrive layout
```
final-wishes.html the encrypted guide
README.txt copy of docs/thumbdrive/README.txt (fill in the blanks)
backups/ dated copies, final-wishes-YYYYMMDD.html
```
Fill in the two blanks in `README.txt` with *where* the passphrase and any
printed copy are kept, never the passphrase itself.
## First-time setup
Either route gives the same kind of file:
- **In a terminal:** `npm run seal` encrypts `data/seed.json` (prompts twice
for a passphrase, minimum 12 characters). To write straight to the drive:
`node build.js --data data/seed.json --out /mnt/f/final-wishes.html`
(WSL needs the drive mounted: `sudo mount -t drvfs F: /mnt/f`).
- **In the browser:** `npm run build`, open `dist/final-wishes.html`, import
a JSON file or start a new document, then Save. You will be asked to
choose a passphrase.
**Never write a seal over a file you want to keep.** `npm run seal` builds
from `data/seed.json`, not from your latest edits; use it only for the very
first file. After that, edit in the page and Save.
After sealing, `data/seed.json` is still plaintext. Delete it (and see
"Security clean-up" below). `data/` and `*.pdf` are git-ignored on purpose.
## Updating
1. Open `final-wishes.html` from the drive, unlock, click **Edit**.
2. Change things, **Done editing**, **Save** (or Ctrl/Cmd+S).
- Chrome/Edge: pick the drive file once; later saves overwrite silently.
- Firefox/Safari: a new `final-wishes.html` downloads. Copy it over the
old one on the drive.
- **Cancel** (next to Save, edit mode only) throws away the unsaved
changes to the section on screen, back to how it was at the last open
or save, and leaves edit mode. It asks first if anything changed. It
works on the Print header page too. Other sections keep their unsaved
edits. A section you added this session is removed. Deleting or moving
sections is not undone by Cancel, and neither is a passphrase change.
Deleting a section asks first and says what is in it (records, items,
visual sequences, images).
3. Saving updates "Last update" and the per-record dates. "Last update" is
what the printed header shows. Editing the header settings themselves does
not change it.
4. If you changed the passphrase, the old file still opens with the *old*
one until you save and replace it.
## Sub-tabs
A *records* section (Banking, say) can be split into **sub-tabs** such as
Standard, Online and Credit Union. Other kinds of section don't have them.
- **Create:** choose Edit, type a name under **Sub-tabs** and press
**+ Add sub-tab**. The first one makes a tab bar appear, with a catch-all
**General** tab first. Records you already had are in General. A section
with no sub-tabs looks exactly as before.
- **Add into a tab:** **+ Add record** and **+ Add visual sequence** add to the
tab you are on.
- **Fix a misplaced record:** each record (and visual sequence) has a
**Sub-tab** drop-down in edit mode. Pick the right tab and it moves there.
- **Order:** the up/down arrows reorder within the tab you are on. The
name box under Sub-tabs renames the selected tab (General too), and its
arrows move the tab left or right.
- **Delete a tab:** the ✕ asks first. Its records move to General, so
nothing is lost. Deleting the last tab turns the section back into a plain list.
- **Collapse all / Expand all** work on the tab you are on.
- **Print:** each tab prints as a sub-heading inside the section (tabs
with nothing in them are left out).
- **Older copies:** a file saved with sub-tabs can't be opened by an older
build of the app. Upgrade the app first (see *Upgrading*).
## 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
like any other field. In **Edit** mode, add one of three ways:
- **+ Add image...** in the record, then choose one or more files.
- **Drag and drop** a file onto the record (adds a new field) or onto an
existing image box (replaces that image).
- **Paste** (Ctrl/Cmd+V) with the cursor inside the record (adds a new field),
or with an image box selected (replaces it). Text pastes are unaffected.
What to expect:
- Only **PNG and JPEG** are accepted. The type is checked from the file's
contents, not its name. Anything else is refused with a message.
- Images are **shrunk** so the longest side is at most 1600 px and re-encoded.
This also removes camera metadata such as GPS location. A large PNG becomes a
JPEG (transparency is lost); small PNGs stay PNG so screenshots stay sharp.
Photos usually end up well under 1 MB; there is a hard limit of about 3 MB
per image.
- Pictures are stored inside the encrypted document, so they are protected by
the passphrase like everything else, but they make `final-wishes.html` bigger
and each save slower. Add what the executor needs, not everything you have.
- **Secret** images are hidden in the viewer behind **Show/Hide** and are
withheld ("[withheld]") from a masked print. A photo of an ID card is as
sensitive as a password: a full "Include secrets" print contains it.
- Click an image in the viewer to enlarge it. In print each image is scaled to
fit the page (at most about 4 inches tall).
- Dropping a file anywhere on the page never navigates away from unsaved work.
## Visual sequences
A **visual sequence** is a numbered series of pictures, each with optional
text, for things that are easier to show than to describe: how to log in to a
bank site, how to cancel a service that hides the button. It is its own block,
not part of a record or item, so it sits exactly where you put it.
- **Where:** in any section. In *records*, *steps* and *checklist* sections use
**+ Add visual sequence** next to the add-record / add-item button. It sits
in the same ordered list, so the up/down arrows place it between records or
items. In a *text* section sequences print after the text. A section can
hold as many as you like. A sequence is not a step: it has no number and no
tick box, and numbering of the items around it carries on unbroken.
- **Adding pictures:** **+ Add images…** (choose several files at once), drop
files on the sequence, or paste a screenshot while the cursor is inside it.
Each becomes a step. Dropping or pasting onto an existing step's box replaces
that step's picture. **+ Add step** adds an empty one. Same image rules as
Images above (PNG/JPEG, shrunk, about 3 MB limit).
- **Text:** each step has a text position, chosen per step: *right of image*,
*under image*, or *no text*. Text keeps its line breaks. Switching to *no
text* hides it but keeps what you typed. Empty text never takes room.
- **Secret** (per step) hides both the picture and the text behind Show/Hide
and withholds it from a masked print. Steps are numbered 1, 2, 3… in view
and in print, and a step is kept on one page.
- Files saved with sequences cannot be opened by older builds; opening an
older file in a newer build (see below) still works. **Cancel** and the
other editing rules work the same as for records.
## Version number
The top of the page shows the app's version after the "Last update" date,
for example **Ver 261109B**: `261109` is the date (YY MM DD) and the letter is
the iteration that day (A first, B second, up to Z). It is the version of the
*app code*, not of your data, so a file saved from a newer build shows the
newer number. After upgrading an old file (below), check that it changed.
For the developer: the bump is automatic. A git pre-commit hook
(`.githooks/pre-commit`) moves `src/version.js` to today's date with the next
letter (or A on a new day) in any commit that changes `src/` or `build.js`.
Docs-only and test-only commits don't bump, and a commit that already changes
the version by hand is left alone. Past Z (26 in a day) it warns and keeps Z.
- Once per clone, switch the hook on: `npm run hooks` (sets
`core.hooksPath` to `.githooks`). Until then commits are not bumped.
- `npm run bump` still bumps by hand if you need it.
- The hook adds `src/version.js` to the commit being made. It works with
`git add ... && git commit` and `git commit -a`; with `git commit <paths>`
the bump is left out of that commit, so use the first form.
## Upgrading the app (new version, same data)
Your data is stored encrypted inside each `final-wishes.html`; the app code
sits beside it in the same file. A file therefore keeps running the version it
was saved with until you move its data into a newer build:
1. `npm run build` (or take a newer `final-wishes.html` build) and open
`dist/final-wishes.html`.
2. On the start screen choose **Open your existing Final Wishes file**, pick
your current file and unlock it with its passphrase. The old file is only
read, not changed.
3. Click **Save** and give the result a **new name** (for example
`final-wishes-new.html`) rather than the current one.
4. Open the new file, unlock it, and look through it. Only then replace the
old file (keep the old one in `backups/`).
Documents made by older versions keep working: anything a newer version added
(such as the print header) falls back to a default until you set it.
## Backups
- **Backup copy** downloads `final-wishes-YYYYMMDD.html` to your Downloads
folder. Move it into `backups/`.
- Keep a second copy off the drive. The file is encrypted, so cloud storage
or a second drive is reasonable. Thumbdrives fail without warning.
- After any important change, open the *copy* once and unlock it to prove it
works.
## The passphrase (the real single point of failure)
- Do not store it on the drive or in the same place as the drive.
- Good options: a sealed envelope with your will in the fire safe, or with
your attorney, plus a second person who knows where it is.
- Make sure your executor knows the drive exists and where the passphrase
is kept. The blanks in `README.txt` exist for this.
- Use a few random words (12+ characters is enforced). Do not reuse the
LastPass master password.
## Printing
**Print...** offers "Withhold secrets" (safe overview) and "Include
secrets" (full copy). 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
pages in Chromium (Chrome/Edge); it has not been checked in Firefox or Safari,
so look at a test print the first time.
### The print header
Every printed page starts with a header line in larger bold type. It is part
of the document, so it is saved with the rest and is encrypted too. Open
**Print header** at the bottom of the sidebar to see a live preview, then
**Edit** to change it:
- Add as many fields as you like. Each is either **Text** (printed as
written) or **Last updated** (an optional label such as `Last update: `
followed by the document's last-update date).
- Each field's alignment is **Left**, **Right** or **Not aligned**. At most one
field can be left aligned and one right aligned; the other choice shows
"(in use)" and is disabled.
- Printed order is always: the left field, then the unaligned fields in the
order listed, then the right field. List order only matters between
unaligned fields. Use the arrows to reorder and the cross to remove.
- **Reset to default** restores the title on the left and "Last update: date"
on the right, which is also what a document with no header setting uses.
- Keep the left and middle text short. If the line gets crowded, the left
field wraps first; the right and middle fields never wrap.
## Reset: erase secrets before working online (issue #19)
To work on the layout somewhere less safe (a shared or online machine), open the file with `?reset=1` on the end of its address, for example `final-wishes.html?reset=1` (`#reset=1` works too). After you unlock it, a banner offers to erase every value marked secret: secret fields, secret images and secret steps. Labels, structure and everything else stay.
Nothing is written until you Save, and saving over the file removes the secrets for good. Use **Backup copy** first, or save under a new name, if you need them again. Choosing "Keep them" dismisses the banner and changes nothing.
## Keep it current
Nothing in the app reminds you to review. Set a yearly reminder. Things that
go stale: card expiry dates, account balances and metal values, advisors'
contact details, anything marked TBD. The "Still to add" section lists
known gaps.
## Security clean-up (issue #8)
- Destroy plaintext copies of the source material once the encrypted file is
verified: `abi-wishes.pdf`, the Word version, and `data/seed.json`.
- Rotate every password and PIN that appeared in the PDF (LastPass master
password, computer PIN, ATM PIN, bank logins), since it existed in
plaintext for years.
- Treat the encrypted file like any sensitive file: an attacker who gets it
can try passphrases offline forever, so the passphrase strength is all that
protects it.
## Limits
This is a guide, not a legal document. It does not replace a will, health
care directive or powers of attorney, and the executor may still need
those to be granted access to accounts.

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

2591
null.html Normal file

File diff suppressed because one or more lines are too long

2423
null.withWorkflow.html Normal file

File diff suppressed because one or more lines are too long

View File

@@ -8,6 +8,7 @@
"build": "node build.js",
"test": "node --test",
"seal": "node build.js --data data/seed.json",
"sanitize": "node sanitize.js",
"bump": "node bump-version.js",
"hooks": "git config core.hooksPath .githooks"
},

92
sanitize.js Normal file
View File

@@ -0,0 +1,92 @@
// Makes a copy of a Final Wishes file with every secret value erased, sealed under a NEW passphrase,
// so it can be kept somewhere less safe (a shared SSD, an online session) for working on the layout.
// The input file is only read. The copy carries the newest app code from src/.
//
// node sanitize.js --in real.html --out /path/copy.html
//
// Passphrases: FW_PASSPHRASE (current) and FW_NEW_PASSPHRASE (for the copy), else prompted for hidden.
// They are never accepted as arguments. Only values flagged `secret` are erased; the summary printed
// at the end lists what is still in the copy so you can judge whether it is safe to put where you plan to.
import { readFileSync, writeFileSync, mkdirSync, existsSync, realpathSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join, resolve } from 'node:path';
import { assemble } from './src/template.js';
import { encrypt, decrypt, passphraseProblem } from './src/crypto.js';
import { assertValid, isSequence } from './src/model.js';
import { clearSecrets } from './src/ops.js';
import { bundleJs, promptHidden } from './build.js';
const root = dirname(fileURLToPath(import.meta.url));
export function extractPayload(html) {
const m = html.match(/<script id="payload"[^>]*>([^<]*)<\/script>/);
if (!m || !m[1].trim()) throw new Error('That file has no encrypted data in it.');
return m[1].trim();
}
// What is left in the document after erasing: per section, counts of kept text values and images.
export function remaining(doc) {
return doc.sections.map((s) => {
let text = 0, images = 0, empty = 0;
const count = (v, isImage) => { if (!v || !String(v).trim()) empty++; else if (isImage) images++; else text++; };
const frames = (q) => { for (const f of q.frames) { count(f.text, false); if (f.image) images++; } };
for (const r of s.records || []) {
if (isSequence(r)) frames(r);
else for (const f of r.fields) count(f.value, f.kind === 'image' || /^data:image\//.test(f.value || ''));
}
for (const it of s.items || []) { if (isSequence(it)) frames(it); else count(it.text, false); }
for (const q of s.sequences || []) frames(q);
if (s.body && String(s.body).trim()) text++;
return { title: s.title, kind: s.kind, text, images };
});
}
// Pure core: encrypted file text in, sanitized file text out. `iterations` is for fast tests only.
export async function sanitize({ html, oldPass, newPass, css, js, iterations }) {
const problem = passphraseProblem(newPass);
if (problem) throw new Error('New passphrase: ' + problem);
if (newPass === oldPass) throw new Error('Choose a different passphrase for the sanitized copy.');
const doc = assertValid(JSON.parse(await decrypt(extractPayload(html), oldPass)));
const erased = clearSecrets(doc);
assertValid(doc);
const payload = await encrypt(JSON.stringify(doc), newPass, iterations);
return { html: assemble({ css, js, payload }), erased, left: remaining(doc) };
}
function parseArgs(argv) {
const a = {};
for (let i = 0; i < argv.length; i++) {
if (argv[i] === '--in') a.in = argv[++i];
else if (argv[i] === '--out') a.out = argv[++i];
else throw new Error(`Unknown argument: ${argv[i]}`);
}
if (!a.in || !a.out) throw new Error('Usage: node sanitize.js --in real.html --out copy.html');
return a;
}
async function main() {
const args = parseArgs(process.argv.slice(2));
const inPath = resolve(args.in), outPath = resolve(args.out);
if (!existsSync(inPath)) throw new Error(`Not found: ${inPath}`);
if (inPath === outPath || (existsSync(outPath) && realpathSync(inPath) === realpathSync(outPath))) {
throw new Error('--out must be a different file from --in.');
}
const oldPass = process.env.FW_PASSPHRASE || await promptHidden('Passphrase of the real file: ');
let newPass = process.env.FW_NEW_PASSPHRASE;
if (!newPass) {
newPass = await promptHidden('New passphrase for the sanitized copy: ');
if (newPass !== await promptHidden('Repeat new passphrase: ')) throw new Error('Passphrases did not match.');
}
const r = await sanitize({
html: readFileSync(inPath, 'utf8'), oldPass, newPass,
css: readFileSync(join(root, 'src', 'style.css'), 'utf8'), js: bundleJs(),
});
mkdirSync(dirname(outPath), { recursive: true });
writeFileSync(outPath, r.html);
console.log(`Wrote ${outPath} (${r.html.length} bytes). Erased ${r.erased} secret value${r.erased === 1 ? '' : 's'}.`);
console.log('\nStill in the copy (review before using it somewhere less safe):');
for (const s of r.left) console.log(` ${s.title} [${s.kind}]: ${s.text} text value${s.text === 1 ? '' : 's'}, ${s.images} image${s.images === 1 ? '' : 's'}`);
console.log(`\nThe real file was not changed. Do not Save the copy over it.`);
}
if (process.argv[1] === fileURLToPath(import.meta.url)) main().catch((e) => { console.error(e.message); process.exit(1); });

View File

@@ -13,6 +13,10 @@
pwChanged: false, // passphrase changed since the last save
tabs: {}, // section id -> id of the sub-tab being shown ('' = General); not saved
collapsed: new Set(), // ids of records folded to just their title (view mode only)
searchOpen: false, // the search controls are showing in place of the toolbar buttons
search: null, // { q, hits: [{sid, eid, n}], i, scroll }: the active search (not saved)
searchAll: false, // true only while building the hidden copy the search counts matches in
walk: null, // { id, k }: the visual sequence shown as a one-step-at-a-time walkthrough (not saved)
revealed: new WeakSet(), // secret field objects currently shown
blob: null, // encrypted payload taken from a file the user chose to open
handle: null, // File System Access handle once the user picked a save location
@@ -157,6 +161,49 @@
const allRecords = () => state.doc.sections.flatMap((s) => (s.records || []).filter((r) => !isSequence(r)));
const addFrameFrom = (seq) => (name, url) => addFrame(seq, url);
// Copy a credential for the reader, then wipe the clipboard after 30 seconds
// (this overwrites whatever is on the clipboard by then, whether or not it is ours).
let clipTimer = null;
async function copyValue(fld) {
try {
await navigator.clipboard.writeText(fld.value);
clearTimeout(clipTimer);
clipTimer = setTimeout(() => { navigator.clipboard.writeText('').catch(() => {}); }, 30000);
setStatus('Copied ' + fld.label + '. The clipboard is cleared in 30 seconds.');
} catch {
setStatus('Could not copy ' + fld.label + '. Show it and copy it by hand.');
}
}
// Screen capture while editing a visual sequence. The stream lives here, not in
// the DOM, so it survives render(). { stream, video, seqId } or null.
let capture = null;
function endCapture() { stopScreenCapture(capture); capture = null; }
async function beginCapture(q) {
endCapture();
try {
const cap = await startScreenCapture();
cap.seqId = q.id;
cap.stream.getVideoTracks()[0].onended = () => { if (capture === cap) { capture = null; setStatus('Screen sharing ended.'); render(); } };
capture = cap;
setStatus('Sharing. Get the site to the screen you want, come back here and click Capture step.');
} catch (err) {
setStatus(err.message);
}
render();
}
async function captureStep(q) {
try {
const url = await processImageFile(await grabScreenFrame(capture));
addCapture(q, url);
changed(q); // clears the status, so set it afterwards
setStatus('Step ' + q.frames.length + ' captured.');
} catch (err) {
setStatus(err.message);
}
render();
}
// Add each file as a new image field on `rec`, or put the first into
// `opts.replace` (an existing image field). Per-file problems are reported
// together; the files that worked are still kept.
@@ -170,7 +217,7 @@
for (const file of files) {
try {
const url = await processImageFile(file);
if (opts.replace && !added) opts.replace[key] = url;
if (opts.replace && !added) { opts.replace[key] = url; if (key === 'image') delete opts.replace.marks; }
else add(file.name, url);
added++;
} catch (err) {
@@ -211,9 +258,117 @@
importFiles(rec, files, { replace: field && field.kind === 'image' ? field : null, pasted: true });
});
function openLightbox(label, src) {
// A step's picture with its markers and boxes laid over it. Positions are fractions
// of the picture, so they stay put at any size, in print too.
function markedImage(img, marks) {
if (!marks || !marks.length) return img;
let n = 0;
return h('div', { class: 'marked' }, img, marks.map((m) => (m.type === 'box'
? h('span', { class: 'mbox', 'aria-hidden': 'true', style: 'left:' + m.x * 100 + '%;top:' + m.y * 100 + '%;width:' + m.w * 100 + '%;height:' + m.h * 100 + '%' })
: h('span', { class: 'mpin', 'aria-hidden': 'true', style: 'left:' + m.x * 100 + '%;top:' + m.y * 100 + '%' }, String(++n)))));
}
// Mark up a step's picture: numbered markers and highlight boxes (kept as overlays, editable
// later) and Blur out (burned into the pixels on Apply, so no readable copy is kept).
async function openAnnotator(q, f) {
const img = new Image();
img.src = f.image;
try { await img.decode(); } catch { return setStatus('That image could not be opened.'); }
const W = img.naturalWidth, H = img.naturalHeight;
const base = document.createElement('canvas');
base.width = W; base.height = H;
const bctx = base.getContext('2d', { willReadFrequently: true });
bctx.drawImage(img, 0, 0);
const marks = structuredClone(f.marks || []);
const undo = [];
let tool = 'marker', blurs = 0, drag = null;
const view = h('canvas', { class: 'annot', width: W, height: H, 'aria-label': 'Picture to mark up' });
const vctx = view.getContext('2d');
const lw = Math.max(3, Math.round(W / 300)), pr = Math.max(14, Math.round(W / 60));
function draw() {
vctx.drawImage(base, 0, 0);
let n = 0;
for (const m of marks) {
if (m.type === 'box') {
vctx.strokeStyle = '#e11'; vctx.lineWidth = lw;
vctx.strokeRect(m.x * W, m.y * H, m.w * W, m.h * H);
} else {
vctx.beginPath(); vctx.arc(m.x * W, m.y * H, pr, 0, 2 * Math.PI);
vctx.fillStyle = '#e11'; vctx.fill(); vctx.lineWidth = 2; vctx.strokeStyle = '#fff'; vctx.stroke();
vctx.fillStyle = '#fff'; vctx.font = '700 ' + Math.round(pr * 1.2) + 'px system-ui, sans-serif';
vctx.textAlign = 'center'; vctx.textBaseline = 'middle'; vctx.fillText(String(++n), m.x * W, m.y * H + 1);
}
}
if (drag) {
const r = normRect(drag.x0, drag.y0, drag.x1, drag.y1, 0);
if (r) {
vctx.setLineDash([8, 6]); vctx.lineWidth = lw; vctx.strokeStyle = tool === 'blur' ? '#000' : '#e11';
vctx.strokeRect(r.x * W, r.y * H, r.w * W, r.h * H); vctx.setLineDash([]);
}
}
}
const at = (e) => {
const b = view.getBoundingClientRect();
return { x: Math.min(1, Math.max(0, (e.clientX - b.left) / b.width)), y: Math.min(1, Math.max(0, (e.clientY - b.top) / b.height)) };
};
view.addEventListener('pointerdown', (e) => {
const p = at(e);
if (tool === 'marker') { marks.push({ type: 'marker', x: p.x, y: p.y }); undo.push(() => marks.pop()); draw(); return; }
view.setPointerCapture(e.pointerId);
drag = { x0: p.x, y0: p.y, x1: p.x, y1: p.y };
});
view.addEventListener('pointermove', (e) => { if (drag) { const p = at(e); drag.x1 = p.x; drag.y1 = p.y; draw(); } });
view.addEventListener('pointerup', (e) => {
if (!drag) return;
const p = at(e);
const r = normRect(drag.x0, drag.y0, p.x, p.y);
drag = null;
if (r && tool === 'box') {
marks.push({ type: 'box', x: r.x, y: r.y, w: r.w, h: r.h }); undo.push(() => marks.pop());
} else if (r && tool === 'blur') {
const snap = bctx.getImageData(0, 0, W, H);
const id = bctx.getImageData(0, 0, W, H);
pixelateRegion(id.data, W, H, { x: r.x * W, y: r.y * H, w: r.w * W, h: r.h * H });
bctx.putImageData(id, 0, 0);
blurs++; undo.push(() => { bctx.putImageData(snap, 0, 0); blurs--; });
}
draw();
});
const tools = [['marker', 'Marker (click)'], ['box', 'Box (drag)'], ['blur', 'Blur out (drag)']];
const radios = tools.map(([v, t]) => h('label', { class: 'radio' },
h('input', { type: 'radio', name: 'annot-tool', value: v, checked: v === tool, onchange: () => { tool = v; } }), ' ' + t));
const dlg = h('dialog', { class: 'card annotator', 'aria-label': 'Mark up picture' },
h('h3', {}, 'Mark up this picture'),
h('p', { class: 'muted small' }, 'Marker: click where the reader should click. Box: drag around something to point at. Blur out: drag over anything private, such as account numbers or balances. Blur is permanent once you Apply and Save; markers and boxes can be changed later.'),
h('div', { class: 'row' }, radios,
btn('Undo', () => { const u = undo.pop(); if (u) { u(); draw(); } }, 'small'),
btn('Clear markers and boxes', () => { if (!marks.length) return; const copy = marks.splice(0); undo.push(() => marks.push(...copy)); draw(); }, 'small')),
view,
h('div', { class: 'row' },
btn('Cancel', () => dlg.close()),
btn('Apply', () => {
if (blurs > 0) {
let url = base.toDataURL(f.image.startsWith('data:image/png') ? 'image/png' : 'image/jpeg', JPEG_QUALITY);
if (!isImageDataUrl(url)) url = base.toDataURL('image/jpeg', JPEG_QUALITY);
if (!isImageDataUrl(url)) return setStatus('The blurred picture is too large to keep.');
f.image = url;
}
if (marks.length) f.marks = marks; else delete f.marks;
changed(q); // clears the status, so set it afterwards
setStatus(blurs > 0 ? 'Picture marked up and blurred. Save to keep it.' : 'Markers and boxes updated.');
dlg.close(); render();
}, 'primary')));
dlg.addEventListener('close', () => dlg.remove());
document.body.append(dlg);
dlg.showModal();
draw();
}
function openLightbox(label, src, marks) {
const dlg = h('dialog', { class: 'card lightbox', 'aria-label': label },
h('h3', {}, label), h('img', { class: 'bigimg', src, alt: label }),
h('h3', {}, label), markedImage(h('img', { class: 'bigimg', src, alt: label }), marks),
h('div', { class: 'row' }, btn('Close', () => dlg.close(), 'primary')));
dlg.addEventListener('close', () => dlg.remove());
document.body.append(dlg);
@@ -222,7 +377,7 @@
// ---------- read-only view ----------
function statusBadge(status) {
return status === 'tbd' ? h('span', { class: 'badge tbd' }, 'TBD') : status === 'done' ? h('span', { class: 'badge done' }, 'Done') : null;
return status === 'tbd' ? h('span', { class: 'badge tbd nosearch' }, 'TBD') : status === 'done' ? h('span', { class: 'badge done nosearch' }, 'Done') : null;
}
function viewImageField(f) {
@@ -271,10 +426,10 @@
function viewRecord(s, r, i) {
const arr = s.records;
const same = sameTab(s);
const closed = state.collapsed.has(r.id);
const closed = !state.searchAll && state.collapsed.has(r.id);
const toggle = () => { state.collapsed[closed ? 'delete' : 'add'](r.id); render(); };
const shift = (dir) => { moveWithin(arr, i, dir, same); changed(r); render(); };
return h('article', { class: 'card' + (closed ? ' collapsed' : '') },
return h('article', { class: 'card' + (closed ? ' collapsed' : ''), 'data-eid': r.id },
h('div', { class: 'rechead' },
h('h3', {}, r.title, ' ', statusBadge(r.status)),
h('span', { class: 'tools' },
@@ -284,7 +439,7 @@
closed ? null : [
r.fields.length ? h('dl', {}, r.fields.map(viewField)) : null,
r.notes ? h('p', { class: 'notes' }, r.notes) : null,
h('p', { class: 'muted small' }, 'Updated ' + r.updated)]);
h('p', { class: 'muted small nosearch' }, 'Updated ' + r.updated)]);
}
function foldBar(entries) {
@@ -302,34 +457,75 @@
const label = q.title + ', step ' + (k + 1);
const layout = hidden ? 'none' : frameLayout(f);
return h('div', { class: 'frame ' + layout },
h('div', { class: 'fnum' }, 'Step ' + (k + 1)),
h('div', { class: 'fnum nosearch' }, 'Step ' + (k + 1)),
hidden ? h('div', {}, h('span', { class: 'secret' }, '(hidden step)'), btn('Show', toggle, 'link', { 'aria-label': 'Show ' + label })) : [
f.image ? h('img', { class: 'fimg', src: f.image, alt: label, tabIndex: 0, title: 'Click to enlarge',
onclick: () => openLightbox(label, f.image), onkeydown: (e) => { if (e.key === 'Enter') openLightbox(label, f.image); } })
f.image ? markedImage(h('img', { class: 'fimg', src: f.image, alt: label, tabIndex: 0, title: 'Click to enlarge',
onclick: () => openLightbox(label, f.image, f.marks), onkeydown: (e) => { if (e.key === 'Enter') openLightbox(label, f.image, f.marks); } }), f.marks)
: h('span', { class: 'muted' }, '(no image)'),
layout !== 'none' ? h('p', { class: 'ftext' }, f.text) : null,
viewUses(f),
f.stop || String(f.ifStuck || '').trim() ? h('div', { class: 'fnotes' },
f.stop ? h('p', { class: 'fstop' }, h('strong', {}, 'Stop here. Do not go further.')) : null,
String(f.ifStuck || '').trim() ? h('p', { class: 'fstuck' }, h('strong', {}, 'If it looks different or fails: '), f.ifStuck) : null) : null,
f.secret ? btn('Hide', toggle, 'link', { 'aria-label': 'Hide ' + label }) : null]);
}
function viewSequence(q) {
return h('article', { class: 'card seq' },
// The credentials a step needs, live from their records: secrets stay masked until shown.
function viewUses(f) {
if (!f.uses || !f.uses.length) return null;
return h('div', { class: 'fuses nosearch' }, h('strong', {}, 'You will need:'), f.uses.map((u) => {
const hit = findFieldRef(state.doc, u);
if (!hit) return h('p', { class: 'muted' }, '(a credential this step used has been removed)');
const fld = hit.field;
const shown = !fld.secret || state.revealed.has(fld);
const toggle = () => { state.revealed[shown ? 'delete' : 'add'](fld); render(); };
return h('div', { class: 'row fuse' },
h('span', {}, hit.record.title + ' \u203A ' + fld.label + ': '),
h('span', { class: fld.secret ? 'secret' : '' }, !fld.value ? '(not set)' : shown ? fld.value : '\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022'),
fld.secret ? btn(shown ? 'Hide' : 'Show', toggle, 'link', { 'aria-label': (shown ? 'Hide ' : 'Show ') + fld.label }) : null,
fld.value ? btn('Copy', () => copyValue(fld), 'small', { 'aria-label': 'Copy ' + fld.label }) : null);
}));
}
const capturedNote = (q) => (q.captured ? ' Captured ' + q.captured + '. The site may have changed since.' : '');
// One step at a time, with Back/Next. A secret step stays hidden until shown, as in the list.
function walkSequence(q) {
const n = q.frames.length;
const k = Math.max(0, Math.min(state.walk.k, n - 1));
const go = (to) => () => { state.walk = { id: q.id, k: to }; render(); };
return h('article', { class: 'card seq walk', 'data-seq': q.id, 'data-eid': q.id },
h('h3', {}, q.title),
q.frames.length ? h('div', { class: 'frames' }, q.frames.map((f, k) => viewFrame(q, f, k))) : h('p', { class: 'muted' }, '(no steps yet)'),
h('p', { class: 'muted small' }, 'Updated ' + q.updated));
viewFrame(q, q.frames[k], k),
h('div', { class: 'row walknav nosearch' },
btn('\u2190 Back', go(k - 1), '', { disabled: k === 0 }),
h('span', { class: 'muted', role: 'status' }, 'Step ' + (k + 1) + ' of ' + n),
btn('Next \u2192', go(k + 1), 'primary', { disabled: k === n - 1 }),
btn('Show all steps', () => { state.walk = null; render(); }, 'link')),
h('p', { class: 'muted small nosearch' }, 'Updated ' + q.updated + '.' + capturedNote(q)));
}
function viewSequence(q) {
if (!state.searchAll && state.walk && state.walk.id === q.id && q.frames.length) return walkSequence(q);
return h('article', { class: 'card seq', 'data-eid': q.id },
h('h3', {}, q.title),
q.frames.length ? btn('Walk through, one step at a time', () => { state.walk = { id: q.id, k: 0 }; render(); }, 'small') : null,
q.frames.length ? h('div', { class: 'frames' }, q.frames.map((f, k) => viewFrame(q, f, k))) : h('p', { class: 'muted nosearch' }, '(no steps yet)'),
h('p', { class: 'muted small nosearch' }, 'Updated ' + q.updated + '.' + capturedNote(q)));
}
const seqItem = (q) => h('li', { class: 'seqitem' }, viewSequence(q));
function viewItem(it, ordered) {
return h('li', { class: 'item ' + it.status },
return h('li', { class: 'item ' + it.status, 'data-eid': it.id },
h('div', {}, h('strong', {}, it.text), ' ', statusBadge(it.status)),
it.detail ? h('p', { class: 'notes' }, it.detail) : null);
}
function viewRecords(s) {
const entries = entriesInTab(s, currentTab(s));
return [tabBar(s),
hasTabs(s) && !entries.length ? h('p', { class: 'muted' }, 'Nothing in this sub-tab yet. Choose Edit to add or move records here.') : null,
foldBar(entries.map((x) => x.e)),
const entries = state.searchAll ? s.records.map((e, i) => ({ e, i })) : entriesInTab(s, currentTab(s));
return [state.searchAll ? null : tabBar(s),
hasTabs(s) && !entries.length ? h('p', { class: 'muted nosearch' }, 'Nothing in this sub-tab yet. Choose Edit to add or move records here.') : null,
state.searchAll ? null : foldBar(entries.map((x) => x.e)),
entries.map(({ e, i }) => (isSequence(e) ? viewSequence(e) : viewRecord(s, e, i)))];
}
@@ -376,7 +572,7 @@
ondragover: (e) => { if (hasFiles(e)) { e.preventDefault(); zone.classList.add('over'); } },
ondragleave: () => zone.classList.remove('over'),
ondrop: (e) => { e.preventDefault(); e.stopPropagation(); zone.classList.remove('over'); onFiles([...e.dataTransfer.files]); } }, attrs),
obj[key] ? h('img', { class: 'fimg', src: obj[key], alt: label }) : null,
obj[key] ? markedImage(h('img', { class: 'fimg', src: obj[key], alt: label }), key === 'image' ? obj.marks : null) : null,
h('p', { class: 'muted small' }, obj[key]
? formatBytes(dataUrlBytes(obj[key])) + '. Drop, paste or choose a file to replace it.'
: 'Drop an image here, paste one while this box is selected, or choose a file.'),
@@ -387,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.
@@ -464,16 +666,45 @@
const LAYOUT_LABELS = [['right', 'Text right of image'], ['under', 'Text under image'], ['none', 'No text']];
// Pick the record fields this step needs; the reader sees them beside the step.
function useEditor(q, f, k) {
const recs = allRecords().filter((r) => r.fields.some((x) => x.kind !== 'image'));
const pick = h('select', { 'aria-label': 'Add a credential to step ' + (k + 1), onchange: () => {
if (!pick.value) return;
const [rid, idx] = pick.value.split('|');
const rec = recs.find((r) => r.id === rid);
if (rec && addUse(f, rec, rec.fields[Number(idx)])) { changed(q); render(); }
} },
h('option', { value: '' }, '+ Use a field from a record\u2026'),
recs.map((r) => h('optgroup', { label: r.title }, r.fields.map((x, i) => (x.kind === 'image' ? null
: h('option', { value: r.id + '|' + i }, x.label + (x.secret ? ' (secret)' : '')))))));
return h('div', {},
h('strong', {}, 'Credentials this step needs'),
(f.uses || []).map((u, i) => {
const hit = findFieldRef(state.doc, u);
return h('div', { class: 'row' },
h('span', {}, hit ? hit.record.title + ' \u203A ' + hit.field.label : '(removed)'),
btn('\u2715', () => { removeUse(f, i); changed(q); render(); }, 'icon danger', { 'aria-label': 'Remove credential from step ' + (k + 1) }));
}),
pick);
}
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) }), () => changed(q)),
f.layout === 'none' ? null : h('label', {}, 'Text', input(f, 'text', { multiline: true, label: 'Text for step ' + (k + 1) }, q)));
(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) }),
f.marks && f.marks.length ? h('span', { class: 'muted small' }, f.marks.length + (f.marks.length === 1 ? ' marker or box' : ' markers and boxes')) : null) : null,
f.layout === 'none' ? null : h('label', {}, 'Text', input(f, 'text', { multiline: true, label: 'Text for step ' + (k + 1) }, q)),
useEditor(q, f, k),
h('label', {}, 'If it looks different or fails', input(f, 'ifStuck', { multiline: true, label: 'If step ' + (k + 1) + ' looks different or fails' }, q)),
h('label', { class: 'check' }, stop, ' Stop here: the reader must not go further without help'));
}
function editSequence(list, q, i, s) {
@@ -487,7 +718,10 @@
q.frames.map((f, k) => editFrame(q, f, k)),
h('div', { class: 'row' },
btn('+ Add step', () => { addFrame(q); changed(q); render(); }, 'small'),
btn('+ Add images\u2026', () => picker.click(), 'small'), picker));
btn('+ Add images\u2026', () => picker.click(), 'small'), picker,
capture && capture.seqId === q.id
? [btn('Capture step', () => captureStep(q), 'primary small'), btn('Stop sharing', () => { endCapture(); setStatus('Stopped sharing.'); render(); }, 'small')]
: btn('Capture from screen\u2026', () => beginCapture(q), 'small', { title: 'Share the window with the site, then capture each screen you want as a step' })));
}
const addSeqBtn = (s) => btn('+ Add visual sequence', () => { addSequence(state.doc, s, s.kind === 'records' ? currentTab(s) : ''); markDirty(); render(); }, 'primary');
@@ -560,62 +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 ? h('img', { class: 'pimg', src: v.image, alt: 'Step ' + (k + 1) })
: 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.layout !== 'none' ? h('p', { class: 'pftext' }, v.text) : null,
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.frames.map((f, k) => printFrame(f, k, includeSecrets)));
q.captured ? h('p', { class: 'pftext' }, 'Captured ' + q.captured + '. The site may have changed since.') : null,
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' },
@@ -625,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();
@@ -681,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 {
@@ -703,10 +1030,19 @@
if (!state.handle) {
state.handle = await window.showSaveFilePicker({ suggestedName: 'final-wishes.html', types: [{ description: 'Final Wishes', accept: { 'text/html': ['.html'] } }] });
}
const w = await state.handle.createWritable();
await w.write(html);
await w.close();
state.status = 'Saved to ' + state.handle.name + '.';
try {
const w = await state.handle.createWritable();
await w.write(html);
await w.close();
state.status = 'Saved to ' + state.handle.name + '.';
} catch (e) {
if (!e || (e.name !== 'NotAllowedError' && e.name !== 'SecurityError')) throw e;
// Chrome created the (empty) file but refuses to write it, e.g. a protected folder.
// Forget the handle so the next Save asks again, and hand over a download instead.
state.handle = null;
downloadFile(html, 'final-wishes.html');
state.status = 'Chrome would not let this page write to the chosen location, so final-wishes.html was downloaded instead. Delete the empty file it left behind and replace your old copy with the download.';
}
state.dirty = false;
snapshot();
} else {
@@ -773,6 +1109,9 @@
}
function render() {
if (capture && !state.editing) endCapture(); // sharing only lasts while editing
if (state.editing) { state.search = null; state.searchOpen = false; } // search is for reading; Edit clears it
const keepFocus = searchEl && searchEl.contains(document.activeElement) ? document.activeElement : null;
root.replaceChildren();
if (!state.doc) return root.append(renderStart());
const onHeader = state.current === HEADER_ID;
@@ -786,18 +1125,176 @@
h('span', { class: 'muted', id: 'version', title: 'Version of this app' }, 'Ver ' + APP_VERSION),
h('span', { id: 'dirty', class: 'badge tbd', hidden: !state.dirty }, 'Unsaved changes'),
h('span', { id: 'status', class: 'muted', role: 'status' }, state.status)),
h('div', { class: 'toolbar' },
// While searching, the search controls take the toolbar's place; Cancel brings the buttons back.
h('div', { class: 'toolbar' }, state.searchOpen ? searchBarEl() : [
btn('Save', () => save(), state.dirty ? 'primary' : ''),
state.editing ? btn('Cancel', cancelEdit, '', { title: 'Discard unsaved changes to this section and stop editing' }) : null,
btn('Backup copy', () => save({ backup: true })),
btn('Change passphrase', changePassphrase),
btn('Print…', openPrintDialog),
btn(state.editing ? 'Done editing' : 'Edit', () => { state.editing = !state.editing; render(); }, state.editing ? 'primary' : ''))),
resetRequested() && !state.resetOffered ? resetBanner() : null,
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"
h('div', { class: 'layout' }, renderNav(),
h('main', {}, onHeader ? [h('h2', {}, 'Print header'), headerPanel()]
: sec ? [h('h2', {}, sec.title), state.editing ? editSection(sec) : viewSection(sec)]
: h('p', { class: 'muted' }, 'No sections yet. Choose Edit to add one.'))));
if (state.searchOpen) updateSearchUi();
if (keepFocus) keepFocus.focus();
highlightSearch();
}
// ---------- search (issue #27) ----------
// The search bar is built once and re-attached on every render(), so what was typed survives.
// Matches are counted in a hidden copy of every section (all sub-tabs, nothing folded) built by
// the same view functions as the page, so the count agrees with what is shown. Secret values,
// buttons, form fields and page furniture are never searched (see SEARCH_SKIP).
const SEARCH_SKIP = 'button,textarea,input,select,script,style,.secret,.nosearch,[hidden]';
let searchEl = null, searchInput = null, searchNote = null, searchBtns = {};
function searchBarEl() {
if (searchEl) return searchEl;
searchInput = h('input', { type: 'search', class: 'searchbox', 'aria-label': 'Search the document', placeholder: 'Search', autocomplete: 'off',
oninput: () => { if (state.search) { state.search = null; clearHighlights(); updateSearchUi(); } },
onkeydown: (e) => {
const found = state.search && state.search.hits.length;
if (e.key === 'Tab' && found) { e.preventDefault(); stepSearch(e.shiftKey ? -1 : 1); }
else if (e.key === 'Enter') {
e.preventDefault();
if (found && state.search.q === searchInput.value.trim()) stepSearch(e.shiftKey ? -1 : 1); else runSearch();
} else if (e.key === 'Escape') cancelSearch();
} });
searchNote = h('span', { class: 'muted small searchnote', role: 'status' });
searchBtns = {
search: btn('Search', runSearch, 'primary'),
prev: btn('\u2190 Previous', () => stepSearch(-1), '', { 'aria-label': 'Previous match' }),
next: btn('Next \u2192', () => stepSearch(1), '', { 'aria-label': 'Next match' }),
cancel: btn('Cancel', cancelSearch),
};
searchEl = h('div', { class: 'searchbar', role: 'search' }, searchInput, searchNote,
searchBtns.search, searchBtns.prev, searchBtns.next, searchBtns.cancel);
return searchEl;
}
function openSearch() {
state.searchOpen = true;
render();
searchInput.focus();
}
function updateSearchUi() {
if (!searchEl) return;
const s = state.search;
const n = s ? s.hits.length : 0;
searchNote.textContent = !s ? '' : n ? (s.i + 1) + ' of ' + n : 'Not found';
searchBtns.prev.disabled = searchBtns.next.disabled = n === 0;
}
// Every text node under `container` that the search may look at.
function searchableText(container) {
const out = [];
const walker = document.createTreeWalker(container, NodeFilter.SHOW_TEXT, {
acceptNode: (n) => (n.parentElement && !n.parentElement.closest(SEARCH_SKIP) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT) });
while (walker.nextNode()) out.push(walker.currentNode);
return out;
}
// Matches under `container`, in order, each labelled with the entry (record, item or
// sequence) it sits in and its count within that entry. '' means section-level text.
function matchesIn(container, q) {
const seen = {};
const out = [];
for (const node of searchableText(container)) {
const ranges = searchRanges(node.nodeValue, q);
if (!ranges.length) continue;
const entry = node.parentElement.closest('[data-eid]');
const eid = entry ? entry.dataset.eid : '';
for (const r of ranges) out.push({ node, start: r.start, end: r.end, eid, n: (seen[eid] = (seen[eid] || 0) + 1) - 1 });
}
return out;
}
function findAllHits(q) {
let host;
state.searchAll = true;
try {
host = h('div', {}, state.doc.sections.map((s) => h('section', { 'data-sid': s.id }, h('h2', {}, s.title), viewSection(s))));
} finally {
state.searchAll = false;
}
const hits = [];
for (const sec of host.querySelectorAll('section[data-sid]')) {
for (const m of matchesIn(sec, q)) hits.push({ sid: sec.dataset.sid, eid: m.eid, n: m.n });
}
return hits;
}
function runSearch() {
const q = searchInput.value.trim();
if (!q) { state.search = null; return render(); }
state.search = { q, hits: findAllHits(q), i: -1 };
if (state.search.hits.length) stepSearch(1); else render();
}
// Cancel: forget the search and put the toolbar buttons back.
function cancelSearch() {
searchInput.value = '';
state.search = null;
state.searchOpen = false;
render();
const again = document.getElementById('searchopen');
if (again) again.focus();
}
// Go to match i: its section, its sub-tab, unfolded, then highlight and scroll to it.
function stepSearch(dir) {
const s = state.search;
if (!s || !s.hits.length) return;
s.i = stepSearchIndex(s.i, dir, s.hits.length);
const hit = s.hits[s.i];
const sec = state.doc.sections.find((x) => x.id === hit.sid);
state.current = hit.sid;
state.walk = null;
if (hit.eid && sec) {
state.collapsed.delete(hit.eid);
const list = [...(sec.records || []), ...(sec.items || []), ...(sec.sequences || [])];
const entry = list.find((x) => x.id === hit.eid);
if (entry && sec.kind === 'records') state.tabs[sec.id] = entryTab(sec, entry);
}
s.scroll = true;
render();
}
function clearHighlights() {
for (const m of root.querySelectorAll('mark.hit')) {
const parent = m.parentNode;
m.replaceWith(...m.childNodes);
parent.normalize();
}
}
// After each render: wrap every match on screen in <mark>, the current one stronger.
function highlightSearch() {
const s = state.search;
if (!s || !s.hits.length || state.current === HEADER_ID) return;
const main = root.querySelector('main');
if (!main) return;
const cur = s.hits[s.i];
const found = matchesIn(main, s.q);
let current = null;
for (let k = found.length - 1; k >= 0; k--) { // last first, so earlier offsets stay valid
const f = found[k];
const range = document.createRange();
range.setStart(f.node, f.start);
range.setEnd(f.node, f.end);
const mark = document.createElement('mark');
mark.className = 'hit' + (cur && state.current === cur.sid && f.eid === cur.eid && f.n === cur.n ? ' cur' : '');
range.surroundContents(mark);
if (mark.classList.contains('cur')) current = mark;
}
if (current && s.scroll) current.scrollIntoView({ block: 'center' });
s.scroll = false;
}
window.addEventListener('hashchange', () => { state.resetOffered = false; render(); });

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

@@ -85,3 +85,92 @@ export async function processImageFile(blob) {
if (bmp.close) bmp.close();
}
}
// Browser only. Screen capture for building a walkthrough: the user shares a
// window or tab, then each grab is one frame. Nothing is recorded or sent anywhere.
export async function startScreenCapture() {
if (!navigator.mediaDevices || !navigator.mediaDevices.getDisplayMedia) {
throw new Error('This browser cannot capture the screen. Take a screenshot and paste it instead.');
}
let stream;
try {
stream = await navigator.mediaDevices.getDisplayMedia({ video: true, audio: false });
} catch (err) {
throw new Error(err && err.name === 'NotAllowedError' ? 'Screen sharing was cancelled.' : 'Screen sharing could not start.');
}
const video = document.createElement('video');
video.srcObject = stream;
video.muted = true;
await video.play();
return { stream, video };
}
export function stopScreenCapture(cap) {
if (cap && cap.stream) cap.stream.getTracks().forEach((t) => t.stop());
}
// The current picture of a started capture, as a PNG blob.
export function grabScreenFrame(cap) {
const v = cap.video;
if (!v.videoWidth || !v.videoHeight) return Promise.reject(new Error('The shared window has no picture yet. Try again in a moment.'));
const canvas = document.createElement('canvas');
canvas.width = v.videoWidth;
canvas.height = v.videoHeight;
canvas.getContext('2d').drawImage(v, 0, 0);
return new Promise((resolve, reject) => canvas.toBlob((b) => (b ? resolve(b) : reject(new Error('Could not grab the picture.'))), 'image/png'));
}
// ---- annotation helpers (issue #25), pure ----
// Marks sit on a frame's picture as fractions of its width and height (0..1), so they
// stay in place however the picture is scaled:
// { type: 'marker', x, y } a numbered circle centred on the point
// { type: 'box', x, y, w, h } a highlight rectangle (x, y = top-left)
// Blur is NOT a mark: it is burned into the picture's pixels (pixelateRegion), so no
// unblurred copy is kept.
export const MARK_TYPES = ['marker', 'box'];
const clamp01 = (v) => Math.min(1, Math.max(0, v));
// A rectangle from two corners (any order), clamped to the picture. null if it is
// too small to mean anything (a stray click).
export function normRect(x0, y0, x1, y1, min = 0.01) {
const ax = clamp01(Math.min(x0, x1)), ay = clamp01(Math.min(y0, y1));
const bx = clamp01(Math.max(x0, x1)), by = clamp01(Math.max(y0, y1));
const w = bx - ax, h = by - ay;
return w < min || h < min ? null : { x: ax, y: ay, w, h };
}
export function isMark(m) {
if (!m || typeof m !== 'object' || !MARK_TYPES.includes(m.type)) return false;
const frac = (v) => typeof v === 'number' && v >= 0 && v <= 1;
if (!frac(m.x) || !frac(m.y)) return false;
if (m.type === 'marker') return true;
return frac(m.w) && frac(m.h) && m.w > 0 && m.h > 0 && m.x + m.w <= 1.0001 && m.y + m.h <= 1.0001;
}
// Block size for blurring a region: coarse enough that small text cannot be read back.
export function blurBlock(w, h) {
return Math.max(12, Math.round(Math.min(w, h) / 3));
}
// Replace each block of rect {x,y,w,h} (pixels) in RGBA `data` (width x height) with its
// average colour, in place. Pixels outside the rectangle are untouched.
export function pixelateRegion(data, width, height, rect, block = blurBlock(rect.w, rect.h)) {
const x0 = Math.max(0, Math.floor(rect.x)), y0 = Math.max(0, Math.floor(rect.y));
const x1 = Math.min(width, Math.ceil(rect.x + rect.w)), y1 = Math.min(height, Math.ceil(rect.y + rect.h));
for (let by = y0; by < y1; by += block) {
for (let bx = x0; bx < x1; bx += block) {
const ex = Math.min(bx + block, x1), ey = Math.min(by + block, y1);
let r = 0, g = 0, b = 0, a = 0, n = 0;
for (let y = by; y < ey; y++) for (let x = bx; x < ex; x++) {
const i = (y * width + x) * 4;
r += data[i]; g += data[i + 1]; b += data[i + 2]; a += data[i + 3]; n++;
}
if (!n) continue;
r = Math.round(r / n); g = Math.round(g / n); b = Math.round(b / n); a = Math.round(a / n);
for (let y = by; y < ey; y++) for (let x = bx; x < ex; x++) {
const i = (y * width + x) * 4;
data[i] = r; data[i + 1] = g; data[i + 2] = b; data[i + 3] = a;
}
}
}
}

View File

@@ -1,4 +1,4 @@
import { isImageDataUrl, MAX_IMAGE_DATA_CHARS } from './images.js';
import { isImageDataUrl, MAX_IMAGE_DATA_CHARS, isMark } from './images.js';
// Data model for the document (plaintext JSON before encryption).
// Pure functions, no DOM; runs in browsers and Node. build.js strips `export`.
@@ -24,12 +24,26 @@ import { isImageDataUrl, MAX_IMAGE_DATA_CHARS } 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
// { type:'box', x, y, w, h }, all fractions 0..1 of the picture
// uses?: [{ record: <record id>, field: <field id> }] credentials this step needs,
// shown beside the step with Show/Hide and Copy. A reference
// that no longer resolves is shown as missing, never an error.
// A record Field may carry `id` (unique within its record): assigned the first time a step
// references it, so the reference survives reordering and renaming the field.
// A sequence may also carry `captured: 'YYYY-MM-DD'`, set when a step is captured from the screen.
// A sequence lives in the same ordered list as the records (records sections) or
// items (steps / checklist sections), so it sits wherever the user puts it, but it
// is not a record or an item (no number, no tick box). A 'text' section keeps its
@@ -165,12 +179,19 @@ export function validate(doc) {
if (!DATE_RE.test(r.updated ?? '')) errs.push(`${where}: updated must be YYYY-MM-DD`);
if (r.notes !== undefined && !isStr(r.notes)) errs.push(`${where}: notes must be a string`);
if (!Array.isArray(r.fields)) return errs.push(`${where}: fields must be an array`);
const fieldIds = new Set();
r.fields.forEach((f, k) => {
const fw = `${where}.fields[${k}]`;
if (!isObj(f)) return errs.push(`${fw}: must be an object`);
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}"`);
else fieldIds.add(f.id);
}
if (f.kind !== undefined && !FIELD_KINDS.includes(f.kind)) errs.push(`${fw}: unknown kind "${f.kind}"`);
if (f.kind === 'image' && isStr(f.value) && f.value !== '' && !isImageDataUrl(f.value)) {
errs.push(`${fw}: image must be a PNG or JPEG under ${Math.round(MAX_IMAGE_DATA_CHARS / 1e6)} MB`);
@@ -178,12 +199,19 @@ 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);
if (q.kind !== 'sequence') errs.push(`${where}: kind must be "sequence"`);
if (!isStr(q.title) || !q.title) errs.push(`${where}: missing title`);
if (!DATE_RE.test(q.updated ?? '')) errs.push(`${where}: updated must be YYYY-MM-DD`);
if (q.captured !== undefined && !DATE_RE.test(q.captured)) errs.push(`${where}: captured must be YYYY-MM-DD`);
if (!Array.isArray(q.frames)) return errs.push(`${where}: frames must be an array`);
q.frames.forEach((f, k) => {
const fw = `${where}.frames[${k}]`;
@@ -193,6 +221,19 @@ 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) {
if (!Array.isArray(f.marks)) errs.push(`${fw}: marks must be an array`);
else f.marks.forEach((m, n) => { if (!isMark(m)) errs.push(`${fw}.marks[${n}]: not a valid marker or box`); });
}
if (f.uses !== undefined) {
if (!Array.isArray(f.uses)) errs.push(`${fw}: uses must be an array`);
else f.uses.forEach((u, m) => {
if (!isObj(u) || !isStr(u.record) || !u.record || !isStr(u.field) || !u.field) errs.push(`${fw}.uses[${m}]: needs record and field ids`);
});
}
});
}

View File

@@ -180,11 +180,24 @@ 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) {
let n = 0;
const frames = (q) => { for (const f of q.frames) if (f.secret && (f.image || String(f.text || '').trim())) { f.image = ''; f.text = ''; n++; } };
const frames = (q) => { for (const f of q.frames) if (f.secret && (f.image || String(f.text || '').trim() || String(f.ifStuck || '').trim())) { f.image = ''; delete f.marks; f.text = ''; if (f.ifStuck) f.ifStuck = ''; n++; } };
for (const s of doc.sections) {
for (const r of s.records || []) {
if (isSequence(r)) frames(r);
@@ -217,6 +230,61 @@ export function addFrame(seq, image = '', layout = 'under') {
return f;
}
// ---- credential references from steps (issue #24) ----
// Every record in the document, wherever it sits (sequences are not records).
export function allRecordsIn(doc) {
return doc.sections.flatMap((s) => (s.records || []).filter((r) => !isSequence(r)));
}
// A field gets an id the first time something references it. Returns it.
export function ensureFieldId(record, field) {
if (field.id) return field.id;
const taken = new Set(record.fields.map((f) => f.id).filter(Boolean));
let n = record.fields.length + 1;
while (taken.has('f' + n)) n++;
field.id = 'f' + n;
return field.id;
}
// { record, field } for a reference, or null if either is gone or the field is an image.
export function findFieldRef(doc, ref) {
const record = allRecordsIn(doc).find((r) => r.id === ref.record);
const field = record && record.fields.find((f) => f.id === ref.field && f.kind !== 'image');
return field ? { record, field } : null;
}
// Add a reference to `frame` for `field` of `record`; no duplicates. Returns true if added.
export function addUse(frame, record, field) {
const ref = { record: record.id, field: ensureFieldId(record, field) };
frame.uses = frame.uses || [];
if (frame.uses.some((u) => u.record === ref.record && u.field === ref.field)) return false;
frame.uses.push(ref);
return true;
}
export function removeUse(frame, i) {
frame.uses.splice(i, 1);
if (!frame.uses.length) delete frame.uses;
}
// A step captured from the screen: a new frame, and the sequence remembers when,
// so the reader can be told the site may have changed since.
export function addCapture(seq, image) {
const f = addFrame(seq, image);
seq.captured = today();
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,27 +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) {
const hasContent = !!(frame.image || String(frame.text || '').trim());
const withheld = !!frame.secret && !includeSecrets && hasContent;
export function frameView(frame, mode) {
const hasContent = !!(frame.image || String(frame.text || '').trim() || String(frame.ifStuck || '').trim());
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,
text: withheld ? '' : m(frame.text),
ifStuck: withheld ? '' : m(String(frame.ifStuck || '').trim()),
stop: withheld ? false : !!frame.stop,
layout: withheld ? 'none' : frameLayout(frame),
};
}
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())) n++; };
// What a step's credential references show: [{ label, record, value, secret, missing }].
// 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, 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, mode), secret: !!f.secret, missing: false }
: { label: '', record: '', value: '', secret: false, missing: true };
});
}
// 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;
}

24
src/search.js Normal file
View File

@@ -0,0 +1,24 @@
// Pure helpers for the search bar (issue #27). No DOM; tested in Node.
// build.js strips `export` when bundling, so names here must not collide with other modules.
// Where `query` occurs in `text`, ignoring case: [{ start, end }], left to right, not overlapping.
// A blank query matches nothing.
export function searchRanges(text, query) {
const q = String(query || '').trim();
if (!q) return [];
const re = new RegExp(q.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi');
const out = [];
let m;
while ((m = re.exec(String(text))) !== null) {
out.push({ start: m.index, end: m.index + m[0].length });
if (m[0].length === 0) re.lastIndex++; // cannot happen for a non-empty query; never loop forever
}
return out;
}
// The next index when stepping `dir` (+1 or -1) through `count` places, wrapping round.
// -1 when there is nowhere to go.
export function stepSearchIndex(i, dir, count) {
if (count <= 0) return -1;
return (((i + dir) % count) + count) % count;
}

View File

@@ -58,6 +58,20 @@ textarea { width: 100%; display: block; } label { display: block; margin-top: .5
.frame.right { grid-template-columns: minmax(0, 3fr) minmax(0, 2fr); } .frame .fimg { margin: 0; }
.fnum { font-weight: 700; color: var(--accent); } .ftext { white-space: pre-wrap; margin: 0; }
li.seqitem { display: block; list-style: none; margin-left: -1.4rem; } .frameedit { border-top: 1px dashed var(--line); padding-top: .5rem; }
.fnotes { grid-column: 1 / -1; display: grid; gap: .35rem; } .fnotes p { margin: 0; }
.marked { position: relative; display: block; width: fit-content; max-width: 100%; line-height: 0; }
.mbox { position: absolute; box-sizing: border-box; border: 3px solid #e11; box-shadow: 0 0 0 1px #fff; border-radius: 3px; pointer-events: none; }
.mpin { position: absolute; box-sizing: border-box; transform: translate(-50%, -50%); width: 1.6rem; height: 1.6rem; border-radius: 50%; background: #e11; color: #fff; border: 2px solid #fff; font: 700 .85rem/1.2rem system-ui, sans-serif; text-align: center; pointer-events: none; }
.annotator { max-width: min(95vw, 70rem); } .annot { display: block; max-width: 100%; max-height: 65vh; margin: .5rem auto; cursor: crosshair; touch-action: none; border: 1px solid var(--line); }
.searchbar { display: flex; flex: 1 1 100%; flex-wrap: wrap; gap: .5rem; align-items: center; }
.searchbox { flex: 1 1 14rem; min-width: 8rem; font: inherit; padding: .4rem .6rem; line-height: 1.2; border: 1px solid var(--line); border-radius: .4rem; background: var(--card); color: var(--fg); }
.searchnote { min-width: 4.5rem; text-align: right; }
mark.hit { background: var(--warn-bg); color: var(--warn-fg); border-radius: .2rem; padding: 0 .1em; }
mark.hit.cur { background: var(--accent); color: var(--bg); outline: 2px solid var(--accent); }
.fuses { grid-column: 1 / -1; } .fuse { align-items: center; margin: .25rem 0; }
.fstop { border: 2px solid var(--danger); color: var(--danger); border-radius: .35rem; padding: .35rem .6rem; }
.fstuck { background: var(--warn-bg); color: var(--warn-fg); border-radius: .35rem; padding: .35rem .6rem; white-space: pre-wrap; }
.walk .fimg { max-height: 28rem; } .walknav { align-items: center; margin-top: .75rem; }
@media (max-width: 700px) { .frame.right { grid-template-columns: minmax(0, 1fr); } }
dialog.lightbox { max-width: 92vw; max-height: 92vh; overflow: auto; } .bigimg { display: block; max-width: 100%; max-height: 75vh; margin: 0 auto .75rem; background: #fff; }
@@ -86,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; }
@@ -101,6 +118,8 @@ dialog.lightbox { max-width: 92vw; max-height: 92vh; overflow: auto; } .bigimg {
.pframe { break-inside: avoid; display: grid; grid-template-columns: minmax(0, 1fr); gap: 3pt 12pt; align-items: start; margin: 0 0 10pt; }
.pframe.right { grid-template-columns: 3.9in minmax(0, 1fr); } .pframe.right .pimg { max-height: 3.4in; }
.pfnum { grid-column: 1 / -1; font: 700 9.5pt system-ui, sans-serif; break-after: avoid; } .pframe p { margin: 0; } .pftext { white-space: pre-wrap; }
.marked { break-inside: avoid; } .mbox { border: 2pt solid #e11; box-shadow: none; } .mpin { width: 14pt; height: 14pt; font: 700 8pt/10pt system-ui, sans-serif; background: #e11; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
.pstop { grid-column: 1 / -1; border: 1.5pt solid #000; padding: 2pt 5pt; }
.psecret { font-family: ui-monospace, Consolas, monospace; }
.ptag { font: 700 8pt system-ui, sans-serif; border: 1pt solid #000; padding: 0 4pt; margin-left: 8pt; border-radius: 2pt; vertical-align: middle; }
.pnotes, .pbody, .pintro { white-space: pre-wrap; margin: 4pt 0 0; }
@@ -110,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 = '261123A';
export const APP_VERSION = '261201A';
const VERSION_RE = /^(\d{6})([A-Z])$/;
export const isVersion = (v) => typeof v === 'string' && VERSION_RE.test(v);

View File

@@ -13,7 +13,7 @@ const repo = join(dirname(fileURLToPath(import.meta.url)), '..');
test('needsBump: only app changes, and only if the version was not already bumped', () => {
assert.equal(needsBump(['src/app.js'], '261109A', '261109A'), true);
assert.equal(needsBump(['build.js'], '261109A', '261109A'), true);
assert.equal(needsBump(['README.md', 'docs/MAINTENANCE.md', 'test/x.test.js', 'OVERVIEW.md'], '261109A', '261109A'), false);
assert.equal(needsBump(['README.md', 'docs/thumbdrive/README.txt', 'test/x.test.js', 'OVERVIEW.md'], '261109A', '261109A'), false);
assert.equal(needsBump(['src/version.js'], '261109A', '261109A'), false);
assert.equal(needsBump(['src/app.js', 'src/version.js'], '261109A', '261109B'), false); // already bumped by hand
assert.equal(needsBump(['src/app.js'], null, '261109A'), false); // first commit of the file

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

@@ -86,3 +86,41 @@ test('displayValue for images: masked when secret, never the data itself', () =>
assert.equal(displayValue({ ...img, value: '' }, false), '(no image)');
assert.equal(countSecrets(docWithField({ ...img, secret: true })), 1);
});
import { normRect, isMark, blurBlock, pixelateRegion } from '../src/images.js';
test('normRect orders corners, clamps to the picture, drops stray clicks', () => {
assert.deepEqual(normRect(0.5, 0.6, 0.2, 0.1), { x: 0.2, y: 0.1, w: 0.3, h: 0.5 });
const c = normRect(-1, -1, 2, 0.5);
assert.deepEqual([c.x, c.y, c.w, c.h], [0, 0, 1, 0.5]);
assert.equal(normRect(0.5, 0.5, 0.503, 0.9), null);
});
test('isMark accepts markers and boxes inside the picture only', () => {
assert.equal(isMark({ type: 'marker', x: 0.5, y: 0.5 }), true);
assert.equal(isMark({ type: 'box', x: 0.1, y: 0.1, w: 0.5, h: 0.5 }), true);
assert.equal(isMark({ type: 'box', x: 0.6, y: 0.1, w: 0.5, h: 0.5 }), false); // runs off the right edge
assert.equal(isMark({ type: 'box', x: 0.1, y: 0.1, w: 0, h: 0.5 }), false);
assert.equal(isMark({ type: 'marker', x: 2, y: 0.5 }), false);
assert.equal(isMark({ type: 'blur', x: 0.1, y: 0.1, w: 0.2, h: 0.2 }), false);
assert.equal(isMark(null), false);
});
test('pixelateRegion averages blocks inside the rectangle and leaves the rest alone', () => {
const W = 40, H = 30;
const data = new Uint8ClampedArray(W * H * 4);
for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) { // a pattern with detail in every pixel
const i = (y * W + x) * 4; data[i] = (x * 37 + y * 11) % 256; data[i + 1] = (x * 5) % 256; data[i + 2] = (y * 9) % 256; data[i + 3] = 255;
}
const before = Uint8ClampedArray.from(data);
pixelateRegion(data, W, H, { x: 10, y: 5, w: 24, h: 20 }, 12);
const px = (a, x, y) => [...a.slice((y * W + x) * 4, (y * W + x) * 4 + 4)].join();
assert.equal(px(data, 10, 5), px(data, 21, 16)); // same 12x12 block, same colour
assert.notEqual(px(data, 10, 5), px(data, 22, 5)); // next block differs
assert.notEqual(px(data, 12, 7), px(before, 12, 7)); // detail is gone
assert.equal(px(data, 9, 5), px(before, 9, 5)); // left of the rectangle: untouched
assert.equal(px(data, 34, 5), px(before, 34, 5)); // right of it
assert.equal(px(data, 15, 25), px(before, 15, 25)); // below it
// total of each channel inside a block is preserved up to rounding (it is an average)
assert.ok(blurBlock(300, 14) >= 12 && blurBlock(900, 600) === 200);
});

View File

@@ -104,6 +104,13 @@ test('sequence validation: layout, image, text, secret, id, title', () => {
bad((x) => { x.frames[0].image = 5; }, /image must be a string/);
bad((x) => { x.frames[0].text = null; }, /text must be a string/);
bad((x) => { x.frames[0].secret = 'yes'; }, /secret must be a boolean/);
bad((x) => { x.frames[0].marks = 'no'; }, /marks must be an array/);
bad((x) => { x.frames[0].marks = [{ type: 'box', x: 0.9, y: 0, w: 0.5, h: 0.5 }]; }, /not a valid marker or box/);
const okm = structuredClone(d); okm.sections[0].records[1].frames[0].marks = [{ type: 'marker', x: 0.3, y: 0.4 }, { type: 'box', x: 0.1, y: 0.1, w: 0.2, h: 0.2 }];
assert.deepEqual(validate(okm), []);
bad((x) => { x.frames[0].ifStuck = 5; }, /ifStuck must be a string/);
bad((x) => { x.frames[0].stop = 'yes'; }, /stop must be a boolean/);
bad((x) => { x.captured = 'yesterday'; }, /captured must be YYYY-MM-DD/);
bad((x) => { x.title = ''; }, /missing title/);
bad((x) => { x.id = d.sections[0].records[0].id; }, /duplicate id/);
bad((x) => { delete x.frames; }, /frames must be an array/);
@@ -116,8 +123,11 @@ test('frameLayout hides empty text; frameView withholds secret frames only when
assert.equal(frameLayout({ layout: 'right', text: 'x' }), 'right');
assert.equal(frameLayout({ layout: 'none', text: 'x' }), 'none');
const f = { image: PNG, text: 'pw is hunter2', layout: 'under', secret: true };
assert.deepEqual(frameView(f, false), { withheld: true, image: '', text: '', layout: 'none' });
assert.deepEqual(frameView(f, false), { withheld: true, image: '', text: '', ifStuck: '', stop: false, layout: 'none' });
assert.equal(frameView(f, true).text, 'pw is hunter2');
const g = { image: PNG, text: '', layout: 'none', ifStuck: ' call 555-0100 ', stop: true };
assert.deepEqual([frameView(g, false).ifStuck, frameView(g, false).stop], ['call 555-0100', true]);
assert.deepEqual([frameView({ ...g, secret: true }, false).ifStuck, frameView({ ...g, secret: true }, false).stop], ['', false]);
assert.equal(frameView({ image: '', text: '', layout: 'under', secret: true }, false).withheld, false);
});
@@ -160,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

@@ -345,3 +345,86 @@ test('clearSecrets erases secret fields and frames, keeps the rest, returns the
assert.deepEqual(validate(doc), []);
assert.equal(clearSecrets(doc), 0);
});
test('addCapture adds a frame and stamps the sequence captured date; clearSecrets clears ifStuck on secret steps', async () => {
const { addCapture, clearSecrets, addSequence } = await import('../src/ops.js');
const doc = emptyDocument('x');
const s = addSection(doc, 'records', 'Banking');
const q = addSequence(doc, s);
assert.equal(q.captured, undefined);
const f = addCapture(q, '');
assert.equal(q.frames.length, 1);
assert.equal(f.layout, 'under');
assert.match(q.captured, /^\d{4}-\d{2}-\d{2}$/);
f.secret = true; f.ifStuck = 'call 555-0100'; f.stop = true; f.image = 'data:image/png;base64,AAAA'; f.marks = [{ type: 'marker', x: 0.5, y: 0.5 }];
assert.equal(clearSecrets(doc), 1);
assert.equal(f.marks, undefined);
assert.equal(f.ifStuck, '');
assert.equal(f.stop, true);
assert.deepEqual(validate(doc), []);
});
test('credential references: field ids are stable, refs resolve, missing ones are detected', async () => {
const { addUse, removeUse, findFieldRef, ensureFieldId, addSequence, addFrame } = await import('../src/ops.js');
const { usesView } = await import('../src/print.js');
const doc = emptyDocument('x');
const s = addSection(doc, 'records', 'Banking');
const r = addRecord(doc, s);
addField(r); addField(r);
r.fields[0].label = 'User'; r.fields[0].value = 'bob';
r.fields[1].label = 'Password'; r.fields[1].value = 'hunter2'; r.fields[1].secret = true;
const q = addSequence(doc, s);
const fr = addFrame(q);
assert.equal(addUse(fr, r, r.fields[1]), true);
assert.equal(addUse(fr, r, r.fields[1]), false); // no duplicates
addUse(fr, r, r.fields[0]);
assert.equal(ensureFieldId(r, r.fields[1]), r.fields[1].id); // stable
assert.notEqual(r.fields[0].id, r.fields[1].id);
assert.deepEqual(validate(doc), []);
const moved = r.fields.reverse(); // reorder: references still resolve
assert.equal(findFieldRef(doc, fr.uses[0]).field.label, 'Password');
assert.deepEqual(usesView(doc, fr, false).map((u) => [u.label, u.value]), [['Password', '[withheld]'], ['User', 'bob']]);
assert.equal(usesView(doc, fr, true)[0].value, 'hunter2');
r.fields.splice(0, 1); // delete the password field
assert.equal(findFieldRef(doc, fr.uses[0]), null);
assert.equal(usesView(doc, fr, true)[0].missing, true);
assert.deepEqual(validate(doc), []); // a dangling reference is not an error
removeUse(fr, 0); removeUse(fr, 0);
assert.equal(fr.uses, undefined);
});
test('validation: uses and field ids', async () => {
const { addSequence, addFrame } = await import('../src/ops.js');
const doc = emptyDocument('x');
const s = addSection(doc, 'records', 'B');
const r = addRecord(doc, s); addField(r); addField(r);
const q = addSequence(doc, s); const fr = addFrame(q);
const bad = (mut, re) => { const c = structuredClone(doc); mut(c.sections[0]); assert.match(validate(c).join('|'), re); };
bad((x) => { x.records[1].frames[0].uses = 'no'; }, /uses must be an array/);
bad((x) => { x.records[1].frames[0].uses = [{ record: 'a' }]; }, /needs record and field ids/);
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);
});

62
test/sanitize.test.js Normal file
View File

@@ -0,0 +1,62 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
import { mkdtempSync, writeFileSync, readFileSync, existsSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { encrypt, decrypt } from '../src/crypto.js';
import { assemble } from '../src/template.js';
import { sanitize, extractPayload } from '../sanitize.js';
const SECRET = 'hunter2-SENTINEL-9431';
const OLD = 'the real long passphrase';
const NEW = 'a throwaway passphrase';
const doc = {
schemaVersion: 1,
meta: { owner: 'O', title: 'T', lastUpdated: '2022-04-14' },
sections: [{ id: 's', title: 'S', kind: 'records', records: [
{ id: 'r', title: 'Acct', status: 'ok', updated: '2022-04-14',
fields: [{ label: 'PW', value: SECRET, secret: true }, { label: 'Bank', value: 'First Bank' }] }] }],
};
const fast = 1000; // PBKDF2 iterations, tests only
async function realFile() {
return assemble({ css: 'x', js: 'y', payload: await encrypt(JSON.stringify(doc), OLD, fast) });
}
test('erases secrets, keeps the rest, re-seals under the new passphrase', async () => {
const html = await realFile();
const r = await sanitize({ html, oldPass: OLD, newPass: NEW, css: 'newcss', js: 'newjs', iterations: fast });
assert.equal(r.erased, 1);
assert.ok(!r.html.includes(SECRET));
assert.ok(r.html.includes('newcss') && r.html.includes('newjs'));
const out = JSON.parse(await decrypt(extractPayload(r.html), NEW));
assert.equal(out.sections[0].records[0].fields[0].value, '');
assert.equal(out.sections[0].records[0].fields[0].secret, true);
assert.equal(out.sections[0].records[0].fields[1].value, 'First Bank');
assert.deepEqual(r.left.map((s) => [s.title, s.text]), [['S', 1]]);
await assert.rejects(decrypt(extractPayload(r.html), OLD));
});
test('refuses the same passphrase, a weak one, or a wrong old one', async () => {
const html = await realFile();
await assert.rejects(sanitize({ html, oldPass: OLD, newPass: OLD, css: '', js: '', iterations: fast }), /different passphrase/);
await assert.rejects(sanitize({ html, oldPass: OLD, newPass: 'short', css: '', js: '', iterations: fast }), /New passphrase/);
await assert.rejects(sanitize({ html, oldPass: 'wrong wrong wrong', newPass: NEW, css: '', js: '', iterations: fast }), /Wrong passphrase/);
});
test('CLI: writes a new file, leaves the input alone, refuses in == out', async () => {
const dir = mkdtempSync(join(tmpdir(), 'fw-san-'));
const inp = join(dir, 'real.html'), out = join(dir, 'copy.html');
const html = await realFile();
writeFileSync(inp, html);
const env = { ...process.env, FW_PASSPHRASE: OLD, FW_NEW_PASSPHRASE: NEW };
const bad = spawnSync('node', ['sanitize.js', '--in', inp, '--out', inp], { env, encoding: 'utf8' });
assert.notEqual(bad.status, 0);
assert.match(bad.stderr, /different file/);
const ok = spawnSync('node', ['sanitize.js', '--in', inp, '--out', out], { env, encoding: 'utf8' });
assert.equal(ok.status, 0, ok.stderr);
assert.match(ok.stdout, /Erased 1 secret value/);
assert.ok(existsSync(out));
assert.equal(readFileSync(inp, 'utf8'), html);
assert.ok(!readFileSync(out, 'utf8').includes(SECRET));
});

29
test/search.test.js Normal file
View File

@@ -0,0 +1,29 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { searchRanges, stepSearchIndex } from '../src/search.js';
test('searchRanges is case-insensitive and finds every place', () => {
assert.deepEqual(searchRanges('Bitwarden, BITWARDEN and bitwarden.', 'bitwarden'),
[{ start: 0, end: 9 }, { start: 11, end: 20 }, { start: 25, end: 34 }]);
assert.deepEqual(searchRanges('Santander', 'BitWarden'), []);
});
test('searchRanges treats the query as plain text, ignores outer spaces, and blank matches nothing', () => {
assert.deepEqual(searchRanges('a.b (c) a.b', 'a.b'), [{ start: 0, end: 3 }, { start: 8, end: 11 }]);
assert.deepEqual(searchRanges('axb', 'a.b'), []); // "." is not a wildcard
assert.deepEqual(searchRanges('(c) [d] $5 ^ \\', '(c)'), [{ start: 0, end: 3 }]);
assert.equal(searchRanges('x', '[').length, 0); // a stray bracket must not throw
assert.deepEqual(searchRanges('go bitwarden go', ' bitwarden '), [{ start: 3, end: 12 }]);
assert.deepEqual(searchRanges('anything', ''), []);
assert.deepEqual(searchRanges('anything', ' '), []);
assert.deepEqual(searchRanges('aaaa', 'aa'), [{ start: 0, end: 2 }, { start: 2, end: 4 }]); // no overlap
});
test('stepSearchIndex wraps both ways and handles no results', () => {
assert.equal(stepSearchIndex(0, 1, 3), 1);
assert.equal(stepSearchIndex(2, 1, 3), 0);
assert.equal(stepSearchIndex(0, -1, 3), 2);
assert.equal(stepSearchIndex(0, 1, 1), 0);
assert.equal(stepSearchIndex(-1, 1, 3), 0); // nothing current yet: forward goes to the first
assert.equal(stepSearchIndex(0, 1, 0), -1);
});