Oregami
Repositories/oxedyne/daimond

oxedyne/daimond/dev/verify_rekey.mjs

68.6 KiB, 1 run

created by r2519314175:637, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1// verify_rekey.mjs — a passphrase change carries EVERY secret across, and leaves
2// none of them lying in memory afterwards.
3//
4// WHAT THIS IS FOR. Daimond seals a secret under a key derived from the user's
5// passphrase (`DaimondIdentity.wrap` / `.unwrap`). Change the passphrase and the key
6// is re-derived under a fresh salt, so anything sealed under the old one is opaque
7// from that moment on — unless the code reads it out first and puts it back.
8//
9// Until 2026-08-14 `doChangePassphrase` re-wrapped exactly two things: `cfg.apiKeyEnc`
10// and `cfg.pushTokenEnc` (plus re-sealing the passkey). It did NOT re-wrap the
11// mailbox passwords in `www/js/mail.js`, the provider API keys in `www/js/models.js`,
12// or the forge voice in `www/js/voice.js`. So changing the passphrase silently made
13// every configured mailbox unopenable and took the app's model connection with it.
14// Nothing said so — the notice claimed the opposite — and the first sign was a mailbox
15// that had stopped working for no stated reason.
16//
17// Nor was that the whole of it. Every re-seal used to sit BELOW two blocks that could
18// `return` on failure, so a failure re-wrapping the API key abandoned the push token,
19// the passkey and (once mail arrived above them) the mailboxes as well. Those returns
20// are gone: each secret is re-sealed in its own try/catch, every failure is collected,
21// and one notice names all of them at the end.
22//
23// The properties, and the last three carry the weight:
24//
25// 1. A MAILBOX PASSWORD SURVIVES. After the change, what is stored unwraps under the
26// NEW passphrase to the same password it had before — measured after a reload and
27// a fresh unlock, so the key is derived from the new passphrase and not merely the
28// one already in memory.
29// 2. SEVERAL MAILBOXES SURVIVE, not just the first. Named one at a time: "the
30// password stored for sam@example.com is still sam's password", never "two
31// entries were re-wrapped".
32// 2a. A PROVIDER API KEY SURVIVES, and 2b SEVERAL PROVIDERS DO. Measured in the three
33// places the defect showed: the stored `keyEnc` opens to the key, `ready()` is
34// true, and `resolve('','')` hands back the key. That table is the shape the
35// original finding took, so it is the shape the check takes.
36// 3. THE FORGE VOICE SURVIVES: `DaimondVoice.header()` hands back the same secret.
37// 4. THE PLAINTEXTS DO NOT OUTLIVE THE CHANGE. `mail.js` holds them in a module-local
38// `rekey` map for the length of the change. Nothing outside that module can see the
39// map, and a flag claiming it is empty would prove nothing, so the hold is measured
40// by ASKING IT TO ACT: every stored password is replaced with a sentinel,
41// `resealAfterRekey()` is called again with `DaimondIdentity.wrap` spied on, and a
42// hold that is still there gives itself away twice — by wrapping a password this
43// file knows the text of, and by overwriting the sentinel.
44// 5. A CHANGE THAT FAILS LEAVES NOTHING IN MEMORY EITHER. The failure path is driven
45// for real: the wrapped private key in storage is corrupted while the new-passphrase
46// dialog is open, so `DaimondIdentity.changePassphrase` genuinely returns
47// `{ ok: false }` after the passwords have been read out. (A wrong CURRENT
48// passphrase cannot be used for this: the first prompt validates it with
49// `DaimondIdentity.verify` and will not close, so the wrong-passphrase case never
50// reaches the code under test at all. That is a good design and an untestable
51// route; corrupting the key store reaches the same branch by the same door.)
52// 6. THE STORED PASSWORD IS NEVER PLAINTEXT. Every localStorage key is read through
53// `Storage.prototype` — past the per-account shim in `accounts.js`, which shadows
54// `getItem` on the INSTANCE — and searched for each password and for the voice,
55// before the change, after it, and after a reload.
56// 7. A FAILURE IN ONE SECRET CANNOT COST ANOTHER. The `apiKeyEnc` re-wrap is made to
57// fail from OUTSIDE the app (`DaimondIdentity.wrap` refuses the API key's own
58// plaintext and nothing else) against UNMODIFIED source, and then three secrets are
59// asked whether they survived: a mailbox and a provider key, both re-sealed ABOVE
60// the failing block, and THE PUSH TOKEN, which is re-sealed BELOW it. The push
61// token is the load-bearing third: it is the only secret in this file that a
62// reinstated `return` would cost, so without it the check would pass whatever
63// happened underneath.
64// 8. THE CHANGE ALWAYS ENDS IN A NOTICE, AND THE NOTICE SAYS THE PASSPHRASE CHANGED
65// BEFORE IT NAMES WHAT FAILED. With the returns gone there is one exit, so a user
66// who stops reading after the first sentence has still been told the thing they
67// must not get wrong.
68// 9. THE SEARCH KEY SURVIVES. `search.js` is `models.js` in miniature and it inherited
69// that file's hole with its shape: `setKey` sealed the key and nothing re-wrapped
70// it, so a passphrase change killed it and `unseal`'s empty-string catch made the
71// dead key indistinguishable from no key at all.
72//
73// AND THE THREE THAT MAKE THE REST SELF-ENFORCING. Checks 1-9 are each about one
74// secret, and a check per secret is a list — the same hand-written list that was wrong
75// four times over. These are about the CLASS:
76//
77// 10. EVERY MODULE THAT SEALS SAYS SO. The source is read for every caller of
78// `DaimondIdentity.wrap` / `.wrapBytes`, and a module holding one while
79// registering no participant and stating no exemption FAILS THE RUN. This is the
80// check that would have caught mail, models, voice and search on the day each was
81// written. It is proved on synthetic source first — an unregistered sealer, an
82// exempted one, a registration sitting in the WRONG file, a call in a comment, a
83// call in a string, and an empty tree — because a grep that matched nothing would
84// otherwise pass in silence, which is this defect wearing a verifier's coat.
85// 11. EVERY REGISTERED PARTICIPANT IS RUN. Measured from OUTSIDE the registry, by
86// wrapping each live participant's own phases before the change and watching them
87// be called: a registry that reported on itself would be self-consistent and prove
88// nothing. This is also the only measurement of `chunks` and `sync`, whose effects
89// are not otherwise visible in a world with no gateway.
90// 12. AND THE SEQUENCE CANNOT BE COST BY ONE PARTICIPANT. A probe that throws is
91// registered between two that record, and the ones after it must still run. The
92// probes also state the two structural promises: every phase is called with NO
93// ARGUMENTS (so no plaintext can arrive on one), the READ happens while the old
94// passphrase still verifies and the RESEAL after it does not (so the two phases
95// really do straddle the key swap), and the registry's own report carries names
96// and counts and none of the secrets this file knows the text of.
97//
98// EACH CHECK IS PROVED AGAINST BROKEN CODE FIRST. The breaks patch the SOURCE UNDER
99// TEST as it is served, the way `verify_capp.mjs` does:
100//
101// node dev/verify_rekey.mjs --break nomail # 1 and 2: mail is never read out
102// node dev/verify_rekey.mjs --break firstonly # 2 only: 1 must stay GREEN
103// node dev/verify_rekey.mjs --break nomodels # 2a and 2b: providers not re-sealed
104// node dev/verify_rekey.mjs --break modelfirstonly # 2b only: 2a must stay GREEN
105// node dev/verify_rekey.mjs --break novoice # 3 only
106// node dev/verify_rekey.mjs --break sticky # 4 only: the hold is not cleared
107// node dev/verify_rekey.mjs --break stickyfail # 5 only: the failure path forgets nothing
108// node dev/verify_rekey.mjs --break keyreturn # 8 only: the notice leads with "Careful"
109// node dev/verify_rekey.mjs --break searchskip # 9 only: the search key is not re-sealed
110// node dev/verify_rekey.mjs --break nosearch # 9 and 10: search registers nothing
111// node dev/verify_rekey.mjs --break unregistered # 10 only: a NEW sealer, registered nowhere
112// node dev/verify_rekey.mjs --break dupname # the refusals check, and 9 with it
113// node dev/verify_rekey.mjs --break nochunks # the chunk map is never dropped
114// node dev/verify_rekey.mjs --break lastonly # 11 only: the last participant is skipped
115// node dev/verify_rekey.mjs --break abandon # 12 and 7: a failure abandons the rest
116// node dev/verify_rekey.mjs # and then, clean
117//
118// FOUR OF THOSE REDDEN MORE THAN ONE CHECK, AND EVERY ONE OF THEM IS MEANT TO — but
119// which, and why, is worth writing down, because a break that reddens six checks has
120// not thereby tested six things.
121//
122// nosearch 2: the module is absent from the running app, and its key dies. That IS
123// the 2026-08-14 defect, in both of the places it showed.
124// dupname 2: the refusal is reported, and the key the refused registration would
125// have saved dies. The refusals check is what this break exists to
126// prove; the dead key follows from it. Note what STAYS GREEN: the
127// running-app check reads the expected names out of the source, and
128// this break edits the source, so it asks for a participant called
129// 'mail' and finds one. Two checks that each look sound can still
130// agree with each other about the wrong thing — which is why the
131// refusal is reported separately and not inferred from the names.
132// lastonly 2: the tail probe is never reached (11) — AND THE PUSH TOKEN DIES,
133// because during the earlier armed change the last registered
134// participant is `push` and not a probe. It CANNOT be isolated further:
135// a loop that drops its last element drops a real secret, and a break
136// that pretended otherwise would be a gentler fault than the one being
137// guarded against.
138// abandon 5: this is the regression the whole restructure exists to prevent, and
139// the spread is the point. It costs the push token (7), the sentence
140// about the API key and therefore its control and check 8, and every
141// probe after the one that threw (11 and 12). Note that the CHEAPEST of
142// those — the control looking for the API key's sentence — goes red
143// first; a run that stopped there would have proved nothing about 11
144// and 12, which is why they are asserted separately and reported above.
145//
146// Where a break can be isolated it is: `searchskip` moves 9 without 10, `unregistered`
147// moves 10 without 9, `nochunks` moves the chunk check alone, and `keyreturn` moves the
148// notice's shape without costing a single secret.
149//
150// `firstonly` is the one that keeps check 2 honest. A break that re-seals nothing
151// reddens 1 and 2 together, and then "several mailboxes survive" has never been tested
152// as anything but a second spelling of "a mailbox survives". `firstonly` re-seals
153// state.accounts[0] and stops, so 1 stays green and only 2 moves. `modelfirstonly` does
154// the same job for 2b against 2a, and `stickyfail` for 5 against 4: it touches the
155// FAILURE path only, so 4 — which is measured on a change that succeeded — stays green.
156//
157// `earlyreturn` IS GONE, AND ITS ABSENCE IS THE RESULT. It used to move the re-seal
158// below the `apiKeyEnc` block and make that block fail, and it reddened five checks at
159// once because the secrets were neither re-sealed nor forgotten. Its anchor — an
160// `if (plain) { … return; }` — no longer exists: nothing between the change and the
161// notice returns or throws out any more, so no ONE-LINE regression can make one
162// secret's failure cost a secret above it. What remains constructible is `keyreturn`,
163// which reinstates the deleted `return` in the API key's catch, and what it costs is
164// the push token BELOW it — never the mail, the voice or the providers above. That
165// asymmetry is the whole of the change, and it is why check 7 now asks about a secret
166// on each side of the failure rather than only about the mailbox.
167//
168// Needs a world: `dev/serve.mjs` and `dev/mockllm.mjs`. No gateway.
169//
170// eval "$(bash dev/world.sh 14 --env)"
171// node dev/verify_rekey.mjs
172//
173// A verifier run WITHOUT that eval drives world 0 on :8777 and does not warn.
174import fs from 'node:fs';
175import path from 'node:path';
176import { fileURLToPath } from 'node:url';
177import { open, PASS } from './harness.mjs';
178
179const HERE = path.dirname(fileURLToPath(import.meta.url));
180const WWW = path.join(HERE, '..', 'www');
181
182const BREAK = (() => {
183 const i = process.argv.indexOf('--break');
184 return i > 0 ? String(process.argv[i + 1] || '') : '';
185})();
186
187const BREAKS = {
188 // The old behaviour: the mailbox passwords are never read out from under the
189 // passphrase that is about to change. Broken at the READ and not at the re-seal,
190 // so that nothing is held either — which is what the code did before the fix, and
191 // keeps this break off check 4.
192 nomail: {
193 file: 'js/mail.js',
194 find: " read: unsealForRekey,",
195 with: " read: function () { return { held: 0, failed: [] }; }, // break nomail",
196 },
197 // Only the first mailbox is re-sealed. Check 1 must stay green under this, or
198 // check 2 was never asking about "several".
199 firstonly: {
200 file: 'js/mail.js',
201 find: " for (var i = 0; i < state.accounts.length; i++) {\n"
202 + " var a = state.accounts[i];\n"
203 + " if (!a || !a.address) continue;",
204 with: " for (var i = 0; i < 1; i++) {\n"
205 + " var a = state.accounts[i];\n"
206 + " if (!a || !a.address) continue;",
207 },
208 // The voice is not read out, so it is not put back.
209 novoice: {
210 file: 'js/voice.js',
211 find: " read: readForRekey,",
212 with: " read: function () { return { held: 0, failed: [] }; }, // break novoice",
213 },
214 // The passwords stay in the module after they have been put back.
215 sticky: {
216 file: 'js/mail.js',
217 find: " } finally { rekey = null; } // in the clear; never held past here",
218 with: " } finally { /* break sticky: the hold is kept */ }",
219 },
220 // A change that failed leaves them held.
221 stickyfail: {
222 file: 'js/daimond.js',
223 find: " try { DaimondRekey.forgetAll(); } catch (e) { /* each one caught its own */ }",
224 with: " // break stickyfail: the failure path forgets nothing",
225 },
226 // The provider keys are never re-sealed: the defect of 2026-08-14, exactly as it
227 // was found. Checks 2a and 2b must reproduce all three of its symptoms.
228 nomodels: {
229 file: 'js/models.js',
230 find: " reseal: resealAfterRekey,",
231 with: " reseal: function () { return { failed: [] }; }, // break nomodels",
232 },
233 // Only the first provider holding a key is re-sealed. Counted AFTER the keyless
234 // `continue`, so a keyless provider sitting first in the store cannot absorb the
235 // allowance and turn 2a red as well — which would put this break on the wrong
236 // check and leave 2b untested.
237 //
238 // TWO SITES, because the allowance has to be declared in one place and spent in
239 // another — and this break was found ALREADY STALE on 2026-08-14: its anchor still
240 // read `var failed = [];` and the line had become `var failed = [], unread = [];`
241 // hours earlier, when the already-unreadable case was added. `--break` refuses an
242 // anchor it cannot find and says so, so nothing passed in silence; but a break that
243 // cannot be applied is a check with nothing behind it, and the only reason anybody
244 // learned is that somebody ran the whole matrix.
245 modelfirstonly: [
246 {
247 file: 'js/models.js',
248 find: " var failed = [], unread = [];",
249 with: " var failed = [], unread = [], _n = 0; // break modelfirstonly",
250 },
251 {
252 file: 'js/models.js',
253 find: " try {\n"
254 + " p.keyEnc = await DaimondIdentity.wrap(key);",
255 with: " if (_n++ >= 1) continue; // break modelfirstonly\n"
256 + " try {\n"
257 + " p.keyEnc = await DaimondIdentity.wrap(key);",
258 },
259 ],
260 // THE OLD EXIT COMES BACK: a failure ends in a bare "Careful" that never says the
261 // passphrase changed. What it costs now is only the sentence — the secrets are all
262 // re-sealed above this line, inside the registry — so it moves check 8 alone, where
263 // once it would have taken the push token with it. That narrowing IS the
264 // restructure, and this break is what states it.
265 keyreturn: {
266 file: 'js/daimond.js',
267 find: " catch (e) { put = { sentences: [t('changepass.rekey_failed')] }; }",
268 with: " catch (e) { put = { sentences: [t('changepass.rekey_failed')] }; }\n"
269 + " if (put.sentences.length) { noticeDialog(t('changepass.careful'), put.sentences.join(' ')); return; }",
270 },
271 // THE REGRESSION THE REGISTRY EXISTS TO PREVENT: the reseal loop returns on the
272 // first failure, so one refused secret abandons every participant below it. Reddens
273 // check 7 (the push token, registered after the API key) and check 12 (the probes
274 // after the one that throws) — and it should redden both, because that is the whole
275 // of what the fault does.
276 abandon: {
277 file: 'js/rekey.js',
278 find: " if (r.failed.length) {\n"
279 + " out.failed.push({ name: p.name, list: r.failed });\n"
280 + " out.sentences.push(say(p, 'failed', r.failed));\n"
281 + " }\n"
282 + " }\n"
283 + " return out;\n"
284 + " }\n"
285 + "\n"
286 + " /// Drop every plaintext held",
287 with: " if (r.failed.length) {\n"
288 + " out.failed.push({ name: p.name, list: r.failed });\n"
289 + " out.sentences.push(say(p, 'failed', r.failed));\n"
290 + " return out; // break abandon\n"
291 + " }\n"
292 + " }\n"
293 + " return out;\n"
294 + " }\n"
295 + "\n"
296 + " /// Drop every plaintext held",
297 },
298 // A participant is registered and never reached. An off-by-one in the loop, which
299 // is the smallest thing that produces the old defect from the new shape: the list
300 // is right and the walk over it is not. The probes register last, so what this
301 // drops is the tail probe and nothing a person owns.
302 lastonly: {
303 file: 'js/rekey.js',
304 find: " var out = { ran: [], failed: [], unread: [], sentences: [] };\n"
305 + " for (var i = 0; i < parts.length; i++) {",
306 with: " var out = { ran: [], failed: [], unread: [], sentences: [] };\n"
307 + " for (var i = 0; i < parts.length - 1; i++) { // break lastonly",
308 },
309 // THE LIVE BUG OF 2026-08-14, in the file it was still live in that morning:
310 // search.js seals a key and registers nothing. The source check must see a sealer
311 // that says nothing, and the key must die — both, because both are true of it.
312 nosearch: {
313 file: 'js/search.js',
314 find: " if (window.DaimondRekey) {\n"
315 + " DaimondRekey.register({\n"
316 + " name: 'search',",
317 with: " if (false) {\n"
318 + " DaimondRekey.register({\n"
319 + " name: 'search',",
320 },
321 // Registered, and the re-seal walks nothing. Check 9 moves and the source check
322 // stays green, which is what makes 9 a measurement of the key rather than a second
323 // spelling of "the registration is there".
324 searchskip: {
325 file: 'js/search.js',
326 find: " var failed = [], unread = [];\n"
327 + " for (var id in store.keys) {",
328 with: " var failed = [], unread = [];\n"
329 + " for (var id in {}) { // break searchskip",
330 },
331 // Two participants under one name. The second is REFUSED rather than replacing the
332 // first, so `refusals()` must not be empty — and the search key, whose registration
333 // this is, is not re-sealed at all.
334 dupname: {
335 file: 'js/search.js',
336 find: " name: 'search',",
337 with: " name: 'mail', // break dupname",
338 },
339 // The chunk map is kept, so the next offload points a fresh manifest at ciphertext
340 // sealed under a passphrase that no longer exists.
341 nochunks: {
342 file: 'js/chunks.js',
343 find: " reseal: forgetMapAfterRekey,",
344 with: " reseal: function () { return { failed: [] }; }, // break nochunks",
345 },
346 // A NEW module that seals and says nothing about it — the shape every one of the
347 // four defects took on the day it was written. It is added to the source the
348 // scanner reads rather than to a file that exists, because what is being proved is
349 // that the scanner CAN see one: a check that has only ever run against a tree where
350 // every module already registers has never been shown to fail at all.
351 unregistered: {
352 add: 'js/newsealer.js',
353 body: "(function () {\n"
354 + " 'use strict';\n"
355 + " async function keep(v) { return await DaimondIdentity.wrap(v); }\n"
356 + " window.DaimondNewSealer = { keep: keep };\n"
357 + "})();\n",
358 },
359};
360
361const ok = [], bad = [];
362const check = (name, pass, detail) => {
363 (pass ? ok : bad).push(name + (detail ? ' — ' + detail : ''));
364 console.log((pass ? ' ok ' : ' FAIL ') + name + (detail ? ' — ' + detail : ''));
365 return pass;
366};
367const sleep = (ms) => new Promise(r => setTimeout(r, ms));
368
369// ── The fixtures ────────────────────────────────────────────────────
370//
371// Three mailboxes, because "several survive" cannot be asked of one, and the
372// passwords are distinctive strings so that the storage sweep in check 6 is looking
373// for something that could not be there by accident.
374const BOXES = [
375 { address: 'alpha@example.com', pass: 'alpha-mailbox-secret-91c4f' },
376 { address: 'sam@example.com', pass: 'sam-mailbox-secret-7b2ed' },
377 { address: 'gamma@example.com', pass: 'gamma-mailbox-secret-4d8ac' },
378];
379// A voice as the forge issues one: graphic ASCII, comfortably over DaimondVoice.MIN.
380const VOICE = 'V01ceSecretForTheForge-abcdefghijklmnopqrs';
381// A SECOND provider, so "several providers survive" is a question with an answer. The
382// first is the one `connectMock` configured, and it is also the default — which is why
383// the check on it can read `ready()` and `resolve()` and the check on this one cannot.
384const P2_ID = 'custom:http://127.0.0.1:9199/v1/chat/completions';
385const P2_NAME = 'Second provider';
386const P2_KEY = 'second-provider-key-6f3ba';
387// The push token: the one secret in this file re-sealed BELOW the API key block.
388const PUSHTOK = 'push-token-secret-2ae71';
389// The search key. `brave` because it is a KNOWN engine that is not `credits`, and
390// `credits` is the one id `setKey` refuses — its key belongs to the gateway.
391const S_ENGINE = 'brave';
392const S_KEY = 'search-service-key-5c19d';
393const NEW1 = 'a first new passphrase for the rekey test';
394const NEW2 = 'a second new passphrase that never takes';
395
396// ── The broken source, served AND scanned ───────────────────────────
397//
398// One edit, two readers. The browser is served the patched file, and the source scan
399// of check 10 reads the SAME patched text — otherwise a break would move the app and
400// leave the scanner reading a tree nobody was running, which is a verifier measuring
401// two different programs and reporting one number.
402const EDITED = new Map(); // served path -> patched body
403const ADDED = new Map(); // a module that exists only for the scanner
404(function applyBreak() {
405 if (!BREAK) return;
406 const spec = BREAKS[BREAK];
407 if (!spec) { console.error(`no such break: ${BREAK}`); process.exit(2); }
408 // A break may name several sites, and every one of them has to land: a break that
409 // reached only one of two guards would leave the other holding, go green, and be
410 // reported as a check that cannot fail when it was never tested.
411 const sites = Array.isArray(spec) ? spec : [spec];
412 for (const site of sites) {
413 if (site.add) { ADDED.set(site.add, site.body); continue; }
414 const src = EDITED.get(site.file) || fs.readFileSync(path.join(WWW, site.file), 'utf8');
415 const n = src.split(site.find).length - 1;
416 if (n !== 1) {
417 console.error(`break '${BREAK}': the anchor appears ${n} times in ${site.file}, `
418 + 'so nothing was broken and the run below would prove nothing.');
419 process.exit(2);
420 }
421 EDITED.set(site.file, src.replace(site.find, site.with));
422 }
423})();
424
425async function routeBreak(page) {
426 for (const [file, body] of EDITED) {
427 await page.route('**/' + file, r => r.fulfill({
428 status: 200, contentType: 'application/javascript', body,
429 }));
430 }
431}
432
433// ── Check 10: every module that seals says so ───────────────────────
434//
435// Read the source, find every caller of the sealing API, and fail on one that neither
436// registers a participant nor states an exemption in the SAME FILE. Same file is the
437// point: a list of exempt modules kept in this verifier would drift from the source it
438// exempts within a month, and the first thing to go stale would be the entry for
439// whichever module had just changed.
440
441/// Where a `/` may begin a regular expression rather than a division.
442const BEFORE_REGEX = /[(,=:[!&|?{};+\-*%~^<>]$/;
443const REGEX_WORD = /\b(return|typeof|case|in|of|new|delete|void|do|else|yield|await)$/;
444
445/// The source with comments, string literals and regular expressions removed.
446///
447/// All three matter. Half the files here MENTION `DaimondIdentity.wrap()` in a doc
448/// comment — sync.js does it in its second paragraph — so a scan of the raw text would
449/// call every one of them a sealer and then be satisfied by registrations that are
450/// themselves only described in prose.
451///
452/// THE REGULAR EXPRESSIONS ARE NOT PEDANTRY, and this is written down because leaving
453/// them out silently broke this scan on its first run. `mail.js` line 149 escapes HTML
454/// with `/[&<>"']/g`; a scanner that knows about quotes and not about regexes reads
455/// that `"` as the start of a string and swallows the next four thousand characters —
456/// which happened to include mail.js's own registration. The check went red on a file
457/// that was correct, and had the swallowed span held the `wrap` call instead it would
458/// have gone GREEN on a file that was not. A scanner that cannot read the language it
459/// polices fails in whichever direction the text happens to fall.
460/// `keepText` keeps what is INSIDE the string literals, for reading the name out of a
461/// registration; the seal and registration checks themselves are made against the view
462/// that drops it, so a module cannot register by mentioning one in a sentence.
463function stripped(src, keepText) {
464 let out = '', i = 0;
465 const n = src.length;
466 while (i < n) {
467 const c = src[i], d = src[i + 1];
468 if (c === '/' && d === '*') { const e = src.indexOf('*/', i + 2); i = e < 0 ? n : e + 2; out += ' '; continue; }
469 if (c === '/' && d === '/') { const e = src.indexOf('\n', i); i = e < 0 ? n : e; out += ' '; continue; }
470 if (c === '"' || c === "'" || c === '`') {
471 const q = c, from = i; i++;
472 while (i < n && src[i] !== q) { i += (src[i] === '\\') ? 2 : 1; }
473 i++;
474 out += keepText ? src.slice(from, Math.min(i, n)) : ' ' + q + q;
475 continue;
476 }
477 if (c === '/') {
478 const lead = out.replace(/\s+$/, '');
479 if (lead === '' || BEFORE_REGEX.test(lead) || REGEX_WORD.test(lead)) {
480 i++;
481 let cls = false; // inside a [...] class, where / is literal
482 while (i < n) {
483 const k = src[i];
484 if (k === '\\') { i += 2; continue; }
485 if (k === '[') cls = true;
486 else if (k === ']') cls = false;
487 else if (k === '/' && !cls) { i++; break; }
488 else if (k === '\n') break; // unterminated: not a regex after all
489 i++;
490 }
491 out += ' /re/ '; continue;
492 }
493 }
494 out += c; i++;
495 }
496 return out;
497}
498
499const SEALS = /DaimondIdentity\s*\??\.\s*wrap(?:Bytes)?\s*\(/;
500/// A COMPUTED reach into the identity module. The property name may be a string this
501/// scan has already blanked, so what is caught is the bracket itself — `DaimondIdentity
502/// ['wrap']` and a variable-keyed call alike. Nothing in the app does this today, so it
503/// costs nothing; if something starts to, it is asked to register like everyone else,
504/// which is the safe direction for a check to be wrong in.
505const ODD = /DaimondIdentity\s*\??\s*\[/;
506const REGS = /DaimondRekey\s*\.\s*register\s*\(/;
507const EXEMPT = /DaimondRekey\s*\.\s*exempt\s*\(/;
508
509/// The names a file registers under, read out of its own source.
510const NAMED = /DaimondRekey\s*\.\s*register\s*\(\s*\{\s*name\s*:\s*['"]([A-Za-z0-9_-]+)['"]/g;
511
512/// Which of these files seal, which of those say nothing about it, and what the ones
513/// that do say call themselves.
514///
515/// `files` is `[{ name, src }]`, so the same function runs over the real tree and over
516/// the synthetic fixtures that prove it can fail.
517function scanSealers(files) {
518 const sealers = [], quiet = [], claims = [];
519 for (const f of files) {
520 const s = stripped(f.src);
521 if (!SEALS.test(s) && !ODD.test(s)) continue;
522 sealers.push(f.name);
523 if (!REGS.test(s) && !EXEMPT.test(s)) quiet.push(f.name);
524 const text = stripped(f.src, true);
525 let m;
526 NAMED.lastIndex = 0;
527 while ((m = NAMED.exec(text)) !== null) if (claims.indexOf(m[1]) < 0) claims.push(m[1]);
528 }
529 return { sealers, quiet, claims };
530}
531
532/// Every module the app is made of, as the browser is being served it.
533function appSources() {
534 const out = [];
535 for (const name of fs.readdirSync(path.join(WWW, 'js')).sort()) {
536 if (!name.endsWith('.js')) continue;
537 const rel = 'js/' + name;
538 out.push({ name: rel, src: EDITED.get(rel) || fs.readFileSync(path.join(WWW, rel), 'utf8') });
539 }
540 for (const [rel, src] of ADDED) out.push({ name: rel, src });
541 return out;
542}
543
544/// The modules that seal something today. NAMED, not counted — a check that asserted
545/// "seven sealers" would go red when a new one arrived and green again the moment
546/// somebody deleted a different one.
547const KNOWN_SEALERS = [
548 'js/chunks.js', 'js/daimond.js', 'js/mail.js', 'js/models.js',
549 'js/search.js', 'js/sync.js', 'js/voice.js',
550];
551
552const s = await open({ name: 'rekey', connect: true, route: routeBreak });
553const { page } = s;
554
555// ── Driving the change the way a person does ────────────────────────
556//
557// Account menu, "Change passphrase…", the current passphrase, then the new one typed
558// rather than generated — the generated path is verify_changepass's subject, and a
559// known new passphrase is what lets this file unlock again afterwards.
560async function changePassphrase(cur, next, before) {
561 await page.evaluate(() => document.getElementById('user-row').click());
562 await sleep(250);
563 await page.evaluate(() => {
564 const b = [...document.querySelectorAll('#admin-home .admin-item')]
565 .find(x => /Change passphrase/.test(x.textContent));
566 if (!b) throw new Error('no "Change passphrase" item in the account menu');
567 b.click();
568 });
569 await page.waitForSelector('.dlg-input', { timeout: 10000 });
570 await page.fill('.dlg-input', cur);
571 await page.click('.dlg-ok');
572 await page.waitForSelector('#cp-modal', { timeout: 10000 });
573 await sleep(200);
574 if (before) await before();
575 await page.click('#cp-modal .id-choose');
576 await sleep(150);
577 await page.fill('#cp-modal #cp-pass', next);
578 await page.fill('#cp-modal #cp-pass2', next);
579 await page.click('#cp-modal .dlg-ok');
580 await page.waitForSelector('#cp-modal', { state: 'detached', timeout: 15000 });
581 // Whatever notice follows — changed, failed, or "be careful" — its words are the
582 // only thing on screen that says which path ran. A notice that never arrives is
583 // returned as '' rather than thrown, so that check 8 fails with one clean red
584 // instead of the whole run collapsing into "the run completed".
585 const came = await page.waitForSelector('.dlg .dlg-ok', { timeout: 15000 })
586 .then(() => true).catch(() => false);
587 if (!came) return { head: '', body: '' };
588 // The HEADING separately, because it is the half that says which exit was taken —
589 // and reading it out of the body would have the check turn on the difference
590 // between "Passphrase changed" and "The passphrase changed, but…", which is one
591 // capital letter.
592 const said = await page.evaluate(() => {
593 const d = document.querySelector('.dlg');
594 const h = d && d.querySelector('h2');
595 const flat = (n) => (n ? (n.innerText || '') : '').replace(/\s+/g, ' ').trim();
596 return { head: flat(h), body: flat(d) };
597 });
598 await page.click('.dlg .dlg-ok');
599 await sleep(300);
600 return said;
601}
602
603/// Unlock after a reload, with a passphrase this file chose.
604async function unlockWith(pass) {
605 await page.reload({ waitUntil: 'domcontentloaded' });
606 await page.waitForSelector('#id-primary', { timeout: 15000 });
607 await page.waitForTimeout(400);
608 await page.fill('#id-pass', pass);
609 await page.evaluate(() => document.getElementById('id-primary').click());
610 const opened = await page.waitForSelector('#identity-modal', { state: 'hidden', timeout: 15000 })
611 .then(() => true).catch(() => false);
612 await page.waitForTimeout(600);
613 return opened;
614}
615
616/// What the password stored for `address` opens to, under the key in force now.
617function opened(address) {
618 return page.evaluate(async (addr) => {
619 const j = JSON.parse(localStorage.getItem('daimond-mail') || '{}');
620 const a = (j.accounts || []).find(x => x.address === addr);
621 if (!a) return { err: 'no such mailbox is stored' };
622 if (!a.pass) return { err: 'the stored password is empty' };
623 try { return { text: await DaimondIdentity.unwrap(a.pass) }; }
624 catch (e) { return { err: String((e && e.message) || e) }; }
625 }, address);
626}
627
628/// What the provider store holds, in the three places the 2026-08-14 defect showed.
629///
630/// The stored `keyEnc` is opened here rather than asked of the module, because
631/// `models.js` keeps a decrypted copy in its `plain` map for the length of an unlocked
632/// session: a check that only asked the module would pass on that copy while the thing
633/// on disk was already unopenable, and would go red one reload later on somebody's
634/// laptop instead of here. `ready()` and `resolve()` are read as well, because they are
635/// what the user meets — a false `ready()` is the app saying it has no model.
636function providerState() {
637 return page.evaluate(async () => {
638 const g = (k) => Storage.prototype.getItem.call(localStorage, k);
639 const mv = JSON.parse(g('daimond-models-v2') || '{}');
640 const out = { order: [], providers: {}, ready: false, resolved: null };
641 for (const id in (mv.providers || {})) {
642 const p = mv.providers[id];
643 out.order.push(id);
644 let opens = '(no keyEnc)';
645 if (p.keyEnc) {
646 try { opens = await DaimondIdentity.unwrap(p.keyEnc); }
647 catch (e) { opens = 'UNREADABLE:' + ((e && e.name) || e); }
648 }
649 out.providers[id] = { name: p.name || '', opens, plaintext: String(p.key || '') };
650 }
651 out.ready = !!DaimondModels.ready();
652 const r = DaimondModels.resolve('', '');
653 out.resolved = r ? String(r.apiKey || '') : null;
654 return out;
655 });
656}
657
658/// What the stored search key opens to, and what the module says about it.
659///
660/// The stored `keyEnc` first, for the same reason the provider check reads it: `plain`
661/// keeps a decrypted copy for the length of an unlocked session, so a check that asked
662/// only the module would pass on that copy while the thing on disk was already dead —
663/// and would go red one reload later, on somebody's laptop.
664function searchState(id) {
665 return page.evaluate(async (engine) => {
666 const g = (k) => Storage.prototype.getItem.call(localStorage, k);
667 const j = JSON.parse(g('daimond-search-v1') || '{}');
668 const row = (j.keys || {})[engine] || null;
669 const out = { has: !!row, opens: '(no keyEnc)', plaintext: '', says: '' };
670 if (row && row.keyEnc) {
671 try { out.opens = await DaimondIdentity.unwrap(row.keyEnc); }
672 catch (e) { out.opens = 'UNREADABLE:' + ((e && e.name) || e); }
673 }
674 if (row) out.plaintext = String(row.key || '');
675 // What the app itself would use for a search, which is the half the user meets.
676 out.says = String(DaimondSearch.key(engine) || '');
677 return out;
678 }, id);
679}
680
681/// What the stored push token opens to.
682function pushNow() {
683 return page.evaluate(async () => {
684 const b = JSON.parse(localStorage.getItem('daimond-byok') || '{}');
685 if (!b.pushTokenEnc) return { err: 'nothing is stored' };
686 try { return { text: await DaimondIdentity.unwrap(b.pushTokenEnc) }; }
687 catch (e) { return { err: String((e && e.name) || e) }; }
688 });
689}
690
691/// The voice, as a request would ask for it.
692function voiceNow() {
693 return page.evaluate(async () => {
694 try {
695 const h = await DaimondVoice.header();
696 return { text: h[DaimondVoice.HEADER] || '' };
697 } catch (e) { return { err: String((e && e.message) || e) }; }
698 });
699}
700
701/// Every localStorage value that carries one of these strings in the clear.
702///
703/// Read through `Storage.prototype`: `accounts.js` shadows `getItem` on the instance
704/// to namespace `daimond-*` keys per account, so a shimmed read of a key that is
705/// already namespaced would look somewhere that does not exist and find nothing.
706function plaintextHits(needles) {
707 return page.evaluate((ns) => {
708 const get = Storage.prototype.getItem, key = Storage.prototype.key;
709 const hits = [];
710 for (let i = 0; i < localStorage.length; i++) {
711 const k = key.call(localStorage, i);
712 const v = get.call(localStorage, k) || '';
713 for (const n of ns) if (v.indexOf(n.text) >= 0) hits.push(`${n.what} in ${k}`);
714 }
715 return hits;
716 }, needles);
717}
718
719/// Is `mail.js` still holding the plaintexts?
720///
721/// Nothing outside that module can see the `rekey` map, so this asks it to ACT on
722/// whatever it is holding and watches what happens. Every stored password is replaced
723/// with a sentinel first, so a hold that is still there is caught twice over: by the
724/// call it makes (a `wrap` of a password this file knows the text of) and by the write
725/// it performs (the sentinel overwritten). Then the real stored values go back, so the
726/// checks after this measure the change and not the probe.
727function heldNow() {
728 return page.evaluate(async (boxes) => {
729 const SENT = 'SENTINEL-not-a-wrapped-password';
730 const raw = localStorage.getItem('daimond-mail') || '{}';
731 const was = {};
732 JSON.parse(raw).accounts.forEach(x => { was[x.address] = String(x.pass || ''); });
733
734 const stamped = JSON.parse(raw);
735 stamped.accounts.forEach(x => { x.pass = SENT; });
736 localStorage.setItem('daimond-mail', JSON.stringify(stamped));
737 window.DaimondMail.reload();
738
739 const real = DaimondIdentity.wrap;
740 const seen = [];
741 DaimondIdentity.wrap = async function (v) { seen.push(String(v)); return await real(v); };
742 let ret = null;
743 try { ret = await DaimondMail.resealAfterRekey(); }
744 catch (e) { ret = { err: String((e && e.message) || e) }; }
745 DaimondIdentity.wrap = real;
746
747 const after = JSON.parse(localStorage.getItem('daimond-mail') || '{}');
748 const wrote = (after.accounts || [])
749 .filter(x => String(x.pass || '') !== SENT).map(x => x.address);
750
751 const back = JSON.parse(localStorage.getItem('daimond-mail') || '{}');
752 back.accounts.forEach(x => { if (was[x.address] != null) x.pass = was[x.address]; });
753 localStorage.setItem('daimond-mail', JSON.stringify(back));
754 window.DaimondMail.reload();
755
756 return {
757 // Named, not counted: which mailbox's password is still in memory.
758 leaked: boxes.filter(b => seen.indexOf(b.pass) >= 0).map(b => b.address),
759 wrote,
760 ret,
761 };
762 }, BOXES);
763}
764
765try {
766 // ── Check 10, and first: the instrument, on source it must fail ──
767 //
768 // Six fixtures, and the first three are the ones that matter. A scan that cannot
769 // see an unregistered sealer would pass every day for ever without once having
770 // looked, and that is precisely the failure being fixed — so it is shown failing
771 // before it is believed.
772 const fx = (name, src) => ({ name, src });
773 const sawQuiet = (files) => scanSealers(files).quiet;
774 const sawSeal = (files) => scanSealers(files).sealers;
775
776 check('the scan SEES a sealer that registers nothing',
777 sawQuiet([fx('js/newthing.js', 'async function f(v) { return await DaimondIdentity.wrap(v); }')])
778 .join() === 'js/newthing.js',
779 'an unregistered sealer is reported');
780 check('the scan ACCEPTS a sealer that states an exemption',
781 sawQuiet([fx('js/newthing.js', 'async function f(v) { return await DaimondIdentity.wrapBytes(v); }\n'
782 + 'DaimondRekey.exempt("newthing", "sealed at the moment of sending; never read back");')]).length === 0,
783 'an exemption at the site is enough');
784 // The drift trap: a registration in ANOTHER file must not answer for this one.
785 // A list kept anywhere but beside the seal is a list that will one day be wrong
786 // about the module it names, and nothing will say so.
787 check('the scan does NOT accept a registration in a different file',
788 sawQuiet([fx('js/a.js', 'DaimondIdentity.wrap(v)'), fx('js/b.js', "DaimondRekey.register({ name: 'a' })")])
789 .join() === 'js/a.js',
790 'the registration has to be where the sealing is');
791 // The bug this scan had on its first run, kept as a check because a scanner that
792 // mis-reads the language can fail in either direction and only one of those is
793 // visible. See `stripped`.
794 check('a regex holding a quote does not blind the scan to what follows it',
795 sawQuiet([fx('js/f.js', 'var re = /[&<>"\']/g;\nDaimondIdentity.wrap(v);\n'
796 + "DaimondRekey.register({ name: 'f' });")]).length === 0
797 && sawSeal([fx('js/g.js', 'var re = /[&<>"\']/g;\nDaimondIdentity.wrap(v);')]).join() === 'js/g.js',
798 'the seal and the registration are both still visible after it');
799 // What it can and cannot see, stated as a check rather than as a claim. The first
800 // two are the spellings a person might reasonably write; the third is the one this
801 // cannot follow, and it is written down here so that nobody reads a green run as
802 // proof that no such call exists.
803 check('the scan follows the spellings a seal is actually written in',
804 sawSeal([fx('js/h.js', 'await DaimondIdentity\n\t.wrap(v)'),
805 fx('js/i.js', "await DaimondIdentity?.wrap(v)"),
806 fx('js/j.js', "await DaimondIdentity['wrapBytes'](v)")]).length === 3,
807 'a line break, an optional chain and a computed name are all still a seal');
808 // WHAT IT CANNOT SEE, and no check is written for it because a check that asserted
809 // the limitation would go red the day somebody removed it: a seal reached through
810 // an ALIAS — `var W = DaimondIdentity.wrap; await W(v)` — is invisible to any
811 // regex, and so is a module that seals by calling a helper in another file. What
812 // covers those is that the alias would have to be written deliberately, and that
813 // the registry is one lookup away at the same call site.
814 check('the scan does not count a seal that is only DESCRIBED',
815 sawSeal([fx('js/c.js', '// see DaimondIdentity.wrap(v) for how this is stored\n'),
816 fx('js/d.js', '/* DaimondIdentity.wrap(v) */'),
817 fx('js/e.js', 'var s = "DaimondIdentity.wrap(";')]).length === 0,
818 'comments and strings are not code');
819 // The check that stops this from being satisfiable by accident. Everything above
820 // asks whether the scan can fail; this asks whether it can pass for having found
821 // nothing at all — which is how a grep-based check dies quietly.
822 check('an empty tree is a FAILURE, not a clean scan',
823 sawSeal([]).length === 0 && KNOWN_SEALERS.length > 0,
824 'zero sealers means the scan is broken, and is reported as such below');
825
826 const scan = scanSealers(appSources());
827 const lost = KNOWN_SEALERS.filter(n => scan.sealers.indexOf(n) < 0);
828 check('the scan found the modules that seal',
829 scan.sealers.length > 0 && lost.length === 0,
830 scan.sealers.length === 0 ? 'IT FOUND NONE — the scan itself is broken'
831 : lost.length ? `it did not see ${lost.join(', ')}, which do seal`
832 : scan.sealers.join(', '));
833 check('EVERY MODULE THAT SEALS EITHER REGISTERS OR SAYS WHY NOT',
834 scan.quiet.length === 0,
835 scan.quiet.length ? `seals and says nothing: ${scan.quiet.join(', ')}`
836 : `${scan.sealers.length} sealers, all accounted for`);
837
838 // ── Seed: three mailboxes and a voice, sealed under the passphrase in force ──
839 await page.waitForSelector('#user-row', { timeout: 15000 });
840 await page.evaluate(async (a) => {
841 const accounts = [];
842 for (const m of a.boxes) {
843 accounts.push({
844 address: m.address, host: 'imap.test.local', port: 993, user: m.address,
845 pass: await DaimondIdentity.wrap(m.pass),
846 folder: 'INBOX',
847 folders: { INBOX: { dir: 'INBOX', uidValidity: 0, lastUid: 0, firstUid: 0,
848 heldBack: 0, limit: 0, lastSync: 0 } },
849 });
850 }
851 localStorage.setItem('daimond-mail',
852 JSON.stringify({ accounts, sel: accounts[0].address }));
853 window.DaimondMail.reload();
854 await DaimondVoice.set(a.voice);
855 // A second provider beside the one connectMock configured. Added through the
856 // module's own doors, so what is measured afterwards is a key stored the way
857 // the app stores one.
858 if (!DaimondModels.providers().some(p => p.id === a.p2.id)) {
859 DaimondModels.addProvider(a.p2.id, { name: a.p2.name, url: a.p2.url });
860 }
861 await DaimondModels.setKey(a.p2.id, a.p2.key);
862 // The search key, through the module's own door: `setKey` seals it, and that is
863 // the line that had nothing putting it back.
864 await DaimondSearch.setKey(a.s.engine, a.s.key);
865 // A map entry standing in for a chunk already in the cloud store, sealed under
866 // the passphrase about to go: nothing may offer it for reuse afterwards. A
867 // plausible entry rather than an empty map, because a check on a map that was
868 // empty to begin with would pass whatever the change did.
869 localStorage.setItem('daimond-chunk-map', JSON.stringify({
870 ['0'.repeat(64)]: ['f'.repeat(64), 4096],
871 }));
872 localStorage.removeItem('daimond-chunk-stale');
873 }, { boxes: BOXES, voice: VOICE, s: { engine: S_ENGINE, key: S_KEY },
874 p2: { id: P2_ID, name: P2_NAME, key: P2_KEY, url: P2_ID.slice('custom:'.length) } });
875
876 // WHO SAYS THEY TAKE PART. The source scan proves every sealer registers in its own
877 // file; this proves the registration RAN. A module that index.html never loads, or
878 // whose registration sits behind a condition that is false in a browser, satisfies
879 // the source and is absent here — which is the gap neither check can see alone.
880 const reg = await page.evaluate(() => ({
881 names: DaimondRekey.names(),
882 refused: DaimondRekey.refusals(),
883 exempt: DaimondRekey.exemptions(),
884 }));
885 // WHAT MUST BE THERE IS READ OUT OF THE SOURCE, not written here. A list of expected
886 // participants kept in this file would be the hand-written list all over again, one
887 // directory along: it would go stale the first time somebody added a module, and it
888 // would go stale silently, which is the whole complaint.
889 const WANT = scan.claims;
890 const absent = WANT.filter(n => reg.names.indexOf(n) < 0);
891 check('every module that seals is registered IN THE RUNNING APP',
892 absent.length === 0 && WANT.length > 0,
893 absent.length ? `never registered: ${absent.join(', ')}`
894 : WANT.length === 0 ? 'the source claims no participants at all, so this proved nothing'
895 : reg.names.join(', '));
896 check('and no registration was refused',
897 reg.refused.length === 0,
898 reg.refused.map(r => `${r.name}: ${r.why}`).join('; ') || 'all accepted');
899
900 // The instrument, proved before anything is measured with it: every fixture is
901 // readable NOW. A check that the password survives is worth nothing if the
902 // password was never there.
903 for (const b of BOXES) {
904 const r = await opened(b.address);
905 check(`fixture: ${b.address}'s password is sealed and readable before the change`,
906 r.text === b.pass, r.err || JSON.stringify(r.text));
907 }
908 const v0 = await voiceNow();
909 check('fixture: the forge voice is sealed and readable before the change',
910 v0.text === VOICE, v0.err || JSON.stringify(v0.text));
911
912 // The two providers, and which of them the store iterates FIRST — `modelfirstonly`
913 // re-seals whichever that is, so the two checks below have to be pinned to the
914 // store's own order rather than to this file's idea of it.
915 const ps0 = await providerState();
916 const withKey = ps0.order.filter(id => ps0.providers[id].opens
917 && ps0.providers[id].opens.indexOf('UNREADABLE') !== 0
918 && ps0.providers[id].opens !== '(no keyEnc)');
919 const P1_ID = withKey[0] || '';
920 const P1_KEY = P1_ID ? ps0.providers[P1_ID].opens : '';
921 check('fixture: two providers hold readable keys before the change',
922 withKey.length >= 2 && ps0.providers[P2_ID] && ps0.providers[P2_ID].opens === P2_KEY
923 && ps0.ready === true && ps0.resolved === P1_KEY,
924 `${withKey.length} keyed; first=${P1_ID}; ready=${ps0.ready}; resolve=${JSON.stringify(ps0.resolved)}`);
925
926 const s0 = await searchState(S_ENGINE);
927 check('fixture: the search key is sealed and readable before the change',
928 s0.opens === S_KEY && s0.says === S_KEY,
929 `stored opens to ${JSON.stringify(s0.opens)}; the module says ${JSON.stringify(s0.says)}`);
930
931 const needles = BOXES.map(b => ({ what: `${b.address}'s password`, text: b.pass }))
932 .concat([{ what: 'the forge voice', text: VOICE }])
933 .concat(P1_KEY ? [{ what: "the first provider's key", text: P1_KEY }] : [])
934 .concat([{ what: "the second provider's key", text: P2_KEY }])
935 .concat([{ what: "the search service's key", text: S_KEY }]);
936 const hits0 = await plaintextHits(needles);
937 check('THE STORED SECRETS ARE NEVER PLAINTEXT (before the change)',
938 hits0.length === 0, hits0.join('; ') || 'nothing in the clear');
939
940 // ── The change ───────────────────────────────────────────────────
941 const said1 = await changePassphrase(PASS, NEW1);
942 console.log(` the app said: ${JSON.stringify(said1.body.slice(0, 200))}`);
943 check('control: the change ended in a notice headed "Passphrase changed"',
944 said1.head === 'Passphrase changed', JSON.stringify(said1.head) || 'no notice appeared');
945
946 // Check 4 is measured HERE, before the reload: a reload would drop the module
947 // and its hold with it, which would make every run green for the wrong reason.
948 const held1 = await heldNow();
949 check('THE PLAINTEXTS DO NOT OUTLIVE THE CHANGE',
950 held1.leaked.length === 0 && held1.wrote.length === 0,
951 held1.leaked.length ? `still held: ${held1.leaked.join(', ')}`
952 : held1.wrote.length ? `re-wrote ${held1.wrote.join(', ')} from a hold that should be empty`
953 : 'the hold is empty');
954
955 // ── Reload, and unlock with the NEW passphrase ───────────────────
956 //
957 // The point of the reload: the wrapping key is now derived from the new
958 // passphrase from scratch. Unwrapping with the key that happened to be in memory
959 // would pass even if the change had never been applied to storage at all.
960 const openedNew = await unlockWith(NEW1);
961 check('control: the new passphrase unlocks the account', openedNew === true,
962 openedNew ? '' : 'the gate did not open, so nothing below means anything');
963
964 for (const b of BOXES) {
965 const r = await opened(b.address);
966 const first = b === BOXES[0];
967 check(first
968 ? `A MAILBOX PASSWORD SURVIVES THE CHANGE (${b.address})`
969 : `SEVERAL MAILBOXES SURVIVE, not just the first (${b.address})`,
970 r.text === b.pass,
971 r.err || (r.text === b.pass ? 'the same password as before'
972 : `opened to ${JSON.stringify(r.text)}, not ${JSON.stringify(b.pass)}`));
973 }
974
975 // ── The provider keys, in the three places the defect showed ─────
976 const ps1 = await providerState();
977 const p1 = ps1.providers[P1_ID] || { opens: '(absent)', plaintext: '' };
978 const p2 = ps1.providers[P2_ID] || { opens: '(absent)', plaintext: '' };
979 check(`A PROVIDER API KEY SURVIVES THE CHANGE (${P1_ID})`,
980 p1.opens === P1_KEY && ps1.ready === true && ps1.resolved === P1_KEY,
981 `keyEnc ${p1.opens === P1_KEY ? 'opens to the same key' : JSON.stringify(p1.opens)}; `
982 + `ready=${ps1.ready}; resolve=${JSON.stringify(ps1.resolved)}`);
983 check(`SEVERAL PROVIDERS SURVIVE, not just the first (${P2_NAME})`,
984 p2.opens === P2_KEY,
985 p2.opens === P2_KEY ? 'the same key as before' : JSON.stringify(p2.opens));
986 // The re-seal writes `p.key = ''`; a plaintext copy left beside the sealed one
987 // would be a key in the clear that nothing ever offers to remove.
988 check('and the re-seal leaves no plaintext key beside the sealed one',
989 !p1.plaintext && !p2.plaintext,
990 `${P1_ID}:${JSON.stringify(p1.plaintext)} ${P2_ID}:${JSON.stringify(p2.plaintext)}`);
991
992 // ── The search key, the one still live that morning ──────────────
993 const s1 = await searchState(S_ENGINE);
994 check(`THE SEARCH KEY SURVIVES THE CHANGE (${S_ENGINE})`,
995 s1.opens === S_KEY && s1.says === S_KEY,
996 s1.opens === S_KEY && s1.says === S_KEY ? 'the same key as before'
997 : `stored opens to ${JSON.stringify(s1.opens)}; the module says ${JSON.stringify(s1.says)}`);
998 check('and the search re-seal leaves no plaintext key beside the sealed one',
999 !s1.plaintext, JSON.stringify(s1.plaintext));
1000
1001 // ── The chunk store, which cannot be re-wrapped and must not be reused ──
1002 //
1003 // `chunks.js` seals AT REST: the ciphertext lives on the gateway for as long as the
1004 // file is in the cloud store, so a passphrase change leaves every chunk up there
1005 // sealed under a key nobody has. It cannot re-wrap them from a dialog — that is
1006 // gigabytes over the wire, and it could not reach a file this device does not hold
1007 // anyway — so what it must do instead is make sure none of that ciphertext is ever
1008 // offered for reuse. The address map goes, and the debt is recorded so that
1009 // `collectChunked` offloads again rather than skipping the files as unchanged.
1010 const chunkState = await page.evaluate(() => ({
1011 map: Storage.prototype.getItem.call(localStorage, 'daimond-chunk-map'),
1012 stale: !!(window.DaimondChunks && DaimondChunks.staleSinceRekey && DaimondChunks.staleSinceRekey()),
1013 }));
1014 check('THE CHUNK ADDRESSES SEALED UNDER THE OLD PASSPHRASE ARE NOT REUSED',
1015 (!chunkState.map || chunkState.map === '{}') && chunkState.stale === true,
1016 `the map is ${JSON.stringify(chunkState.map)}; a re-offload is owed: ${chunkState.stale}`);
1017
1018 const v1 = await voiceNow();
1019 check('THE FORGE VOICE SURVIVES THE CHANGE',
1020 v1.text === VOICE, v1.err || (v1.text === VOICE ? 'the same secret as before'
1021 : `now ${JSON.stringify(v1.text)}`));
1022
1023 const hits1 = await plaintextHits(needles);
1024 check('THE STORED SECRETS ARE NEVER PLAINTEXT (after the change and a reload)',
1025 hits1.length === 0, hits1.join('; ') || 'nothing in the clear');
1026
1027 // ── A change that FAILS ──────────────────────────────────────────
1028 //
1029 // Driven for real. The wrapped private key is corrupted while the new-passphrase
1030 // dialog is open — after the current passphrase has been accepted and before
1031 // `changePassphrase` opens the key with it — so the GCM tag fails and the real
1032 // function returns `{ ok: false }` on the real path, with the mailbox passwords
1033 // already read out and held.
1034 //
1035 // What each mailbox opens to on the way in, so that "a failed change changed
1036 // nothing" is asked as exactly that, against the state the failure met. Compared
1037 // with the FIXTURE instead, this would go red under any break that had already
1038 // broken the mailbox — reporting the earlier defect a second time, in a check that
1039 // is not about it.
1040 const beforeFail = {};
1041 for (const b of BOXES) beforeFail[b.address] = JSON.stringify(await opened(b.address));
1042 let savedPriv = '';
1043 const said2 = await changePassphrase(NEW1, NEW2, async () => {
1044 savedPriv = await page.evaluate(() => {
1045 const raw = localStorage.getItem('daimond-id-priv') || '';
1046 const c = raw[5] === 'A' ? 'B' : 'A';
1047 localStorage.setItem('daimond-id-priv', raw.slice(0, 5) + c + raw.slice(6));
1048 return raw;
1049 });
1050 });
1051 await page.evaluate((raw) => localStorage.setItem('daimond-id-priv', raw), savedPriv);
1052 console.log(` the app said: ${JSON.stringify(said2.body.slice(0, 140))}`);
1053
1054 // Control, and it is load-bearing: check 5 is about the FAILURE path, so the
1055 // change really must have failed. If it had gone through, the probe below would
1056 // be measuring the success path under another name.
1057 const state = await page.evaluate(async (a) => ({
1058 old: await DaimondIdentity.verify(a.NEW1),
1059 neu: await DaimondIdentity.verify(a.NEW2),
1060 }), { NEW1, NEW2 });
1061 check('control: the failed change really did not happen',
1062 state.old === true && state.neu === false,
1063 `${NEW1.slice(0, 12)}… still opens: ${state.old}; the attempted one opens: ${state.neu}`);
1064
1065 const held2 = await heldNow();
1066 check('A FAILED CHANGE LEAVES NO PASSWORD IN MEMORY',
1067 held2.leaked.length === 0 && held2.wrote.length === 0,
1068 held2.leaked.length ? `still held: ${held2.leaked.join(', ')}`
1069 : held2.wrote.length ? `re-wrote ${held2.wrote.join(', ')} from a hold that should be empty`
1070 : 'the hold is empty');
1071
1072 // And the mailboxes are exactly as the failed change found them.
1073 for (const b of BOXES) {
1074 const now = JSON.stringify(await opened(b.address));
1075 check(`a failed change leaves ${b.address}'s stored password as it found it`,
1076 now === beforeFail[b.address],
1077 now === beforeFail[b.address] ? 'unchanged' : `${beforeFail[b.address]} -> ${now}`);
1078 }
1079
1080 const hits2 = await plaintextHits(needles);
1081 check('THE STORED SECRETS ARE NEVER PLAINTEXT (after the failed change)',
1082 hits2.length === 0, hits2.join('; ') || 'nothing in the clear');
1083
1084 // ── One secret's failure, against unmodified code ────────────────
1085 //
1086 // Every re-seal now sits in its own try/catch and none of them returns, so a
1087 // failure in any one of them is supposed to cost nothing but a sentence in the
1088 // notice. In an ordinary run they all succeed, which is exactly why that claim
1089 // cannot be read off a clean run: it needs a failure, and it needs one that is not
1090 // simulated by patching the source. So the API key's re-wrap is made to fail from
1091 // OUTSIDE the app — `DaimondIdentity.wrap` refuses that one plaintext — and three
1092 // secrets are asked whether they survived: a mailbox and a provider key from ABOVE
1093 // the failing block, and the push token from BELOW it.
1094 //
1095 // The push token is the one that matters. A reinstated `return` in the API key's
1096 // catch — the single line this restructure deleted — costs nothing above it, so a
1097 // check that asked only about the mailbox would stay green through the very
1098 // regression it was written for.
1099 //
1100 // The push credential is seeded into the stored config and picked up by a reload,
1101 // because `afterUnlock` is what puts `cfg.pushToken` in memory and `doChangePassphrase`
1102 // reads it from there. The mail, voice and provider fixtures are re-set under the
1103 // key in force so that this section measures ITS change and not what an earlier
1104 // break left behind.
1105 await page.evaluate(async (tok) => {
1106 const b = JSON.parse(localStorage.getItem('daimond-byok') || '{}');
1107 b.pushHost = 'https://example.invalid/repo.git';
1108 b.pushUser = 'tester';
1109 b.pushTokenEnc = await DaimondIdentity.wrap(tok);
1110 localStorage.setItem('daimond-byok', JSON.stringify(b));
1111 }, PUSHTOK);
1112 const openedAgain = await unlockWith(NEW1);
1113 check('control: the push credential is in memory for the change to re-seal',
1114 openedAgain === true && (await pushNow()).text === PUSHTOK,
1115 JSON.stringify((await pushNow()).text || (await pushNow()).err));
1116
1117 const armed = await page.evaluate(async (a) => {
1118 const j = JSON.parse(localStorage.getItem('daimond-mail'));
1119 for (const x of j.accounts) {
1120 const m = a.boxes.find(b => b.address === x.address);
1121 if (m) x.pass = await DaimondIdentity.wrap(m.pass);
1122 }
1123 localStorage.setItem('daimond-mail', JSON.stringify(j));
1124 window.DaimondMail.reload();
1125 await DaimondVoice.set(a.voice);
1126 // Set again deliberately, and not because the re-seal is doubted: it is set
1127 // here so that this section is independent of whether the re-seal above worked.
1128 // Without it `nomodels` would leave `cfg.apiKey` empty, the API key block would
1129 // be SKIPPED rather than failing, and this whole section would measure nothing
1130 // while reporting green.
1131 const d = DaimondModels.getDefault();
1132 if (d && d.provider) await DaimondModels.setKey(d.provider, a.key);
1133 const r = DaimondModels.resolve('', '');
1134 // Only now: `setKey` wraps the key itself, and a refusal installed first would
1135 // have stopped the arrangement rather than the change.
1136 const real = DaimondIdentity.wrap;
1137 DaimondIdentity.wrap = async function (v) {
1138 if (String(v) === a.key) throw new Error('the API key cannot be re-wrapped (probe)');
1139 return await real(v);
1140 };
1141 return !!(r && r.apiKey === a.key);
1142 }, { boxes: BOXES, voice: VOICE, key: P1_KEY });
1143 check('control: the API key is readable, so the block that will fail really runs',
1144 armed === true, armed ? '' : 'no provider key resolved; the checks below prove nothing');
1145
1146 const NEW3 = 'a third new passphrase, with the api key failing';
1147 const said3 = await changePassphrase(NEW1, NEW3);
1148 console.log(` the app said: ${JSON.stringify(said3.body)}`);
1149 // Specifically the API key's own sentence. `/could not be re-encrypted/` alone also
1150 // matches the PROVIDERS sentence, which the same refusal produces — the default
1151 // provider's key IS `cfg.apiKey`, so one refused plaintext fails both — and a
1152 // control that cannot tell the two apart would pass while the block it is about
1153 // had been skipped.
1154 check('control: the API key re-wrap really did fail',
1155 /your API key could not be re-encrypted/.test(said3.body), JSON.stringify(said3.body.slice(0, 160)));
1156 // Check 8. One exit, and it leads with the sentence that is true whatever else
1157 // went wrong. Before the restructure this path ended in a bare "Careful" and the
1158 // user was never told the passphrase had changed at all.
1159 check('THE NOTICE SAYS THE PASSPHRASE CHANGED AND THEN NAMES WHAT FAILED',
1160 said3.head === 'Passphrase changed'
1161 && /your API key could not be re-encrypted/.test(said3.body),
1162 `heading ${JSON.stringify(said3.head)}`);
1163
1164 const opened3 = await unlockWith(NEW3);
1165 check('control: the third passphrase unlocks the account', opened3 === true);
1166 const r3 = await opened(BOXES[0].address);
1167 const ps3 = await providerState();
1168 const pu3 = await pushNow();
1169 check('A FAILURE IN ONE SECRET CANNOT COST A MAILBOX (above it)',
1170 r3.text === BOXES[0].pass,
1171 r3.err || (r3.text === BOXES[0].pass ? `${BOXES[0].address} survived` : JSON.stringify(r3.text)));
1172 check('A FAILURE IN ONE SECRET CANNOT COST A PROVIDER KEY (above it)',
1173 (ps3.providers[P2_ID] || {}).opens === P2_KEY,
1174 JSON.stringify((ps3.providers[P2_ID] || {}).opens));
1175 check('A FAILURE IN ONE SECRET CANNOT COST THE PUSH TOKEN (below it)',
1176 pu3.text === PUSHTOK,
1177 pu3.err ? `the stored token is ${pu3.err}` : JSON.stringify(pu3.text));
1178
1179 // And a failed re-wrap must not fall back to writing the thing in the clear:
1180 // `saveCfg` stores a plaintext `apiKey` whenever `apiKeyEnc` is empty, which is a
1181 // deliberate path for a browser with no identity and would be a leak here.
1182 const hits3 = await plaintextHits(needles.concat([{ what: 'the push token', text: PUSHTOK }]));
1183 check('THE STORED SECRETS ARE NEVER PLAINTEXT (after a change with a failure in it)',
1184 hits3.length === 0, hits3.join('; ') || 'nothing in the clear');
1185
1186 // ── Checks 11 and 12: the sequence, watched from outside it ──────
1187 //
1188 // Everything above is about a particular secret, and a check per secret is a list —
1189 // the same hand-written list that was wrong four times over. What follows is about
1190 // the walk itself, and it is measured from OUTSIDE the registry: each live
1191 // participant's own phases are wrapped before the change and watched being called,
1192 // because a registry reporting on itself would be self-consistent and prove
1193 // nothing. It is also the only measurement `chunks` and `sync` get — neither has a
1194 // visible effect in a world with no gateway, and "it is in the list" is not the
1195 // same claim as "it was reached".
1196 //
1197 // Four probes go in behind the real ones. `probe-throws` sits between two that
1198 // record, so the ones after a failure are asked whether they still ran; `probe-a`
1199 // carries both phases and reports whether the OLD passphrase still verified when
1200 // each was called, which is how the two phases are shown to straddle the key swap
1201 // rather than merely to happen in the right order in the source.
1202 const NEW4 = 'a fourth new passphrase, this one watched by probes';
1203 const registered = await page.evaluate((a) => {
1204 const P = window.__probe = {
1205 ran: [], read: [], args: [], reports: [], forgot: 0,
1206 verifyAtRead: null, verifyAtReseal: null,
1207 };
1208 // The live participants, wrapped where they stand. `participants()` hands back
1209 // the objects themselves; a copy could show only that a list exists.
1210 DaimondRekey.participants().forEach((p) => {
1211 const rs = p.reseal, rd = p.read;
1212 p.reseal = function () {
1213 P.ran.push(p.name); P.args.push(p.name + '/reseal:' + arguments.length);
1214 return rs.apply(this, arguments);
1215 };
1216 if (rd) p.read = function () {
1217 P.read.push(p.name); P.args.push(p.name + '/read:' + arguments.length);
1218 return rd.apply(this, arguments);
1219 };
1220 });
1221 // And what the registry hands back to the caller, so it can be searched for
1222 // anything it had no business carrying.
1223 const rl = DaimondRekey.readAll, ra = DaimondRekey.resealAll;
1224 DaimondRekey.readAll = async function () {
1225 const r = await rl.apply(null, arguments); P.reports.push(JSON.stringify(r)); return r;
1226 };
1227 DaimondRekey.resealAll = async function () {
1228 const r = await ra.apply(null, arguments); P.reports.push(JSON.stringify(r)); return r;
1229 };
1230 DaimondRekey.register({
1231 name: 'probe-a',
1232 read: async function () {
1233 P.read.push('probe-a'); P.args.push('probe-a/read:' + arguments.length);
1234 P.verifyAtRead = await DaimondIdentity.verify(a.cur);
1235 return { held: 0, failed: [] };
1236 },
1237 reseal: async function () {
1238 P.ran.push('probe-a'); P.args.push('probe-a/reseal:' + arguments.length);
1239 P.verifyAtReseal = await DaimondIdentity.verify(a.cur);
1240 return { failed: [] };
1241 },
1242 forget: function () { P.forgot++; },
1243 });
1244 DaimondRekey.register({
1245 name: 'probe-throws',
1246 reseal: function () { P.ran.push('probe-throws'); throw new Error('a probe that fails'); },
1247 });
1248 DaimondRekey.register({
1249 name: 'probe-b',
1250 reseal: function () { P.ran.push('probe-b'); return { failed: [] }; },
1251 });
1252 DaimondRekey.register({
1253 name: 'probe-tail',
1254 reseal: function () { P.ran.push('probe-tail'); return { failed: [] }; },
1255 });
1256 return DaimondRekey.names();
1257 }, { cur: NEW3 });
1258
1259 const said4 = await changePassphrase(NEW3, NEW4);
1260 const P = await page.evaluate(() => window.__probe);
1261 console.log(` the app said: ${JSON.stringify(said4.body.slice(0, 200))}`);
1262 check('control: the watched change happened', said4.head === 'Passphrase changed',
1263 JSON.stringify(said4.head) || 'no notice appeared');
1264
1265 // Asked as "is anything in the list unreached", NOT as "did twelve things run". A
1266 // literal count would go red the day somebody registers a ninth module, and would
1267 // be reporting the wrong fault when it did — this check is about the walk, and the
1268 // question of who is on the list belongs to the two checks that already ask it.
1269 // The floor underneath it is what stops an empty registry passing: the four probes
1270 // this file registered itself must be there, and something of the app's must be
1271 // there with them.
1272 const PROBES = ['probe-a', 'probe-throws', 'probe-b', 'probe-tail'];
1273 const never = registered.filter(n => P.ran.indexOf(n) < 0);
1274 const noProbes = PROBES.filter(n => registered.indexOf(n) < 0);
1275 check('EVERY REGISTERED PARTICIPANT IS RUN, and none is registered into silence',
1276 never.length === 0 && noProbes.length === 0 && registered.length > PROBES.length,
1277 never.length ? `registered and never reached: ${never.join(', ')}`
1278 : noProbes.length ? `the probes never registered: ${noProbes.join(', ')}`
1279 : registered.length <= PROBES.length ? 'nothing but the probes is registered'
1280 : `${registered.length} ran: ${P.ran.join(', ')}`);
1281 // The one that follows the failure, and not the whole tail: "everything ran" is
1282 // check 11's question, and asking it twice would put this check red for a reason
1283 // that has nothing to do with a failure being contained.
1284 check('A PARTICIPANT THAT THROWS COSTS ONLY ITSELF',
1285 P.ran.indexOf('probe-throws') >= 0 && P.ran.indexOf('probe-b') >= 0,
1286 P.ran.indexOf('probe-throws') < 0 ? 'the throwing probe never ran, so nothing was proved'
1287 : `after it: ${P.ran.slice(P.ran.indexOf('probe-throws') + 1).join(', ') || 'NOTHING'}`);
1288 check('THE READ IS BEFORE THE KEY CHANGES AND THE RESEAL IS AFTER',
1289 P.verifyAtRead === true && P.verifyAtReseal === false,
1290 `the old passphrase verified at read: ${P.verifyAtRead}; at reseal: ${P.verifyAtReseal}`);
1291 // Structural, and it is what makes "the registry learns no secret" a property of
1292 // the interface rather than a promise in a comment: there is no parameter for a
1293 // plaintext to arrive on.
1294 const carried = P.args.filter(a => !/:0$/.test(a));
1295 check('NO PHASE IS CALLED WITH ANYTHING AT ALL',
1296 P.args.length > 0 && carried.length === 0,
1297 carried.length ? `called with arguments: ${carried.join(', ')}`
1298 : `${P.args.length} calls, every one of them empty-handed`);
1299 const report = P.reports.join(' ');
1300 const leaked = needles.concat([{ what: 'the push token', text: PUSHTOK }])
1301 .concat([{ what: 'the new passphrase', text: NEW4 }])
1302 .filter(n => report.indexOf(n.text) >= 0).map(n => n.what);
1303 check('THE REGISTRY CARRIES NAMES AND COUNTS, NEVER A SECRET',
1304 leaked.length === 0 && /probe-throws/.test(report),
1305 leaked.length ? `it carried ${leaked.join(', ')}`
1306 : /probe-throws/.test(report) ? 'a report with a named failure in it, and no secret'
1307 : 'the report named nothing at all, so this proved nothing');
1308
1309} catch (e) {
1310 check('the run completed', false, String((e && e.message) || e));
1311} finally {
1312 await s.close?.().catch(() => {});
1313}
1314
1315console.log(`\n${ok.length} passed, ${bad.length} failed`);
1316if (BREAK) {
1317 console.log(bad.length
1318 ? `\nbreak '${BREAK}' produced failures, as it must:\n - ${bad.join('\n - ')}`
1319 : `\nBREAK '${BREAK}' CHANGED NOTHING — the check it targets is not proving anything.`);
1320}
1321process.exit(bad.length ? 1 : 0);