Files
ng-eventually/packages/polyfill/src/emulated-verifier/reach.ts
T
Sylvain Duchesne 0a2b8b1fbf docs: dire partout que la lecture par lot n'existe plus
Le contrat publie et l'api-contract etaient traites avec le retrait lui-meme ;
restaient les documents qui decrivaient readUnion comme la primitive de
lecture du paquet, ou qui nommaient le module disparu.

Ce que les lecteurs apprennent maintenant : lire un document, c'est
docs.sparqlQuery ancre dessus, et lire plusieurs documents, c'est cet appel
une fois par document -- avec la decision sur une lecture qui echoue ecrite
au point d'appel. Deux consequences sont dites plutot que decouvertes : une
lecture refusee leve au lieu de rendre une liste vide, et les sujets sous le
prefixe reserve urn:ng-eventually: reviennent dans le resultat, a l'appelant
de les ignorer -- sans aucun gain de droits, les deux registres qu'un
document ordinaire porte etant l'adresse de sa boite et, pour un document
public, la cle que son magasin sert deja a qui la demande.

Les briefs dates ne sont pas touches : ils decrivent un etat de juillet, et
le reecrire falsifierait ce qui avait ete decide alors.
2026-09-21 14:11:35 +02:00

185 lines
11 KiB
TypeScript

/**
* reach — may the CONNECTED virtual user touch this document at all?
*
* The one predicate every path to `ng` consults, so the boundary is decided in a
* single place instead of being re-argued at each call site.
*
* ── The boundary ──────────────────────────────────────────────────────────
* A virtual user must simulate the boundary of the future single-user wallet:
* every access function is confined to the user currently connected
* (`setCurrentUser`), and no cross-user access is permitted. Otherwise the
* consumer is coded against a reach that will never exist — the same failure mode
* as an ACL where the real model is key possession, one level down.
*
* Two ways a document is legitimately reachable, and no others:
*
* 1. **You hold its cap.** Either because you created it (the store refiles the
* cap) or because someone delivered it to you. This is the whole of the
* access model, so it is the whole of the predicate.
* There is no second way, and there used to be a third door here: an explicit list of
* NURIs "declared infrastructure", exempt from the boundary. It was removed on
* 2026-08-07 with **zero callers**, an always-empty set, and a header describing two
* exempted documents that were never registered — dead scaffolding whose documentation
* claimed a hole existed where none did. The machinery reaches the shim through
* `shared-wallet/physical.ts`, which is a different FUNCTION rather than an exemption,
* and that is the stronger arrangement the module below already argues for.
*
* ── What may be exempt, and why so little ─────────────────────────────────
* > The only reads/writes not confined to a virtual user are those that make
* > multi-user operation possible at all. Nothing common — only the indexing
* > mechanisms that make the virtual users work.
*
* The test an exemption must pass: *does removing it stop the virtual users from
* functioning, or does it merely stop users from seeing each other's content?* Only the
* first qualifies — and the answer is that no exemption is needed at all: the one thing
* that qualifies (the shim) is reached through its own unguarded FUNCTIONS
* (`shared-wallet/physical.ts`), so nothing has to be waved through here.
*
* Depositing into another user's inbox is NOT handled here: it is a write to a
* document you do not hold, and it is legitimate — the only channel by which a
* link crosses from one user to another, hence the bootstrap of the whole
* reachability graph. It is allowed at the inbox surface, which is where the
* asymmetry (deposit yes, read no) is expressed.
*
* At migration this module disappears: the boundary becomes the wallet itself.
*/
import { getCaps } from "../shared-wallet/bootstrap";
import { targetOf } from "../model/nuri";
import type { Nuri } from "../model/types";
/**
* Do we POSSESS the cap of `nuri`? Not "does this string carry one" — a caller may
* legitimately be holding the bare form and possess the cap elsewhere, which is the
* normal case: NURIs travel bare through content and indexes, while the cap sits in
* what the user holds. Possession is what decides; the shape of the reference the
* caller happens to have in hand decides nothing.
*
* `targetOf` first, so a cap-bearing reference and its bare form answer alike.
*
* Inert until the first cap exists (`caps.isEnforcing()`), so a consumer that never
* touches caps keeps working. Once ANY cap has been issued the boundary applies to
* every user, including one holding nothing: that is the isolation.
*
* ── Whose possession, when it is not the connected identity's ─────────────
* `holderKey` names the ring to consult instead of the connected one. Exactly one caller
* passes it: the emulated inbox processor (`inbox-processor.ts`), which drains an inbox on
* behalf of its OWNER while another identity holds the session. Left out — which is every
* other call site — the question is asked of whoever is connected, unchanged.
*
* It does not WIDEN the boundary: the named holder must hold the cap just the same. What it
* fixes is which ring the question is about, so that work decided for one identity is not
* judged against another's possession.
*/
// @provenance mayReach kind=aligned level=1 ref=engine/verifier/src/verifier.rs:load_repo_from_read_cap — upstream possession decides by whether the key opens the repo at all; here it is a lookup, because nothing is encrypted yet
export function mayReach(nuri: Nuri, holderKey?: string): boolean {
const caps = getCaps();
if (!caps.isEnforcing()) return true;
const target = targetOf(nuri);
const held =
holderKey === undefined ? caps.capFor(target) : caps.capForHolder(holderKey, target);
return held !== undefined;
}
/**
* **Rule 1 — authorization**, at the PASSAGE POINTS (`docs.*`, `subscribe`).
*
* Nothing reaches `ng` unless the connected user possesses the document's cap. This
* is the guard: it fires on a request that should never have been made, and its job
* is to make sure the attempt fails rather than succeeds quietly.
*
* Deliberately duplicated with rule 2 below — see {@link mustNotAttempt}. Two rules,
* two places, one criterion: a lapse in either is caught by the other.
*
* `holderKey` asks the question of a NAMED ring rather than the connected one — see
* {@link mayReach}. The refusal names it too, or a processor's refusal would read as the
* connected identity's, which is the one thing nobody would then go and check.
*/
// @provenance assertMayReach kind=aligned level=1 ref=engine/verifier/src/verifier.rs:load_repo_from_read_cap — the throwing form, at the passage points; upstream the equivalent failure is a repo that simply never decrypts
export function assertMayReach(nuri: Nuri, op: string, holderKey?: string): void {
if (mayReach(nuri, holderKey)) return;
const who = holderKey === undefined ? "the connected user" : `holder ${JSON.stringify(holderKey)}`;
throw new Error(
`[ng-eventually] ${op}: refused — ${who} does not hold this document's ` +
"cap. Naming a document does not grant access to it: a cap is looked up in what " +
`you hold, or it was delivered to you. ${JSON.stringify(nuri)}`,
);
}
/**
* **Writing is OWNERSHIP, not possession of a read key.**
*
* Upstream the right to write is membership of the repo: `verify_permission`
* (`engine/repo/src/repo.rs:584`) is reachable only through `Commit::verify_perm` →
* `Commit::verify` (`engine/repo/src/commit.rs:780,897`), so it fires on commits and
* never on reads. Nothing about HOW a reader came by the read key bears on it — a public
* store hands its read cap to whoever asks (`PublicRepoLinkV0`,
* `engine/net/src/types.rs:5098`), and a cap deposited in an inbox is a Link someone gave
* you (`AddLinkV0`, "external repos only", `engine/repo/src/types.rs:1939-1948`). Neither
* makes you a member.
*
* ── What this replaced, and why ───────────────────────────────────────────
* Until 2026-08-07 this asked *"was this cap served to me by a public store?"* and
* refused only then. That predicate was wrong in BOTH directions, and an adversarial
* review found each end:
*
* - too lax — a cap received in an inbox passed, so an application could write into a
* document it merely reads. Someone could ship collaborative editing on it and lose
* it at migration. It was labelled cap-enforcement's responsibility, but
* cap-enforcement is key MATERIAL and this is a model relation;
* - too strict — the owner of her own public document was refused, whenever she opened
* it from its reference before her store had been listed (a deep link, a fresh
* session). The comment beside the code asserted the opposite.
*
* One predicate pushed two ways is the signal that it was the wrong predicate. Ownership
* is the right one, it is durable (it is read from the Store branch, the emulated
* `AddRepo`, not from session memory), and it answers both.
*
* ── What it does NOT cover ────────────────────────────────────────────────
* Delegated writing. Upstream a repo's owner may add members (`AddMember` /
* `AddPermission`); this library emulates none of that, so here only the owner writes —
* which is a repo's state upstream until someone is added. A narrowing, in the safe
* direction, and one an application cannot build a habit on because the target's answer
* (be granted permission) has no surface here to build on.
*
* The library's own registers do not come through here at all: they go through
* `docs.registerUpdate`, because a store document is not OWNED in this sense — it IS a
* store, and the verifier commits to it on its own behalf.
*/
// @provenance assertMayWrite kind=aligned level=1 ref=engine/repo/src/commit.rs:verify_perm — upstream the right to write is membership of the repo, checked on commits only; ownership stands in for it here
export async function assertMayWrite(nuri: Nuri, op: string): Promise<void> {
const caps = getCaps();
if (!caps.isEnforcing()) return;
const target = targetOf(nuri);
// Created here — authorship, and the cheap answer. It is also the ONLY record for a
// document made through the raw `docs.docCreate`, which has no store to file into.
if (caps.mintedHere(target)) return;
// Otherwise ask the durable register: the Store branch, the emulated `AddRepo`.
const { ownsDocument } = await import("./branch-registers");
if (await ownsDocument(target)) return;
throw new Error(
`[ng-eventually] ${op}: refused — writing needs the WRITE cap, and reading a document ` +
"never grants it. A public store serves its read cap to anyone, and a cap deposited " +
`in your inbox is one someone gave you; neither makes you the document's owner. ${JSON.stringify(nuri)}`,
);
}
/**
* **Rule 2 — do not even attempt**, at the CALLERS (`open-repo`,
* `subscribe`'s callers…).
*
* A reader that does not hold a document's cap must not issue the operation at all.
* Not attempting and being refused are different things: the first is a caller that
* knows what it holds, the second is one that hoped and got caught. Only the first
* is the model — upstream you cannot even address a repo you have no cap for.
*
* Practically it also stops the library from asking the broker for documents it has
* no business asking about, which is work, noise, and a leak of intent.
*
* `holderKey` names the ring the question is about — see {@link mayReach}.
*/
// @provenance mustNotAttempt kind=aligned level=1 ref=engine/verifier/src/request_processor.rs:resolve_target — upstream a repo you cannot open answers `RepoNotFound`; this is the do-not-even-attempt form of the same absence
export function mustNotAttempt(nuri: Nuri, holderKey?: string): boolean {
return !mayReach(nuri, holderKey);
}