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
+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 });