fix: à la reconnexion, on retrouve ce qu'on possède — pas seulement ce qu'on a reçu

Une application signalait deux symptômes. Ils sont indépendants, et ils ont une
racine commune : se connecter ne rejouait qu'UN des registres durables du
portefeuille.

connectedUser lisait les AddLink de la branche User — ce qu'on vous a partagé —
et rien d'autre. Les capacités des documents que vous avez FAITS vivent sur la
branche Store, et un seul chemin les relisait : listMyEntityDocs. Une
application qui recharge et va droit à sa note ne tenait donc rien pour elle.
Constaté : capFor(note) vaut undefined juste après une connexion résolue, et
devient défini dès que listMyEntityDocs passe.

Le public survivait en lecture parce que fetchReadCap va rechercher la clé dans
le store ; il échouait quand même à l'écriture, qui ne fait pas cette démarche.

Deuxième défaut : myInboxes énumérait les inbox sans en remettre la clé au
détenteur. Se connecter demandait donc un document qu'on n'avait pas de quoi
lire — sur une inbox, que l'application n'a jamais nommée puisque rien ne le
lui permet.

Troisième défaut, et c'est lui qui rendait tout ça fatal : un drainage refusé
faisait échouer toute la connexion. Une inbox n'étant pas consommée par un
échec, elle refusait à chaque tentative suivante. D'où le « trois fois sur
trois », et d'où un verrouillage plutôt qu'un partage manquant.

C'est ma spécification qui l'a créé. En rendant les échecs visibles j'avais
écrasé une distinction : ne pas ATTEINDRE la file est une panne, et refuser la
session est juste ; ne pas pouvoir APPLIQUER un élément est une donnée, et ça ne
doit priver personne de sa session. Le drainage par inbox est désormais isolé —
signalé haut et fort, les autres files drainées, la session accordée — tandis
qu'énumérer les files et restaurer rejettent toujours.

Le parcours e2e ratait les deux : personne ne se reconnecte après avoir ouvert
son document aux messages. Il s'arrêtait une reconnexion trop tôt.
This commit is contained in:
Sylvain Duchesne
2026-08-16 17:23:27 +02:00
parent b50591f5bd
commit f6d1734679
8 changed files with 1113 additions and 49 deletions
+1
View File
@@ -6,3 +6,4 @@
## Raw markers (consolidate into blocks, then delete) ## Raw markers (consolidate into blocks, then delete)
- TOUCHED packages/polyfill/src/shared-wallet/account-registry.ts @2026-08-16 (session f93872b5-293a-4916-a353-181409a96d42) - TOUCHED packages/polyfill/src/shared-wallet/account-registry.ts @2026-08-16 (session f93872b5-293a-4916-a353-181409a96d42)
- TOUCHED packages/polyfill/src/shared-wallet/bootstrap.ts @2026-08-16 (session f93872b5-293a-4916-a353-181409a96d42) - TOUCHED packages/polyfill/src/shared-wallet/bootstrap.ts @2026-08-16 (session f93872b5-293a-4916-a353-181409a96d42)
- TOUCHED packages/polyfill/src/emulated-verifier/connect.ts @2026-08-16 (session f93872b5-293a-4916-a353-181409a96d42)
@@ -37,7 +37,7 @@ import { sparqlQuery } from "../surface/docs";
import { readForHolder, registerUpdate } from "./register-write"; import { readForHolder, registerUpdate } from "./register-write";
import { getCaps, getCurrentUser } from "../shared-wallet/bootstrap"; import { getCaps, getCurrentUser } from "../shared-wallet/bootstrap";
import { escapeLiteral } from "../surface/sparql"; import { escapeLiteral } from "../surface/sparql";
import { hasReadCap, isNuri, toNuri } from "../model/nuri"; import { hasReadCap, isNuri, targetOf, toNuri } from "../model/nuri";
import { mustNotAttempt } from "./reach"; import { mustNotAttempt } from "./reach";
import { fetchReadCap } from "./public-store"; import { fetchReadCap } from "./public-store";
import { ensureRepoOpen } from "./open-repo"; import { ensureRepoOpen } from "./open-repo";
@@ -51,6 +51,7 @@ import {
session, session,
readBindings, readBindings,
bindingValue, bindingValue,
lookupAccount,
resolveAccount, resolveAccount,
storeOf, storeOf,
readUserStore, readUserStore,
@@ -188,28 +189,97 @@ export async function publishInboxAddress(doc: Nuri, inbox: Nuri): Promise<void>
* The ReadCaps recorded on a store's Store branch — its documents, each with its * The ReadCaps recorded on a store's Store branch — its documents, each with its
* key. The emulated replay of `AddRepo`, and the reason a fresh session recovers * key. The emulated replay of `AddRepo`, and the reason a fresh session recovers
* what it owns without recomputing anything. * what it owns without recomputing anything.
*
* **Propagates a failed read**, like {@link readLinks} beside it and for the same reason:
* empty and unreadable are the same value here and could not mean more different things —
* "I own nothing in this store" against "every document I own is invisible and nothing
* said so". {@link restoreOwnCaps} is the caller that cannot survive the confusion, since
* its whole contract is that the connection either did the restore or says it did not.
* A caller that genuinely prefers to carry on catches it itself, and one of them does.
*/ */
export async function readStoreCaps(storeDoc: Nuri): Promise<ReadCap[]> { export async function readStoreCaps(storeDoc: Nuri): Promise<ReadCap[]> {
const s = await session(); const s = await session();
const out: ReadCap[] = []; const out: ReadCap[] = [];
try { const res = await sparqlQuery(
const res = await sparqlQuery( s.sessionId,
s.sessionId, `SELECT ?c WHERE { <${STORE_BRANCH_SUBJECT}> <${P.readCap}> ?c }`,
`SELECT ?c WHERE { <${STORE_BRANCH_SUBJECT}> <${P.readCap}> ?c }`, undefined,
undefined, storeDoc,
storeDoc, "readStoreCaps",
"readStoreCaps", );
); for (const row of readBindings(res)) {
for (const row of readBindings(res)) { const v = bindingValue(row, "c");
const v = bindingValue(row, "c"); if (v && hasReadCap(v)) out.push(v);
if (v && hasReadCap(v)) out.push(v);
}
} catch (error) {
console.error(accessLogPrefix() + " readStoreCaps failed:", error);
} }
return out; return out;
} }
/**
* Put back in the connected user's hands the key of EVERY document it owns — the three
* Store branches read back, which is the emulated replay of `AddRepo { read_cap }`
* (`AddRepo::verify` → `Verifier::load_repo_from_read_cap`,
* `engine/verifier/src/verifier.rs:2237`).
*
* ── Why connecting has to do this, and why the store record is not enough ──
* A document's cap is written in exactly one durable place — the Store branch of the
* store it was created in ({@link holdOwnCap}) — and until 2026-08-16 exactly one path
* read it back: `listMyEntityDocs`. So a creator that reloaded the page and went straight
* to the document it had just made, without listing that scope first, held nothing for it:
* the read was refused, the batch read (`readUnion`) dropped it silently, and the write
* was refused. Its own document, denied to its own author, on the first refresh.
*
* Restoring what a user HOLDS is already what connecting means here — that is what the
* User-branch Links step does for caps RECEIVED from others. Its own documents are the
* other half of the same act, and the more fundamental one: a received cap is a bonus, a
* created document is the user's own content.
*
* The scope stores are filed first ({@link fileOwnStructure}), because the Store branch
* lives INSIDE the store document and reading it is itself a guarded read. Not left to a
* side effect of whatever ran before: the order is carried by this composition rather than
* by where the call happens to sit.
*
* `holderKey` is the ring these land in — captured by the caller when it decided whose
* connection this is, and handed back here, exactly as `readLinks`' caller does. See
* `caps.holderKey`.
*
* Nothing to restore is not a failure: an identity with no account yet owns no store to
* read. A failed READ is one, and it propagates — the caller is `connect.connectedUser`,
* whose contract is that it did the work or said it did not.
*/
export async function restoreOwnCaps(holderKey: string): Promise<void> {
const holder = getCurrentUser();
if (holder === null) return;
// `lookupAccount`, not `resolveAccount`: a read that could not ANSWER must not arrive
// here as "this identity has no account", which is the one absence entitled to silence.
// Its caller resolved the same account a moment ago, so this is a cache hit.
const record = await lookupAccount(holder);
if (record === null) return;
// The store documents themselves, or the reads below would be refused for want of the
// very structure this user owns by BEING a user.
fileOwnStructure(holder, record);
const caps = getCaps();
for (const scope of ["public", "protected", "private"] as const) {
const store = storeOf(record, scope);
if (!store) continue;
// COLD-START heal, and it is the whole point of this function running at CONNECTION
// time: on a fresh session the store repo is not yet in the verifier's `self.repos`,
// and an anchored read of a repo that is not open returns 0 rows — it does not fail.
// Without this the restore would answer "you own nothing" on exactly the session that
// needs it, silently, which is the failure-as-absence this whole path exists against.
// Same guard `readUserStore` and `readLinks` already apply to the same documents.
await ensureRepoOpen(store);
for (const cap of await readStoreCaps(store)) {
// `learnFor`, never a fresh mint: the cap must be the value the Store branch
// carries — see the note in `holdOwnCap` on why a second mint locks the owner out
// the day the stand-in value becomes a real key.
caps.learnFor(holderKey, cap);
// Which store a document sits in is a registry fact, not one recorded beside the
// caps, so it is re-applied here — marking only, like `listMyEntityDocs` does.
if (scope === "public") caps.markInPublicStore(targetOf(cap));
}
}
}
/** /**
* WHERE to deposit for `doc` — its inbox address, or `undefined` if its owner never * WHERE to deposit for `doc` — its inbox address, or `undefined` if its owner never
* opened one. The deposit-side counterpart of {@link openDocumentInbox}, and the * opened one. The deposit-side counterpart of {@link openDocumentInbox}, and the
@@ -348,6 +418,24 @@ export async function readInboxCapsFor(doc: Nuri): Promise<Nuri | undefined> {
/** /**
* Every inbox this user may READ: its own, plus one per document it opened an * Every inbox this user may READ: its own, plus one per document it opened an
* inbox on. What `connect.connectedUser` drains, and what `isOwnInbox` answers from. * inbox on. What `connect.connectedUser` drains, and what `isOwnInbox` answers from.
*
* ── Listing an inbox PUTS IT IN YOUR HANDS, both levels alike ─────────────
* An `AddInboxCap` record is not a note that an inbox exists — upstream it IS the key:
* `AddInboxCapV0 { repo_id, overlay, priv_key }` (`engine/repo/src/types.rs:1973`), which
* `update_inbox_cap_v0` applies straight into the repo (`verifier.rs:1920`). So a session
* that can enumerate an inbox from that record can read it, by construction.
*
* Here the record carries the pair and not the key, so the entitlement it expresses is
* honoured the same way {@link fileOwnInbox} already honours it for a user's OWN two
* inboxes, one line above: the cap is minted from the NURI for the holder the record
* belongs to. Same emulation, same stand-in, and at migration both are replaced by the
* `priv_key` the record carries.
*
* Left out until 2026-08-16 for the DOCUMENT inboxes, and the consequence was not a
* missing feature: connecting enumerated an inbox it then had no key to read, the guarded
* read refused it, and the refusal came back out of `ensureIdentity()` — a rejected
* sign-in, on a document the application had never named, repeating at every connection
* because the record is durable. Reported live, three sign-ins out of three.
*/ */
export async function myInboxes(): Promise<Nuri[]> { export async function myInboxes(): Promise<Nuri[]> {
const holder = getCurrentUser(); const holder = getCurrentUser();
@@ -358,7 +446,11 @@ export async function myInboxes(): Promise<Nuri[]> {
if ((await resolveAccount(holder)) !== null) { if ((await resolveAccount(holder)) !== null) {
for (const scope of ["public", "protected"] as const) out.push(await userInbox(holder, scope)); for (const scope of ["public", "protected"] as const) out.push(await userInbox(holder, scope));
} }
for (const { inbox } of await readInboxCapPairs()) out.push(inbox); for (const { inbox } of await readInboxCapPairs()) {
// The record entitles this holder to read it — see the note above.
fileOwnInbox(holder, inbox);
out.push(inbox);
}
return out; return out;
} }
@@ -9,14 +9,28 @@
* *
* Two steps, in order, and the order matters: * Two steps, in order, and the order matters:
* *
* 1. **Restore** — read the Links already applied (`storeRegistry.readLinks`, the * 1. **Restore** — replay the durable registers back into what this user holds. All of
* emulated `AddLink` records on the User branch of the private store) back into * them: the Store branches of its three stores (the emulated `AddRepo { read_cap }` —
* what this user holds. This is durable state; it costs one read and needs no inbox. * the documents it CREATED, `branch-registers.restoreOwnCaps`) and the User branch's
* Links (the emulated `AddLink` — the caps it was GIVEN, `readLinks`). Durable state,
* a handful of reads, no inbox needed.
* 2. **Process** — drain the user's inbox (`inbox.processInbox`), which files any * 2. **Process** — drain the user's inbox (`inbox.processInbox`), which files any
* new Link durably and puts it among what the user holds. * new Link durably and puts it among what the user holds.
* *
* Restoring first means a reconnecting user can read its shared documents * Restoring first means a reconnecting user can read its documents immediately, without
* immediately, without waiting on the inbox round-trip. * waiting on the inbox round-trip.
*
* ── Restoring means ALL the registers, and that is a scar ─────────────────
* Until 2026-08-16 this step read the Links and nothing else, so a fresh page put back the
* caps a person had been GIVEN and not the ones for documents they had MADE. The Store
* branch was read by exactly one other path — `listMyEntityDocs` — so a creator who
* reloaded and went straight back to its own note (a route, a deep link) was refused it:
* the read threw, the batch read dropped it silently, and the write was refused. Its own
* document, denied to its own author, on the first refresh.
*
* The lesson generalises past that one register: what connecting owes is *everything the
* wallet durably says this user holds*, and any register left out of this step is a
* capability that exists on disk and not in the session.
* *
* ── Fire-and-forget, on purpose ─────────────────────────────────────────── * ── Fire-and-forget, on purpose ───────────────────────────────────────────
* `setCurrentUser` is synchronous and every consumer calls it from synchronous * `setCurrentUser` is synchronous and every consumer calls it from synchronous
@@ -36,9 +50,30 @@
import { getCaps, getCurrentUser } from "../shared-wallet/bootstrap"; import { getCaps, getCurrentUser } from "../shared-wallet/bootstrap";
import { lookupAccount } from "../shared-wallet/account-registry"; import { lookupAccount } from "../shared-wallet/account-registry";
import { accessLogPrefix } from "../shared-wallet/access-log"; import { accessLogPrefix, shortNuri } from "../shared-wallet/access-log";
import { myInboxes, readLinks } from "./branch-registers"; import { myInboxes, readLinks, restoreOwnCaps } from "./branch-registers";
import { processInbox } from "../surface/inbox"; import { processInbox } from "../surface/inbox";
import type { Nuri } from "../model/types";
/**
* Where the failure of ONE queue goes.
*
* Not a rejection — see the rule on {@link connectedUser} for why a queue is not the
* connection — and emphatically not silence. Same channel, same prefix and the same
* ungated `console.error` as {@link startConnect} below and as the deferred drain
* (`emulated-verifier/inbox-processor.ts`, whose header argues this exact point): a
* diagnostic may be opt-in, a failure may not.
*/
function reportUndrained(inbox: Nuri, error: unknown): void {
console.error(
accessLogPrefix() +
" connected, but this queue could not be drained — a share deposited in it is not " +
"applied yet, and connecting again will try it again: " +
shortNuri(inbox) +
":",
error,
);
}
/** The in-flight connection work, per user key — so two calls do not race. */ /** The in-flight connection work, per user key — so two calls do not race. */
const inFlight = new Map<string, Promise<void>>(); const inFlight = new Map<string, Promise<void>>();
@@ -55,8 +90,9 @@ const inFlight = new Map<string, Promise<void>>();
* a swallowed error. It swallowed **every** failure until 2026-08-13, offline broker * a swallowed error. It swallowed **every** failure until 2026-08-13, offline broker
* included, and that is what this shape replaces. * included, and that is what this shape replaces.
* *
* The rule, one line: **any failure rejects; only "there was nothing to do" resolves * The rule, one line: **failing to ESTABLISH the session rejects; failing to apply one of
* quietly.** Exactly three cases are nothing to do, and none of them is a failure: * its queues is reported and does not deny anyone their session.** And "there was nothing
* to do" resolves quietly. Exactly three cases are nothing to do, and none is a failure:
* *
* - **no identity connected** — anonymous holds nothing and owns no inbox; * - **no identity connected** — anonymous holds nothing and owns no inbox;
* - **the identity has no account yet** — nothing to restore, no queue to drain, and * - **the identity has no account yet** — nothing to restore, no queue to drain, and
@@ -66,9 +102,26 @@ const inFlight = new Map<string, Promise<void>>();
* - **the identity changed under the run** — abandoning is correct, and the next * - **the identity changed under the run** — abandoning is correct, and the next
* connection picks the work up (see `stillConnected`). * connection picks the work up (see `stillConnected`).
* *
* A restore that did not happen makes every shared document invisible, and an inbox that * ── Why a queue is NOT the connection, corrected 2026-08-16 ───────────────
* was not drained leaves a share unapplied. Both are the same event for the person using * This said "there is no third category here" and rejected on an undrained inbox too. The
* the application, so both are failures — there is no third category here. * reasoning was that an unapplied share and a lost restore look the same to a person. What
* it missed is what happens NEXT: an inbox is not consumed by failing, so a queue that
* cannot be applied is still on the list at the following connection, and the one after
* that. One unapplicable item therefore did not delay a share — it **locked the person out
* of the application, permanently**, and got worse rather than better with time. Reported
* live by a consuming application, three sign-ins out of three.
*
* That is strictly worse than the silence the 2026-08-13 shape replaced, and it collapsed
* a distinction that has to stay open: **failing to REACH the queues** (the session cannot
* proceed at all — reject, unchanged) against **failing to apply what is in one** (data,
* one queue, one person's share — report it, drain the others, let them in).
*
* The split needs no error classification, and that is what makes it trustworthy: the
* restore step is a plain `await` and still rejects, so a broker that cannot answer fails
* the connection there, before any queue is reached. Only the per-inbox drain is caught.
*
* Not silence: {@link reportUndrained} is loud and ungated, and the caps a share carries
* are not lost — the deposit stays in the queue, so the next connection applies it.
* *
* Not fixed with a retry, a timeout or a flag on purpose: deciding *what to do* about a * Not fixed with a retry, a timeout or a flag on purpose: deciding *what to do* about a
* broker that cannot answer belongs to the caller, and it can only decide if it is told. * broker that cannot answer belongs to the caller, and it can only decide if it is told.
@@ -113,7 +166,12 @@ export async function connectedUser(): Promise<void> {
// the same fault `inbox.share` was fixed for on 2026-08-10. // the same fault `inbox.share` was fixed for on 2026-08-10.
if ((await lookupAccount(holder)) === null) return; if ((await lookupAccount(holder)) === null) return;
if (!stillConnected()) return; if (!stillConnected()) return;
// 1. Durable first: what this user has already applied. // 1. Durable first, and ALL of it — see the header. The documents this user MADE, from
// the Store branches of its own stores, and then the caps it was GIVEN, from the
// User branch. Own documents first: they are the user's own content, and a person
// coming back to the note they wrote should not be waiting on anybody's share.
await restoreOwnCaps(holderKey);
if (!stillConnected()) return;
const links = await readLinks(); const links = await readLinks();
if (!stillConnected()) return; if (!stillConnected()) return;
for (const cap of links) getCaps().learnFor(holderKey, cap); for (const cap of links) getCaps().learnFor(holderKey, cap);
@@ -124,14 +182,24 @@ export async function connectedUser(): Promise<void> {
// applies to the SAME private store, and interleaving those writes buys // applies to the SAME private store, and interleaving those writes buys
// nothing on a queue that is nearly always empty. // nothing on a queue that is nearly always empty.
// //
// A queue that cannot be read stops the loop, so the inboxes after it are left // A queue that fails is reported and the next one is still drained — see the rule
// undrained — as before. What changed is that stopping is now audible: the caller // above for why one unapplicable item must not deny a person their session, nor
// is told the connection did not complete instead of being handed a resolved // take the OTHER queues down with it. Enumerating them is a different act and is
// promise over a half-drained wallet. // not caught: not knowing which queues exist is the session failing to establish.
const inboxes = await myInboxes(); const inboxes = await myInboxes();
for (const inbox of inboxes) { for (const inbox of inboxes) {
if (!stillConnected()) return; if (!stillConnected()) return;
await processInbox(inbox); try {
await processInbox(inbox);
} catch (error) {
// An identity that moved MID-DRAIN throws here too — `processInbox` resolves the
// holder at each step, so the new one is refused an inbox that is not theirs. That
// is abandoning, which this function has always called "not a failure", and
// reporting it would put a broker-looking error in the log every time a page
// switches user. The loop is about to return for the same reason.
if (!stillConnected()) return;
reportUndrained(inbox, error);
}
} }
})(); })();
@@ -1291,7 +1291,18 @@ export async function listMyEntityDocs(id: string, scope: Scope): Promise<Nuri[]
// holder when it runs — so hand the captured key back rather than trust that the // holder when it runs — so hand the captured key back rather than trust that the
// identity has not moved. See `caps.holderKey`. // identity has not moved. See `caps.holderKey`.
const holderKey = caps.holderKey(); const holderKey = caps.holderKey();
for (const cap of await readStoreCaps(store)) caps.learnFor(holderKey, cap); // Tolerant HERE, and only here: `readStoreCaps` propagates (see it, and `readLinks`
// beside it), because the connection's restore cannot report success over a read that
// never answered. This caller returns the LISTING, which it already has by now, and a
// listing without its keys is what it answered before this distinction existed —
// unchanged rather than quietly turned into a throw on a published call.
let stored: ReadCap[] = [];
try {
stored = await readStoreCaps(store);
} catch (error) {
console.error(accessLogPrefix() + " readStoreCaps failed:", error);
}
for (const cap of stored) caps.learnFor(holderKey, cap);
// Which store a document sits in is a registry fact, not one recorded beside the // Which store a document sits in is a registry fact, not one recorded beside the
// caps, so it is re-applied here. Marking only — the caps just came from the Store // caps, so it is re-applied here. Marking only — the caps just came from the Store
// branch above, and minting a second one beside them is the trap `holdOwnCap` warns // branch above, and minting a second one beside them is the trap `holdOwnCap` warns
@@ -9,11 +9,20 @@
* is *"the app works but the documents shared with me never appear"* — the worst kind, * is *"the app works but the documents shared with me never appear"* — the worst kind,
* because it looks like a permission decision and is a swallowed error. * because it looks like a permission decision and is a swallowed error.
* *
* The rule this file pins, one line: **any failure must surface; only "there was nothing to * The rule this file pins, one line: **failing to ESTABLISH the session surfaces; failing
* do" may resolve quietly.** Nothing to do means exactly two things — no identity is * to apply one of its queues is reported and does not deny the session; only "there was
* connected, or the identity has no account yet (connecting must never PROVISION one, see * nothing to do" resolves quietly.** Nothing to do means exactly two things — no identity
* `connect.ts`) — plus abandoning when the identity changed under the run, which is not a * is connected, or the identity has no account yet (connecting must never PROVISION one,
* failure either: the next connection picks it up. * see `connect.ts`) — plus abandoning when the identity changed under the run, which is not
* a failure either: the next connection picks it up.
*
* The queue clause was added 2026-08-16, and it is a correction rather than a softening.
* Rejecting on an undrained inbox looked like the same rigour as the rest, and it was not:
* a queue that cannot be applied is not consumed by failing, so it is still there at the
* next connection and the one after — one unapplicable item denied a live application's
* user their sign-in, permanently, three times out of three. Reporting it and carrying on
* is what makes the failure recoverable instead of terminal; nothing about it is silent
* (the branch below asserts the report, and that the OTHER queues still ran).
* *
* ── Why every branch is here, not just the interesting ones ─────────────── * ── Why every branch is here, not just the interesting ones ───────────────
* A swallowed failure is invisible by construction, so a suite that covers "the happy path * A swallowed failure is invisible by construction, so a suite that covers "the happy path
@@ -408,21 +417,76 @@ test("a document-inbox list that cannot be read fails the connection", async ()
await expect(connectedUser()).rejects.toThrow(/RepoNotFound/); await expect(connectedUser()).rejects.toThrow(/RepoNotFound/);
}); });
test("an inbox that cannot be drained fails the connection, and the rest stay undrained", async () => { /**
// Draining is what APPLIES a share. An inbox that could not be read may hold the cap this * The one branch where a failure does NOT reject — and the four things that have to hold
// very reconnection was for, so a silent skip loses it with no trace — and it took the * at once for that to be honest. Rewritten 2026-08-16, when the previous contract
// remaining inboxes down with it, silently too. It still stops at the first failure; the * ("stop at the first failure, reject") was reported doing this to a live application:
// difference is that stopping is now audible. * one queue it could not apply denied its user the application, at every sign-in, because
* an inbox that fails is not consumed and is still there next time. See `connect.ts`.
*
* A queue is not the session. Failing to REACH the queues still rejects — that case is
* the test above, and it is untouched.
*/
test("an inbox that cannot be drained is reported, the rest are drained, and the session stands", async () => {
const faults = noFaults();
const ng = inject(faults);
const note = await aliceSharesANoteWithBob();
adoptCurrentUser("bob");
const publicInbox = await userInbox("bob", "public"); // the first of the two drained
const protectedInbox = await userInbox("bob", "protected"); // where Alice's share landed
faults.inboxRead = publicInbox;
const reported: string[] = [];
const realError = console.error;
console.error = (...args: unknown[]): void => void reported.push(args.map(String).join(" "));
try {
// 1. The person gets their session. This is what the previous contract denied them.
await connectedUser();
} finally {
console.error = realError;
}
// 2. The queue after the failing one was still drained — a failure that took the others
// down with it lost shares that had nothing to do with it.
expect(ng.inboxReads).toEqual([publicInbox, protectedInbox]);
// 3. …so the share this reconnection was for actually arrived.
expect(holds(note)).toBe(true);
// 4. And it is NOT silence: the failure names the queue and carries the broker's error.
// Ungated — this suite never turns the access log on.
expect(reported.some((line) => line.includes("RepoNotFound"))).toBe(true);
expect(reported.some((line) => line.includes("could not be drained"))).toBe(true);
});
// The property the live report was actually about: not one refused sign-in, but EVERY one
// of them. An inbox is not consumed by failing to be read, so a fault that persists is
// still on the drain list at the next connection — which, under the previous contract, made
// the first refusal permanent rather than transient. Signing in twice over the same
// standing fault is the cheapest way to pin that it no longer is.
test("a queue that keeps failing does not deny the session at the NEXT connection either", async () => {
const faults = noFaults(); const faults = noFaults();
const ng = inject(faults); const ng = inject(faults);
await aliceSharesANoteWithBob(); await aliceSharesANoteWithBob();
adoptCurrentUser("bob"); adoptCurrentUser("bob");
const publicInbox = await userInbox("bob", "public"); // the first of the two drained const publicInbox = await userInbox("bob", "public");
faults.inboxRead = publicInbox; faults.inboxRead = publicInbox; // a standing fault: nothing about it heals
await expect(connectedUser()).rejects.toThrow(/RepoNotFound/); const realError = console.error;
expect(ng.inboxReads).toEqual([publicInbox]); // the protected one was never reached console.error = (): void => undefined;
try {
await connectedUser();
// A second connection, the way a reload produces one: the caches go, the wallet stays.
resetRegistryCache();
resetCaps();
adoptCurrentUser("bob");
await connectedUser();
} finally {
console.error = realError;
}
// Both connections went all the way through the list rather than stopping at the fault.
expect(ng.inboxReads.filter((r) => r === publicInbox).length).toBe(2);
}); });
// --- abandoning on an identity switch: not a failure ------------------------ // --- abandoning on an identity switch: not a failure ------------------------
@@ -0,0 +1,134 @@
/**
* reload-inbox-drain.test.ts — signing in again, over an inbox that was opened last time.
*
* ── The report this reproduces ────────────────────────────────────────────
* *"`ensureIdentity()` rejects inside its own inbox processing, about a document the
* application never named. The application deposits through a published call; the failure
* happens afterwards, inside the package."*
*
* The document nobody named is an INBOX. An application opens one on a note it owns
* (`storeRegistry.openDocumentInbox`) and hands out nothing: the deposit side names the
* NOTE (`inbox.postToDocument`) and the read side names it too (`inbox.readForDocument`).
* There is deliberately no published way to ask for an address, so the inbox document is
* the package's from end to end.
*
* Connecting drains every inbox the user may read — its own two, plus one per document it
* opened one on, read back from the User branch (the emulated `AddInboxCap`). Reading an
* inbox is a guarded read like any other, so a session that does not hold the inbox's key
* cannot drain it. And that key reaches the owner's hands exactly once, when the inbox is
* MINTED; nothing puts it back on a later session.
*
* So the second connection asks for a document it may not touch, is refused, and the
* refusal comes back out of `ensureIdentity()` — not as an empty screen but as a rejected
* sign-in. It will be rejected at every future connection too, because an inbox that could
* not be drained is still on the list next time.
*
* ── Why the applicative journey never saw it ──────────────────────────────
* `e2e/notebook.ts` journey 3 has Alice open her note for messages and Bob deposit into
* it; Bob reopens the application, Alice never does. The journey stops one reconnection
* short of the state this suite starts from.
*/
import { test, expect, describe, afterAll, beforeEach } from "bun:test";
import { docs, inbox as inboxSurface, storeRegistry } from "../src/index";
import { getCaps } from "../src/shared-wallet/bootstrap";
import { runScheduledInboxProcessingNow } from "../src/emulated-verifier/inbox-processor";
import { bootPage, forgetEverything, reloadPage, signIn, SESSION, type Quad } from "./wallet-fake";
import type { Nuri } from "../src/model/types";
const TITLE = "urn:test:title";
const MESSAGE = "j'apporte le café";
/**
* The first visit, in the application's own vocabulary: Alice writes a note and opens it
* for messages; Bob leaves one on it. Both of them name the NOTE and nothing else.
*
* Returns the note, which is all an application ever holds — the inbox NURI is read off
* the wallet afterwards, by the test alone, to say WHICH document the refusal is about.
*/
async function aNoteOpenForMessages(quads: Quad[]): Promise<Nuri> {
bootPage(quads);
await signIn("alice");
const note = await storeRegistry.createEntityDoc("public");
await docs.sparqlUpdate(
SESSION.sessionId,
`INSERT DATA { <${note}> <${TITLE}> "Courses" }`,
note,
"writeEntity",
);
await storeRegistry.openDocumentInbox(note);
await signIn("bob");
await inboxSurface.postToDocument(note, { payload: { text: MESSAGE }, from: "bob", ts: 1 });
return note;
}
/**
* The inbox Alice's note was opened on, read off the WALLET — the emulated `AddInboxCap`
* record, which is where the connection's drain list comes from. The test asks the wallet
* because no application can ask the package.
*/
function inboxOnTheNote(quads: Quad[], note: Nuri): Nuri {
const record = quads.find((q) => q.p === "urn:ng-eventually:shim:inboxCap" && q.o.startsWith(note + " "));
if (!record) throw new Error("no AddInboxCap record was written for the note");
return record.o.split(" ")[1] as Nuri;
}
/** Alice's note, found the way her application finds it: by listing her own store. */
async function myNote(): Promise<Nuri> {
const mine = await storeRegistry.listMyEntityDocs("public");
const note = mine[0];
if (!note) throw new Error("the note Alice wrote is not in her store");
return note;
}
beforeEach(() => {
forgetEverything();
});
afterAll(() => {
forgetEverything();
});
describe("signing in again, after opening one of my documents for messages", () => {
test("the connection work `ensureIdentity()` awaits does not reject", async () => {
const quads: Quad[] = [];
await aNoteOpenForMessages(quads);
reloadPage(quads);
await signIn("alice");
});
test("the reconnected session holds the key of the inbox it is asked to drain", async () => {
const quads: Quad[] = [];
const note = await aNoteOpenForMessages(quads);
const inbox = inboxOnTheNote(quads, note);
reloadPage(quads);
await signIn("alice").catch(() => undefined);
expect(getCaps().capFor(inbox)).toBeDefined();
});
test("the message left on my note is there when I come back", async () => {
const quads: Quad[] = [];
await aNoteOpenForMessages(quads);
reloadPage(quads);
await signIn("alice").catch(() => undefined);
const mine = await inboxSurface.readForDocument(await myNote());
expect(mine.map((d) => (d.payload as { text: string }).text)).toEqual([MESSAGE]);
});
// The deferred drain runs under whoever is connected — Bob, here — and reports to the
// access log rather than to a caller. It must not decide whether the owner can sign in.
test("a deferred drain having run first does not change the owner's sign-in", async () => {
const quads: Quad[] = [];
await aNoteOpenForMessages(quads);
await runScheduledInboxProcessingNow();
reloadPage(quads);
await signIn("alice");
});
});
@@ -0,0 +1,414 @@
/**
* reload-own-document.test.ts — the creator, after a page RELOAD, meets its own document.
*
* ── The report this reproduces ────────────────────────────────────────────
* *"Create an object, refresh the browser, and the creator is denied access to the object
* it just created."*
*
* A page reload is not a subtle event: every module-level cache the library holds is gone
* (the caps registry among them), and the durable wallet is exactly as the first session
* left it. What survives is what was WRITTEN — the scope index's Main branch (`contains`),
* its Store branch (`readCap`, the emulated `AddRepo`), and the document's own triples.
*
* So the question this suite asks is: after `ensureIdentity()` has connected the same
* identity over the same wallet, what does the creator get when it goes back to the
* document it made? And it asks it three ways, because three different defects hide behind
* the word "denied":
*
* - the document is ABSENT from the listing;
* - it is listed, and reading it returns NOTHING;
* - reading it is REFUSED with an error.
*
* …and for all three scopes, because a document in a public store serves its key to
* whoever asks (`emulated-verifier/public-store.ts`) while a protected or private one
* does not — so the scope is exactly the variable that decides.
*
* ── How the reload is simulated ───────────────────────────────────────────
* By dropping every piece of the library's module state ({@link reload}) while the fake
* broker keeps its quads. Nothing is hand-planted: the second session starts from an
* empty cap registry and an unresolved shim, and has to find its way back through the
* pointer, the doc-shim and the account record exactly as a fresh page does.
*/
import { test, expect, describe, mock, afterAll, beforeEach } from "bun:test";
import { configure, docs, storeRegistry, readUnion } from "../src/index";
import {
configureStoreRegistry,
setCurrentUser,
resetCaps,
resetConfig,
resetStoreRegistry,
getCaps,
} from "../src/shared-wallet/bootstrap";
import { resetRegistryCache } from "../src/shared-wallet/account-registry";
import type { RegistrySession } from "../src/shared-wallet/account-registry";
import { resetOpenedRepos } from "../src/emulated-verifier/open-repo";
import { resetPublicStoreFetches } from "../src/emulated-verifier/public-store";
import { connectedUser } from "../src/emulated-verifier/connect";
import type { NgLike, Nuri, Scope, UseShapeLike } from "../src/model/types";
const SESSION: RegistrySession = { sessionId: "sid-reload", privateStoreId: "PRIV-RELOAD" };
const SHIM = "urn:ng-eventually:shim";
const INBOX = "urn:ng-eventually:inbox";
const RDF_TYPE = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
/** The application's own predicate — the note's title, in the document it created. */
const TITLE = "urn:test:title";
const ALL_SCOPES: Scope[] = ["public", "protected", "private"];
// --- the fake broker -------------------------------------------------------
interface Quad {
g: string;
s: string;
p: string;
o: string;
}
/** Reverse of the lib's `escapeLiteral`: one left-to-right pass over `\x`. */
function unescapeLiteral(s: string): string {
let out = "";
for (let i = 0; i < s.length; i++) {
if (s[i] === "\\" && i + 1 < s.length) {
const next = s[++i];
out += next === "n" ? "\n" : next === "r" ? "\r" : next === "t" ? "\t" : next!;
} else out += s[i];
}
return out;
}
interface Token {
kind: "term" | "sep";
value: string;
}
/**
* Tokenize a triple body into IRIs, literals, `a`, `;` and `.`.
*
* A tokenizer rather than one regex per known query shape: the reload path issues
* writes from six different modules, and a per-shape fake would answer only the shapes
* whoever wrote it happened to think of — which is how a fake ends up green on a state
* the library never reaches.
*/
function tokenize(body: string): Token[] {
const re = /<([^>]*)>|"((?:[^"\\]|\\.)*)"|(;)|(\.)|\ba\b/g;
const out: Token[] = [];
let m: RegExpExecArray | null;
while ((m = re.exec(body)) !== null) {
if (m[1] !== undefined) out.push({ kind: "term", value: m[1] });
else if (m[2] !== undefined) out.push({ kind: "term", value: unescapeLiteral(m[2]) });
else if (m[3] !== undefined) out.push({ kind: "sep", value: ";" });
else if (m[4] !== undefined) out.push({ kind: "sep", value: "." });
else out.push({ kind: "term", value: RDF_TYPE });
}
return out;
}
/** `<s> p o ; p o . <s2> p o` → the triples it carries. */
function parseTriples(body: string): Array<{ s: string; p: string; o: string }> {
const toks = tokenize(body);
const out: Array<{ s: string; p: string; o: string }> = [];
let subject: string | null = null;
let i = 0;
while (i < toks.length) {
const t = toks[i]!;
if (t.kind === "sep") {
if (t.value === ".") subject = null;
i += 1;
continue;
}
if (subject === null) {
subject = t.value;
i += 1;
continue;
}
const p = toks[i];
const o = toks[i + 1];
if (!p || !o || p.kind === "sep" || o.kind === "sep") break;
out.push({ s: subject, p: p.value, o: o.value });
i += 2;
}
return out;
}
/**
* A quad-store fake `ng`. It holds the wallet; the library holds nothing across a
* {@link reload}, which is the whole point.
*
* No `doc_subscribe`: `ensureRepoOpen` is then the documented no-op of the unit-fake path
* (`emulated-verifier/open-repo.ts`), so an anchored read resolves directly. That is a
* limit of the fake broker, not a library state — the defect under test is about keys,
* not about bringing a repo into the session.
*/
function makeWallet(quads: Quad[] = []) {
let docCounter = 0;
const doc_create = mock(async () => `did:ng:o:doc${++docCounter}`);
const sparql_update = mock(async (...a: unknown[]) => {
const query = a[1] as string;
const anchor = a[2] as string | undefined;
const del = query.match(/DELETE\s+WHERE\s*\{([\s\S]*)\}/i);
if (del) {
const pattern = del[1]!.match(/<([^>]+)>\s+<([^>]+)>\s+\?/);
if (pattern && anchor !== undefined) {
for (let i = quads.length - 1; i >= 0; i--) {
const q = quads[i]!;
if (q.g === anchor && q.s === pattern[1] && q.p === pattern[2]) quads.splice(i, 1);
}
}
return undefined;
}
const wrapped = query.match(/GRAPH\s+<([^>]+)>\s*\{([\s\S]*)\}/);
const g = wrapped ? wrapped[1]! : anchor;
if (g === undefined) return undefined;
const body = wrapped
? wrapped[2]!
: query.replace(/^[\s\S]*?INSERT\s+DATA\s*\{/i, "").replace(/\}\s*$/, "");
for (const t of parseTriples(body)) quads.push({ g, ...t });
return undefined;
});
const sparql_query = mock(async (...a: unknown[]) => {
const query = a[1] as string;
const anchor = a[3] as string | undefined;
const wrapped = query.match(/GRAPH\s+<([^>]+)>/);
const g = wrapped ? wrapped[1]! : anchor;
const inGraph = quads.filter((q) => q.g === g);
// The whole-document read (`read-model.readDoc`).
if (/SELECT\s+\?s\s+\?p\s+\?o/.test(query)) {
return {
results: {
bindings: inGraph.map((q) => ({
s: { value: q.s },
p: { value: q.p },
o: { value: q.o },
})),
},
};
}
// The account record — several predicates on one subject.
if (query.includes(`<${SHIM}:docPublic>`)) {
const subjM = query.match(/<([^>]+)>\s+a\s+<[^>]*:Account>/);
const only = subjM ? subjM[1]! : null;
const bySubject = new Map<string, Record<string, string>>();
for (const q of inGraph) {
if (only !== null && q.s !== only) continue;
const rec = bySubject.get(q.s) ?? {};
if (q.p === `${SHIM}:id`) rec.id = q.o;
if (q.p === `${SHIM}:docPublic`) rec.docPublic = q.o;
if (q.p === `${SHIM}:docProtected`) rec.docProtected = q.o;
if (q.p === `${SHIM}:docPrivate`) rec.docPrivate = q.o;
bySubject.set(q.s, rec);
}
const bindings = [...bySubject.values()]
.filter((r) => r.id !== undefined)
.map((r) => ({
id: { value: r.id! },
docPublic: { value: r.docPublic ?? "" },
docProtected: { value: r.docProtected ?? "" },
docPrivate: { value: r.docPrivate ?? "" },
}));
return { results: { bindings } };
}
// An inbox's deposits — several predicates on one subject, `from` optional.
if (query.includes(`<${INBOX}:payload>`)) {
const bySubject = new Map<string, Record<string, string>>();
for (const q of inGraph) {
const rec = bySubject.get(q.s) ?? {};
if (q.p === `${INBOX}:payload`) rec.payload = q.o;
if (q.p === `${INBOX}:ts`) rec.ts = q.o;
if (q.p === `${INBOX}:from`) rec.from = q.o;
bySubject.set(q.s, rec);
}
const bindings = [...bySubject.values()]
.filter((r) => r.payload !== undefined && r.ts !== undefined)
.map((r) => {
const row: Record<string, { value: string }> = {
payload: { value: r.payload! },
ts: { value: r.ts! },
};
if (r.from !== undefined) row.from = { value: r.from };
return row;
});
return { results: { bindings } };
}
// Everything else the library reads is one bound subject, one bound predicate,
// one variable: the pointer, the store index, the Store/User/Header branches,
// the inbox index and its owner.
const one = query.match(/<([^>]+)>\s+<([^>]+)>\s+\?(\w+)/);
if (one) {
const bindings = inGraph
.filter((q) => q.s === one[1] && q.p === one[2])
.map((q) => ({ [one[3]!]: { value: q.o } }));
return { results: { bindings } };
}
return { results: { bindings: [] } };
});
return { doc_create, sparql_update, sparql_query, _quads: quads };
}
// --- the page --------------------------------------------------------------
function boot(quads: Quad[]): ReturnType<typeof makeWallet> {
const ng = makeWallet(quads);
configure({ ng: ng as unknown as NgLike, useShape: (() => {}) as unknown as UseShapeLike });
configureStoreRegistry({ getSession: async () => SESSION, normalizeId: (id) => id.trim() });
return ng;
}
/**
* A page RELOAD: everything the library holds in module scope goes, the wallet stays.
*
* Each call here drops one module's state, and together they are all of it — the config
* and the captured session, the registry caches (accounts, the resolved doc-shim, the
* inbox index), the opened repos, the outer-overlay memo, the caps, and who is connected.
* A fresh page has none of them, so neither does the session that follows.
*/
function reload(quads: Quad[]): ReturnType<typeof makeWallet> {
setCurrentUser(null);
resetConfig();
resetStoreRegistry();
resetRegistryCache();
resetOpenedRepos();
resetPublicStoreFetches();
resetCaps();
return boot(quads);
}
/** Sign in and let the connection work finish — what `ensureIdentity()` awaits. */
async function signIn(id: string): Promise<void> {
setCurrentUser(id);
await connectedUser();
}
/** The first visit: sign in, create the note, write its title into it. */
async function firstVisit(quads: Quad[], scope: Scope): Promise<Nuri> {
boot(quads);
await signIn("alice");
const note = await storeRegistry.createEntityDoc(scope);
await docs.sparqlUpdate(
SESSION.sessionId,
`INSERT DATA { <${note}> <${TITLE}> "the note" }`,
note,
"writeEntity",
);
return note;
}
beforeEach(() => {
setCurrentUser(null);
resetConfig();
resetStoreRegistry();
resetRegistryCache();
resetOpenedRepos();
resetPublicStoreFetches();
resetCaps();
});
afterAll(() => {
setCurrentUser(null);
resetConfig();
resetStoreRegistry();
resetRegistryCache();
resetOpenedRepos();
resetPublicStoreFetches();
resetCaps();
});
// --- the reproduction ------------------------------------------------------
describe("after a reload, the creator comes back to its own document", () => {
// Shape 1 — is it even there? The listing is the path the applicative journey takes,
// and it is also the path that REFILES the caps, so it is asked first and alone.
for (const scope of ALL_SCOPES) {
test(`[${scope}] it is still LISTED among my documents`, async () => {
const quads: Quad[] = [];
const note = await firstVisit(quads, scope);
reload(quads);
await signIn("alice");
expect(await storeRegistry.listMyEntityDocs(scope)).toContain(note);
});
}
// Shape 2 — listed, but does reading it answer? `readUnion` is the library's own
// listing read, and it DROPS a document whose cap the reader does not hold: a failure
// that arrives as an absence, which is the family this project has been bitten by.
for (const scope of ALL_SCOPES) {
test(`[${scope}] reading it by reference answers its content`, async () => {
const quads: Quad[] = [];
const note = await firstVisit(quads, scope);
reload(quads);
await signIn("alice");
// The application kept the reference (a route, a deep link) and reads it directly,
// without listing its store first.
const subjects = await readUnion([note]);
expect(subjects.map((s) => s.props[TITLE]?.[0])).toEqual(["the note"]);
});
}
// Shape 3 — is it REFUSED? The guarded passage point, which is what an application
// reaches through `docs.*` and what every read of the library goes through.
for (const scope of ALL_SCOPES) {
test(`[${scope}] reading it through the guarded surface is not refused`, async () => {
const quads: Quad[] = [];
const note = await firstVisit(quads, scope);
reload(quads);
await signIn("alice");
await docs.sparqlQuery(
SESSION.sessionId,
"SELECT ?s ?p ?o WHERE { ?s ?p ?o }",
undefined,
note,
"readDoc",
);
});
}
// …and the same question for a WRITE: editing the note one made is the other half of
// "denied access to the object it just created".
for (const scope of ALL_SCOPES) {
test(`[${scope}] writing to it again is not refused`, async () => {
const quads: Quad[] = [];
const note = await firstVisit(quads, scope);
reload(quads);
await signIn("alice");
await docs.sparqlUpdate(
SESSION.sessionId,
`INSERT DATA { <${note}> <${TITLE}> "edited" }`,
note,
"writeEntity",
);
});
}
// What the connection itself restored, stated as a fact rather than inferred from the
// symptom: does the reconnected session HOLD the key of the document it created?
for (const scope of ALL_SCOPES) {
test(`[${scope}] the reconnected session holds its key`, async () => {
const quads: Quad[] = [];
const note = await firstVisit(quads, scope);
reload(quads);
await signIn("alice");
expect(getCaps().capFor(note)).toBeDefined();
});
}
});
+280
View File
@@ -0,0 +1,280 @@
/**
* wallet-fake — a durable fake broker, and the page RELOAD that runs over it.
*
* Not a `*.test.ts`, so `bun test` does not pick it up: it is the montage two suites share
* ({@link reloadOwnDocument} / the inbox drain), and both of them are about what survives a
* reload — which is exactly the thing a per-file fake cannot express, because the wallet
* has to outlive the library while the library keeps nothing.
*
* ── What makes it a wallet and not a stub ─────────────────────────────────
* The quads live in the fake, never in the library. {@link reloadPage} drops every piece of
* the library's module state and hands back a session that has to find its way home through
* the store-root pointer, the doc-shim and the account record — the way a fresh page does.
* Nothing is planted: a second session sees exactly what the first one WROTE.
*
* The SPARQL it answers is a tokenizer plus five shapes, rather than one regex per query
* the author happened to think of: the reload path issues reads and writes from six
* modules, and a fake that answers only the shapes someone enumerated is how a suite goes
* green over a state the library never reaches.
*/
import { mock } from "bun:test";
import { configure } from "../src/index";
import {
configureStoreRegistry,
setCurrentUser,
resetCaps,
resetConfig,
resetStoreRegistry,
} from "../src/shared-wallet/bootstrap";
import { resetRegistryCache } from "../src/shared-wallet/account-registry";
import type { RegistrySession } from "../src/shared-wallet/account-registry";
import { resetOpenedRepos } from "../src/emulated-verifier/open-repo";
import { resetPublicStoreFetches } from "../src/emulated-verifier/public-store";
import { connectedUser } from "../src/emulated-verifier/connect";
import type { NgLike, UseShapeLike } from "../src/model/types";
export const SESSION: RegistrySession = { sessionId: "sid-wallet", privateStoreId: "PRIV-WALLET" };
const SHIM = "urn:ng-eventually:shim";
const INBOX = "urn:ng-eventually:inbox";
const RDF_TYPE = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
export interface Quad {
g: string;
s: string;
p: string;
o: string;
}
/** Reverse of the lib's `escapeLiteral`: one left-to-right pass over `\x`. */
function unescapeLiteral(s: string): string {
let out = "";
for (let i = 0; i < s.length; i++) {
if (s[i] === "\\" && i + 1 < s.length) {
const next = s[++i];
out += next === "n" ? "\n" : next === "r" ? "\r" : next === "t" ? "\t" : next!;
} else out += s[i];
}
return out;
}
interface Token {
kind: "term" | "sep";
value: string;
}
/** Tokenize a triple body into IRIs, literals, `a`, `;` and `.`. */
function tokenize(body: string): Token[] {
const re = /<([^>]*)>|"((?:[^"\\]|\\.)*)"|(;)|(\.)|\ba\b/g;
const out: Token[] = [];
let m: RegExpExecArray | null;
while ((m = re.exec(body)) !== null) {
if (m[1] !== undefined) out.push({ kind: "term", value: m[1] });
else if (m[2] !== undefined) out.push({ kind: "term", value: unescapeLiteral(m[2]) });
else if (m[3] !== undefined) out.push({ kind: "sep", value: ";" });
else if (m[4] !== undefined) out.push({ kind: "sep", value: "." });
else out.push({ kind: "term", value: RDF_TYPE });
}
return out;
}
/** `<s> p o ; p o . <s2> p o` → the triples it carries. */
function parseTriples(body: string): Array<{ s: string; p: string; o: string }> {
const toks = tokenize(body);
const out: Array<{ s: string; p: string; o: string }> = [];
let subject: string | null = null;
let i = 0;
while (i < toks.length) {
const t = toks[i]!;
if (t.kind === "sep") {
if (t.value === ".") subject = null;
i += 1;
continue;
}
if (subject === null) {
subject = t.value;
i += 1;
continue;
}
const p = toks[i];
const o = toks[i + 1];
if (!p || !o || p.kind === "sep" || o.kind === "sep") break;
out.push({ s: subject, p: p.value, o: o.value });
i += 2;
}
return out;
}
export interface FakeWallet {
doc_create: ReturnType<typeof mock>;
sparql_update: ReturnType<typeof mock>;
sparql_query: ReturnType<typeof mock>;
_quads: Quad[];
}
/**
* A quad-store fake `ng` over `quads` — the durable half. The library holds nothing across
* a {@link reloadPage}; this does.
*
* No `doc_subscribe`: `ensureRepoOpen` is then the documented no-op of the unit-fake path
* (`emulated-verifier/open-repo.ts`), so an anchored read resolves directly. A limit of the
* fake broker, not a library state.
*/
export function makeWallet(quads: Quad[]): FakeWallet {
let docCounter = 0;
const doc_create = mock(async () => `did:ng:o:doc${++docCounter}`);
const sparql_update = mock(async (...a: unknown[]) => {
const query = a[1] as string;
const anchor = a[2] as string | undefined;
const del = query.match(/DELETE\s+WHERE\s*\{([\s\S]*)\}/i);
if (del) {
const pattern = del[1]!.match(/<([^>]+)>\s+<([^>]+)>\s+\?/);
if (pattern && anchor !== undefined) {
for (let i = quads.length - 1; i >= 0; i--) {
const q = quads[i]!;
if (q.g === anchor && q.s === pattern[1] && q.p === pattern[2]) quads.splice(i, 1);
}
}
return undefined;
}
const wrapped = query.match(/GRAPH\s+<([^>]+)>\s*\{([\s\S]*)\}/);
const g = wrapped ? wrapped[1]! : anchor;
if (g === undefined) return undefined;
const body = wrapped
? wrapped[2]!
: query.replace(/^[\s\S]*?INSERT\s+DATA\s*\{/i, "").replace(/\}\s*$/, "");
for (const t of parseTriples(body)) quads.push({ g, ...t });
return undefined;
});
const sparql_query = mock(async (...a: unknown[]) => {
const query = a[1] as string;
const anchor = a[3] as string | undefined;
const wrapped = query.match(/GRAPH\s+<([^>]+)>/);
const g = wrapped ? wrapped[1]! : anchor;
const inGraph = quads.filter((q) => q.g === g);
// The whole-document read (`read-model.readDoc`).
if (/SELECT\s+\?s\s+\?p\s+\?o/.test(query)) {
return {
results: {
bindings: inGraph.map((q) => ({
s: { value: q.s },
p: { value: q.p },
o: { value: q.o },
})),
},
};
}
// The account record — several predicates on one subject.
if (query.includes(`<${SHIM}:docPublic>`)) {
const subjM = query.match(/<([^>]+)>\s+a\s+<[^>]*:Account>/);
const only = subjM ? subjM[1]! : null;
const bySubject = new Map<string, Record<string, string>>();
for (const q of inGraph) {
if (only !== null && q.s !== only) continue;
const rec = bySubject.get(q.s) ?? {};
if (q.p === `${SHIM}:id`) rec.id = q.o;
if (q.p === `${SHIM}:docPublic`) rec.docPublic = q.o;
if (q.p === `${SHIM}:docProtected`) rec.docProtected = q.o;
if (q.p === `${SHIM}:docPrivate`) rec.docPrivate = q.o;
bySubject.set(q.s, rec);
}
const bindings = [...bySubject.values()]
.filter((r) => r.id !== undefined)
.map((r) => ({
id: { value: r.id! },
docPublic: { value: r.docPublic ?? "" },
docProtected: { value: r.docProtected ?? "" },
docPrivate: { value: r.docPrivate ?? "" },
}));
return { results: { bindings } };
}
// An inbox's deposits — several predicates on one subject, `from` optional.
if (query.includes(`<${INBOX}:payload>`)) {
const bySubject = new Map<string, Record<string, string>>();
for (const q of inGraph) {
const rec = bySubject.get(q.s) ?? {};
if (q.p === `${INBOX}:payload`) rec.payload = q.o;
if (q.p === `${INBOX}:ts`) rec.ts = q.o;
if (q.p === `${INBOX}:from`) rec.from = q.o;
bySubject.set(q.s, rec);
}
const bindings = [...bySubject.values()]
.filter((r) => r.payload !== undefined && r.ts !== undefined)
.map((r) => {
const row: Record<string, { value: string }> = {
payload: { value: r.payload! },
ts: { value: r.ts! },
};
if (r.from !== undefined) row.from = { value: r.from };
return row;
});
return { results: { bindings } };
}
// Everything else the library reads is one bound subject, one bound predicate, one
// variable: the pointer, the store index, the Store/User/Header branches, the inbox
// index and its owner.
const one = query.match(/<([^>]+)>\s+<([^>]+)>\s+\?(\w+)/);
if (one) {
const bindings = inGraph
.filter((q) => q.s === one[1] && q.p === one[2])
.map((q) => ({ [one[3]!]: { value: q.o } }));
return { results: { bindings } };
}
return { results: { bindings: [] } };
});
return { doc_create, sparql_update, sparql_query, _quads: quads };
}
/** Wire the library onto `quads` — what a page load does. */
export function bootPage(quads: Quad[]): FakeWallet {
const ng = makeWallet(quads);
configure({ ng: ng as unknown as NgLike, useShape: (() => {}) as unknown as UseShapeLike });
configureStoreRegistry({ getSession: async () => SESSION, normalizeId: (id) => id.trim() });
return ng;
}
/**
* Drop everything the library holds in module scope — what a page reload does.
*
* Each call drops one module's state, and together they are all of it: the config and the
* captured session, the registry caches (accounts, the resolved doc-shim, the inbox index),
* the opened repos, the outer-overlay memo, the caps, and who is connected.
*/
export function forgetEverything(): void {
setCurrentUser(null);
resetConfig();
resetStoreRegistry();
resetRegistryCache();
resetOpenedRepos();
resetPublicStoreFetches();
resetCaps();
}
/** A page RELOAD: the library forgets, the wallet does not. */
export function reloadPage(quads: Quad[]): FakeWallet {
forgetEverything();
return bootPage(quads);
}
/**
* Sign in and let the connection work finish — what `ensureIdentity()` awaits, reached by
* the harness's internal path rather than through the `barrier` (there is no DOM here).
*
* It REJECTS exactly where `ensureIdentity()` would, which is the point: a suite about a
* sign-in that fails cannot use a sign-in that cannot fail.
*/
export async function signIn(id: string): Promise<void> {
setCurrentUser(id);
await connectedUser();
}