docs+refactor(client): fidelity pass — id identity, drop connections, no faux-login, accurate NextGraph framing

Align the polyfill's surface and docs with the verified NextGraph reality and
remove application-level concepts:

- Identity is an ID, not a username: AccountRecord.id, shim predicate shim:id,
  normalizeId; accounts core becomes IdentityStore (set/clear/get) — the faux
  login/logout framing is gone (identity is set at wallet-import time).
- Relationship/connection is an application concept, not a platform primitive
  (NextGraph has no bilateral-connection primitive: grantee is unpersisted
  scaffolding, cap-send is unimplemented). Remove connections.ts; caps exposes
  only a directed grantRead(doc, granteeId) + a read-only protectedDocsOf(owner).
  Delete the now-dead isolation.ts social-visibility axis.
- Inbox docs: NextGraph has no separate curator — the recipient's own verifier
  unseals and applies each queued sealed message inline (process_inbox);
  inbox_post_link is a proposed/future API. Stop attributing the emulated
  curator to the platform.
- Read isolation reframed around the outcome: no cap -> empty union read;
  targeted read of an unheld repo -> RepoNotFound; cap introspection
  (canRead/governsRead) is emulation-only with no NextGraph API behind it.
- read-model.md corrected: the listing path is per-doc ANCHORED default-graph
  queries, never the anchorless GRAPH ?g union (that is O(wallet)); the probe
  section no longer claims the opposite.
- README recap table restructured (target | current NextGraph status | current
  emulation); INDEX_ACCOUNT documented as reservedAccount("index") in the
  sentinel namespace; de-domained generic-layer comments; softened tone.

Consumer application (Festipod) rewired separately to own the relationship
concept and feed the lib an id. Lib gates: bun test 83 pass / 0 fail, tsc clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Sylvain Duchesne
2026-07-06 14:02:16 +02:00
parent d39b12885a
commit 63ecfeeff8
31 changed files with 1059 additions and 1396 deletions
+28 -37
View File
@@ -1,8 +1,7 @@
import { test, expect } from "bun:test";
import {
AccountStore,
browserAccountStore,
normalizeUsername,
IdentityStore,
browserIdentityStore,
ACCOUNT_STORAGE_KEY,
type AccountStorage,
} from "../src/accounts";
@@ -18,47 +17,39 @@ function fakeStorage(): AccountStorage & { map: Map<string, string> } {
};
}
test("normalizeUsername: strips leading @, trims, lowercases", () => {
expect(normalizeUsername("marie")).toBe("marie");
expect(normalizeUsername("@Marie")).toBe("marie");
expect(normalizeUsername(" @@MARIE ")).toBe("marie");
expect(normalizeUsername(null)).toBe("");
expect(normalizeUsername(undefined)).toBe("");
});
test("AccountStore: login persists a trimmed username, get reads it back", () => {
test("IdentityStore: set persists a trimmed id, get reads it back", () => {
const s = fakeStorage();
const store = new AccountStore(s);
const store = new IdentityStore(s);
expect(store.get()).toBeNull();
expect(store.login(" Marie ")).toBe("Marie"); // trimmed, NOT normalized (display form)
expect(store.get()).toBe("Marie");
expect(s.map.get(ACCOUNT_STORAGE_KEY)).toBe("Marie");
expect(store.set(" marie ")).toBe("marie"); // trimmed
expect(store.get()).toBe("marie");
expect(s.map.get(ACCOUNT_STORAGE_KEY)).toBe("marie");
});
test("AccountStore: blank login is ignored, keeps the previous value", () => {
const store = new AccountStore(fakeStorage());
store.login("bob");
expect(store.login(" ")).toBe("bob");
test("IdentityStore: a blank id is ignored, keeps the previous value", () => {
const store = new IdentityStore(fakeStorage());
store.set("bob");
expect(store.set(" ")).toBe("bob");
expect(store.get()).toBe("bob");
});
test("AccountStore: logout clears the username (no throw)", () => {
const store = new AccountStore(fakeStorage());
store.login("bob");
store.logout();
test("IdentityStore: clear removes the id (no throw)", () => {
const store = new IdentityStore(fakeStorage());
store.set("bob");
store.clear();
expect(store.get()).toBeNull();
});
test("AccountStore: null storage degrades to non-persisting (SSR-safe)", () => {
const store = new AccountStore(null);
test("IdentityStore: null storage degrades to non-persisting (SSR-safe)", () => {
const store = new IdentityStore(null);
expect(store.get()).toBeNull();
expect(store.login("bob")).toBe("bob"); // returns the value, just doesn't persist
expect(store.set("bob")).toBe("bob"); // returns the value, just doesn't persist
expect(store.get()).toBeNull();
store.logout(); // no throw
store.clear(); // no throw
});
test("AccountStore: swallows storage errors on read and write", () => {
test("IdentityStore: swallows storage errors on read and write", () => {
const throwing: AccountStorage = {
getItem: () => {
throw new Error("boom");
@@ -70,15 +61,15 @@ test("AccountStore: swallows storage errors on read and write", () => {
throw new Error("boom");
},
};
const store = new AccountStore(throwing);
const store = new IdentityStore(throwing);
expect(store.get()).toBeNull(); // read error swallowed → null
expect(() => store.login("bob")).not.toThrow();
expect(() => store.logout()).not.toThrow();
expect(() => store.set("bob")).not.toThrow();
expect(() => store.clear()).not.toThrow();
});
test("browserAccountStore returns a working store (uses global localStorage if present)", () => {
const store = browserAccountStore("ng-eventually.test.account");
expect(store).toBeInstanceOf(AccountStore);
// Behaves regardless of environment: login returns the value.
expect(store.login("zoe")).toBe("zoe");
test("browserIdentityStore returns a working store (uses global localStorage if present)", () => {
const store = browserIdentityStore("ng-eventually.test.account");
expect(store).toBeInstanceOf(IdentityStore);
// Behaves regardless of environment: set returns the value.
expect(store.set("zoe")).toBe("zoe");
});
+20 -1
View File
@@ -13,7 +13,7 @@ test("protected documents: owner + explicitly granted principals only", () => {
caps.open("did:ng:o:prot", "protected", "alice");
expect(caps.canRead("did:ng:o:prot", "alice")).toBe(true);
expect(caps.canRead("did:ng:o:prot", "bob")).toBe(false);
caps.grantRead("did:ng:o:prot", "bob"); // bob becomes a connection of alice
caps.grantRead("did:ng:o:prot", "bob"); // a directed grant issues bob the read cap
expect(caps.canRead("did:ng:o:prot", "bob")).toBe(true);
});
@@ -25,6 +25,25 @@ test("private documents: owner only", () => {
expect(caps.canRead("did:ng:o:priv", null)).toBe(false);
});
test("protectedDocsOf surfaces an owner's protected documents for directed grants", () => {
const caps = new CapRegistry();
caps.open("did:ng:o:prot1", "protected", "alice");
caps.open("did:ng:o:prot2", "protected", "alice");
caps.open("did:ng:o:pub", "public", "alice"); // not protected → excluded
caps.open("did:ng:o:priv", "private", "alice"); // not protected → excluded
caps.open("did:ng:o:bob", "protected", "bob"); // other owner → excluded
expect(caps.protectedDocsOf("alice").sort()).toEqual([
"did:ng:o:prot1",
"did:ng:o:prot2",
]);
expect(caps.protectedDocsOf("bob")).toEqual(["did:ng:o:bob"]);
expect(caps.protectedDocsOf("carol")).toEqual([]);
// A directed grant on one of them makes the reader read that doc only.
caps.grantRead("did:ng:o:prot1", "carol");
expect(caps.canRead("did:ng:o:prot1", "carol")).toBe(true);
expect(caps.canRead("did:ng:o:prot2", "carol")).toBe(false);
});
test("write is restricted to write-cap holders; the creator always holds it", () => {
const caps = new CapRegistry();
caps.open("did:ng:o:pub", "public", "alice");
-60
View File
@@ -1,60 +0,0 @@
/**
* ConnectionRegistry — BILATERAL connection materialization (T03.h).
*
* A connection is live only when BOTH sides have asserted the other. A unilateral
* (self-declared) assertion yields no neighbour — the defence against a reader who
* fakes a connection to an owner to read that owner's protected documents.
*/
import { test, expect } from "bun:test";
import { ConnectionRegistry, bilateralConnections } from "../src/connections";
test("a UNILATERAL assertion yields NO neighbour", () => {
const reg = new ConnectionRegistry();
reg.assert("mallory", "alice"); // mallory self-declares; alice never asserts back
expect([...reg.neighbors("mallory")]).toEqual([]);
expect([...reg.neighbors("alice")]).toEqual([]);
});
test("a BILATERAL assertion (both sides) materializes the link", () => {
const reg = new ConnectionRegistry();
reg.assert("alice", "bob");
reg.assert("bob", "alice");
expect([...reg.neighbors("alice")]).toEqual(["bob"]);
expect([...reg.neighbors("bob")]).toEqual(["alice"]);
});
test("mixed: only the reciprocated peers surface", () => {
const reg = new ConnectionRegistry();
reg.assert("alice", "bob"); // reciprocated below
reg.assert("bob", "alice");
reg.assert("alice", "carol"); // NOT reciprocated by carol
reg.assert("dave", "alice"); // dave asserts alice, alice never asserts dave
expect([...reg.neighbors("alice")].sort()).toEqual(["bob"]);
});
test("self-assertion and empty are ignored", () => {
const reg = new ConnectionRegistry();
reg.assert("alice", "alice");
reg.assert("", "bob");
reg.assert("alice", "");
expect([...reg.neighbors("alice")]).toEqual([]);
});
test("bilateralConnections adapts to the Connections interface", () => {
const reg = new ConnectionRegistry();
reg.assertAll([
{ from: "alice", to: "bob" },
{ from: "bob", to: "alice" },
]);
const conns = bilateralConnections(reg);
expect([...conns.neighbors("alice")]).toEqual(["bob"]);
expect([...conns.neighbors("carol")]).toEqual([]);
});
test("clear() removes all assertions", () => {
const reg = new ConnectionRegistry();
reg.assert("alice", "bob");
reg.assert("bob", "alice");
reg.clear();
expect([...reg.neighbors("alice")]).toEqual([]);
});
+9 -9
View File
@@ -102,7 +102,7 @@ function makeFakeNg() {
// Shim account SELECT. Two shapes: the full scan (`?acc a <Account>`) and
// the TARGETED bounded resolve (`<subj> a <Account>`), which binds one
// subject — honour that subject filter so the bounded query is O(1)/exact.
if (query.includes(`<${SHIM}:username>`)) {
if (query.includes(`<${SHIM}:id>`)) {
const subjM = query.match(new RegExp(`GRAPH <[^>]+>\\s*\\{\\s*<([^>]+)>\\s+a\\s+<${SHIM}:Account>`));
const onlySubject = subjM ? subjM[1]! : null;
const bySubject = new Map<string, Record<string, string>>();
@@ -110,16 +110,16 @@ function makeFakeNg() {
if (q.g !== anchor) continue;
if (onlySubject !== null && q.s !== onlySubject) continue;
const rec = bySubject.get(q.s) ?? {};
if (q.p === `${SHIM}:username`) rec.username = q.o;
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.username)
.filter((r) => r.id)
.map((r) => ({
username: { value: r.username! },
id: { value: r.id! },
docPublic: { value: r.docPublic ?? "" },
docProtected: { value: r.docProtected ?? "" },
docPrivate: { value: r.docPrivate ?? "" },
@@ -167,7 +167,7 @@ function inject() {
configure({ ng: ng as any, useShape: (() => {}) as any });
configureStoreRegistry({
getSession: async () => SESSION,
normalizeUser: (u) => u.trim().replace(/^@+/, "").toLowerCase(),
normalizeId: (u) => u.trim().replace(/^@+/, "").toLowerCase(),
});
resetRegistryCache();
setCurrentUser(null);
@@ -256,10 +256,10 @@ test("(d) submitToIndex refuses a PROTECTED/PRIVATE document (public-only)", asy
resetCaps();
});
test("INDEX_ACCOUNT lives in the reserved namespace (no typed username can equal it)", () => {
// The index account occupies a key no user input can produce: it is prefixed
// with a NUL control char, which a user cannot type into a username field and
// which no `normalizeUser` output (a typeable value) contains. So it is
test("INDEX_ACCOUNT lives in the reserved namespace (no typed id can equal it)", () => {
// The index account occupies a key no consumer input can produce: it is prefixed
// with a NUL control char, which a user cannot type into an id field and
// which no `normalizeId` output (a typeable value) contains. So it is
// disjoint from the keys "index" / "@index" a hostile user would submit.
expect(INDEX_ACCOUNT.startsWith("\u0000")).toBe(true); // unreachable-by-typing sentinel
expect(INDEX_ACCOUNT).not.toBe("index");
+35 -31
View File
@@ -1,15 +1,18 @@
/**
* ReadCap ACTIVE (T03.h) — end-to-end proof that the emulated SDK enforces
* per-DOCUMENT isolation, driven by per-entity documents + BILATERAL connections.
* ReadCap ACTIVE — end-to-end proof that the emulated SDK enforces per-DOCUMENT
* isolation, driven by per-entity documents + DIRECTED read grants.
*
* Mirrors exactly what the app does: create an entity document through the REAL
* registry (`createEntityDoc`), declare its cap policy via
* `getCaps().open(doc, scope, owner)`, set the current identity, and declare
* connections as the CURRENT identity's own peers (authenticated, bilateral). The
* read filter then discriminates:
* (a) unconnected principal denied a PROTECTED doc; granted after a BILATERAL
* connection; PUBLIC readable throughout — via the ACTIVE ReadCap.
* (b) a UNILATERAL / self-declared connection grants NOTHING.
* Mirrors what the app does: create an entity document through the REAL registry
* (`createEntityDoc`), declare its cap policy via `getCaps().open(doc, scope,
* owner)`, set the current identity, and — when the app decides two identities
* are related — issue a DIRECTED read grant on each of the owner's protected
* documents (`getCaps().grantRead(doc, granteeId)`). Whether identities are
* "connected" is the application's own concept: this test plays that role
* directly. The read filter then discriminates:
* (a) an ungranted principal is denied a PROTECTED doc; granted once the owner
* issues a directed grant; PUBLIC readable throughout — via the ACTIVE
* ReadCap.
* (b) no grant → no protected read (a reader cannot grant itself).
*/
import { test, expect, mock, afterAll } from "bun:test";
import { createEntityDoc, resetRegistryCache } from "../src/store-registry";
@@ -22,7 +25,6 @@ import {
getCaps,
resetCaps,
setCurrentUser,
declareConnections,
} from "../src/polyfill";
import { filterReadable } from "../src/read-filter";
@@ -43,13 +45,19 @@ function inject() {
sparql_query: mock(async () => ({ results: { bindings: [] } })),
};
configure({ ng: ng as any, useShape: (() => {}) as any });
configureStoreRegistry({ getSession: async () => SESSION, normalizeUser: (u) => u.trim() });
configureStoreRegistry({ getSession: async () => SESSION, normalizeId: (id) => id.trim() });
resetRegistryCache();
resetCaps();
setCurrentUser(null);
return ng;
}
/** The app's relationship concept, played inline: grant `reader` the read cap of
* every protected document owned by `owner`. */
function grantOwnerProtectedTo(owner: string, reader: string) {
for (const doc of getCaps().protectedDocsOf(owner)) getCaps().grantRead(doc, reader);
}
test("ReadCap active: a private entity doc created via the real registry is hidden from another principal", async () => {
inject();
@@ -70,9 +78,9 @@ test("ReadCap active: a private entity doc created via the real registry is hidd
expect(getCaps().hasReadPolicy()).toBe(true);
});
// (a) protected hidden while unconnected → revealed after a BILATERAL connection;
// public readable regardless — all through the ACTIVE ReadCap.
test("(a) PROTECTED doc: hidden unconnected, revealed after BILATERAL connection, PUBLIC always readable", async () => {
// (a) protected hidden while ungranted → revealed after a DIRECTED grant; public
// readable regardless — all through the ACTIVE ReadCap.
test("(a) PROTECTED doc: hidden ungranted, revealed after a DIRECTED grant, PUBLIC always readable", async () => {
inject();
const aliceProtected = await createEntityDoc("alice", "protected");
@@ -86,22 +94,22 @@ test("(a) PROTECTED doc: hidden unconnected, revealed after BILATERAL connection
];
const view = (u: string) => filterReadable(items, getCaps(), u).map((i) => i["@id"]).sort();
// BEFORE any connection: bob sees only the public item.
// BEFORE any grant: bob sees only the public item.
expect(view("bob")).toEqual(["u1"]);
expect(view("alice")).toEqual(["p1", "u1"]);
// BILATERAL: alice asserts bob AND bob asserts alice → the link materializes and
// the SDK issues the protected doc's read cap to bob.
declareConnections(["bob"], "alice");
declareConnections(["alice"], "bob");
// The app decides alice↔bob are related and grants bob the read cap of alice's
// protected documents.
grantOwnerProtectedTo("alice", "bob");
expect(view("bob")).toEqual(["p1", "u1"]);
// A third, unconnected principal still sees only the public one.
// A third, ungranted principal still sees only the public one.
expect(view("carol")).toEqual(["u1"]);
});
// (b) A UNILATERAL / self-declared connection must NOT grant protected read.
test("(b) a UNILATERAL / self-declared connection grants NO protected read", async () => {
// (b) An identity gets no protected read until the OWNER issues the grant — a
// reader cannot grant itself.
test("(b) no directed grant → no protected read", async () => {
inject();
const aliceProtected = await createEntityDoc("alice", "protected");
@@ -109,15 +117,11 @@ test("(b) a UNILATERAL / self-declared connection grants NO protected read", asy
const items = [{ "@graph": aliceProtected, "@id": "p1" }];
const view = (u: string) => filterReadable(items, getCaps(), u).map((i) => i["@id"]);
// The ATTACKER (mallory) self-declares a connection to alice — a UNILATERAL
// assertion authored by mallory. Alice NEVER asserts mallory back.
declareConnections(["alice"], "mallory");
expect(view("mallory")).toEqual([]); // still denied — no bilateral link
// mallory holds no grant on alice's protected doc → denied.
expect(view("mallory")).toEqual([]);
// Even if alice connects to bob (a different, legitimate bilateral link),
// mallory's one-sided assertion still grants nothing.
declareConnections(["bob"], "alice");
declareConnections(["alice"], "bob");
// Granting bob (a different, legitimate reader) leaves mallory denied.
grantOwnerProtectedTo("alice", "bob");
expect(view("mallory")).toEqual([]);
expect(view("bob")).toEqual(["p1"]);
});
-68
View File
@@ -1,68 +0,0 @@
import { test, expect } from "bun:test";
import {
applyIsolation,
connectionsFromLinks,
visibleSet,
isVisible,
type IsolationAccessors,
} from "../src/isolation";
import type { Scope } from "../src/types";
// Generic item: owner + scope. ZERO domain — the accessors read these fields.
interface Item {
id: string;
owner: string;
scope: Scope;
}
const acc: IsolationAccessors<Item> = { ownerOf: (i) => i.owner, scopeOf: (i) => i.scope };
// alice —— bob (carol is unconnected)
const links = [{ a: "alice", b: "bob" }];
const conns = connectionsFromLinks(links);
test("connectionsFromLinks / visibleSet: self + direct connections, both directions", () => {
expect([...conns.neighbors("alice")].sort()).toEqual(["bob"]);
expect([...conns.neighbors("bob")].sort()).toEqual(["alice"]);
expect([...conns.neighbors("carol")]).toEqual([]);
expect([...visibleSet("alice", conns)].sort()).toEqual(["alice", "bob"]);
expect([...visibleSet("carol", conns)].sort()).toEqual(["carol"]);
});
test("isVisible matrix: public=all, protected=owner+connections, private=owner", () => {
const vis = visibleSet("alice", conns); // { alice, bob }
// public → everyone, regardless of owner
expect(isVisible("public", "carol", "alice", vis)).toBe(true);
// protected → owner must be in the visible set
expect(isVisible("protected", "bob", "alice", vis)).toBe(true);
expect(isVisible("protected", "carol", "alice", vis)).toBe(false);
// private → owner must be the current principal
expect(isVisible("private", "alice", "alice", vis)).toBe(true);
expect(isVisible("private", "bob", "alice", vis)).toBe(false);
});
test("applyIsolation narrows a mixed collection for the current principal", () => {
const items: Item[] = [
{ id: "e", owner: "carol", scope: "public" }, // public → kept for all
{ id: "p1", owner: "alice", scope: "protected" }, // own protected → kept
{ id: "p2", owner: "bob", scope: "protected" }, // connection's protected → kept
{ id: "p3", owner: "carol", scope: "protected" }, // stranger's protected → dropped
{ id: "s1", owner: "alice", scope: "private" }, // own private → kept
{ id: "s2", owner: "bob", scope: "private" }, // connection's private → dropped
];
const forAlice = applyIsolation(items, "alice", conns, acc).map((i) => i.id);
expect(forAlice).toEqual(["e", "p1", "p2", "s1"]);
const forCarol = applyIsolation(items, "carol", conns, acc).map((i) => i.id);
// carol sees: public + her own protected + her own private
expect(forCarol).toEqual(["e", "p3"]);
});
test("applyIsolation with empty principal passes everything through (hydration guard)", () => {
const items: Item[] = [
{ id: "s1", owner: "alice", scope: "private" },
{ id: "p1", owner: "bob", scope: "protected" },
];
expect(applyIsolation(items, "", conns, acc).map((i) => i.id)).toEqual(["s1", "p1"]);
});
+2 -2
View File
@@ -34,7 +34,7 @@ function inject(triplesByDoc: Record<string, Array<[string, string]>>) {
configure({ ng: ng as any, useShape: (() => {}) as any });
configureStoreRegistry({
getSession: async () => ({ sessionId: "sid-rm", privateStoreId: "priv" }),
normalizeUser: (u: string) => u,
normalizeId: (u: string) => u,
});
return ng;
}
@@ -96,7 +96,7 @@ test("a doc that fails to read is skipped, not aborting the batch", async () =>
configure({ ng: ng as any, useShape: (() => {}) as any });
configureStoreRegistry({
getSession: async () => ({ sessionId: "sid-rm", privateStoreId: "priv" }),
normalizeUser: (u: string) => u,
normalizeId: (u: string) => u,
});
const subjects = await readUnion(["did:ng:o:ok", "did:ng:o:bad"]);
+1 -1
View File
@@ -43,7 +43,7 @@ test("escapeIri percent-encodes every IRI-breaking character", () => {
test("escapeIri neutralises a full breakout attempt", () => {
const attack = 'x> <urn:evil> "pwn';
const encoded = escapeIri(attack);
// The encoded username cannot contain a raw `>`, `<`, `"` or space, so it
// The encoded id cannot contain a raw `>`, `<`, `"` or space, so it
// cannot escape the surrounding <PREFIX:...> IRI.
expect(encoded).not.toMatch(/[<>" ]/);
});
+22 -22
View File
@@ -112,7 +112,7 @@ function makeFakeNg() {
const sparql_query = mock(async (...a: unknown[]) => {
const query = a[1] as string;
const anchor = a[3] as string | undefined;
if (query.includes("<urn:ng-eventually:shim:username>")) {
if (query.includes("<urn:ng-eventually:shim:id>")) {
// Account SELECT, scoped to the anchor graph. Two shapes: the full scan
// (`?acc a <Account>`) and the TARGETED bounded resolve (`<subj> a
// <Account>`) which binds one subject — honour that subject so the bounded
@@ -124,16 +124,16 @@ function makeFakeNg() {
if (q.g !== anchor) continue;
if (onlySubject !== null && q.s !== onlySubject) continue;
const rec = bySubject.get(q.s) ?? {};
if (q.p === "urn:ng-eventually:shim:username") rec.username = q.o;
if (q.p === "urn:ng-eventually:shim:id") rec.id = q.o;
if (q.p === "urn:ng-eventually:shim:docPublic") rec.docPublic = q.o;
if (q.p === "urn:ng-eventually:shim:docProtected") rec.docProtected = q.o;
if (q.p === "urn:ng-eventually:shim:docPrivate") rec.docPrivate = q.o;
bySubject.set(q.s, rec);
}
const bindings = [...bySubject.values()]
.filter((r) => r.username)
.filter((r) => r.id)
.map((r) => ({
username: { value: r.username! },
id: { value: r.id! },
docPublic: { value: r.docPublic ?? "" },
docProtected: { value: r.docProtected ?? "" },
docPrivate: { value: r.docPrivate ?? "" },
@@ -157,7 +157,7 @@ function inject() {
configure({ ng: ng as any, useShape: (() => {}) as any });
configureStoreRegistry({
getSession: async () => SESSION,
normalizeUser: (u) => u.trim().replace(/^@+/, "").toLowerCase(),
normalizeId: (u) => u.trim().replace(/^@+/, "").toLowerCase(),
});
resetRegistryCache();
return ng;
@@ -170,7 +170,7 @@ beforeEach(() => {
test("ensureAccount creates 3 scope docs and persists them to the shim", async () => {
const rec = await ensureAccount("Alice");
expect(rec.username).toBe("Alice");
expect(rec.id).toBe("Alice");
expect(fake.doc_create).toHaveBeenCalledTimes(3);
expect(rec.docPublic).toMatch(/^did:ng:o:doc/);
expect(rec.docProtected).not.toBe(rec.docPublic);
@@ -191,7 +191,7 @@ test("loadShim round-trips a persisted account across a cache reset", async () =
resetRegistryCache(); // force a re-read from the fake store
const map = await loadShim();
const rec = map.get("bob");
expect(rec?.username).toBe("Bob");
expect(rec?.id).toBe("Bob");
expect(rec?.docPublic).toMatch(/^did:ng:o:doc/);
});
@@ -260,19 +260,19 @@ test("listEntityDocs fans out across multiple accounts", async () => {
test("allAccounts reflects every ensured account", async () => {
await ensureAccount("Gina");
await ensureAccount("Hank");
const names = (await allAccounts()).map((a) => a.username).sort();
const names = (await allAccounts()).map((a) => a.id).sort();
expect(names).toEqual(["Gina", "Hank"]);
});
// --- SPARQL injection hardening (F1) --------------------------------------
//
// A malicious username must NOT be able to break out of the literal / IRI it
// A malicious id must NOT be able to break out of the literal / IRI it
// lands in and inject arbitrary triples into the shim (the account→doc trust
// root). We inspect the exact SPARQL string the registry hands to sparql_update.
/** The raw INSERT DATA string produced by ensureAccount for `username`. */
async function insertFor(username: string): Promise<string> {
await ensureAccount(username);
/** The raw INSERT DATA string produced by ensureAccount for `id`. */
async function insertFor(id: string): Promise<string> {
await ensureAccount(id);
const calls = fake.sparql_update.mock.calls;
return calls[calls.length - 1]![1] as string;
}
@@ -284,31 +284,31 @@ function rawQuoteCount(s: string): number {
return (withoutEscapes.match(/"/g) ?? []).length;
}
test("injection: username with a quote cannot open extra literals", async () => {
test("injection: id with a quote cannot open extra literals", async () => {
const evil = 'x" ; <urn:evil> "pwn';
const update = await insertFor(evil);
// A well-formed INSERT DATA with 4 predicate literals has exactly 8 raw
// quotes (the delimiters). The injected `"` must have been escaped, so the
// count stays 8 — no extra literal was opened.
expect(rawQuoteCount(update)).toBe(8);
// The escaped username is present as a single literal value — the injected
// The escaped id is present as a single literal value — the injected
// `<urn:evil>` survives only as INERT text inside that literal (its
// surrounding quotes are escaped `\"`), never as query syntax.
expect(update).toContain('"x\\" ; <urn:evil> \\"pwn"');
});
test("injection: username with '>' cannot break out of the account-subject IRI", async () => {
test("injection: id with '>' cannot break out of the account-subject IRI", async () => {
const evil = "x> <urn:evil";
const update = await insertFor(evil);
// The account subject is `<urn:ng-eventually:shim:account:...>` — the encoded
// username must NOT contain a raw `>` that would close the IRI early.
// id must NOT contain a raw `>` that would close the IRI early.
const subjMatch = update.match(/<urn:ng-eventually:shim:account:([^>]*)>/)!;
expect(subjMatch).not.toBeNull();
expect(subjMatch[1]).not.toMatch(/[<>" ]/); // fully percent-encoded
expect(subjMatch[1]).toContain("%3E"); // the `>` became %3E
});
test("injection: newline / control chars in username are neutralised", async () => {
test("injection: newline / control chars in id are neutralised", async () => {
const evil = "a\nb\tc";
const update = await insertFor(evil);
// In the literal: escaped to \n / \t (no raw control char).
@@ -342,20 +342,20 @@ function escapeLiteralRef(v: string): string {
.replace(/\t/g, "\\t")}"`;
}
test("injection: a malicious username still round-trips through the shim", async () => {
test("injection: a malicious id still round-trips through the shim", async () => {
const evil = 'eve" ; <urn:evil> "x';
const rec = await ensureAccount(evil);
expect(rec.username).toBe(evil);
expect(rec.id).toBe(evil);
resetRegistryCache();
const map = await loadShim();
// The stored username came back verbatim (escaping is lossless) under its
// The stored id came back verbatim (escaping is lossless) under its
// normalized key, and exactly ONE account exists (no injected extra subject).
const key = evil.trim().replace(/^@+/, "").toLowerCase();
expect(map.get(key)?.username).toBe(evil);
expect(map.get(key)?.id).toBe(evil);
expect(map.size).toBe(1);
});
test("normalizeUser defaults to trim when not provided", async () => {
test("normalizeId defaults to trim when not provided", async () => {
const ng = makeFakeNg();
configure({ ng: ng as any, useShape: (() => {}) as any });
configureStoreRegistry({ getSession: async () => SESSION });