Refactor read filter from per-item grant to per-document ReadCap

Model the read filter on NextGraph's real ReadCap mechanism instead of an
invented per-item grant. Verified in nextgraph-rs: there is no Document type
(document = repo); a store is a container repo referencing other repos by RDF
overlay; holding a store's cap does NOT grant the repos it contains (each repo
needs its own cap; no read-cap inheritance). So the access unit is the
DOCUMENT = an item's `@graph`, never the item.

- caps.ts: CapRegistry (read/write caps per document NURI + public docs;
  open/grantRead/grantWrite/makePublic/canRead/canWrite/governsRead/
  hasReadPolicy). Replaces access.ts (Grant).
- read-filter.ts: filter keeps an item iff its `@graph` document is readable
  (held cap or public); items with no `@graph` or in an ungoverned document are
  kept. No injected grantOf — the filter reads `@graph` and consults the
  registry (automatic, domain-agnostic).
- polyfill.ts: getCaps()/resetCaps() replace setGrantOf/getGrantOf; useShape
  filters only when caps.hasReadPolicy() (else passthrough, no regression).
- tests: caps.test.ts (6) + read-filter.test.ts (4), incl. no-inheritance
  between documents. 10 pass; tsc rc=0.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Sylvain Duchesne
2026-06-29 11:19:57 +02:00
parent 672067d513
commit 88d96857fb
9 changed files with 231 additions and 149 deletions
-42
View File
@@ -1,42 +0,0 @@
/**
* Capability emulation — pure, generic, no domain rules. Mirrors what the broker
* will enforce via real caps; at migration these checks disappear (the broker
* only ever syncs/serves what the wallet is authorized for).
*/
import type { Grant, PrincipalId, Scope } from "./types";
/** May `principal` read a document carrying `grant`? */
export function canRead(grant: Grant, principal: PrincipalId | null): boolean {
if (grant.read.includes("public")) return true;
if (principal === null) return false;
return grant.read.includes(principal);
}
/** May `principal` write a document carrying `grant`? */
export function canWrite(grant: Grant, principal: PrincipalId | null): boolean {
if (principal === null) return false;
return grant.write.includes(principal);
}
/**
* The grant a freshly created document gets, by scope, for its `owner`. These
* are the *defaults* a creator attaches; further sharing (e.g. granting a
* connection read on a protected doc) is a separate explicit act.
*/
export function defaultGrant(scope: Scope, owner: PrincipalId): Grant {
switch (scope) {
case "public":
return { read: ["public"], write: [owner] };
case "protected":
return { read: [owner], write: [owner] };
case "private":
return { read: [owner], write: [owner] };
}
}
/** Add a read grant to a principal (e.g. when a connection is accepted). */
export function grantRead(grant: Grant, principal: PrincipalId): Grant {
if (grant.read.includes(principal)) return grant;
return { ...grant, read: [...grant.read, principal] };
}
+97
View File
@@ -0,0 +1,97 @@
/**
* Capability emulation — generic, no domain rules. Models NextGraph **ReadCaps**
* (and write caps) as faithfully as a data layer can.
*
* In NextGraph a ReadCap is possession of a *document's* (repo's) read key: the
* broker only ever delivers documents the wallet holds a cap for. The access
* UNIT is therefore the **document = repo**, identified here by its NURI — the
* `@graph` an item lives in — **never the item**. (Verified in nextgraph-rs:
* a store is just a container repo; holding a store's cap does NOT grant the
* repos it references — each document needs its own cap. So this registry is
* purely per-document, with NO store-level inheritance.)
*
* At migration this whole layer disappears: the broker/verifier enforces the
* real caps and `useShape` already returns only authorized documents.
*/
import type { Nuri, PrincipalId, Scope } from "./types";
/**
* Who holds the read/write cap of each document. The consumer populates it via
* cap operations (create-public, grant-to-a-connection…) exactly as it will in
* the target; this layer enforces possession generically — it knows no policy.
*/
export class CapRegistry {
/** doc NURI → principals holding its READ cap. */
private readers = new Map<Nuri, Set<PrincipalId>>();
/** doc NURI → principals holding its WRITE cap. */
private writers = new Map<Nuri, Set<PrincipalId>>();
/** doc NURIs readable by everyone (public_store repos — no cap needed). */
private publicDocs = new Set<Nuri>();
/** Grant `principal` the READ cap of document `doc`. */
grantRead(doc: Nuri, principal: PrincipalId): void {
add(this.readers, doc, principal);
}
/** Grant `principal` the WRITE cap of document `doc`. */
grantWrite(doc: Nuri, principal: PrincipalId): void {
add(this.writers, doc, principal);
}
/** Mark `doc` public (readable without a cap — a public_store repo). */
makePublic(doc: Nuri): void {
this.publicDocs.add(doc);
}
/**
* Apply the caps a creator attaches to a fresh document, by scope. Public →
* world-readable; protected/private → only the owner reads. The owner always
* holds the write cap. Further sharing is a separate explicit grant.
*/
open(doc: Nuri, scope: Scope, owner: PrincipalId): void {
if (scope === "public") this.makePublic(doc);
else this.grantRead(doc, owner);
this.grantWrite(doc, owner);
}
/** Is `doc` under any READ-cap policy? (Undeclared docs are not enforced.) */
governsRead(doc: Nuri): boolean {
return this.publicDocs.has(doc) || this.readers.has(doc);
}
/** Does `principal` hold a READ cap for `doc` (or is `doc` public)? */
canRead(doc: Nuri, principal: PrincipalId | null): boolean {
if (this.publicDocs.has(doc)) return true;
if (principal === null) return false;
return this.readers.get(doc)?.has(principal) ?? false;
}
/** Is `doc` under any WRITE-cap policy? */
governsWrite(doc: Nuri): boolean {
return this.writers.has(doc);
}
/** Does `principal` hold a WRITE cap for `doc`? */
canWrite(doc: Nuri, principal: PrincipalId | null): boolean {
if (principal === null) return false;
return this.writers.get(doc)?.has(principal) ?? false;
}
/** No READ policy declared → the read filter stays inert (passthrough). */
hasReadPolicy(): boolean {
return this.readers.size > 0 || this.publicDocs.size > 0;
}
clear(): void {
this.readers.clear();
this.writers.clear();
this.publicDocs.clear();
}
}
function add(m: Map<Nuri, Set<PrincipalId>>, doc: Nuri, principal: PrincipalId): void {
let s = m.get(doc);
if (!s) m.set(doc, (s = new Set()));
s.add(principal);
}
+14 -14
View File
@@ -9,7 +9,7 @@
*/
import type { NgLike, UseShapeLike, PrincipalId } from "./types";
import type { GrantResolver } from "./read-filter";
import { CapRegistry } from "./caps";
export interface EventuallyConfig {
/** The REAL `@ng-org/web` `ng` (injected to avoid a hard import / alias loop). */
@@ -24,18 +24,17 @@ export interface EventuallyConfig {
init?: (...args: any[]) => any;
/** REAL `@ng-org/orm` `initNg` (ORM signals) — forwarded by the lib's `initNg()`. */
initNg?: (...args: any[]) => any;
/** How to read a document's emulated grant. When set, reads are filtered. */
grantOf?: GrantResolver;
}
let cfg: EventuallyConfig | null = null;
let currentUser: PrincipalId | null = null;
let grantOf: GrantResolver | 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();
export function configure(c: EventuallyConfig): void {
cfg = c;
currentUser = c.currentUser ?? null;
grantOf = c.grantOf ?? null;
}
/** @internal — used by the SDK-shaped wrappers to reach the injected real SDK. */
@@ -53,16 +52,17 @@ export function getCurrentUser(): PrincipalId | null {
return currentUser;
}
/** Set/clear how reads resolve a document's grant. null → reads pass through. */
export function setGrantOf(fn: GrantResolver | null): void {
grantOf = fn;
/** The emulated cap registry — the app grants/opens caps on it (as it will via
* real cap operations in the target). The read filter consults it. */
export function getCaps(): CapRegistry {
return caps;
}
export function getGrantOf(): GrantResolver | null {
return grantOf;
/** Reset all emulated caps (mainly for tests / fresh sessions). */
export function resetCaps(): void {
caps = new CapRegistry();
}
// Capability helpers — polyfill-era surface (caps are emulated now; native at
// migration). Re-exported here so the whole polyfill API lives under /polyfill.
export { canRead, canWrite, defaultGrant, grantRead } from "./access";
export type { GrantResolver } from "./read-filter";
// Cap surface — polyfill-era (caps are emulated now; native at migration).
// Re-exported here so the whole polyfill API lives under /polyfill.
export { CapRegistry } from "./caps";
+31 -21
View File
@@ -1,34 +1,47 @@
/**
* Read filter — the polyfill of capability-based read access.
*
* In the target, the broker only delivers documents the user holds a read cap
* In the target, the broker only delivers documents the user holds a **ReadCap**
* for, so `useShape` already returns an authorized subset. Here (single shared
* wallet, everything readable) we reproduce that: a read-filtered VIEW over the
* reactive set that yields only items whose emulated grant satisfies the current
* user. Removed at migration (the broker does it natively).
* wallet, everything readable) we reproduce that with a read-filtered VIEW over
* the reactive set: it keeps only items whose **document** (its `@graph` = the
* repo it lives in) the current user may read, per the {@link CapRegistry}.
*
* Faithful to NextGraph: the access unit is the DOCUMENT, not the item. In a
* mono-store layout (every item in one repo) the filter is therefore all-or-
* nothing on that document — which is exactly the native behavior, and why
* fine-grained isolation requires one document per entity. Removed at migration.
*/
import { canRead } from "./access";
import type { Grant, PrincipalId } from "./types";
import type { CapRegistry } from "./caps";
import type { PrincipalId } from "./types";
/** The document (repo NURI) an item lives in — its `@graph`. */
function docOf(item: unknown): string | null {
const g = (item as Record<string, unknown> | null)?.["@graph"];
return typeof g === "string" ? g : null;
}
/**
* Reads a document's emulated grant. Return `undefined` when the item carries no
* grant — such items are kept (the filter only restricts items that DECLARE a
* grant). The consumer injects this (the lib stays domain-agnostic).
* May `user` read this item? An item with no `@graph`, or in a document under no
* cap policy, is KEPT (the filter only restricts documents that DECLARE a cap —
* mirrors the prior behavior and keeps ungoverned data flowing).
*/
export type GrantResolver = (item: unknown) => Grant | undefined;
function readable(item: unknown, caps: CapRegistry, user: PrincipalId | null): boolean {
const doc = docOf(item);
if (doc === null) return true;
if (!caps.governsRead(doc)) return true;
return caps.canRead(doc, user);
}
/** Pure: keep only the items the user may read. Ungranted items are kept. */
/** Pure: keep only the items the user may read. */
export function filterReadable<T>(
items: Iterable<T>,
grantOf: GrantResolver,
caps: CapRegistry,
user: PrincipalId | null,
): T[] {
const out: T[] = [];
for (const item of items) {
const g = grantOf(item);
if (g === undefined || canRead(g, user)) out.push(item);
}
for (const item of items) if (readable(item, caps, user)) out.push(item);
return out;
}
@@ -41,13 +54,10 @@ export function filterReadable<T>(
*/
export function makeReadFilteredView<S extends object>(
set: S,
grantOf: GrantResolver,
caps: CapRegistry,
getUser: () => PrincipalId | null,
): S {
const keep = (item: unknown): boolean => {
const g = grantOf(item);
return g === undefined || canRead(g, getUser());
};
const keep = (item: unknown): boolean => readable(item, caps, getUser());
return new Proxy(set, {
get(target, prop, receiver) {
if (prop === Symbol.iterator) {
-13
View File
@@ -13,19 +13,6 @@ export type Scope = "public" | "protected" | "private";
* Polyfill: a chosen id (e.g. a username), because everyone shares one wallet. */
export type PrincipalId = string;
/**
* Emulated capability attached to a document — mirrors real NextGraph caps,
* which the broker/verifier will enforce natively at migration. The app attaches
* these via cap operations exactly as it will in the target; this layer enforces
* them generically (it does NOT know any authorization policy).
*/
export interface Grant {
/** Read grant: `"public"` = everyone, otherwise explicit principals. */
read: Array<PrincipalId | "public">;
/** Write grant: principals allowed to write the document. */
write: PrincipalId[];
}
/**
* Loose shape of the real `@ng-org/web` `ng` object that we wrap. Injected by
* the consumer at {@link configure} — we never hard-import the SDK, which keeps
+9 -8
View File
@@ -1,16 +1,17 @@
/**
* Wrapped `useShape`: same signature as `@ng-org/orm`. When a grant resolver is
* configured, the returned set is a read-filtered VIEW (only items the current
* user may read); otherwise it passes the real set through unchanged. At
* migration the filtering disappears — the broker only delivers authorized docs.
* Wrapped `useShape`: same signature as `@ng-org/orm`. When a read-cap policy is
* declared, the returned set is a read-filtered VIEW (only items in documents the
* current user holds a ReadCap for); otherwise it passes the real set through
* unchanged. At migration the filtering disappears — the broker only delivers
* authorized documents.
*/
import { getConfig, getCurrentUser, getGrantOf } from "./polyfill";
import { getConfig, getCurrentUser, getCaps } from "./polyfill";
import { makeReadFilteredView } from "./read-filter";
export function useShape(shapeType: unknown, scope: unknown): unknown {
const set = getConfig().useShape(shapeType, scope) as object;
const grantOf = getGrantOf();
if (!grantOf) return set; // no policy configured → passthrough (filter inert)
return makeReadFilteredView(set, grantOf, getCurrentUser);
const caps = getCaps();
if (!caps.hasReadPolicy()) return set; // no policy configured → passthrough
return makeReadFilteredView(set, caps, getCurrentUser);
}