diff --git a/doc/2026-11-01_design_id2283.md b/doc/2026-11-01_design_id2283.md new file mode 100644 index 000000000..62bfdda29 --- /dev/null +++ b/doc/2026-11-01_design_id2283.md @@ -0,0 +1,192 @@ +# Design: jurisdiction-aware per-user hosted stores + +- Date: 2026-11-01 +- Status: **proposed** — this records the recommendation for #2283; it is not an implementation or a residency guarantee. +- Issue: [#2283](https://github.com/developing-today/code/issues/2283), under epic #2056; related siblings are #2284 (shared worlds) and #2285 (Cloudflare mechanics and vendor guarantees). +- Code snapshot reviewed: `a9e976ac2` (`design/id-2283`, at `origin/main` before this note). +- Direction: this expands the latest, still-unmerged proposal in [PR #3406](https://github.com/developing-today/code/pull/3406). Treat it as a proposed decision, not as merged code or Drew's approval. + +## Decision to make + +Adopt one jurisdiction-aware contract for hosted per-user stores: persist the policy-selected jurisdiction before creating or routing to a Durable Object (DO); derive the DO identity from the authenticated subject **and** jurisdiction; get both ID and stub from that jurisdiction's restricted namespace; fail closed if the object's jurisdiction cannot be proved; keep blobs jurisdiction-local; keep the shared directory data-minimal and disclose its single fixed-location exception; and make cross-jurisdiction movement a fenced, resumable state machine. + +The signup policy for this scope is `us`, as #2283 requests. It is a deployment policy constant, not a geolocation result, user choice, or fallback for missing data. Do not enable signup or migration until the configured DO namespace and R2 bucket have passed the account-specific gate in #3403, based on #2285. Do not make a residency claim until the applicable vendor questions in #2285 are answered. The user-facing region selector remains out of scope; shared-world semantics remain #2284. + +## Context and evidence + +### What exists at this checkout + +`pkgs/id` is the native Rust/Iroh application surface, not the hosted Cloudflare registry or Worker. Keep those models separate: + +| Current code | Evidence | Design consequence | +| --- | --- | --- | +| A native `Account` contains a public-key-derived ID, display name, verification flag, additional public keys, and confirmed email addresses; there is no jurisdiction field in this record. | [`pkgs/id/src/directory.rs:76-89`](../pkgs/id/src/directory.rs#L76-L89) | The field requested by #2283 belongs in the hosted account/routing record. Do not silently add hosted jurisdiction semantics to the native account model. | +| Native signup generates a random secret and derives the account ID from its Ed25519 public key; keyed signup uses a supplied public key. | [`pkgs/id/src/directory.rs:570-580`](../pkgs/id/src/directory.rs#L570-L580), [`:612-618`](../pkgs/id/src/directory.rs#L612-L618) | A local `Account.id` is not the hosted Google `sub`. Do not pass the native ID to the hosted `userObjectId` contract. | +| Native blob storage is either persistent local `FsStore`/redb or ephemeral `MemStore`; `open_store` selects between them. | [`pkgs/id/src/store.rs:224-237`](../pkgs/id/src/store.rs#L224-L237), [`:332-338`](../pkgs/id/src/store.rs#L332-L338); local store path [`pkgs/id/src/lib.rs:301-306`](../pkgs/id/src/lib.rs#L301-L306) | R2 pinning is a new hosted storage contract, not a property of the current native blob store. | +| A restored native world opens its own `directory.jsonl`. | [`pkgs/id/src/world_store.rs:381-386`](../pkgs/id/src/world_store.rs#L381-L386) | The proposed shared D1 directory is not this per-world native directory. | + +The current native code therefore does not prove Cloudflare namespace behavior, `ctx.id.jurisdiction`, R2 binding support, or D1 placement. Those are hosted-runtime/account facts for #2285/#3403, not facts inferable from these Rust files. The claims below about Cloudflare routing and migration are proposed contracts from #2283, not descriptions of implemented `pkgs/id` behavior. + +### Source precedence and conflicts + +The #2283 body explicitly requires `userObjectId(sub, jurisdiction)`, jurisdiction-local blob deduplication, and a minimal shared directory. The newer Nov 1 proposal in #3406 retains those directions and adds the deployment gate, write fencing, and recovery detail. I follow that latest direction while keeping #3406 marked unmerged. + +There is an older conflict worth making explicit before implementation: the Oct 30 hosted SSO spec names the DO from `binding_id` rather than `sub` ([`doc/2026-10-30T22-45-00Z_design_hosted_provisioning_sso_binding.md:42-46`](2026-10-30T22-45-00Z_design_hosted_provisioning_sso_binding.md#L42-L46), [`:257-264`](2026-10-30T22-45-00Z_design_hosted_provisioning_sso_binding.md#L257-L264)); permits cross-user plaintext blob dedupe ([`:265-268`](2026-10-30T22-45-00Z_design_hosted_provisioning_sso_binding.md#L265-L268)); and includes raw `sub`, contact email, tier, and metering fields in the registry ([`:24-37`](2026-10-30T22-45-00Z_design_hosted_provisioning_sso_binding.md#L24-L37)). For this issue, the newer, explicit #2283 contract and its Nov 1 proposal win: use `sub` in the required jurisdiction-aware derivation, dedupe only within a jurisdiction, and keep the shared directory to pseudonymous routing/migration metadata plus the public records #2283 allows. This issue does not redesign account rebind behavior; do not silently substitute `binding_id` or alias two stores. Reconcile the older SSO spec before implementing the hosted adapter if its rebind guarantees are still required. + +## Viable options and recommendation + +### 1. Where jurisdiction comes from + +| Option | Trade-off | +| --- | --- | +| Persist a deployment policy constant at account creation (`us` for this scope). | No user-facing choice; simple, deterministic, and matches #2283. Needs a hard capability gate so a configured-but-unavailable jurisdiction cannot create a store. | +| Infer it from request location, email, or an account hint. | Convenient-looking, but unstable, unauthoritative, and can change between requests; it cannot safely choose a persistent object's identity. | +| Ask the user to select a region at signup. | Makes choice explicit but is out of scope and forces product, disclosure, and support decisions before the requested routing foundation exists. | + +**Recommend the policy constant**, written once in the hosted account record before any DO ID is derived. Missing, invalid, or unprovisioned jurisdiction is an error; it never means `us` by fallback. `us` signup stays disabled until the actual account/runtime and resource configuration pass #3403/#2285. + +### 2. How to derive and access a user object + +| Option | Trade-off | +| --- | --- | +| Keep `idFromName("google:" + sub)` on the unrestricted namespace. | Smallest diff, but dropping the jurisdiction silently finds a different, empty object; the unrestricted namespace accepts the mismatch instead of exposing the routing bug. This is the split-brain trap called out in #2283. | +| Encode jurisdiction into a name but continue using the unrestricted namespace. | Names may be distinguishable, but the binding does not enforce jurisdiction and a caller can still omit or mis-key it. | +| Derive and get through `env.USERS.jurisdiction(stored).idFromName(...)` and that same restricted namespace. | A mismatch is rejected by the binding; callers have one narrow routing seam and cannot accidentally select the unrestricted object. It requires every caller to use the shared module. | + +**Recommend the restricted namespace.** One routing module accepts required `(sub, jurisdiction)` inputs with no default and owns the raw binding. It derives the ID and obtains the stub from the same `env.USERS.jurisdiction(jurisdiction)` namespace. The authoritative hosted directory supplies the jurisdiction; request headers, geolocation, local account IDs, and caller-supplied IDs do not. Static checks and tests prohibit bypassing the module through the unrestricted binding. + +### 3. Blob and directory residency + +For R2, the alternatives are one global bucket (cheap dedupe, weak jurisdiction isolation) or separate jurisdiction-bound buckets (more duplicated bytes and config, but the binding and dedupe domain match the owning store). **Recommend one R2 bucket per supported jurisdiction**, repeating the jurisdiction in the `wrangler` binding configuration as #2283 requires. Resolve the bucket only from the authoritative jurisdiction; no global fallback. Content-addressed deduplication and garbage collection are local to a bucket. A hash key is not proof that bytes exist or match: verify content on transfer. + +For the shared directory, the alternatives are a single minimal directory at one explicitly configured location, or separate directories per jurisdiction. **Recommend the single minimal directory for this issue**, because #2283 specifically asks to document it as one residency exception and it keeps account-to-store routing singular. Its fixed location must be explicitly configured and verified, not guessed from a deployment name. The trade-off is that routing metadata for every jurisdiction is stored at that one location. If policy cannot accept that exception, block affected signup/migration and revisit per-jurisdiction directory topology; do not quietly broaden the exception. + +The directory may contain a pseudonymous/hashed subject key, public keys, public server records, and the minimum routing/migration fields required to find and move a store. A hash is pseudonymization, not anonymization. It must not contain graph/journal content, blob bytes, private profile content, or the older SSO spec's email, tier, and metering fields under this design. State the shared directory's fixed jurisdiction and this exception in deployment and privacy documentation. This does not claim that request processing, logs, KV caches, backups, shared worlds, or federation are jurisdiction-confined; #2284/#2285 address adjacent gaps. + +### 4. How to move an account + +| Option | Trade-off | +| --- | --- | +| Edit the directory row or run a one-off copy/delete script. | Cannot fence stale writers or make retries safe; a crash can leave two active stores or lose writes. Not acceptable. | +| Online dual-write during copy. | Avoids maintenance but requires ordering, idempotency, and conflict semantics across every mutation, alarm, WebSocket, and bridge path; no such hosted write contract is established here. | +| First-class pending state, write fence, snapshot/copy, verification, atomic route switch, then cleanup. | Requires a maintenance window and more state, but gives one active authority and resumable recovery. | + +**Recommend the fenced state machine** required by #2283. The directory's pending state alone is not a write fence: the source object must reject stale writes at commit and acknowledge a durable freeze before export. The directory CAS to the verified target is the switch's linearization point. Source remains frozen afterward; recovery after target writes is a forward repair or a new reverse migration, never an unfreeze or blind pointer rollback. + +## Proposed contract and invariants + +### Hosted account and routing record + +Create the hosted account/routing record atomically at signup, before any object lookup or creation. Its jurisdiction starts at the policy value `us`. Duplicate signup returns the existing mapping; it never overwrites jurisdiction. Ordinary profile updates cannot change jurisdiction. Only the migration state machine may change it, using compare-and-swap against the current jurisdiction, migration ID, phase, and routing epoch. + +The minimum record is conceptually: + +| Field | Meaning | +| --- | --- | +| `subject_key` | Pseudonymous/hashed key for the authenticated provider subject; never use email as identity. | +| `account_id` | Opaque internal account identity if the hosted registry needs one; never substitute the native Ed25519 account ID without an explicit binding. | +| `jurisdiction` | Current serving jurisdiction, set before object identity is derived. | +| `jurisdiction_pending` | Nullable target while a migration is underway. | +| `migration_id`, `migration_phase` | Idempotent resumable operation identity and state. | +| `routing_epoch` | Monotonically increasing fence against stale routes and callers. | +| Public-key/public-server rows | Only the public directory records allowed by #2283; no graph content. | + +Legacy or unrestricted objects are inventoried and handled through an explicit reviewed migration. Never relabel an unknown object as `us`, auto-create an empty replacement after a routing error, or treat absence of jurisdiction as the policy default. + +### Required routing seam + +The conceptual interface is: + +```ts +userObjectId(sub: Subject, jurisdiction: Jurisdiction): DurableObjectId +userStore(env: Env, sub: Subject, jurisdiction: Jurisdiction): UserStoreStub +``` + +These names are proposed contracts, not existing APIs. Both parameters are required at compile time and validated at runtime. `userObjectId` derives the ID from the restricted namespace; `userStore` returns a stub from that same namespace. Do not export the raw namespace to request handlers. A missing/unsupported value, missing binding, or mismatch is a hard failure, not a fallback. The hosted `sub` identity is distinct from `pkgs/id`'s local key-derived account ID. + +### Fail-closed object assertion + +Every identity-touching hosted entry point—fetch, RPC, WebSocket connect/message/close, initialization, import/export, admin operation, alarm, and background work—must assert before reading or mutating identity data, writing, scheduling, or producing an external effect: + +1. `ctx.id.jurisdiction` is defined and supported. +2. It equals the expected jurisdiction from trusted routing context and the object's persisted identity/jurisdiction. +3. The trusted context is associated with the authenticated account and current routing epoch; it is not client supplied. + +The guard reports a safe failure and an operational signal without disclosing account data. Arbitrary reads must not initialize a second empty store. Identity-free health paths must not touch user state. + +Both `undefined` cases in #2283 are fail-closed: (a) an unrestricted namespace does not provide the jurisdiction assertion, and (b) an alarm created before 2026-03-15 may run with `ctx.id.jurisdiction === undefined`. Such an alarm performs no account read/write or reschedule based on the missing value. A separately authorized request may repair an old alarm only after proving that the object is already the correct restricted object and obtaining the authoritative route; otherwise quarantine it. Never infer `us` from an undefined alarm context. + +### R2 and shared directory + +Bind one R2 bucket per supported jurisdiction and repeat the jurisdiction on each `wrangler` binding as the issue requires. Validate deployed resource names, binding jurisdiction, and account support in the provisioning canary. Blob writes, reads, dedupe, and GC use only the bucket for the authoritative active jurisdiction. Migration transfer is an explicit source-to-target operation. Never delete a shared source blob merely because one account migrated; GC requires a jurisdiction-local reachability proof across all accounts, in-flight writes, migrations, and retention roots. + +The D1 directory is one explicitly configured fixed-location control plane for all hosted accounts. Document the location and the single shared-directory exception. Allowlist its schema to the pseudonymous subject mapping, public keys/public server records, and minimum routing/migration metadata. Tests reject graph/journal/blob content and prohibited private fields. If the exact D1 placement or the exception is not acceptable under deployment policy, fail closed rather than claiming per-user residency that the architecture does not provide. + +### Migration state and write fence + +The user-visible state sequence is: + +```text +stable(source, epoch E) + → jurisdiction_pending(target, migration M) + → export frozen source + → create restricted target + → import + → verify + → atomic directory switch(target, epoch E+2) + → delete source after retention +``` + +Persist intermediate phases and checkpoints under `M`; acquire a per-account lease/fencing token; make steps idempotent and resumable. Before export, route the account into retryable maintenance, fence mutations at the source's durable commit point (including existing WebSockets, RPCs, alarms, bridges, and background jobs), drain in-flight work, and wait for an acknowledged durable freeze watermark. The target is import-only and non-serving until the directory switch and activation. A stale stub must not bypass the source fence. If any mutation path cannot be fenced, migration is blocked. + +The source remains authoritative until a verified target is switched by compare-and-swap. On ambiguous results, reread authoritative state and resume from its recorded phase. Before switch, abort by discarding/quarantining the target and unfreezing the source only after a new-epoch CAS confirms it is still authoritative. After switch, never unfreeze the source: repair forward or perform a new fenced reverse migration that includes writes accepted by the target. + +## Single-account runbook sketch (`us` → `eu`) + +This is a controlled migration, not a user-facing control. Run it only after both jurisdictions, bindings, transfer policy, credentials, capacity, and schema compatibility have passed #2285/#3403. If any precondition is unknown, stop before creating a target. + +1. **Preflight and fence.** Authenticate the operator and account. Verify the current row and source object; ensure the target ID is absent or belongs to this same migration (never overwrite unrelated data). Create migration ID `M`, record source/target/epoch and preflight evidence, then CAS to pending. Enter maintenance, fence and drain all writers, and record the source's durable freeze watermark. +2. **Export.** Export a consistent snapshot at that watermark: graph, complete journal, schema version, public keys, signed bytes, and a manifest of every reachable blob's key/hash/size. Preserve signed bytes exactly—verify them later, do not re-sign. Record a manifest digest and counts in the checkpoint; keep the export in approved protected storage. +3. **Create and import.** Copy every manifest blob into the target jurisdiction bucket through the approved transfer path; verify destination bytes/hash and size even if a content key already existed. Create the target through the target restricted namespace and initialize it only for migration `M`. Import idempotently from the manifest. A partial target remains non-serving; a retry with a different manifest for `M` is rejected. +4. **Verify.** Independently read the target and compare manifest digest, graph/journal counts and canonical contents, schema version, all referenced blob bytes/hashes/sizes, and signature verification against the same public keys. Confirm target identity/jurisdiction and that the frozen source has no writes after its watermark. Any discrepancy leaves source frozen and authoritative; repair, retry, or explicitly abort. +5. **Switch and activate.** CAS the directory from `(source, pending target, M, verified, E+1)` to `(target, M, switched, E+2)`. This is the single routing linearization point. Keep source fenced. Activate target only after it confirms the authoritative row; if the process crashes after CAS, resume activation from durable state. Invalidate routing caches and reconnect sessions/bridges using account identity, not a cached DO ID. Verify target reads and writes and unchanged signature bytes. +6. **Retain and clean up.** Keep the frozen source for the defined recovery period and audit target read-back. Then run an idempotent fenced source-DO deletion and confirm completion. Do not delete source R2 blobs as part of this account migration; other users may still reference them. Retire the migration record only after required retention. Physical backup/PITR erasure is separate from logical deletion and must not be implied. + +Before switch, an abort can return to the source with a new epoch after discarding/quarantining target state. After switch, if target writes were accepted, recovery is a forward repair or a new reverse migration, never a pointer flip. A timeout around the switch means reread the directory, not guess. + +## Failure modes and implementation acceptance + +| Failure mode | Required behavior / acceptance | +| --- | --- | +| Jurisdiction absent, invalid, unsupported, or not provisioned | Signup/routing is rejected before ID derivation or store creation; no default-to-US, global, or alternate-jurisdiction fallback. | +| ID derivation drops jurisdiction | Tests prove the required two-argument routing module is the only route and that the unrestricted namespace cannot be reached from handlers; no silent second/empty store. | +| Restricted binding/ID mismatch | The binding rejects it; a test proves the error propagates without using another namespace. | +| `ctx.id.jurisdiction` undefined on unrestricted object or pre-2026-03-15 alarm | Guard fails closed before side effects; alarm is repaired only through the proven restricted-object path or quarantined. | +| Stale route, in-flight write, WebSocket, alarm, bridge, or background job races with migration | Every commit checks durable fence and epoch; migration cannot export/switch until source freeze acknowledgement. | +| Partial export/copy/import, corruption, duplicate worker, or crash | Checkpoints are resumable/idempotent; blob bytes and signed data are independently verified; source remains authoritative before CAS. | +| Switch commits but activation/response times out | Reread D1 and resume activation; source stays fenced; no unsafe rollback. | +| Shared blob deleted or directory leaks graph/private fields | Per-jurisdiction reachability-safe GC only; D1 schema allowlist and tests reject graph/journal/blob and prohibited private fields. | +| Unsupported account feature or unverified residency assumption | Deployment gate blocks production enablement and residency claims; mocks/emulators do not count as account proof. | + +Implementation acceptance must cover all seven #2283 requirements: (1) policy jurisdiction persisted before DO creation and immutable except migration; (2) one no-default `userObjectId(sub, jurisdiction)` route; (3) restricted namespace selected from stored jurisdiction; (4) fail-closed `ctx.id.jurisdiction` assertion on every identity-touching entry, including both undefined cases; (5) separate jurisdiction-bound R2 and local dedupe; (6) minimal fixed-location D1 exception documented; and (7) first-class pending/export/create/import/verify/switch/delete migration with unchanged signatures. The one-account runbook above must be exercised in staging before production migration. + +Tests should include required-argument/type and runtime validation; raw-binding bypass checks; cross-jurisdiction ID separation; table-driven guards for every entry point and both undefined cases; directory uniqueness/immutability/CAS/epoch transitions; per-bucket dedupe isolation; D1 schema allowlist; and fault/concurrency injection at each migration checkpoint. Integration tests cover snapshot and signature preservation, missing/corrupt blobs, safe shared-blob retention, abort before switch, ambiguous CAS, crash recovery after switch, activation, and reverse migration after target writes. A deployed canary in the actual Cloudflare account must verify restricted namespace behavior, `ctx.id.jurisdiction`, legacy alarm behavior, and matching jurisdiction-bound R2 bindings; local Rust tests and DO-shaped mocks cannot establish those facts. + +## Phased implementation plan + +Each phase is a separately mergeable follow-on. Keep production signup/migration disabled until the capability gate passes; later phases can merge behind that gate. + +| Phase | Follow-on | Goal and dependency | Done check | +| --- | --- | --- | --- | +| 0. Capability gate | [#3403](https://github.com/developing-today/code/issues/3403), informed by [#2285](https://github.com/developing-today/code/issues/2285) | Verify actual-account DO/R2 behavior and configuration; fail closed for missing/unsupported jurisdiction. No vendor residency claim is inferred from the mechanics PoC. | Account canary verifies restricted `us`/target namespace, jurisdiction assertion, mismatch rejection, and matching R2 read/write; config tests show signup cannot enable if any prerequisite is absent. | +| 1. Authoritative record | [#3399](https://github.com/developing-today/code/issues/3399) | Add hosted directory/signup policy, unique pseudonymous subject mapping, immutable jurisdiction, routing epoch, migration metadata, and legacy inventory. Depends on the deployment gate contract. | Duplicate signup preserves the original row; missing/invalid jurisdiction rejects; ordinary profile writes cannot change it; transaction/CAS tests pass. | +| 2. Restricted router and guards | [#3400](https://github.com/developing-today/code/issues/3400) | Encapsulate ID derivation and raw binding; select restricted namespace and guard all identity entry points/alarms. Depends on phase 1 and the hosted DO interface. | No subject-only overload or unrestricted handler access; mismatch and both undefined cases fail before side effects; all entry-point tests pass. | +| 3. Data placement | [#3401](https://github.com/developing-today/code/issues/3401) | Bind jurisdiction-local R2, keep dedupe/GC local, enforce shared D1 allowlist and document its fixed-location exception. Depends on phase 0 provisioning and phases 1–2 routing. | Config and tests reject missing/mismatched bucket; cross-bucket isolation works; directory tests reject graph/private content; disclosure names the actual directory location and limitations. | +| 4. Migration control plane | [#3404](https://github.com/developing-today/code/issues/3404) | Persist migration phases, lease/fencing token, CAS/epochs, maintenance, source freeze/drain, and target activation. Depends on the authoritative record, router, storage contracts, and actual write/bridge/WebSocket paths. | Fault/concurrency tests prove no switch without source freeze, target cannot serve early, stale writers are fenced, and ambiguous CAS resumes safely. | +| 5. Transfer, verify, cleanup | [#3402](https://github.com/developing-today/code/issues/3402) | Implement versioned export/import, blob manifest/copy, byte/signature verification, resumability, retention, source deletion, and separate safe GC. Depends on phase 4. | Staging exercises the single-account runbook; interruption/corruption/abort/recovery tests pass; signed bytes survive unchanged and shared blobs are not prematurely deleted. | + +The follow-ons already exist; this design creates none and does not change #2284 or #2285. Resolve/reconcile the older hosted SSO spec's `binding_id`, blob-dedupe, and registry-field conflict before the hosted adapter is implemented, using this issue and the latest #3406 proposal as the decision direction. + +## Questions for Drew + +**None required to proceed with this design.** The issue already chooses the policy-default `us`, no region UI, and a minimal shared-directory exception. The `sub`/`binding_id` conflict is resolved for this issue by #2283's explicit function contract and the newer Nov 1 proposal; the SSO document reconciliation is called out above rather than used to stall the record. Actual account support and vendor residency confirmation are external prerequisites tracked by #2285/#3403, not assumptions to approve here.