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
@@ -9,11 +9,20 @@
* 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.
*
* The rule this file pins, one line: **any failure must surface; only "there was nothing to
* do" may resolve quietly.** Nothing to do means exactly two things — no identity is
* connected, or the identity has no account yet (connecting must never PROVISION one, 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 rule this file pins, one line: **failing to ESTABLISH the session surfaces; failing
* to apply one of its queues is reported and does not deny the session; only "there was
* nothing to do" resolves quietly.** Nothing to do means exactly two things — no identity
* is connected, or the identity has no account yet (connecting must never PROVISION one,
* 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 ───────────────
* 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/);
});
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
// very reconnection was for, so a silent skip loses it with no trace — and it took the
// remaining inboxes down with it, silently too. It still stops at the first failure; the
// difference is that stopping is now audible.
/**
* The one branch where a failure does NOT reject — and the four things that have to hold
* at once for that to be honest. Rewritten 2026-08-16, when the previous contract
* ("stop at the first failure, reject") was reported doing this to a live application:
* 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 ng = inject(faults);
await aliceSharesANoteWithBob();
adoptCurrentUser("bob");
const publicInbox = await userInbox("bob", "public"); // the first of the two drained
faults.inboxRead = publicInbox;
const publicInbox = await userInbox("bob", "public");
faults.inboxRead = publicInbox; // a standing fault: nothing about it heals
await expect(connectedUser()).rejects.toThrow(/RepoNotFound/);
expect(ng.inboxReads).toEqual([publicInbox]); // the protected one was never reached
const realError = console.error;
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 ------------------------
@@ -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();
}