feat(client): real per-document isolation + bilateral connections + deposit guards
The ReadCap filter now enforces on per-entity documents (consumers create one doc per entity, so each has a declared policy — private→owner, protected→owner+ connections, public→all). Isolation is genuinely active, not dormant. - connections.ts (new): a BILATERAL connection registry — a link grants protected read only when BOTH sides have asserted it (each assertion bound to its author). A unilateral/self-declared connection grants nothing (closes the confused-deputy hole). declareConnections is authenticated to the current identity. - inbox.post: `from` is bound to the current identity — a spoofed `from` throws. - discovery.submitToIndex: PUBLIC-ONLY — a governed non-public doc is refused (no protected/private leak into the world-readable index). - docs/simulation.md: documents this as application-level emulated isolation on a shared wallet (not crypto); at NextGraph maturity → real caps, consumer unchanged. 89 tests pass (+10 covering: active protected isolation via bilateral connect, unilateral grants nothing, from-spoof rejected, non-public submit refused). tsc rc=0. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,90 @@
|
||||
/**
|
||||
* connections — a BILATERAL (two-sided, authenticated) connection registry.
|
||||
*
|
||||
* STOPGAP / polyfill-era. In the target, "connected" means the two wallets have
|
||||
* *each* issued the other a capability (a mutual, cryptographically-authenticated
|
||||
* link). A single side cannot manufacture the relationship. Here — one shared
|
||||
* wallet, everything physically readable — the registry reproduces that property
|
||||
* as data: a connection between `a` and `b` is materialized ONLY when BOTH sides
|
||||
* have asserted it.
|
||||
*
|
||||
* ── Why bilateral (the adversarial finding this defends) ──────────────────────
|
||||
* "protected = owner + connections" must not be bypassable by a reader who simply
|
||||
* self-declares a connection to the owner. If a single directed assertion granted
|
||||
* access, any principal could read any owner's protected documents by unilaterally
|
||||
* claiming a link. So the registry keeps DIRECTED assertions and exposes as
|
||||
* `neighbors(p)` only the principals `q` for which BOTH `assert(p → q)` AND
|
||||
* `assert(q → p)` are present — the materialized two-sided link.
|
||||
*
|
||||
* ── Generic by construction ───────────────────────────────────────────────────
|
||||
* Knows no application domain. The consumer maps its own relationship (accepted
|
||||
* friendships, follows-back, …) onto directed assertions: each side asserts the
|
||||
* other. Only when both assertions exist is the link live and does it drive a
|
||||
* protected read grant (via {@link CapRegistry.grantReadToConnections}). Removed
|
||||
* at migration, where a real mutual capability replaces the materialized link.
|
||||
*/
|
||||
|
||||
import type { Connections } from "./isolation";
|
||||
import type { PrincipalId } from "./types";
|
||||
|
||||
/**
|
||||
* One directed connection assertion: `from` asserts a connection to `to`. A link
|
||||
* is live (and grants protected read) only when the reverse assertion also
|
||||
* exists. The consumer's own social graph is fed as these directed assertions.
|
||||
*/
|
||||
export interface ConnectionAssertion {
|
||||
from: PrincipalId;
|
||||
to: PrincipalId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Accumulates directed assertions and exposes the BILATERAL neighbourhood. Both
|
||||
* `assert(a → b)` and `assert(b → a)` must be present for `a`/`b` to be neighbours.
|
||||
*/
|
||||
export class ConnectionRegistry {
|
||||
/** principal → the set of principals it has asserted a connection TO. */
|
||||
private asserted = new Map<PrincipalId, Set<PrincipalId>>();
|
||||
|
||||
/** Record that `from` asserts a connection to `to` (one direction only). */
|
||||
assert(from: PrincipalId, to: PrincipalId): void {
|
||||
if (!from || !to || from === to) return;
|
||||
let s = this.asserted.get(from);
|
||||
if (!s) this.asserted.set(from, (s = new Set()));
|
||||
s.add(to);
|
||||
}
|
||||
|
||||
/** Record a batch of directed assertions. */
|
||||
assertAll(assertions: Iterable<ConnectionAssertion>): void {
|
||||
for (const { from, to } of assertions) this.assert(from, to);
|
||||
}
|
||||
|
||||
/** Has `from` asserted a connection to `to` (one direction)? */
|
||||
hasAsserted(from: PrincipalId, to: PrincipalId): boolean {
|
||||
return this.asserted.get(from)?.has(to) ?? false;
|
||||
}
|
||||
|
||||
/**
|
||||
* The BILATERAL neighbours of `principal`: every `q` such that `principal` and
|
||||
* `q` have each asserted the other. A unilateral (one-sided) assertion yields
|
||||
* NO neighbour — the defence against self-declared connections.
|
||||
*/
|
||||
neighbors(principal: PrincipalId): Set<PrincipalId> {
|
||||
const out = new Set<PrincipalId>();
|
||||
const outgoing = this.asserted.get(principal);
|
||||
if (!outgoing) return out;
|
||||
for (const to of outgoing) if (this.hasAsserted(to, principal)) out.add(to);
|
||||
return out;
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.asserted.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adapt a {@link ConnectionRegistry} to the {@link Connections} interface consumed
|
||||
* by {@link CapRegistry.grantReadToConnections}. Only bilateral links surface.
|
||||
*/
|
||||
export function bilateralConnections(registry: ConnectionRegistry): Connections {
|
||||
return { neighbors: (principal) => registry.neighbors(principal) };
|
||||
}
|
||||
@@ -41,6 +41,7 @@
|
||||
|
||||
import * as inbox from "./inbox";
|
||||
import { ensureAccount, reservedAccount } from "./store-registry";
|
||||
import { getCaps } from "./polyfill";
|
||||
import type { Nuri, PrincipalId } from "./types";
|
||||
|
||||
/**
|
||||
@@ -66,11 +67,19 @@ export interface IndexEntry {
|
||||
/** Options for {@link submitToIndex}. */
|
||||
export interface SubmitOptions {
|
||||
/**
|
||||
* Who is submitting. Omit (or pass `null`) for an ANONYMOUS submission; pass a
|
||||
* principal id to identify the submitter. Defaults to the current polyfill user
|
||||
* when the property is entirely absent (mirrors {@link inbox.post}).
|
||||
* Who is submitting. Omit for the current identity, or pass `null` for an
|
||||
* ANONYMOUS submission. `from` is BOUND to the current identity by the inbox
|
||||
* (naming another principal is rejected as a spoof — see {@link inbox.post}).
|
||||
*/
|
||||
from?: PrincipalId | null;
|
||||
/**
|
||||
* The NURI of the document being made discoverable. When given, the index
|
||||
* enforces PUBLIC-ONLY: a document under a non-public (protected/private) read
|
||||
* policy is REFUSED — the public index must never leak a governed document's
|
||||
* NURI. Omit it only for a ref with no addressable document (rare); a governed
|
||||
* doc always passes it so the guard can fire.
|
||||
*/
|
||||
doc?: Nuri;
|
||||
/** Optional deposit timestamp (ms epoch). Omitted → `Date.now()`. Passing it
|
||||
* keeps tests deterministic. */
|
||||
ts?: number;
|
||||
@@ -100,8 +109,23 @@ async function indexInboxNuri(): Promise<Nuri> {
|
||||
* entry. GENERIC: `ref` is opaque here (the consumer serializes whatever a
|
||||
* client needs to later locate the entity — e.g. an entity document NURI plus
|
||||
* discovery metadata). `from` follows the inbox convention (anonymous if `null`).
|
||||
*
|
||||
* PUBLIC-ONLY: when `opts.doc` names the document being surfaced, a document under
|
||||
* a non-public read policy (protected/private) is REFUSED — the global index is
|
||||
* world-readable, so admitting a governed doc's NURI would leak it past its scope.
|
||||
*/
|
||||
export async function submitToIndex(ref: unknown, opts?: SubmitOptions): Promise<void> {
|
||||
const doc = opts?.doc;
|
||||
if (doc !== undefined) {
|
||||
const caps = getCaps();
|
||||
// A governed doc is submittable ONLY if it is public (anonymous may read it).
|
||||
if (caps.governsRead(doc) && !caps.canRead(doc, null)) {
|
||||
throw new Error(
|
||||
"[ng-eventually] submitToIndex: only PUBLIC documents may be submitted to " +
|
||||
"the discovery index — a protected/private document must not be surfaced.",
|
||||
);
|
||||
}
|
||||
}
|
||||
const target = await indexInboxNuri();
|
||||
await inbox.post(target, {
|
||||
payload: ref,
|
||||
|
||||
@@ -90,11 +90,31 @@ function readBindings(result: unknown): Array<Record<string, { value: string }>>
|
||||
*
|
||||
* Appends `{ from, payload, ts }` into the inbox document via `docs.sparqlUpdate`
|
||||
* (the real injected `ng`). Each deposit is a fresh RDF subject in the inbox
|
||||
* graph, so concurrent deposits don't collide. `from` is optional: pass `null`
|
||||
* for an anonymous deposit; omit it entirely to default to the current user.
|
||||
* graph, so concurrent deposits don't collide.
|
||||
*
|
||||
* `from` is BOUND TO THE CURRENT IDENTITY — it is authenticated, not
|
||||
* caller-supplied. Omit it to stamp the current user; pass `null` to deposit
|
||||
* ANONYMOUSLY (a legitimate choice — "identified if known, anonymous otherwise").
|
||||
* A `from` naming ANOTHER principal is a SPOOF and is REJECTED: in the target the
|
||||
* broker seals the sender from the wallet's own key, so a client cannot forge
|
||||
* another's identity. (At migration this check is redundant — the seal enforces
|
||||
* it — but until then it closes the spoof the shared wallet would otherwise allow.)
|
||||
*/
|
||||
export async function post(targetInbox: Nuri, opts: PostOptions): Promise<void> {
|
||||
const from = opts.from === undefined ? getCurrentUser() : opts.from;
|
||||
const current = getCurrentUser();
|
||||
let from: PrincipalId | null;
|
||||
if (opts.from === undefined) {
|
||||
from = current; // default: stamp the current identity
|
||||
} else if (opts.from === null) {
|
||||
from = null; // explicit anonymous deposit
|
||||
} else if (opts.from === current) {
|
||||
from = opts.from; // identifying as self — allowed
|
||||
} else {
|
||||
throw new Error(
|
||||
"[ng-eventually] inbox.post: `from` must be the current identity or null " +
|
||||
"(anonymous) — depositing as another principal is a spoof.",
|
||||
);
|
||||
}
|
||||
const ts = opts.ts ?? Date.now();
|
||||
const sid = await sessionId();
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
import type { NgLike, UseShapeLike, PrincipalId } from "./types";
|
||||
import type { RegistrySession } from "./store-registry";
|
||||
import { CapRegistry } from "./caps";
|
||||
import type { Connections } from "./isolation";
|
||||
import { ConnectionRegistry, bilateralConnections } from "./connections";
|
||||
|
||||
/**
|
||||
* Consumer-injected dependencies of the storeRegistry (polyfill-era). The
|
||||
@@ -47,6 +47,9 @@ let registryDeps: Required<StoreRegistryDeps> | null = null;
|
||||
/** The emulated ReadCap/WriteCap registry. Empty until the app declares caps;
|
||||
* while it has no read policy the read filter passes through (no regression). */
|
||||
let caps = new CapRegistry();
|
||||
/** The emulated BILATERAL connection registry. Accumulates directed assertions
|
||||
* (each authored by the asserting identity); only two-sided links materialize. */
|
||||
let connectionRegistry = new ConnectionRegistry();
|
||||
|
||||
export function configure(c: EventuallyConfig): void {
|
||||
cfg = c;
|
||||
@@ -108,24 +111,44 @@ export function getCaps(): CapRegistry {
|
||||
}
|
||||
|
||||
/**
|
||||
* Declare the current session's CONNECTIONS to the SDK — the domain sharing act
|
||||
* "a protected document is readable by its owner AND that owner's connections".
|
||||
* The consumer knows who is connected to whom (its own social graph) and hands
|
||||
* that graph to the SDK; the SDK issues the corresponding read access on every
|
||||
* protected document it governs (public stays world-readable, private stays
|
||||
* owner-only). Re-call whenever the connection graph changes.
|
||||
* Declare the CURRENT identity's own connections to the SDK — the domain sharing
|
||||
* act "a protected document is readable by its owner AND that owner's connections".
|
||||
*
|
||||
* SDK-shaped: the consumer passes a {@link Connections} (who-is-connected-to-whom)
|
||||
* and gets access enforcement — it never touches a document NURI, a store id, or
|
||||
* the cap registry internals.
|
||||
* AUTHENTICATED / BILATERAL. Each entry in `peers` is a principal the CURRENT user
|
||||
* (`getCurrentUser()`, or an explicit `as`) asserts a connection to. The lib
|
||||
* records that assertion as authored BY the current identity — a session can only
|
||||
* ever assert its OWN side. A protected read is granted between two principals only
|
||||
* when BOTH have asserted the other (a materialized two-sided link). So a reader
|
||||
* who unilaterally self-declares a connection to an owner gets NOTHING: the owner
|
||||
* never asserted them back. Public stays world-readable; private stays owner-only.
|
||||
* Re-callable whenever the connection graph changes (additive + idempotent).
|
||||
*
|
||||
* SDK-shaped: the consumer passes principals only — never a document NURI, a store
|
||||
* id, or the cap registry internals. `as` names the asserting identity explicitly
|
||||
* (defaults to the current user); the consumer normally omits it.
|
||||
*/
|
||||
export function declareConnections(connections: Connections): void {
|
||||
caps.grantReadToConnections((owner) => connections.neighbors(owner));
|
||||
export function declareConnections(peers: Iterable<PrincipalId>, as?: PrincipalId): void {
|
||||
const self = as ?? currentUser;
|
||||
if (self) for (const peer of peers) connectionRegistry.assert(self, peer);
|
||||
// Re-derive protected grants from the CURRENT bilateral view (only two-sided
|
||||
// links surface as neighbours). Idempotent: grants only ever accumulate.
|
||||
caps.grantReadToConnections((owner) => connectionRegistry.neighbors(owner));
|
||||
}
|
||||
|
||||
/** @internal — the bilateral connection registry (mainly for tests / adapters). */
|
||||
export function getConnectionRegistry(): ConnectionRegistry {
|
||||
return connectionRegistry;
|
||||
}
|
||||
|
||||
/** The current bilateral connection view (only two-sided links surface). */
|
||||
export function getConnections() {
|
||||
return bilateralConnections(connectionRegistry);
|
||||
}
|
||||
|
||||
/** Reset all emulated caps (mainly for tests / fresh sessions). */
|
||||
export function resetCaps(): void {
|
||||
caps = new CapRegistry();
|
||||
connectionRegistry = new ConnectionRegistry();
|
||||
}
|
||||
|
||||
// Cap surface — polyfill-era (caps are emulated now; native at migration).
|
||||
|
||||
Reference in New Issue
Block a user