From eeba5d00dbe3d84815a1606bb600f334bb75aa26 Mon Sep 17 00:00:00 2001 From: Eric Bell Date: Mon, 30 Nov 2026 20:15:47 -0500 Subject: [PATCH] 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 --- OVERVIEW.md | 4 +-- README.md | 13 ++++--- docs/thumbdrive/README.txt | 2 ++ src/app.js | 71 +++++++++++++++++++++----------------- src/model.js | 16 +++++++-- src/ops.js | 13 +++++++ src/print.js | 51 ++++++++++++++++++++------- test/model.test.js | 11 ++++++ test/ops.test.js | 23 ++++++++++++ test/print.test.js | 65 ++++++++++++++++++++++++++++++++++ 10 files changed, 218 insertions(+), 51 deletions(-) diff --git a/OVERVIEW.md b/OVERVIEW.md index 28cd797..3092aaa 100644 --- a/OVERVIEW.md +++ b/OVERVIEW.md @@ -61,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. @@ -80,7 +80,7 @@ A **visual sequence** (`kind: 'sequence'`, numbered `frames` of image + text wit **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 `` whose `` 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 `
` whose `` 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 three views (issue #29): "withhold secrets" (default, mode `masked`), "lawyer's view" (`lawyer`: shows secrets flagged `lawyer: true`, still withholds plain secrets) and "include secrets" (`complete`). `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 diff --git a/README.md b/README.md index 9b9d155..0d6499b 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ The passphrase is prompted for (hidden) or read from `FW_PASSPHRASE`. - `src/version.js` the version shown at the top (`Ver YYMMDDX`); `npm run bump` advances it by hand; a pre-commit hook (`npm run hooks` once per clone) does it on every commit that changes the app -- `src/print.js` print helpers (secret masking, header layout) +- `src/print.js` print helpers (secret masking in three views, header layout) - `src/app.js` + `src/style.css` the UI, including the Print header panel - `src/template.js` the HTML skeleton shared by `build.js` and in-page Save - `docs/thumbdrive/` what goes on the drive alongside the HTML file @@ -135,7 +135,7 @@ Standard, Online and Credit Union. Other kinds of section don't have them. ## Images Any record can hold pictures (scans of documents, photos of a safe's contents, a screenshot of where to click). They are another kind of field, so -they have a label, a **secret** checkbox, reorder arrows and a delete button +they have a label, a **Normal / Lawyer / Secret** choice, reorder arrows and a delete button like any other field. In **Edit** mode, add one of three ways: - **+ Add image...** in the record, then choose one or more files. @@ -295,8 +295,13 @@ Documents made by older versions keep working: anything a newer version added LastPass master password. ## Printing -**Print...** offers "Withhold secrets" (safe overview) and "Include -secrets" (full copy). Print on Letter paper with the browser's own +**Print...** offers "Withhold secrets" (safe overview), "Lawyer's view" 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. A lawyer's-view copy is still sensitive, so store it 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 diff --git a/docs/thumbdrive/README.txt b/docs/thumbdrive/README.txt index 00235f7..54e9c62 100644 --- a/docs/thumbdrive/README.txt +++ b/docs/thumbdrive/README.txt @@ -22,6 +22,8 @@ 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. - "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 diff --git a/src/app.js b/src/app.js index d256fd2..97f1cf2 100644 --- a/src/app.js +++ b/src/app.js @@ -583,22 +583,28 @@ return zone; } + // Normal / Lawyer / Secret chooser for a field or step (replaces the old "secret" checkbox). + const LEVELS = [['normal', 'Normal'], ['lawyer', 'Lawyer'], ['secret', 'Secret']]; + function levelSelect(x, label, onChange) { + const sel = h('select', { 'aria-label': label, onchange: () => { setLevel(x, sel.value); onChange(); } }, + LEVELS.map(([v, t]) => h('option', { value: v, selected: levelOf(x) === v }, t))); + return h('label', { class: 'check' }, sel); + } + function editImageField(r, f, i) { - const secret = h('input', { type: 'checkbox', checked: !!f.secret, 'aria-label': 'Secret', - onchange: () => { f.secret = secret.checked || undefined; if (!f.secret) delete f.secret; changed(r); } }); + const secret = levelSelect(f, 'Visibility of ' + (f.label || 'image field'), () => changed(r)); const zone = imageZone(f, 'value', f.label, { 'data-field': String(i) }, (files) => importFiles(r, files, { replace: f }), () => changed(r)); return h('div', { class: 'field imagefield' }, - h('div', { class: 'row' }, input(f, 'label', { label: 'Field label' }, r), h('label', { class: 'check' }, secret, ' secret'), rowTools(r.fields, i, 'image field', r)), + h('div', { class: 'row' }, input(f, 'label', { label: 'Field label' }, r), secret, rowTools(r.fields, i, 'image field', r)), zone); } function editField(r, f, i) { if (f.kind === 'image') return editImageField(r, f, i); - const secret = h('input', { type: 'checkbox', checked: !!f.secret, 'aria-label': 'Secret', - onchange: () => { f.secret = secret.checked || undefined; if (!f.secret) delete f.secret; changed(r); } }); + const secret = levelSelect(f, 'Visibility of ' + (f.label || 'field'), () => changed(r)); return h('div', { class: 'row field' }, input(f, 'label', { label: 'Field label' }, r), input(f, 'value', { label: 'Field value' }, r), - h('label', { class: 'check' }, secret, ' secret'), rowTools(r.fields, i, 'field', r)); + secret, rowTools(r.fields, i, 'field', r)); } // "Sub-tab: [select]" for a record or sequence; changing it moves the entry to that tab. @@ -684,14 +690,13 @@ } function editFrame(q, f, k) { - const secret = h('input', { type: 'checkbox', checked: !!f.secret, 'aria-label': 'Secret step', - onchange: () => { f.secret = secret.checked || undefined; if (!f.secret) delete f.secret; changed(q); } }); + const secret = levelSelect(f, 'Visibility of step ' + (k + 1), () => changed(q)); const stop = h('input', { type: 'checkbox', checked: !!f.stop, 'aria-label': 'Stop here, step ' + (k + 1), onchange: () => { f.stop = stop.checked || undefined; if (!f.stop) delete f.stop; changed(q); } }); const layout = h('select', { 'aria-label': 'Text position for step ' + (k + 1), onchange: () => { f.layout = layout.value; changed(q); render(); } }, LAYOUT_LABELS.map(([v, t]) => h('option', { value: v, selected: f.layout === v }, t))); return h('div', { class: 'field imagefield frameedit' }, - h('div', { class: 'row' }, h('strong', {}, 'Step ' + (k + 1)), layout, h('label', { class: 'check' }, secret, ' secret'), rowTools(q.frames, k, 'step', q)), + h('div', { class: 'row' }, h('strong', {}, 'Step ' + (k + 1)), layout, secret, rowTools(q.frames, k, 'step', q)), imageZone(f, 'image', q.title + ', step ' + (k + 1), { 'data-frame': String(k) }, (files) => importFiles(q, files, { key: 'image', replace: f, add: addFrameFrom(q) }), () => { if (!f.image) delete f.marks; changed(q); }), f.image ? h('div', { class: 'row' }, btn('Mark up picture\u2026', () => openAnnotator(q, f), 'small', { 'aria-label': 'Mark up the picture for step ' + (k + 1) }), @@ -789,37 +794,37 @@ const box = (status) => h('span', { class: 'cb ' + status, 'aria-hidden': 'true' }, status === 'done' ? '✓' : ''); // Text, or the picture itself for a visible image field. - function printCell(f, includeSecrets) { - if (f.kind === 'image' && f.value && (!f.secret || includeSecrets)) return h('img', { class: 'pimg', src: f.value, alt: f.label }); - return displayValue(f, includeSecrets); + function printCell(f, mode) { + if (f.kind === 'image' && f.value && !isHidden(f, mode)) return h('img', { class: 'pimg', src: f.value, alt: f.label }); + return displayValue(f, mode); } - function printFrame(f, k, includeSecrets) { - const v = frameView(f, includeSecrets); + function printFrame(f, k, mode) { + const v = frameView(f, mode); return h('div', { class: 'pframe ' + v.layout }, h('div', { class: 'pfnum' }, 'Step ' + (k + 1)), v.withheld ? h('p', { class: 'psecret' }, '[withheld]') : v.image ? markedImage(h('img', { class: 'pimg', src: v.image, alt: 'Step ' + (k + 1) }), f.marks) : h('p', {}, '(no image)'), v.layout !== 'none' ? h('p', { class: 'pftext' }, v.text) : null, - v.withheld ? null : usesView(state.doc, f, includeSecrets).map((u) => h('p', { class: 'pftext' }, + v.withheld ? null : usesView(state.doc, f, mode).map((u) => h('p', { class: 'pftext' }, u.missing ? '(a credential this step used has been removed)' : 'You will need: ' + u.record + ' \u203A ' + u.label + ': ' + u.value)), v.stop ? h('p', { class: 'pstop' }, h('strong', {}, 'STOP HERE. Do not go further.')) : null, v.ifStuck ? h('p', { class: 'pftext' }, h('strong', {}, 'If it looks different or fails: '), v.ifStuck) : null); } - function printSequence(q, includeSecrets) { + function printSequence(q, mode) { return h('div', { class: 'pseq' }, h('h3', {}, q.title), q.captured ? h('p', { class: 'pftext' }, 'Captured ' + q.captured + '. The site may have changed since.') : null, - q.frames.map((f, k) => printFrame(f, k, includeSecrets))); + q.frames.map((f, k) => printFrame(f, k, mode))); } - function printRecord(r, includeSecrets) { + function printRecord(r, mode) { return h('div', { class: 'prec' + (r.status === 'tbd' ? ' tbd' : '') }, h('h3', {}, r.title, r.status === 'tbd' ? h('span', { class: 'ptag' }, 'TBD') : null), r.fields.length ? h('table', {}, h('tbody', {}, r.fields.map((f) => h('tr', {}, - h('th', {}, f.label), h('td', { class: f.secret ? 'psecret' : '' }, printCell(f, includeSecrets)))))) : null, + h('th', {}, f.label), h('td', { class: f.secret ? 'psecret' : '' }, printCell(f, mode)))))) : null, r.notes ? h('p', { class: 'pnotes' }, r.notes) : null); } @@ -829,27 +834,29 @@ it.detail ? h('p', { class: 'pnotes' }, it.detail) : null); } - function buildPrintDoc(includeSecrets) { + function buildPrintDoc(rawMode) { + const mode = normalizeMode(rawMode); 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 === '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 so the browser repeats it, in flow, at the top of every page. printRoot.replaceChildren(h('table', { class: 'ptable' }, @@ -859,18 +866,20 @@ 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 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('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(); diff --git a/src/model.js b/src/model.js index d56e20a..1199215 100644 --- a/src/model.js +++ b/src/model.js @@ -24,12 +24,16 @@ import { isImageDataUrl, MAX_IMAGE_DATA_CHARS, isMark } from './images.js'; // // Record: { id, title, status: 'ok'|'tbd', updated: 'YYYY-MM-DD', // fields: [Field], notes?: string } -// Field: { label, value, secret?: boolean, kind?: 'text'|'image' } (kind defaults to text) +// Field: { label, value, secret?: boolean, lawyer?: boolean, kind?: 'text'|'image' } (kind defaults to text) +// Three levels: normal (no flags), lawyer (`secret: true, lawyer: true`: masked on screen and +// in the masked print, shown in the lawyer's view) and secret (`secret: true`: shown only in +// the complete print). `lawyer` is only valid together with `secret: true`, so an older +// build that ignores it still treats the item as a secret. // An image field's value is a PNG/JPEG data URL, or '' when no image is set yet. // Item: { id, text, status: 'open'|'done'|'tbd', detail?: string } // Sequence (visual sequence): { id, kind: 'sequence', title, updated: 'YYYY-MM-DD', // frames: [Frame] } -- a numbered series of pictures with optional text. -// Frame: { image: PNG/JPEG data URL or '', text, layout: 'right'|'under'|'none', secret?: boolean, +// Frame: { image: PNG/JPEG data URL or '', text, layout: 'right'|'under'|'none', secret?: boolean, lawyer?: boolean, // ifStuck?: string, what to do if the screen looks different or the step fails // stop?: boolean, "stop here and call someone" marker; ifStuck says who/why // marks?: [Mark] overlay on the picture: { type:'marker', x, y } or @@ -182,6 +186,7 @@ export function validate(doc) { if (!isStr(f.label) || !f.label) errs.push(`${fw}: missing label`); if (!isStr(f.value)) errs.push(`${fw}: value must be a string`); if (f.secret !== undefined && typeof f.secret !== 'boolean') errs.push(`${fw}: secret must be a boolean`); + checkLawyer(f, fw); if (f.id !== undefined) { if (!isStr(f.id) || !f.id) errs.push(`${fw}: id must be a non-empty string`); else if (fieldIds.has(f.id)) errs.push(`${fw}: duplicate field id "${f.id}"`); @@ -194,6 +199,12 @@ export function validate(doc) { }); } + function checkLawyer(f, fw) { + if (f.lawyer === undefined) return; + if (typeof f.lawyer !== 'boolean') errs.push(`${fw}: lawyer must be a boolean`); + else if (f.lawyer && f.secret !== true) errs.push(`${fw}: lawyer needs secret: true`); + } + function checkSequence(q, where) { if (!isObj(q)) return errs.push(`${where}: must be an object`); checkId(q.id, where); @@ -210,6 +221,7 @@ export function validate(doc) { if (!isStr(f.text)) errs.push(`${fw}: text must be a string`); if (!FRAME_LAYOUTS.includes(f.layout)) errs.push(`${fw}: bad layout "${f.layout}"`); if (f.secret !== undefined && typeof f.secret !== 'boolean') errs.push(`${fw}: secret must be a boolean`); + checkLawyer(f, fw); if (f.ifStuck !== undefined && !isStr(f.ifStuck)) errs.push(`${fw}: ifStuck must be a string`); if (f.stop !== undefined && typeof f.stop !== 'boolean') errs.push(`${fw}: stop must be a boolean`); if (f.marks !== undefined) { diff --git a/src/ops.js b/src/ops.js index 9c33130..85fb135 100644 --- a/src/ops.js +++ b/src/ops.js @@ -180,6 +180,19 @@ export function allSequences(doc) { return out; } +// The level of a field or frame: 'normal', 'lawyer' or 'secret' (see model.js). +export function levelOf(x) { + return !x.secret ? 'normal' : x.lawyer ? 'lawyer' : 'secret'; +} + +// Set the level, keeping the flags canonical: lawyer is stored only with secret: true, +// and an item with no flag has no keys at all. +export function setLevel(x, level) { + if (level === 'normal') { delete x.secret; delete x.lawyer; } + else if (level === 'lawyer') { x.secret = true; x.lawyer = true; } + else { x.secret = true; delete x.lawyer; } +} + // Erase the content of every secret field and secret frame (labels, structure // and the secret flags stay). Returns how many values were erased. export function clearSecrets(doc) { diff --git a/src/print.js b/src/print.js index f0e1c9b..1fa2b95 100644 --- a/src/print.js +++ b/src/print.js @@ -3,16 +3,34 @@ import { defaultHeaderFields, isSequence } from './model.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'. +export const PRINT_MODES = ['masked', 'lawyer', 'complete']; +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); + return m === 'complete' ? false : m === 'lawyer' ? !item.lawyer : true; +} + // 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]'; + return isHidden(field, mode) ? '[withheld]' : field.value; } return field.value || '(blank)'; } @@ -45,9 +63,9 @@ export function frameLayout(frame) { // What to show for a frame. A secret frame (picture and text) is withheld // unless secrets are included; a frame with nothing in it is never "withheld". -export function frameView(frame, includeSecrets) { +export function frameView(frame, mode) { const hasContent = !!(frame.image || String(frame.text || '').trim() || String(frame.ifStuck || '').trim()); - const withheld = !!frame.secret && !includeSecrets && hasContent; + const withheld = isHidden(frame, mode) && hasContent; return { withheld, image: withheld ? '' : frame.image, @@ -59,27 +77,36 @@ export function frameView(frame, includeSecrets) { } // What a step's credential references show: [{ label, record, value, secret, missing }]. -// A secret value is a placeholder unless includeSecrets; a reference that no longer +// A secret value is a placeholder unless the view shows it; a reference that no longer // resolves is marked missing. Uses displayValue so masking matches the rest of print. -export function usesView(doc, frame, includeSecrets) { +export function usesView(doc, frame, mode) { return (frame.uses || []).map((u) => { const rec = doc.sections.flatMap((s) => (s.records || []).filter((r) => !isSequence(r))).find((r) => r.id === u.record); const f = rec && rec.fields.find((x) => x.id === u.field && x.kind !== 'image'); - return f ? { label: f.label, record: rec.title, value: displayValue(f, includeSecrets), secret: !!f.secret, missing: false } + return f ? { label: f.label, record: rec.title, value: displayValue(f, mode), secret: !!f.secret, missing: false } : { label: '', record: '', value: '', secret: false, missing: true }; }); } -export function countSecrets(doc) { - let n = 0; - const frames = (q) => { for (const f of q.frames) if (f.secret && (f.image || String(f.text || '').trim() || String(f.ifStuck || '').trim())) n++; }; +// How many filled-in secret values the document holds: { lawyer, secret } where +// `lawyer` counts lawyer-level ones and `secret` the plain ones. Empty ones don't count. +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; +} diff --git a/test/model.test.js b/test/model.test.js index 4851391..a92db81 100644 --- a/test/model.test.js +++ b/test/model.test.js @@ -170,3 +170,14 @@ test('sub-tabs: valid shapes pass, bad ones are reported', () => { d = good(); d.sections[1].records[0].subsection = 'x'; assert.match(validate(d).join('\n'), /not one of this section's sub-tabs/); }); + +test('lawyer must be a boolean and needs secret: true, on fields and frames', () => { + const withField = (f) => { const d = good(); d.sections[1].records[0].fields = [{ label: 'A', value: 'x', ...f }]; return d; }; + assert.deepEqual(validate(withField({ secret: true, lawyer: true })), []); + assert.deepEqual(validate(withField({ secret: true, lawyer: false })), []); + assert.match(validate(withField({ lawyer: true })).join('\n'), /lawyer needs secret: true/); + assert.match(validate(withField({ secret: true, lawyer: 'yes' })).join('\n'), /lawyer must be a boolean/); + const withFrame = (fr) => { const d = good(); d.sections[0].sequences = [{ id: 'q1', kind: 'sequence', title: 'Q', updated: '2022-04-14', frames: [{ image: '', text: 't', layout: 'none', ...fr }] }]; return d; }; + assert.deepEqual(validate(withFrame({ secret: true, lawyer: true })), []); + assert.match(validate(withFrame({ lawyer: true })).join('\n'), /lawyer needs secret: true/); +}); diff --git a/test/ops.test.js b/test/ops.test.js index 9c4e004..7b3dd67 100644 --- a/test/ops.test.js +++ b/test/ops.test.js @@ -405,3 +405,26 @@ test('validation: uses and field ids', async () => { bad((x) => { x.records[0].fields[0].id = 'f1'; x.records[0].fields[1].id = 'f1'; }, /duplicate field id/); bad((x) => { x.records[0].fields[0].id = ''; }, /id must be a non-empty string/); }); + +test('levelOf and setLevel keep lawyer/secret flags canonical', async () => { + const { levelOf, setLevel } = await import('../src/ops.js'); + const f = { label: 'a', value: 'x' }; + assert.equal(levelOf(f), 'normal'); + setLevel(f, 'lawyer'); + assert.deepEqual(f, { label: 'a', value: 'x', secret: true, lawyer: true }); + assert.equal(levelOf(f), 'lawyer'); + setLevel(f, 'secret'); + assert.deepEqual(f, { label: 'a', value: 'x', secret: true }); + assert.equal(levelOf(f), 'secret'); + setLevel(f, 'lawyer'); setLevel(f, 'normal'); + assert.deepEqual(f, { label: 'a', value: 'x' }); // no stray keys + assert.equal(levelOf({ lawyer: true }), 'normal'); // lawyer alone is not a secret +}); + +test('clearSecrets erases lawyer-level values too', async () => { + const { clearSecrets } = await import('../src/ops.js'); + const doc = { sections: [{ records: [{ fields: [{ label: 'n', value: '12345', secret: true, lawyer: true }, { label: 'o', value: 'open' }] }] }] }; + assert.equal(clearSecrets(doc), 1); + assert.equal(doc.sections[0].records[0].fields[0].value, ''); + assert.equal(doc.sections[0].records[0].fields[1].value, 'open'); +}); diff --git a/test/print.test.js b/test/print.test.js index 96857c8..46aa553 100644 --- a/test/print.test.js +++ b/test/print.test.js @@ -44,3 +44,68 @@ 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); +});