@getcirrus/space-conformance 0.0.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/base-CGsQgOwR.d.ts +472 -0
- package/dist/base-CGsQgOwR.d.ts.map +1 -0
- package/dist/cli.js +26 -18
- package/dist/cli.js.map +1 -1
- package/dist/coverage-cK1NBo-P.js +2250 -0
- package/dist/coverage-cK1NBo-P.js.map +1 -0
- package/dist/descriptors-BUCV_BuG.js +4428 -0
- package/dist/descriptors-BUCV_BuG.js.map +1 -0
- package/dist/full-CKsHg6ox.js +852 -0
- package/dist/full-CKsHg6ox.js.map +1 -0
- package/dist/full.d.ts +44 -17
- package/dist/full.d.ts.map +1 -1
- package/dist/full.js +3 -3
- package/dist/index.d.ts +90 -28
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +115 -93
- package/dist/index.js.map +1 -1
- package/lexicons/MANIFEST.json +4 -4
- package/lexicons/managedspace/checkAccess.json +44 -0
- package/lexicons/managedspace/policy.json +22 -0
- package/lexicons/memberspace/defs.json +22 -0
- package/lexicons/{simplespace → memberspace}/listMembers.json +15 -17
- package/lexicons/memberspace/member.json +23 -0
- package/lexicons/memberspace/policy.json +40 -0
- package/lexicons/memberspace/putMembers.json +43 -0
- package/lexicons/memberspace/removeMembers.json +43 -0
- package/lexicons/personalspace/policy.json +11 -0
- package/lexicons/space/applyWrites.json +6 -11
- package/lexicons/space/authorizeSpaceSync.json +109 -0
- package/lexicons/space/clearRecords.json +34 -0
- package/lexicons/space/confirmRegistration.json +44 -0
- package/lexicons/space/createRecord.json +7 -14
- package/lexicons/space/createSpace.json +58 -0
- package/lexicons/space/defs.json +61 -16
- package/lexicons/space/deleteRecord.json +5 -9
- package/lexicons/space/deleteSpace.json +31 -0
- package/lexicons/space/exportSpaceMeta.json +31 -0
- package/lexicons/space/getBlob.json +4 -7
- package/lexicons/space/getDelegationToken.json +3 -5
- package/lexicons/space/getLatestCommit.json +8 -7
- package/lexicons/space/getRecord.json +9 -9
- package/lexicons/space/getRepo.json +8 -11
- package/lexicons/space/getSpace.json +43 -0
- package/lexicons/space/importRepo.json +27 -0
- package/lexicons/space/importSpaceMeta.json +25 -0
- package/lexicons/space/listBlobs.json +3 -10
- package/lexicons/space/listRecords.json +10 -16
- package/lexicons/space/listRepoOps.json +23 -23
- package/lexicons/space/listSpaces.json +30 -14
- package/lexicons/space/listWriters.json +66 -0
- package/lexicons/space/notifyCredentialsRevoked.json +30 -0
- package/lexicons/space/notifyRepoUpdate.json +44 -0
- package/lexicons/space/notifySpaceUpdate.json +53 -0
- package/lexicons/space/policy.json +26 -0
- package/lexicons/space/putRecord.json +7 -14
- package/lexicons/space/removeWriter.json +35 -0
- package/lexicons/space/updateSpace.json +43 -0
- package/package.json +11 -11
- package/dist/base-D8a-ZK57.d.ts +0 -249
- package/dist/base-D8a-ZK57.d.ts.map +0 -1
- package/dist/coverage-DhJZu8P8.js +0 -1914
- package/dist/coverage-DhJZu8P8.js.map +0 -1
- package/dist/full-D4ufJLcw.js +0 -409
- package/dist/full-D4ufJLcw.js.map +0 -1
- package/dist/operator-BErXCDow.js +0 -923
- package/dist/operator-BErXCDow.js.map +0 -1
- package/lexicons/simplespace/addMember.json +0 -37
- package/lexicons/simplespace/checkUserAccess.json +0 -43
- package/lexicons/simplespace/createSpace.json +0 -74
- package/lexicons/simplespace/defs.json +0 -47
- package/lexicons/simplespace/deleteSpace.json +0 -32
- package/lexicons/simplespace/getSpace.json +0 -53
- package/lexicons/simplespace/removeMember.json +0 -37
- package/lexicons/simplespace/updateSpace.json +0 -57
- package/lexicons/space/getSpaceCredential.json +0 -67
- package/lexicons/space/listRepos.json +0 -75
- package/lexicons/space/notifySpaceDeleted.json +0 -24
- package/lexicons/space/notifyWrite.json +0 -38
- package/lexicons/space/registerNotify.json +0 -49
- package/lexicons/space/unregisterNotify.json +0 -29
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"descriptors-BUCV_BuG.js","names":["runnable: Check[]","skipped: FilteredCatalog[\"skipped\"]","json: unknown","error: string | undefined","json","body: number[]","P","values: Record<string, string>","MAC_COVERED_HEADER: Record<MacProfile, string>","doc","MAC_PROFILES: Record<string, MacProfile>","sigHeaders: Record<string, string>","keyShare: string | undefined","sharedSecret: Uint8Array | undefined","macProfile: MacProfile | undefined","response: Response","evidence: Record<string, string>","misses: string[]","problems: string[]","baseChecks: Check[]","L","C","P","op","created: string | undefined","seen: Array<{\n\t\t\t\tspace: string;\n\t\t\t\trepoRev?: string;\n\t\t\t\tdata?: unknown;\n\t\t\t\tspaceRev?: string;\n\t\t\t}>","cursor: string | undefined","problems: string[]","create","spaceChecks: Check[]","L","P","C","ACCOUNT_REFUSALS","misses: string[]","problems: string[]","refusals: Array<[string, { endpoint: string; token: string }]>","variants: Array<[string, CredentialCallOptions[\"signature\"]]>","variants: Array<[string, Omit<CredentialCallOptions, \"params\">]>","listWriters","reads: Array<[string, Record<string, string>]>","probes: Array<\n\t\t\t\t[string, Record<string, string>, (k: string) => string]\n\t\t\t>","credentialChecks: Check[]","L","P","problems: string[]","hostChecks: Check[]","L","C","P","misses: string[]","attempts: Array<[string, string, Record<string, unknown>]>","accepted: string[]","misanswered: string[]","recordChecks: Check[]","operatorChecks: Check[]","deliveries: InboxDelivery[]","body: unknown","response: Response","cryptoCheckDescriptors: CheckDescriptor[]"],"sources":["../src/model.ts","../src/registry.ts","../src/http.ts","../src/encoding.ts","../src/space-auth.ts","../src/did.ts","../src/checks/probe.ts","../src/checks/base.ts","../src/checks/space.ts","../src/checks/credential.ts","../src/checks/host.ts","../src/checks/records.ts","../src/checks/operator.ts","../src/inbox.ts","../src/descriptors.ts"],"sourcesContent":["/**\n * The check model.\n *\n * A check is a black-box probe of a live spaces implementation: an async\n * function over a transport, plus machine-readable metadata that says what\n * it tests, on whose authority, and what it needs from the harness.\n *\n * Tiers, and why they matter: a conformance suite that fails\n * implementations on its author's opinions poisons its own authority.\n * Every `must` check cites specified behavior — a lexicon shape, a\n * declared error name, a requirement in the proposal or the upstream PDS\n * design spec. `should` checks encode reference-implementation behavior\n * the spec leaves open, and are calibrated by running this suite against\n * the reference: a `should` the reference fails is stale by definition.\n * `info` checks report implementation choices and never fail anyone.\n */\n\nexport type Tier = \"must\" | \"should\" | \"info\";\n\n/** Where a check's claim comes from. Every `must` check needs at least one. */\nexport interface Citation {\n\t/**\n\t * - `lexicon`: a vendored lexicon (machine-checked by the coverage\n\t * generator).\n\t * - `proposal` / `pds-design-spec`: the upstream prose specs.\n\t * - `changeset`: an upstream changeset (`.changeset/<name>.md` on the\n\t * alpha branch). For alpha protocol mechanics no lexicon can express —\n\t * the credential HTTP signature, the MAC exchange, key discovery — the\n\t * changeset is the alpha's only normative prose, so it is a citable\n\t * source for a `must`.\n\t * - `reference`: what the reference implementation happens to do. Fine\n\t * for a `should`; never enough on its own for a `must`.\n\t */\n\tsource:\n\t\t| \"lexicon\"\n\t\t| \"proposal\"\n\t\t| \"pds-design-spec\"\n\t\t| \"changeset\"\n\t\t| \"reference\";\n\t/**\n\t * Locator within the source: a lexicon id (optionally `#def` or\n\t * `@error:Name`), a proposal section anchor, a design-spec heading or a\n\t * changeset name. Lexicon locators are machine-checked by the coverage\n\t * generator.\n\t */\n\tref: string;\n}\n\n/**\n * What the harness must supply for a check to run. A runner skips (and\n * reports as \"not testable\") any check whose needs it cannot meet.\n *\n * - `operator`: an authenticated session on the target (any full-access\n * scheme; how it was obtained is the harness's business).\n * - `oauth-session`: specifically an OAuth-granted session with `space:`\n * scopes — only harnesses that can drive the target's consent flow.\n * - `identities`: harness-controlled DIDs with resolvable documents and\n * held keys, for playing reader/writer roles.\n * - `syncer-inbox`: an endpoint the harness serves that the target can\n * reach — registered as a syncer's `notify` endpoint, and named (through\n * a resolvable `did#serviceId`) as a `managedspace` managing app.\n * - `pds-blobs`: the target is a full PDS implementing\n * `com.atproto.repo.uploadBlob` and `com.atproto.sync.getBlob` — needed\n * to prove a space blob is not served publicly. A standalone space host,\n * or an isolated space-routes fixture, does not provide it.\n * - `pds-delegation`: the target implements\n * `com.atproto.space.getDelegationToken`, so the operator can obtain a\n * credential for its own non-public space (the self-flow) with no\n * harness-held reader key. A space-routes fixture does not provide it.\n * - `alpha-libs`: the transport can execute the alpha crypto libraries\n * (`@atproto/space`), whose bundle pulls node-only dependencies. Real\n * checks never declare it — importing the full entry implies it — but\n * the browser catalog's metadata stubs do, so a browser harness (which\n * never declares it) reports them \"not testable here\" instead of\n * running a stub.\n */\nexport type Capability =\n\t| \"operator\"\n\t| \"oauth-session\"\n\t| \"identities\"\n\t| \"syncer-inbox\"\n\t| \"pds-blobs\"\n\t| \"pds-delegation\"\n\t| \"alpha-libs\";\n\nexport type CheckStatus =\n\t| \"pass\"\n\t| \"fail\"\n\t| \"skipped\" // capability not available, or filtered out\n\t| \"error\"; // the check itself broke; distinct from a failing target\n\nexport interface CheckResult {\n\tid: string;\n\ttier: Tier;\n\tstatus: CheckStatus;\n\t/** One line: what was observed, or why skipped/errored. */\n\tdetail: string;\n\tcitations: Citation[];\n\t/** Optional request/response evidence for the report. */\n\tevidence?: unknown;\n\tdurationMs?: number;\n}\n\n/**\n * An identity the harness controls: a DID the target can resolve, plus the\n * key behind its `#atproto` verification method. The harness signs as this\n * party — delegation tokens as a reader, service auth as a writer's PDS,\n * credentials and revocations as a foreign space authority.\n */\nexport interface HarnessIdentity {\n\tdid: string;\n\t/** Sign bytes with the identity's `#atproto` key (ES256K/ES256), compact. */\n\tsign(bytes: Uint8Array): Promise<Uint8Array>;\n\t/** JWT `alg` for {@link sign}. */\n\tjwtAlg: string;\n}\n\nexport interface IdentityProvider {\n\t/** Mint (or reuse) a harness identity by role label. */\n\tidentity(role: string): Promise<HarnessIdentity>;\n}\n\n/**\n * A syncer endpoint the harness serves: the `notify` target of\n * `authorizeSpaceSync`, which the space host calls back with\n * `com.atproto.space.confirmRegistration` and `notifySpaceUpdate`. The\n * same endpoint doubles as a `managedspace` managing app answering\n * `com.atproto.managedspace.checkAccess`.\n *\n * `createSyncerInbox()` implements all of this over a fetch-style handler;\n * a harness only has to route requests for `endpoint` to it.\n */\nexport interface SyncerInbox {\n\t/** The base URL registered as `notify.endpoint` (`{endpoint}/xrpc/...`). */\n\tendpoint: string;\n\t/**\n\t * A `did#serviceId` reference whose DID document routes that service to\n\t * `endpoint`, for naming the inbox as a managing app. The target sends\n\t * service auth addressed to it.\n\t */\n\tservice: string;\n\t/**\n\t * Issue a fresh notify token for `space`. The inbox confirms a\n\t * registration (echoes the challenge) and accepts notifications only for\n\t * tokens it issued for that space; anything else is refused with 400.\n\t */\n\tissueToken(space: string): string;\n\t/** Wait for a delivery matching the predicate, or time out (null). */\n\twaitFor(\n\t\tpredicate: (delivery: InboxDelivery) => boolean,\n\t\ttimeoutMs: number,\n\t): Promise<InboxDelivery | null>;\n\t/**\n\t * Answer queries for `lxm` (e.g. `com.atproto.managedspace.checkAccess`)\n\t * with the handler's JSON body; pass undefined to stop answering. Queries\n\t * are recorded as deliveries either way.\n\t */\n\trespond(\n\t\tlxm: string,\n\t\thandler: ((delivery: InboxDelivery) => unknown) | undefined,\n\t): void;\n\t/**\n\t * The client_id of an OAuth client the inbox publishes:\n\t * `{endpoint}/client-metadata.json`, a client-metadata document (served\n\t * by the inbox) whose `jwks` holds one ES256 key — what a space host\n\t * fetches to verify a client attestation.\n\t */\n\tclientId: string;\n\t/**\n\t * Mint a client attestation for {@link clientId} addressed to `aud`\n\t * (`spaceHostAud(authority)`), signed by the published key: typ\n\t * `atproto-client-attestation+jwt`, iss = sub = client_id, a fresh jti,\n\t * 60 seconds of life.\n\t */\n\tattest(aud: string): Promise<string>;\n}\n\nexport interface InboxDelivery {\n\tlxm: string;\n\t/** Parsed JSON body of a procedure. */\n\tbody: unknown;\n\t/** Query parameters of a query. */\n\tparams?: Record<string, string>;\n\tauthorization?: string;\n\t/** The HTTP status the inbox answered with. */\n\tstatus: number;\n\treceivedAt: number;\n}\n\n/** Description of the implementation under test. */\nexport interface Target {\n\t/** Public origin, e.g. https://pds.example.com */\n\torigin: string;\n\t/** The DID whose repos / spaces the target serves. */\n\tdid: string;\n\t/** Free-form implementation label for the report (\"cirrus\", \"reference\"). */\n\timplementation?: string;\n\t/**\n\t * The PLC directory did:plc identities resolve against (the target's own\n\t * and the repos it reads). Defaults to https://plc.directory.\n\t */\n\tplcDirectory?: string;\n}\n\nexport interface CheckContext {\n\ttarget: Target;\n\tfetch: typeof fetch;\n\t/**\n\t * Present when the harness has an authenticated session on the target.\n\t * Provide `authorize` when auth is plain header injection (a bearer\n\t * token), or `fetch` when each request must be individually signed — an\n\t * OAuth session's DPoP proof depends on the method and URL, so it cannot\n\t * be expressed as headers alone. At least one is required;\n\t * `fetch` wins when both are present.\n\t */\n\toperator?: {\n\t\t/** Add auth to a request (header injection). */\n\t\tauthorize?(init: RequestInit & { headers: Headers }): Promise<void>;\n\t\t/** A fetch that carries the operator's credentials on every request. */\n\t\tfetch?: typeof fetch;\n\t\t/** True when this session came from an OAuth grant with space: scopes. */\n\t\toauth: boolean;\n\t};\n\tidentities?: IdentityProvider;\n\tsyncerInbox?: SyncerInbox;\n\t/**\n\t * Resolve a DID document. Optional: by default the suite fetches did:web\n\t * documents from their host and did:plc documents from\n\t * `target.plcDirectory`, over `fetch`. An in-process fixture with its own\n\t * resolution supplies this instead.\n\t */\n\tresolveDid?(did: string): Promise<unknown>;\n\t/**\n\t * Scratch space shared across checks in one run — e.g. the probe space\n\t * a setup check created, reused by later checks. Keys are namespaced by\n\t * convention (`\"probe.space.uri\"`).\n\t */\n\tstate: Map<string, unknown>;\n\t/** Structured logging into the run report. */\n\tlog(message: string): void;\n}\n\nexport interface Check {\n\tid: string;\n\ttitle: string;\n\ttier: Tier;\n\tcitations: Citation[];\n\tneeds: Capability[];\n\t/**\n\t * Capabilities the check exercises when the harness supplies them but\n\t * does not need: without one it still runs, and its detail says which\n\t * side of the behaviour it could not check (e.g. a refusal whose success\n\t * path needs a syncer inbox). Never a substitute for `needs` when the\n\t * check proves nothing without the capability.\n\t */\n\tuses?: Capability[];\n\t/** Creates or deletes state on the target (probe spaces, records). */\n\tdestructive?: boolean;\n\t/** Depends on real time passing (expiry windows); excluded by default. */\n\tslow?: boolean;\n\t/** Overrides the runner's per-check timeout (for slow checks). */\n\ttimeoutMs?: number;\n\trun(ctx: CheckContext): Promise<CheckOutcome>;\n}\n\n/** What a check's run() returns; the runner wraps it into a CheckResult. */\nexport interface CheckOutcome {\n\tstatus: \"pass\" | \"fail\";\n\tdetail: string;\n\tevidence?: unknown;\n}\n\nexport const pass = (detail: string, evidence?: unknown): CheckOutcome => ({\n\tstatus: \"pass\",\n\tdetail,\n\t...(evidence !== undefined ? { evidence } : {}),\n});\n\nexport const fail = (detail: string, evidence?: unknown): CheckOutcome => ({\n\tstatus: \"fail\",\n\tdetail,\n\t...(evidence !== undefined ? { evidence } : {}),\n});\n","/**\n * The check registry: catalog definition, validation and filtering.\n */\n\nimport type { Capability, Check, Tier } from \"./model.js\";\n\n/**\n * Define a check, enforcing the catalog's structural rules at\n * registration time rather than in review:\n *\n * - ids are `area.slug`, unique within a catalog;\n * - a `must` check carries at least one citation to specified behavior —\n * without one it is someone's opinion and belongs in `should` or `info`.\n */\nexport function defineCheck(check: Check): Check {\n\tif (!/^[a-z0-9-]+\\.[a-z0-9-]+$/.test(check.id)) {\n\t\tthrow new Error(`Check id must be \"area.slug\" (kebab-case): ${check.id}`);\n\t}\n\tif (check.tier === \"must\" && check.citations.length === 0) {\n\t\tthrow new Error(\n\t\t\t`Check ${check.id} is tier \"must\" but cites nothing. Cite the lexicon, proposal or design spec — or demote it.`,\n\t\t);\n\t}\n\treturn check;\n}\n\nexport interface CatalogFilter {\n\ttiers?: Tier[];\n\t/** Capabilities the harness can provide. */\n\tcapabilities?: Capability[];\n\t/** Include checks that create/delete state on the target. */\n\tdestructive?: boolean;\n\t/** Include checks that wait out real expiry windows. */\n\tslow?: boolean;\n\t/** Restrict to areas (the part of the id before the dot). */\n\tareas?: string[];\n\tids?: string[];\n}\n\nexport interface FilteredCatalog {\n\trunnable: Check[];\n\t/** Checks excluded with the reason, for honest reporting. */\n\tskipped: Array<{ check: Check; reason: string }>;\n}\n\nexport function buildCatalog(checks: Check[]): Check[] {\n\tconst seen = new Set<string>();\n\tfor (const check of checks) {\n\t\tif (seen.has(check.id)) {\n\t\t\tthrow new Error(`Duplicate check id: ${check.id}`);\n\t\t}\n\t\tseen.add(check.id);\n\t}\n\treturn checks;\n}\n\n/**\n * Partition a catalog into runnable and skipped for a given harness. A\n * skipped check is part of the report — \"not testable here\" must never\n * silently read as \"conformant\".\n */\nexport function filterCatalog(\n\tcatalog: Check[],\n\tfilter: CatalogFilter,\n): FilteredCatalog {\n\tconst capabilities = new Set(filter.capabilities ?? []);\n\tconst runnable: Check[] = [];\n\tconst skipped: FilteredCatalog[\"skipped\"] = [];\n\n\t// Treat empty scoping arrays as \"unset\". An empty ids/areas/tiers list\n\t// otherwise matches nothing and yields a run of zero checks that reads\n\t// as clean — the exact silent-pass this suite must never produce.\n\tconst ids = filter.ids?.length ? filter.ids : undefined;\n\tconst areas = filter.areas?.length ? filter.areas : undefined;\n\tconst tiers = filter.tiers?.length ? filter.tiers : undefined;\n\n\tfor (const check of catalog) {\n\t\tif (ids && !ids.includes(check.id)) continue;\n\t\tconst area = check.id.split(\".\")[0]!;\n\t\tif (areas && !areas.includes(area)) continue;\n\t\tif (tiers && !tiers.includes(check.tier)) {\n\t\t\tskipped.push({ check, reason: `tier ${check.tier} excluded` });\n\t\t\tcontinue;\n\t\t}\n\t\tif (check.destructive && !filter.destructive) {\n\t\t\tskipped.push({ check, reason: \"destructive checks not enabled\" });\n\t\t\tcontinue;\n\t\t}\n\t\tif (check.slow && !filter.slow) {\n\t\t\tskipped.push({ check, reason: \"slow checks not enabled\" });\n\t\t\tcontinue;\n\t\t}\n\t\tconst missing = check.needs.filter((need) => !capabilities.has(need));\n\t\tif (missing.length > 0) {\n\t\t\tskipped.push({\n\t\t\t\tcheck,\n\t\t\t\treason: `missing capabilities: ${missing.join(\", \")}`,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\trunnable.push(check);\n\t}\n\treturn { runnable, skipped };\n}\n","/**\n * Small HTTP helpers shared by checks. Every check talks to the target\n * over `ctx.fetch`, so a target is anything with a `fetch` — an in-process\n * Hono app, a live origin, or a mock.\n */\n\nimport type { CheckContext } from \"./model.js\";\n\nexport function xrpcUrl(\n\torigin: string,\n\tnsid: string,\n\tparams?: Record<string, string | undefined>,\n): string {\n\tconst url = new URL(`${origin}/xrpc/${nsid}`);\n\tfor (const [key, value] of Object.entries(params ?? {})) {\n\t\tif (value !== undefined) url.searchParams.set(key, value);\n\t}\n\treturn url.toString();\n}\n\nexport interface XrpcResult {\n\tstatus: number;\n\t/** Parsed JSON body, or undefined for non-JSON responses. */\n\tjson?: unknown;\n\t/** The atproto `error` name, when the body carries one. */\n\terror?: string;\n\theaders: Headers;\n\tresponse: Response;\n}\n\nexport async function toResult(response: Response): Promise<XrpcResult> {\n\tconst contentType = response.headers.get(\"Content-Type\") ?? \"\";\n\tlet json: unknown;\n\tlet error: string | undefined;\n\tif (contentType.includes(\"application/json\")) {\n\t\tjson = await response\n\t\t\t.clone()\n\t\t\t.json()\n\t\t\t.catch(() => undefined);\n\t\tif (json && typeof json === \"object\" && \"error\" in json) {\n\t\t\terror = String((json as { error: unknown }).error);\n\t\t}\n\t}\n\treturn {\n\t\tstatus: response.status,\n\t\tjson,\n\t\terror,\n\t\theaders: response.headers,\n\t\tresponse,\n\t};\n}\n\n/** GET an XRPC query. `headers` may carry auth. */\nexport async function xrpcGet(\n\tctx: CheckContext,\n\tnsid: string,\n\tparams?: Record<string, string | undefined>,\n\theaders?: HeadersInit,\n): Promise<XrpcResult> {\n\tconst response = await ctx.fetch(xrpcUrl(ctx.target.origin, nsid, params), {\n\t\tmethod: \"GET\",\n\t\theaders,\n\t});\n\treturn toResult(response);\n}\n\n/** POST an XRPC procedure with a JSON body. */\nexport async function xrpcPost(\n\tctx: CheckContext,\n\tnsid: string,\n\tbody: unknown,\n\theaders?: HeadersInit,\n): Promise<XrpcResult> {\n\tconst merged = new Headers(headers);\n\tmerged.set(\"Content-Type\", \"application/json\");\n\tconst response = await ctx.fetch(xrpcUrl(ctx.target.origin, nsid), {\n\t\tmethod: \"POST\",\n\t\theaders: merged,\n\t\tbody: JSON.stringify(body),\n\t});\n\treturn toResult(response);\n}\n\n/** Add the operator's auth to a headers object, if a session is present. */\nexport async function operatorHeaders(\n\tctx: CheckContext,\n\textra?: HeadersInit,\n): Promise<Headers> {\n\tconst headers = new Headers(extra);\n\tif (ctx.operator?.authorize) {\n\t\tawait ctx.operator.authorize({ headers });\n\t}\n\treturn headers;\n}\n\n/**\n * A fetch that carries the operator's credentials: the operator's own\n * signing fetch when it has one (an OAuth session's DPoP proof must sign\n * each request individually), otherwise the transport fetch with\n * `authorize`-injected headers. With no operator at all it falls back to\n * the plain transport — the runner skips operator-needing checks then, so\n * that path is only reached by checks that can also run anonymously.\n */\nexport function operatorFetch(ctx: CheckContext): typeof fetch {\n\tconst operator = ctx.operator;\n\tif (!operator) return ctx.fetch;\n\tif (operator.fetch) return operator.fetch;\n\tconst baseFetch = ctx.fetch;\n\treturn async (input, init) => {\n\t\tconst headers = new Headers(init?.headers);\n\t\tawait operator.authorize?.({ ...init, headers });\n\t\treturn baseFetch(input, { ...init, headers });\n\t};\n}\n\n/**\n * The same context with the operator's credentials on `fetch`, so a check\n * can write `xrpcGet(asOperator(ctx), …)` for authenticated calls while\n * keeping the bare `ctx` for requests that must stay anonymous.\n */\nexport function asOperator(ctx: CheckContext): CheckContext {\n\treturn { ...ctx, fetch: operatorFetch(ctx) };\n}\n\n/** POST raw bytes (an archive upload) to an XRPC procedure. */\nexport async function xrpcPostBytes(\n\tctx: CheckContext,\n\tnsid: string,\n\tbytes: Uint8Array,\n\theaders?: HeadersInit,\n\tcontentType = \"application/vnd.dasl.star\",\n): Promise<XrpcResult> {\n\tconst merged = new Headers(headers);\n\tmerged.set(\"Content-Type\", contentType);\n\tconst response = await ctx.fetch(xrpcUrl(ctx.target.origin, nsid), {\n\t\tmethod: \"POST\",\n\t\theaders: merged,\n\t\tbody: bytes as BodyInit,\n\t});\n\treturn toResult(response);\n}\n","/**\n * Dependency-free byte encodings shared by the browser-safe helpers:\n * base64 (padded, unpadded and url-safe), base58btc for did:key, base32\n * for CIDs, and a few byte utilities. Kept here so the browser catalog\n * never pulls a multiformats or noble dependency for a dozen lines of code.\n */\n\nexport const utf8 = (s: string): Uint8Array => new TextEncoder().encode(s);\n\nexport function concatBytes(parts: Uint8Array[]): Uint8Array {\n\tconst out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));\n\tlet offset = 0;\n\tfor (const part of parts) {\n\t\tout.set(part, offset);\n\t\toffset += part.length;\n\t}\n\treturn out;\n}\n\nexport function bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n\treturn a.length === b.length && a.every((byte, i) => byte === b[i]);\n}\n\nexport function toBase64(bytes: Uint8Array): string {\n\tlet bin = \"\";\n\tfor (const b of bytes) bin += String.fromCharCode(b);\n\treturn btoa(bin);\n}\n\nexport const toBase64Url = (bytes: Uint8Array): string =>\n\ttoBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n\n/** Decode base64 or base64url, padded or not. */\nfunction fromBase64(input: string): Uint8Array {\n\tlet s = input.replace(/-/g, \"+\").replace(/_/g, \"/\").replace(/=+$/, \"\");\n\ts = s.padEnd(Math.ceil(s.length / 4) * 4, \"=\");\n\tconst bin = atob(s);\n\tconst out = new Uint8Array(bin.length);\n\tfor (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n\treturn out;\n}\n\nconst B58 = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n\nexport function toBase58(bytes: Uint8Array): string {\n\tlet zeros = 0;\n\twhile (zeros < bytes.length && bytes[zeros] === 0) zeros++;\n\tlet n = 0n;\n\tfor (const b of bytes) n = n * 256n + BigInt(b);\n\tlet out = \"\";\n\twhile (n > 0n) {\n\t\tout = B58[Number(n % 58n)] + out;\n\t\tn /= 58n;\n\t}\n\treturn \"1\".repeat(zeros) + out;\n}\n\nexport function fromBase58(input: string): Uint8Array {\n\tlet zeros = 0;\n\twhile (zeros < input.length && input[zeros] === \"1\") zeros++;\n\tlet n = 0n;\n\tfor (const ch of input) {\n\t\tconst value = B58.indexOf(ch);\n\t\tif (value < 0) throw new Error(`invalid base58 character: ${ch}`);\n\t\tn = n * 58n + BigInt(value);\n\t}\n\tconst body: number[] = [];\n\twhile (n > 0n) {\n\t\tbody.unshift(Number(n % 256n));\n\t\tn /= 256n;\n\t}\n\treturn new Uint8Array([...new Array<number>(zeros).fill(0), ...body]);\n}\n\nconst B32 = \"abcdefghijklmnopqrstuvwxyz234567\";\n\nexport function toBase32(bytes: Uint8Array): string {\n\tlet out = \"\";\n\tlet bits = 0;\n\tlet value = 0;\n\tfor (const byte of bytes) {\n\t\tvalue = (value << 8) | byte;\n\t\tbits += 8;\n\t\twhile (bits >= 5) {\n\t\t\tout += B32[(value >>> (bits - 5)) & 31];\n\t\t\tbits -= 5;\n\t\t}\n\t}\n\tif (bits > 0) out += B32[(value << (5 - bits)) & 31];\n\treturn out;\n}\n\n/** A CIDv1 (raw codec, sha2-256) for some bytes — a well-formed blob CID. */\nexport async function rawCid(bytes: Uint8Array): Promise<string> {\n\tconst digest = new Uint8Array(\n\t\tawait crypto.subtle.digest(\"SHA-256\", bytes as BufferSource),\n\t);\n\t// version 1, codec raw (0x55), multihash sha2-256 (0x12) of 32 bytes\n\treturn `b${toBase32(concatBytes([new Uint8Array([0x01, 0x55, 0x12, 0x20]), digest]))}`;\n}\n\nexport async function sha256(bytes: Uint8Array): Promise<Uint8Array> {\n\treturn new Uint8Array(\n\t\tawait crypto.subtle.digest(\"SHA-256\", bytes as BufferSource),\n\t);\n}\n\n/** Decode a compact JWT's header and payload without verifying it. */\nexport function decodeJwt(jwt: string): {\n\theader: Record<string, unknown>;\n\tpayload: Record<string, unknown>;\n} {\n\tconst parts = jwt.split(\".\");\n\tif (parts.length !== 3) throw new Error(\"not a compact JWT\");\n\tconst decode = (part: string) =>\n\t\tJSON.parse(new TextDecoder().decode(fromBase64(part))) as Record<\n\t\t\tstring,\n\t\t\tunknown\n\t\t>;\n\treturn { header: decode(parts[0]!), payload: decode(parts[1]!) };\n}\n\n/** `$bytes` JSON wire form → bytes, or undefined if it isn't one. */\nexport function lexBytes(value: unknown): Uint8Array | undefined {\n\tif (\n\t\tvalue &&\n\t\ttypeof value === \"object\" &&\n\t\ttypeof (value as { $bytes?: unknown }).$bytes === \"string\"\n\t) {\n\t\treturn fromBase64((value as { $bytes: string }).$bytes);\n\t}\n\treturn undefined;\n}\n\nconst TID_CHARS = \"234567abcdefghijklmnopqrstuvwxyz\";\nconst TID_RE = /^[234567abcdefghij][234567abcdefghijklmnopqrstuvwxyz]{12}$/;\n\nexport const isTid = (value: unknown): value is string =>\n\ttypeof value === \"string\" && TID_RE.test(value);\n\n/** A TID for a given time in microseconds since the epoch (clock id 0). */\nexport function tidAt(micros: bigint): string {\n\tlet n = (micros << 10n) & 0x7fffffffffffffffn;\n\tlet out = \"\";\n\tfor (let i = 0; i < 13; i++) {\n\t\tout = TID_CHARS[Number(n & 31n)] + out;\n\t\tn >>= 5n;\n\t}\n\treturn out;\n}\n\nexport const tidNow = (): string => tidAt(BigInt(Date.now()) * 1000n);\n","/**\n * Browser-safe space credential presentation: P-256 did:key credential\n * keys, the `atproto-space-credential` HTTP message signature, and the\n * MAC request (`Accept-Signature`, keyed by an HPKE-exported secret) a\n * syncer sends with every credentialed read of a commit or record.\n *\n * Deliberately dependency-free (WebCrypto and BigInt only) so the checks\n * that present a credential — the operator's own credential flow, the MAC\n * and signature refusals — run in a browser bundle too. Every format here\n * mirrors `@atproto/space` byte for byte (`createSpaceSigHeaders`,\n * `encapsulate`, `formatMacRequest`); the full test suite cross-checks\n * each against the reference library, so a drift fails CI rather than\n * every run against a real host.\n *\n * Verifying a MAC (rather than requesting one) needs the reference\n * library's commit and record encodings, so it lives behind the full\n * entry.\n */\n\nimport {\n\tconcatBytes,\n\tfromBase58,\n\ttoBase58,\n\ttoBase64,\n\ttoBase64Url,\n\tutf8,\n} from \"./encoding.js\";\n\n// --- P-256 points ------------------------------------------------------\n\nconst P = 2n ** 256n - 2n ** 224n + 2n ** 192n + 2n ** 96n - 1n;\nconst B = 0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604bn;\nconst N = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n;\n\nconst P256_MULTICODEC = new Uint8Array([0x80, 0x24]); // p256-pub, varint\nconst K256_MULTICODEC = new Uint8Array([0xe7, 0x01]); // secp256k1-pub, varint\n\nfunction bytesToBigInt(bytes: Uint8Array): bigint {\n\tlet n = 0n;\n\tfor (const b of bytes) n = (n << 8n) | BigInt(b);\n\treturn n;\n}\n\nfunction bigIntToBytes(n: bigint, length: number): Uint8Array {\n\tconst out = new Uint8Array(length);\n\tfor (let i = length - 1; i >= 0; i--) {\n\t\tout[i] = Number(n & 0xffn);\n\t\tn >>= 8n;\n\t}\n\treturn out;\n}\n\nfunction modPow(base: bigint, exp: bigint, mod: bigint): bigint {\n\tlet result = 1n;\n\tbase %= mod;\n\twhile (exp > 0n) {\n\t\tif (exp & 1n) result = (result * base) % mod;\n\t\tbase = (base * base) % mod;\n\t\texp >>= 1n;\n\t}\n\treturn result;\n}\n\n/** 0x04 || x || y → 0x02/0x03 || x. Curve-agnostic (secp256k1 too). */\nexport function compressP256(uncompressed: Uint8Array): Uint8Array {\n\tif (uncompressed.length !== 65 || uncompressed[0] !== 0x04) {\n\t\tthrow new Error(\"expected an uncompressed EC point\");\n\t}\n\tconst prefix = (uncompressed[64]! & 1) === 1 ? 0x03 : 0x02;\n\treturn concatBytes([new Uint8Array([prefix]), uncompressed.subarray(1, 33)]);\n}\n\n/** 0x02/0x03 || x → 0x04 || x || y. */\nexport function decompressP256(compressed: Uint8Array): Uint8Array {\n\tif (\n\t\tcompressed.length !== 33 ||\n\t\t(compressed[0] !== 2 && compressed[0] !== 3)\n\t) {\n\t\tthrow new Error(\"expected a compressed P-256 point\");\n\t}\n\tconst x = bytesToBigInt(compressed.subarray(1));\n\tconst rhs = (((x * x * x - 3n * x + B) % P) + P) % P;\n\t// P ≡ 3 (mod 4), so the square root is rhs^((P+1)/4).\n\tlet y = modPow(rhs, (P + 1n) / 4n, P);\n\tif ((y * y) % P !== rhs) throw new Error(\"point is not on P-256\");\n\tif ((y & 1n) !== BigInt(compressed[0]! & 1)) y = P - y;\n\treturn concatBytes([\n\t\tnew Uint8Array([0x04]),\n\t\tbigIntToBytes(x, 32),\n\t\tbigIntToBytes(y, 32),\n\t]);\n}\n\nexport type DidKeyAlg = \"ES256\" | \"ES256K\";\n\n/** Format a did:key from a public key (compressed or, for P-256, not). */\nexport function formatDidKey(alg: DidKeyAlg, keyBytes: Uint8Array): string {\n\tif (alg === \"ES256\") {\n\t\tconst compressed =\n\t\t\tkeyBytes.length === 65 ? compressP256(keyBytes) : keyBytes;\n\t\treturn `did:key:z${toBase58(concatBytes([P256_MULTICODEC, compressed]))}`;\n\t}\n\tif (keyBytes.length !== 33) {\n\t\tthrow new Error(\"secp256k1 keys must be given compressed\");\n\t}\n\treturn `did:key:z${toBase58(concatBytes([K256_MULTICODEC, keyBytes]))}`;\n}\n\n/** Parse a did:key, returning its algorithm and compressed key bytes. */\nfunction parseDidKey(didKey: string): {\n\talg: DidKeyAlg;\n\tcompressed: Uint8Array;\n} {\n\tif (!didKey.startsWith(\"did:key:z\")) throw new Error(\"not a did:key\");\n\tconst bytes = fromBase58(didKey.slice(\"did:key:z\".length));\n\tif (bytes[0] === 0x80 && bytes[1] === 0x24) {\n\t\treturn { alg: \"ES256\", compressed: bytes.subarray(2) };\n\t}\n\tif (bytes[0] === 0xe7 && bytes[1] === 0x01) {\n\t\treturn { alg: \"ES256K\", compressed: bytes.subarray(2) };\n\t}\n\tthrow new Error(\"unsupported did:key type\");\n}\n\nexport function isP256DidKey(value: unknown): boolean {\n\ttry {\n\t\treturn typeof value === \"string\" && parseDidKey(value).alg === \"ES256\";\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n// --- credential keys ---------------------------------------------------\n\n/**\n * A P-256 key a space credential is bound to (its `cnf.kid`). Each request\n * presenting the credential is signed by it. Transport-owned: any fresh\n * key will do, so it is never tied to a harness identity.\n */\nexport interface CredentialKey {\n\t/** The key as a P-256 did:key — what `credentialKid` carries. */\n\tdid: string;\n\t/** Sign with ECDSA P-256/SHA-256, returning a 64-byte compact signature. */\n\tsign(bytes: Uint8Array): Promise<Uint8Array>;\n}\n\nexport async function createCredentialKey(): Promise<CredentialKey> {\n\tconst pair = await crypto.subtle.generateKey(\n\t\t{ name: \"ECDSA\", namedCurve: \"P-256\" },\n\t\ttrue,\n\t\t[\"sign\"],\n\t);\n\tconst raw = new Uint8Array(\n\t\tawait crypto.subtle.exportKey(\"raw\", pair.publicKey),\n\t);\n\treturn {\n\t\tdid: formatDidKey(\"ES256\", raw),\n\t\tasync sign(bytes) {\n\t\t\tconst sig = new Uint8Array(\n\t\t\t\tawait crypto.subtle.sign(\n\t\t\t\t\t{ name: \"ECDSA\", hash: \"SHA-256\" },\n\t\t\t\t\tpair.privateKey,\n\t\t\t\t\tbytes as BufferSource,\n\t\t\t\t),\n\t\t\t);\n\t\t\t// WebCrypto does not normalise s. Verifiers accept either form, but\n\t\t\t// low-S is the conservative choice for a key every host must accept.\n\t\t\tconst s = bytesToBigInt(sig.subarray(32));\n\t\t\tif (s > N / 2n) sig.set(bigIntToBytes(N - s, 32), 32);\n\t\t\treturn sig;\n\t\t},\n\t};\n}\n\n// --- client attestations ---------------------------------------------------\n\n/** `CLIENT_ATTESTATION_TYP` of `@atproto/space`. */\nexport const CLIENT_ATTESTATION_TYP = \"atproto-client-attestation+jwt\";\n\n/**\n * How a space authority is addressed as the space host — the audience of\n * delegation tokens and client attestations (`spaceHostAud` of\n * `@atproto/space`).\n */\nexport const spaceHostAud = (authority: string): string =>\n\t`${authority}#atproto_pds`;\n\n/**\n * A client attestation as `@atproto/space`'s `buildClientAttestation`\n * shapes it — typ `atproto-client-attestation+jwt`, the signing key's\n * `kid`, iss = sub = client_id, aud, iat, exp and a fresh jti — signed ES256\n * by `sign` (a 64-byte compact signature).\n */\nexport async function signClientAttestation(opts: {\n\tclientId: string;\n\taud: string;\n\tkid: string;\n\tsign(bytes: Uint8Array): Promise<Uint8Array>;\n\texpiresInSec?: number;\n}): Promise<string> {\n\tconst iat = Math.floor(Date.now() / 1000);\n\tconst part = (obj: unknown) => toBase64Url(utf8(JSON.stringify(obj)));\n\tconst input = `${part({ alg: \"ES256\", typ: CLIENT_ATTESTATION_TYP, kid: opts.kid })}.${part(\n\t\t{\n\t\t\tiss: opts.clientId,\n\t\t\tsub: opts.clientId,\n\t\t\taud: opts.aud,\n\t\t\tiat,\n\t\t\texp: iat + (opts.expiresInSec ?? 60),\n\t\t\tjti: toBase64Url(crypto.getRandomValues(new Uint8Array(16))),\n\t\t},\n\t)}`;\n\treturn `${input}.${toBase64Url(await opts.sign(utf8(input)))}`;\n}\n\n// --- HTTP message signature --------------------------------------------\n\nexport const SPACE_CREDENTIAL_SCHEME = \"Atproto-Space-Credential\";\nconst CREDENTIAL_SIG_TAG = \"atproto-space-credential\";\nconst CREDENTIAL_COMPONENTS = [\"authorization\", \"atproto-space-audience\"];\n\n/** Serialise RFC 9651 parameters: strings quoted, integers bare. */\nfunction serializeParams(params: Array<[string, string | number]>): string {\n\treturn params\n\t\t.map(([k, v]) => `;${k}=${typeof v === \"number\" ? v : `\"${v}\"`}`)\n\t\t.join(\"\");\n}\n\nexport interface CredentialSigOptions {\n\tauthorization: string;\n\taudience: string;\n\t/** The signature's label. Hosts find it by tag, so any label works; default `sig`. */\n\tlabel?: string;\n\t/** Parameters after `tag` (e.g. `keyid`, `alg`, `created`), in order. */\n\tparams?: Array<[string, string | number]>;\n\t/** Covered components; defaults to exactly the two the protocol requires. */\n\tcomponents?: string[];\n\t/** Replace the tag (probing hosts that must ignore other tags). */\n\ttag?: string;\n}\n\n/** One signature's `Signature-Input` and `Signature` dictionary members. */\nexport async function credentialSigMembers(\n\tkey: Pick<CredentialKey, \"sign\">,\n\topts: CredentialSigOptions,\n): Promise<{ input: string; signature: string }> {\n\tconst components = opts.components ?? CREDENTIAL_COMPONENTS;\n\tconst label = opts.label ?? \"sig\";\n\tconst signatureParams = `(${components.map((c) => `\"${c}\"`).join(\" \")})${serializeParams(\n\t\t[[\"tag\", opts.tag ?? CREDENTIAL_SIG_TAG], ...(opts.params ?? [])],\n\t)}`;\n\tconst values: Record<string, string> = {\n\t\tauthorization: opts.authorization,\n\t\t\"atproto-space-audience\": opts.audience,\n\t};\n\tconst base = [\n\t\t...components.map((c) => `\"${c}\": ${(values[c] ?? \"\").trim()}`),\n\t\t`\"@signature-params\": ${signatureParams}`,\n\t].join(\"\\n\");\n\tconst signature = await key.sign(utf8(base));\n\treturn {\n\t\tinput: `${label}=${signatureParams}`,\n\t\t// RFC 9651 byte sequences are padded base64.\n\t\tsignature: `${label}=:${toBase64(signature)}:`,\n\t};\n}\n\n/**\n * The headers that present a space credential: the `Authorization` scheme,\n * the audience DID (the service being called — the repo DID at a repo\n * host, the authority DID at the space host) and an RFC 9421 signature by\n * the credential's key covering exactly those two fields, tagged\n * `atproto-space-credential`.\n */\nexport async function spaceSigHeaders(\n\tkey: Pick<CredentialKey, \"sign\">,\n\topts: CredentialSigOptions,\n): Promise<Record<string, string>> {\n\tconst { input, signature } = await credentialSigMembers(key, opts);\n\treturn {\n\t\tauthorization: opts.authorization,\n\t\t\"atproto-space-audience\": opts.audience,\n\t\t\"signature-input\": input,\n\t\tsignature,\n\t};\n}\n\n// --- KEM / MAC request -------------------------------------------------\n\nexport const COMMIT_MAC_PROFILE = \"atproto-space-commit\";\nexport const RECORD_MAC_PROFILE = \"atproto-space-record\";\nexport type MacProfile = typeof COMMIT_MAC_PROFILE | typeof RECORD_MAC_PROFILE;\n\n/** The response header each profile's MAC covers. */\nexport const MAC_COVERED_HEADER: Record<MacProfile, string> = {\n\t[COMMIT_MAC_PROFILE]: \"atproto-space-commit\",\n\t[RECORD_MAC_PROFILE]: \"atproto-space-record\",\n};\n\n/**\n * One `Accept-Signature` member asking for a MAC under `profile`, keyed by\n * the shared secret for `keyShare`:\n * `mac=(\"atproto-space-commit\";sf);keyid=\"did:key:…\";tag=\"atproto-space-commit\"`.\n */\nexport function formatMacRequest(\n\tprofile: MacProfile,\n\tkeyShare: string,\n\topts: { label?: string; params?: Array<[string, string | number]> } = {},\n): string {\n\treturn `${opts.label ?? \"mac\"}=(\"${MAC_COVERED_HEADER[profile]}\";sf)${serializeParams(\n\t\t[[\"keyid\", keyShare], [\"tag\", profile], ...(opts.params ?? [])],\n\t)}`;\n}\n\nconst uint16be = (n: number) => new Uint8Array([n >>> 8, n & 0xff]);\nconst HPKE_VERSION = utf8(\"HPKE-v1\");\nconst KEM_ID = concatBytes([utf8(\"KEM\"), uint16be(0x0010)]);\nconst SUITE_ID = concatBytes([\n\tutf8(\"HPKE\"),\n\tuint16be(0x0010), // DHKEM(P-256, HKDF-SHA256)\n\tuint16be(0x0001), // HKDF-SHA256\n\tuint16be(0xffff), // Export-only AEAD\n]);\nconst EMPTY = new Uint8Array(0);\n\nasync function hmac(key: Uint8Array, data: Uint8Array): Promise<Uint8Array> {\n\t// An empty HMAC key is equivalent to a block of zeros (RFC 2104), and\n\t// WebCrypto refuses zero-length keys.\n\tconst k = await crypto.subtle.importKey(\n\t\t\"raw\",\n\t\t(key.length ? key : new Uint8Array(32)) as BufferSource,\n\t\t{ name: \"HMAC\", hash: \"SHA-256\" },\n\t\tfalse,\n\t\t[\"sign\"],\n\t);\n\treturn new Uint8Array(\n\t\tawait crypto.subtle.sign(\"HMAC\", k, data as BufferSource),\n\t);\n}\n\nconst labeledExtract = (\n\tid: Uint8Array,\n\tsalt: Uint8Array,\n\tlabel: string,\n\tikm: Uint8Array,\n) => hmac(salt, concatBytes([HPKE_VERSION, id, utf8(label), ikm]));\n\n// HKDF-Expand for L = 32: a single block.\nconst labeledExpand = (\n\tid: Uint8Array,\n\tprk: Uint8Array,\n\tlabel: string,\n\tinfo: Uint8Array,\n) =>\n\thmac(\n\t\tprk,\n\t\tconcatBytes([\n\t\t\tuint16be(32),\n\t\t\tHPKE_VERSION,\n\t\t\tid,\n\t\t\tutf8(label),\n\t\t\tinfo,\n\t\t\tnew Uint8Array([1]),\n\t\t]),\n\t);\n\n/**\n * Syncer side of the space KEM: HPKE secret export (RFC 9180 §6.2) in base\n * mode with DHKEM(P-256, HKDF-SHA256), HKDF-SHA256 and the Export-only\n * AEAD, `info = \"atproto-mac\"`, an empty exporter context and L = 32 —\n * spelled out as the ECDH and HKDF steps it performs. The returned\n * `keyShare` is HPKE's `enc`, as a compressed did:key. Use once per request.\n */\nexport async function encapsulate(\n\tauthorKemDidKey: string,\n): Promise<{ keyShare: string; sharedSecret: Uint8Array }> {\n\tconst parsed = parseDidKey(authorKemDidKey);\n\tif (parsed.alg !== \"ES256\") throw new Error(\"KEM key must be P-256\");\n\tconst authorBytes = decompressP256(parsed.compressed);\n\tconst authorKey = await crypto.subtle.importKey(\n\t\t\"raw\",\n\t\tauthorBytes as BufferSource,\n\t\t{ name: \"ECDH\", namedCurve: \"P-256\" },\n\t\tfalse,\n\t\t[],\n\t);\n\tconst ephemeral = await crypto.subtle.generateKey(\n\t\t{ name: \"ECDH\", namedCurve: \"P-256\" },\n\t\ttrue,\n\t\t[\"deriveBits\"],\n\t);\n\tconst enc = new Uint8Array(\n\t\tawait crypto.subtle.exportKey(\"raw\", ephemeral.publicKey),\n\t);\n\tconst dh = new Uint8Array(\n\t\tawait crypto.subtle.deriveBits(\n\t\t\t{ name: \"ECDH\", public: authorKey },\n\t\t\tephemeral.privateKey,\n\t\t\t256,\n\t\t),\n\t);\n\tconst eaePrk = await labeledExtract(KEM_ID, EMPTY, \"eae_prk\", dh);\n\tconst kemSecret = await labeledExpand(\n\t\tKEM_ID,\n\t\teaePrk,\n\t\t\"shared_secret\",\n\t\tconcatBytes([enc, authorBytes]),\n\t);\n\tconst pskIdHash = await labeledExtract(SUITE_ID, EMPTY, \"psk_id_hash\", EMPTY);\n\tconst infoHash = await labeledExtract(\n\t\tSUITE_ID,\n\t\tEMPTY,\n\t\t\"info_hash\",\n\t\tutf8(\"atproto-mac\"),\n\t);\n\tconst context = concatBytes([new Uint8Array([0]), pskIdHash, infoHash]);\n\tconst secret = await labeledExtract(SUITE_ID, kemSecret, \"secret\", EMPTY);\n\tconst exporterSecret = await labeledExpand(SUITE_ID, secret, \"exp\", context);\n\tconst sharedSecret = await labeledExpand(\n\t\tSUITE_ID,\n\t\texporterSecret,\n\t\t\"sec\",\n\t\tEMPTY,\n\t);\n\treturn { keyShare: formatDidKey(\"ES256\", enc), sharedSecret };\n}\n","/**\n * Browser-safe DID resolution, just enough for the suite: fetch a DID\n * document (did:web from its host, did:plc from a PLC directory) and read\n * the keys and service entries the spaces protocol relies on — `#atproto`\n * (signs space tokens), `#atproto_kem` (the repo's KEM key) and\n * `#atproto_pds` (the account's host, which is also its space host).\n *\n * Resolution goes through `ctx.fetch`, so an in-process fixture that\n * serves its own did:web document resolves without a network. A harness\n * with unusual resolution supplies `ctx.resolveDid` instead.\n */\n\nimport type { CheckContext } from \"./model.js\";\nimport { fromBase58 } from \"./encoding.js\";\nimport { compressP256, formatDidKey } from \"./space-auth.js\";\n\nexport const DEFAULT_PLC_DIRECTORY = \"https://plc.directory\";\n\nexport interface DidDocument {\n\tid: string;\n\talsoKnownAs?: string[];\n\tverificationMethod?: Array<{\n\t\tid: string;\n\t\ttype: string;\n\t\tcontroller?: string;\n\t\tpublicKeyMultibase?: string;\n\t}>;\n\tservice?: Array<{ id: string; type: string; serviceEndpoint: unknown }>;\n}\n\n/** The URL a DID document is fetched from, mirroring the reference resolver. */\nexport function didDocumentUrl(did: string, plcDirectory?: string): string {\n\tif (did.startsWith(\"did:web:\")) {\n\t\tconst host = decodeURIComponent(did.slice(\"did:web:\".length));\n\t\tif (host.includes(\":\") && !/^localhost:\\d+$/.test(host)) {\n\t\t\tthrow new Error(`did:web with a path is not supported: ${did}`);\n\t\t}\n\t\tconst scheme = host.split(\":\")[0] === \"localhost\" ? \"http\" : \"https\";\n\t\treturn `${scheme}://${host}/.well-known/did.json`;\n\t}\n\tif (did.startsWith(\"did:plc:\")) {\n\t\treturn `${(plcDirectory ?? DEFAULT_PLC_DIRECTORY).replace(/\\/+$/, \"\")}/${did}`;\n\t}\n\tthrow new Error(`unsupported DID method: ${did}`);\n}\n\nexport async function resolveDidDocument(\n\tctx: Pick<CheckContext, \"fetch\" | \"target\" | \"resolveDid\">,\n\tdid: string,\n): Promise<DidDocument> {\n\tif (ctx.resolveDid) {\n\t\tconst doc = await ctx.resolveDid(did);\n\t\tif (!doc) throw new Error(`could not resolve ${did}`);\n\t\treturn doc as DidDocument;\n\t}\n\tconst url = didDocumentUrl(did, ctx.target.plcDirectory);\n\tconst res = await ctx.fetch(url, {\n\t\theaders: { accept: \"application/did+ld+json,application/json\" },\n\t});\n\tif (!res.ok)\n\t\tthrow new Error(`resolving ${did}: ${url} returned ${res.status}`);\n\tconst doc = (await res.json()) as DidDocument;\n\tif (doc.id !== did) {\n\t\tthrow new Error(`DID document for ${did} names itself ${doc.id}`);\n\t}\n\treturn doc;\n}\n\nconst matchesFragment = (id: string, did: string, fragment: string) =>\n\tid === `#${fragment}` || id === `${did}#${fragment}`;\n\n/**\n * A verification method as a did:key, accepting the `Multikey` form and\n * the legacy 2019 types PLC still emits (raw key bytes, no multicodec).\n */\nexport function verificationMethodDidKey(\n\tdoc: DidDocument,\n\tfragment: string,\n): string | undefined {\n\tconst method = (doc.verificationMethod ?? []).find((m) =>\n\t\tmatchesFragment(m.id, doc.id, fragment),\n\t);\n\tconst multibase = method?.publicKeyMultibase;\n\tif (!method || !multibase?.startsWith(\"z\")) return undefined;\n\ttry {\n\t\tif (method.type === \"Multikey\") {\n\t\t\treturn `did:key:${multibase}`;\n\t\t}\n\t\tconst raw = fromBase58(multibase.slice(1));\n\t\tif (method.type === \"EcdsaSecp256r1VerificationKey2019\") {\n\t\t\treturn formatDidKey(\"ES256\", raw.length === 65 ? compressP256(raw) : raw);\n\t\t}\n\t\tif (method.type === \"EcdsaSecp256k1VerificationKey2019\") {\n\t\t\t// Point compression is curve-agnostic: parity of y, then x.\n\t\t\treturn formatDidKey(\n\t\t\t\t\"ES256K\",\n\t\t\t\traw.length === 65 ? compressP256(raw) : raw,\n\t\t\t);\n\t\t}\n\t} catch {\n\t\treturn undefined;\n\t}\n\treturn undefined;\n}\n\nexport function serviceEndpoint(\n\tdoc: DidDocument,\n\tfragment: string,\n): string | undefined {\n\tconst entry = (doc.service ?? []).find((s) =>\n\t\tmatchesFragment(s.id, doc.id, fragment),\n\t);\n\treturn typeof entry?.serviceEndpoint === \"string\"\n\t\t? entry.serviceEndpoint\n\t\t: undefined;\n}\n\n/**\n * The repo's `#atproto_kem` key, cached per run: every MAC request against\n * a repo needs it, and a run reads the same few repos many times.\n */\nexport async function kemKeyFor(\n\tctx: Pick<CheckContext, \"fetch\" | \"target\" | \"resolveDid\" | \"state\">,\n\tdid: string,\n): Promise<string> {\n\tconst cacheKey = `did.kem.${did}`;\n\tconst cached = ctx.state.get(cacheKey);\n\tif (typeof cached === \"string\") return cached;\n\tconst doc = await resolveDidDocument(ctx, did);\n\tconst kem = verificationMethodDidKey(doc, \"atproto_kem\");\n\tif (!kem) throw new Error(`${did} publishes no #atproto_kem key`);\n\tctx.state.set(cacheKey, kem);\n\treturn kem;\n}\n","/**\n * Browser-safe helpers the checks share: probe spaces, operator writes,\n * obtaining a space credential, and presenting it (HTTP signature plus,\n * where the method returns a commit or record, a MAC request).\n *\n * Everything here needs only `fetch` and WebCrypto, so the operator\n * checks — which include the operator's own credential flow — run in a\n * browser as well as in the CLI and the vitest adapter.\n */\n\nimport {\n\tasOperator,\n\ttoResult,\n\txrpcGet,\n\txrpcPost,\n\txrpcUrl,\n\ttype XrpcResult,\n} from \"../http.js\";\nimport type { CheckContext } from \"../model.js\";\nimport { kemKeyFor } from \"../did.js\";\nimport {\n\tCOMMIT_MAC_PROFILE,\n\tRECORD_MAC_PROFILE,\n\tSPACE_CREDENTIAL_SCHEME,\n\tcreateCredentialKey,\n\tencapsulate,\n\tformatMacRequest,\n\tspaceSigHeaders,\n\ttype CredentialKey,\n\ttype CredentialSigOptions,\n\ttype MacProfile,\n} from \"../space-auth.js\";\n\n// The probe collections and space type are published, resolvable\n// lexicons under the suite's own authority (see ../../probe-lexicons) —\n// so strict, dynamically-resolving targets can validate them, while\n// AppViews ignore them (nothing under earth.cirrus.check.* is app.bsky.*).\nexport const POST = \"earth.cirrus.check.note\";\nexport const note = (text: string) => ({ $type: POST, text });\nexport const PROBE_TYPE = \"earth.cirrus.check.space\";\n\n/**\n * A syntactically valid DID no host serves: the authority of spaces the\n * operator does not own, and the subject of reads of a repo no host holds.\n */\nexport const FOREIGN_DID = \"did:web:space-conformance.invalid\";\n\n// --- policies ----------------------------------------------------------\n\nexport type Policy = { $type: string } & Record<string, unknown>;\n\nexport const personalspace = (): Policy => ({\n\t$type: \"com.atproto.personalspace.policy\",\n});\n\nexport const memberspace = (\n\tconfig: {\n\t\tpublicRead?: boolean;\n\t\tpublicWrite?: boolean;\n\t\tallowedApps?: string[];\n\t\tpublishPolicy?: boolean;\n\t\tpublishMembers?: boolean;\n\t} = {},\n): Policy => ({ $type: \"com.atproto.memberspace.policy\", ...config });\n\nexport const managedspace = (\n\tmanagingApp: string,\n\tconfig: { publishPolicy?: boolean } = {},\n): Policy => ({\n\t$type: \"com.atproto.managedspace.policy\",\n\tmanagingApp,\n\t...config,\n});\n\n/** A public-read memberspace: anyone may obtain a credential, no token needed. */\nexport const publicRead = (): Policy => memberspace({ publicRead: true });\n\n// --- probe spaces ------------------------------------------------------\n\nexport interface ProbeSpace {\n\turi: string;\n\ttype: string;\n\tskey: string;\n}\n\n/** A run-unique skey so probe spaces never collide with real ones. */\nexport function probeSkey(): string {\n\tconst rand = crypto.getRandomValues(new Uint8Array(8));\n\treturn `probe${Array.from(rand, (b) => b.toString(36))\n\t\t.join(\"\")\n\t\t.slice(0, 10)}`;\n}\n\n/**\n * The prefix of every space URI (`SPACE_URI_PREFIX` of `@atproto/syntax`):\n * since the 2026-11-24 alpha a space is `at:space/{spaceDid}/{spaceType}/{skey}`\n * and a record in it appends `/{authorDid}/{collection}/{rkey}`. There is no\n * `at://` form of a space URI.\n */\nconst SPACE_URI_PREFIX = \"at:space/\";\n\n/** The space-ref of a space: `at:space/{did}/{type}/{skey}`. */\nexport const spaceUri = (\n\tdid: string,\n\tskey: string,\n\ttype: string = PROBE_TYPE,\n): string => `${SPACE_URI_PREFIX}${did}/${type}/${skey}`;\n\n/** The URI of a record in a space: the space-ref plus author/collection/rkey. */\nexport const spaceRecordUri = (\n\tspace: string,\n\tauthor: string,\n\tcollection: string,\n\trkey: string,\n): string => `${space}/${author}/${collection}/${rkey}`;\n\n/**\n * The pre-2026-11-24 form, `at://{did}/space/{type}/{skey}` — only for\n * probes that a host must now refuse it in a `space` param.\n */\nexport const legacySpaceUri = (\n\tdid: string,\n\tskey: string,\n\ttype: string = PROBE_TYPE,\n): string => `at://${did}/space/${type}/${skey}`;\n\n/** A space URI under `did` that nobody has created. */\nexport const unknownSpaceUri = (did: string): string =>\n\tspaceUri(did, probeSkey());\n\n/** The authority DID a space URI names: the first segment after the prefix. */\nexport const spaceAuthority = (space: string): string =>\n\t(space.startsWith(SPACE_URI_PREFIX)\n\t\t? space.slice(SPACE_URI_PREFIX.length)\n\t\t: space\n\t).split(\"/\")[0]!;\n\n/**\n * Create a probe space owned by the target's operator. The default policy\n * is a closed memberspace — only the authority can read it.\n */\nexport async function createProbeSpace(\n\tctx: CheckContext,\n\tpolicy: Policy = memberspace(),\n\tskey: string = probeSkey(),\n): Promise<ProbeSpace> {\n\tconst res = await xrpcPost(asOperator(ctx), \"com.atproto.space.createSpace\", {\n\t\tspaceType: PROBE_TYPE,\n\t\tskey,\n\t\tpolicy,\n\t});\n\tif (res.status !== 200) {\n\t\tthrow new Error(\n\t\t\t`createSpace failed: ${res.status} ${res.error ?? \"\"} ${JSON.stringify(res.json)}`,\n\t\t);\n\t}\n\tconst uri = (res.json as { space: string }).space;\n\tif (typeof uri !== \"string\") {\n\t\tthrow new Error(\n\t\t\t`createSpace returned no space: ${JSON.stringify(res.json)}`,\n\t\t);\n\t}\n\treturn { uri, type: PROBE_TYPE, skey };\n}\n\n/** Delete a probe space, best-effort (cleanup). */\nexport async function deleteProbeSpace(\n\tctx: CheckContext,\n\tspace: string,\n): Promise<void> {\n\tawait xrpcPost(asOperator(ctx), \"com.atproto.space.deleteSpace\", {\n\t\tspace,\n\t}).catch(() => {});\n}\n\n/** Operator creates a record in a space; returns the response. */\nexport async function operatorCreateRecord(\n\tctx: CheckContext,\n\tspace: string,\n\tcollection: string,\n\trkey: string,\n\trecord: Record<string, unknown>,\n): Promise<XrpcResult> {\n\treturn xrpcPost(asOperator(ctx), \"com.atproto.space.createRecord\", {\n\t\tspace,\n\t\trepo: ctx.target.did,\n\t\tcollection,\n\t\trkey,\n\t\trecord,\n\t});\n}\n\n/** Operator write that must succeed (setup, not the thing under test). */\nexport async function mustCreateRecord(\n\tctx: CheckContext,\n\tspace: string,\n\trkey: string,\n\ttext = rkey,\n): Promise<{ uri: string; cid: string }> {\n\tconst res = await operatorCreateRecord(ctx, space, POST, rkey, note(text));\n\tif (res.status !== 200) {\n\t\tthrow new Error(\n\t\t\t`setup createRecord failed: ${res.status} ${res.error ?? \"\"}`,\n\t\t);\n\t}\n\treturn res.json as { uri: string; cid: string };\n}\n\n/** Operator's own read of its repo in a space (no MAC needed or asked). */\nexport function operatorGetRecord(\n\tctx: CheckContext,\n\tspace: string,\n\trkey: string,\n\tcollection = POST,\n): Promise<XrpcResult> {\n\treturn xrpcGet(asOperator(ctx), \"com.atproto.space.getRecord\", {\n\t\tspace,\n\t\trepo: ctx.target.did,\n\t\tcollection,\n\t\trkey,\n\t});\n}\n\n// --- credentials -------------------------------------------------------\n\nexport interface Credential {\n\tcredential: string;\n\tkey: CredentialKey;\n\t/** The space it was issued for. */\n\tspace: string;\n}\n\n/**\n * Ask the space's authority to authorise sync. Nothing authenticates the\n * request itself: the body carries the key to bind, and optionally a\n * delegation token (who the user is), a client attestation (which app)\n * and a `notify` registration.\n */\nexport async function requestCredential(\n\tctx: CheckContext,\n\tspace: string,\n\topts: {\n\t\tdelegationToken?: string;\n\t\tclientAttestation?: string;\n\t\tcredentialKey?: string;\n\t\tkey?: CredentialKey;\n\t\tnotify?: { endpoint: string; token: string };\n\t} = {},\n): Promise<{\n\tresult: XrpcResult;\n\tcredential?: Credential;\n\tspaceRev?: string;\n}> {\n\tconst key = opts.key ?? (await createCredentialKey());\n\tconst result = await xrpcPost(ctx, \"com.atproto.space.authorizeSpaceSync\", {\n\t\tspace,\n\t\tcredentialKey: opts.credentialKey ?? key.did,\n\t\t...(opts.delegationToken ? { delegationToken: opts.delegationToken } : {}),\n\t\t...(opts.clientAttestation\n\t\t\t? { clientAttestation: opts.clientAttestation }\n\t\t\t: {}),\n\t\t...(opts.notify ? { notify: opts.notify } : {}),\n\t});\n\tif (result.status === 200) {\n\t\tconst body = result.json as { credential?: unknown; spaceRev?: unknown };\n\t\tif (typeof body.credential === \"string\") {\n\t\t\treturn {\n\t\t\t\tresult,\n\t\t\t\tcredential: { credential: body.credential, key, space },\n\t\t\t\t...(typeof body.spaceRev === \"string\"\n\t\t\t\t\t? { spaceRev: body.spaceRev }\n\t\t\t\t\t: {}),\n\t\t\t};\n\t\t}\n\t}\n\treturn { result };\n}\n\n/** A tokenless credential for a public-read space; throws if refused. */\nexport async function obtainPublicCredential(\n\tctx: CheckContext,\n\tspace: string,\n): Promise<Credential> {\n\tconst { result, credential } = await requestCredential(ctx, space);\n\tif (!credential) {\n\t\tthrow new Error(\n\t\t\t`tokenless authorizeSpaceSync for a public-read space failed: ${result.status} ${result.error ?? \"\"}`,\n\t\t);\n\t}\n\treturn credential;\n}\n\n/**\n * Obtain a credential the way a real app does: ask the target's own\n * `getDelegationToken` (with the operator session) for a delegation token,\n * then exchange it at `authorizeSpaceSync`. It needs no harness-held\n * reader key, so it runs against any real PDS and exercises the target's\n * own token minting.\n */\nexport async function obtainCredentialViaDelegation(\n\tctx: CheckContext,\n\tspace: string,\n): Promise<{\n\tresult: XrpcResult;\n\tcredential?: Credential;\n\tdelegation: XrpcResult;\n}> {\n\tconst delegation = await xrpcGet(\n\t\tasOperator(ctx),\n\t\t\"com.atproto.space.getDelegationToken\",\n\t\t{ space },\n\t);\n\tif (delegation.status !== 200) {\n\t\treturn { result: delegation, delegation };\n\t}\n\tconst token = (delegation.json as { token: string }).token;\n\tconst { result, credential } = await requestCredential(ctx, space, {\n\t\tdelegationToken: token,\n\t});\n\treturn { result, delegation, ...(credential ? { credential } : {}) };\n}\n\n/** Which MAC profile each repo-host read asks for. */\nconst MAC_PROFILES: Record<string, MacProfile> = {\n\t\"com.atproto.space.getLatestCommit\": COMMIT_MAC_PROFILE,\n\t\"com.atproto.space.getRepo\": COMMIT_MAC_PROFILE,\n\t\"com.atproto.space.listRepoOps\": COMMIT_MAC_PROFILE,\n\t\"com.atproto.space.getRecord\": RECORD_MAC_PROFILE,\n};\n\nexport interface CredentialCallOptions {\n\t/** Query params (GET) — or omit and pass `body` for a procedure. */\n\tparams?: Record<string, string | undefined>;\n\tbody?: unknown;\n\t/**\n\t * The audience DID: the service being called. Defaults to the `repo`\n\t * param (a repo-host read), else the space's authority (a space-host\n\t * method).\n\t */\n\taudience?: string;\n\t/**\n\t * The MAC to ask for. Defaults to the profile of what the method returns\n\t * (commit or record) for the four MAC'd reads, nothing otherwise. `false`\n\t * sends no `Accept-Signature`; an object requests the profile with a\n\t * custom label or extra parameters; a function builds the whole header\n\t * from a fresh key share (malformed-request probes).\n\t */\n\tmac?:\n\t\t| MacProfile\n\t\t| false\n\t\t| {\n\t\t\t\tprofile: MacProfile;\n\t\t\t\tlabel?: string;\n\t\t\t\tparams?: Array<[string, string | number]>;\n\t\t }\n\t\t| { header: (keyShare: string) => string; profile: MacProfile };\n\t/** Authorization scheme spelling; defaults to `Atproto-Space-Credential`. */\n\tscheme?: string;\n\t/** Sign with this key instead of the credential's own. */\n\tsignWith?: CredentialKey;\n\t/** Signature label, parameters, components or tag overrides. */\n\tsignature?: Omit<CredentialSigOptions, \"authorization\" | \"audience\">;\n\t/** Replace the signature headers wholesale (e.g. two signatures). */\n\tsignatureHeaders?: (\n\t\tdefaults: Record<string, string>,\n\t) => Promise<Record<string, string>>;\n\t/** Send no signature headers at all. */\n\tunsigned?: boolean;\n}\n\nexport interface CredentialResult extends XrpcResult {\n\t/** The MAC request's encapsulation, when a MAC was requested. */\n\tkeyShare?: string;\n\tsharedSecret?: Uint8Array;\n\tmacProfile?: MacProfile;\n}\n\n/** Present a credential on one request: signature, audience, MAC request. */\nexport async function credentialCall(\n\tctx: CheckContext,\n\tcredential: Credential,\n\tnsid: string,\n\topts: CredentialCallOptions = {},\n): Promise<CredentialResult> {\n\tconst repo = opts.params?.repo;\n\tconst audience = opts.audience ?? repo ?? spaceAuthority(credential.space);\n\tconst authorization = `${opts.scheme ?? SPACE_CREDENTIAL_SCHEME} ${credential.credential}`;\n\tlet sigHeaders: Record<string, string> = opts.unsigned\n\t\t? { authorization }\n\t\t: await spaceSigHeaders(opts.signWith ?? credential.key, {\n\t\t\t\tauthorization,\n\t\t\t\taudience,\n\t\t\t\t...opts.signature,\n\t\t\t});\n\tif (opts.signatureHeaders)\n\t\tsigHeaders = await opts.signatureHeaders(sigHeaders);\n\tconst headers = new Headers(sigHeaders);\n\n\tlet keyShare: string | undefined;\n\tlet sharedSecret: Uint8Array | undefined;\n\tlet macProfile: MacProfile | undefined;\n\tconst mac = opts.mac ?? MAC_PROFILES[nsid];\n\tif (mac) {\n\t\tif (!repo) throw new Error(`${nsid}: a MAC request needs the repo DID`);\n\t\tconst profile = typeof mac === \"string\" ? mac : mac.profile;\n\t\t// A repo nobody hosts has no KEM key to resolve; a fresh P-256 key\n\t\t// stands in, giving a well-formed request the host must refuse anyway.\n\t\tconst kem = await kemKeyFor(ctx, repo).catch(\n\t\t\tasync () => (await createCredentialKey()).did,\n\t\t);\n\t\tconst enc = await encapsulate(kem);\n\t\theaders.set(\n\t\t\t\"accept-signature\",\n\t\t\ttypeof mac === \"object\" && \"header\" in mac\n\t\t\t\t? mac.header(enc.keyShare)\n\t\t\t\t: formatMacRequest(\n\t\t\t\t\t\tprofile,\n\t\t\t\t\t\tenc.keyShare,\n\t\t\t\t\t\ttypeof mac === \"object\" ? mac : {},\n\t\t\t\t\t),\n\t\t);\n\t\tkeyShare = enc.keyShare;\n\t\tsharedSecret = enc.sharedSecret;\n\t\tmacProfile = profile;\n\t}\n\n\tlet response: Response;\n\tif (opts.body !== undefined) {\n\t\theaders.set(\"Content-Type\", \"application/json\");\n\t\tresponse = await ctx.fetch(xrpcUrl(ctx.target.origin, nsid), {\n\t\t\tmethod: \"POST\",\n\t\t\theaders,\n\t\t\tbody: JSON.stringify(opts.body),\n\t\t});\n\t} else {\n\t\tresponse = await ctx.fetch(xrpcUrl(ctx.target.origin, nsid, opts.params), {\n\t\t\tmethod: \"GET\",\n\t\t\theaders,\n\t\t});\n\t}\n\tconst result = await toResult(response);\n\treturn {\n\t\t...result,\n\t\t...(keyShare ? { keyShare } : {}),\n\t\t...(sharedSecret ? { sharedSecret } : {}),\n\t\t...(macProfile ? { macProfile } : {}),\n\t};\n}\n\n/** A credential-authenticated GET with the default audience and MAC request. */\nexport function credentialGet(\n\tctx: CheckContext,\n\tcredential: Credential,\n\tnsid: string,\n\tparams: Record<string, string | undefined>,\n): Promise<CredentialResult> {\n\treturn credentialCall(ctx, credential, nsid, { params });\n}\n\n/** Run named probes and fail with every one that missed, not just the first. */\nexport async function expectEach(\n\tprobes: Array<\n\t\t[string, () => Promise<XrpcResult>, (r: XrpcResult) => boolean]\n\t>,\n): Promise<{ ok: boolean; detail: string; evidence: Record<string, string> }> {\n\tconst evidence: Record<string, string> = {};\n\tconst misses: string[] = [];\n\tfor (const [name, call, accept] of probes) {\n\t\tconst res = await call();\n\t\tevidence[name] = describe(res);\n\t\tif (!accept(res)) misses.push(`${name} → ${describe(res)}`);\n\t}\n\treturn { ok: misses.length === 0, detail: misses.join(\"; \"), evidence };\n}\n\nexport const errorIs =\n\t(...names: string[]) =>\n\t(r: XrpcResult) =>\n\t\tr.error !== undefined && names.includes(r.error);\n\n/** Summarise a response for a detail line. */\nexport const describe = (res: XrpcResult): string =>\n\t`${res.status}${res.error ? ` ${res.error}` : \"\"}`;\n\nconst isAuthRefusal = (res: XrpcResult): boolean =>\n\tres.status === 401 || res.status === 403;\n","/**\n * Browser-safe checks that need no session: discovery and unauthenticated\n * request shapes. They need only `fetch` — no token minting, no\n * @atproto/space — so they run in any transport, including a browser\n * bundle, against any host the user names.\n */\n\nimport { defineCheck } from \"../registry.js\";\nimport { xrpcGet, xrpcPost } from \"../http.js\";\nimport { pass, fail, type Check, type CheckContext } from \"../model.js\";\nimport {\n\tresolveDidDocument,\n\tserviceEndpoint,\n\tverificationMethodDidKey,\n\ttype DidDocument,\n} from \"../did.js\";\nimport { createCredentialKey, isP256DidKey } from \"../space-auth.js\";\nimport { describe, spaceUri, unknownSpaceUri } from \"./probe.js\";\n\nconst changeset = (ref: string) => ({ source: \"changeset\" as const, ref });\nconst lexicon = (ref: string) => ({ source: \"lexicon\" as const, ref });\nconst proposal = (ref: string) => ({ source: \"proposal\" as const, ref });\n\n/** The target's DID document, resolved once per run by its DID method. */\nasync function targetDoc(ctx: CheckContext): Promise<DidDocument> {\n\tconst cached = ctx.state.get(\"did.doc.target\");\n\tif (cached) return cached as DidDocument;\n\tconst doc = await resolveDidDocument(ctx, ctx.target.did);\n\tctx.state.set(\"did.doc.target\", doc);\n\treturn doc;\n}\n\nconst sameOrigin = (a: string, b: string) => {\n\ttry {\n\t\treturn new URL(a).origin === new URL(b).origin;\n\t} catch {\n\t\treturn false;\n\t}\n};\n\nconst discoveryPdsService = defineCheck({\n\tid: \"discovery.pds-service\",\n\ttitle: \"The authority's #atproto_pds service is the space host\",\n\ttier: \"must\",\n\tcitations: [\n\t\tproposal(\"0016#space-authority\"),\n\t\tchangeset(\"plain-keys-resolve\"),\n\t],\n\tneeds: [],\n\tasync run(ctx) {\n\t\t// The alpha dropped #atproto_space_host: a space authority is resolved\n\t\t// like any account, and its PDS is its space host. So the target DID\n\t\t// must route to this origin through #atproto_pds.\n\t\tconst doc = await targetDoc(ctx);\n\t\tconst endpoint = serviceEndpoint(doc, \"atproto_pds\");\n\t\tif (!endpoint) return fail(\"no #atproto_pds service entry\", doc.service);\n\t\treturn sameOrigin(endpoint, ctx.target.origin)\n\t\t\t? pass(`#atproto_pds is ${endpoint}`)\n\t\t\t: fail(\n\t\t\t\t\t`#atproto_pds is ${endpoint}, not the target origin ${ctx.target.origin}`,\n\t\t\t\t\tdoc.service,\n\t\t\t\t);\n\t},\n});\n\nconst discoverySigningKey = defineCheck({\n\tid: \"discovery.signing-key\",\n\ttitle: \"The DID document exposes the #atproto key that signs space tokens\",\n\ttier: \"must\",\n\tcitations: [\n\t\tproposal(\"0016#space-authority\"),\n\t\tchangeset(\"plain-keys-resolve\"),\n\t],\n\tneeds: [],\n\tasync run(ctx) {\n\t\tconst doc = await targetDoc(ctx);\n\t\tconst key = verificationMethodDidKey(doc, \"atproto\");\n\t\treturn key\n\t\t\t? pass(`#atproto is ${key}`)\n\t\t\t: fail(\"no usable #atproto verification method\", doc.verificationMethod);\n\t},\n});\n\nconst discoveryKemKey = defineCheck({\n\tid: \"discovery.kem-key\",\n\ttitle: \"The DID document publishes a P-256 #atproto_kem key\",\n\ttier: \"must\",\n\tcitations: [\n\t\tproposal(\"0016#kem-key\"),\n\t\tlexicon(\"com.atproto.space.getLatestCommit\"),\n\t],\n\tneeds: [],\n\tasync run(ctx) {\n\t\t// A syncer derives each request's MAC secret by ECDH against the\n\t\t// repo's #atproto_kem key. Without it no credentialed read of this\n\t\t// account's repos can be authenticated at all.\n\t\tconst doc = await targetDoc(ctx);\n\t\tconst key = verificationMethodDidKey(doc, \"atproto_kem\");\n\t\tif (!key)\n\t\t\treturn fail(\n\t\t\t\t\"no #atproto_kem verification method\",\n\t\t\t\tdoc.verificationMethod,\n\t\t\t);\n\t\tif (!isP256DidKey(key))\n\t\t\treturn fail(`#atproto_kem is not a P-256 key: ${key}`);\n\t\t// \"The entry MUST have\": id {did}#atproto_kem, controller the DID,\n\t\t// type Multikey.\n\t\tconst entry = (doc.verificationMethod ?? []).find((m) =>\n\t\t\tm.id.endsWith(\"#atproto_kem\"),\n\t\t)!;\n\t\tconst problems: string[] = [];\n\t\tif (entry.type !== \"Multikey\") problems.push(`type ${entry.type}`);\n\t\tif (entry.controller !== doc.id)\n\t\t\tproblems.push(`controller ${entry.controller}`);\n\t\treturn problems.length\n\t\t\t? fail(`#atproto_kem entry: ${problems.join(\", \")}`, entry)\n\t\t\t: pass(`#atproto_kem is ${key}`);\n\t},\n});\n\nconst discoveryLegacyEntries = defineCheck({\n\tid: \"discovery.legacy-space-entries\",\n\ttitle: \"Reports any pre-alpha #atproto_space / #atproto_space_host entries\",\n\ttier: \"info\",\n\tcitations: [changeset(\"plain-keys-resolve\")],\n\tneeds: [],\n\tasync run(ctx) {\n\t\tconst doc = await targetDoc(ctx);\n\t\tconst legacy = [\n\t\t\t...(doc.verificationMethod ?? []).map((m) => m.id),\n\t\t\t...(doc.service ?? []).map((s) => s.id),\n\t\t].filter((id) => /#atproto_space(_host)?$/.test(id));\n\t\treturn pass(\n\t\t\tlegacy.length\n\t\t\t\t? `still publishes ${legacy.join(\", \")} (ignored by the alpha)`\n\t\t\t\t: \"no legacy space entries\",\n\t\t);\n\t},\n});\n\nconst authGetRecordRequiresAuth = defineCheck({\n\tid: \"auth.getrecord-unauthenticated-refused\",\n\ttitle: \"space.getRecord refuses an unauthenticated request\",\n\ttier: \"must\",\n\tcitations: [lexicon(\"com.atproto.space.getRecord\")],\n\tneeds: [],\n\tasync run(ctx) {\n\t\t// A read with no credential and no session must be refused on the\n\t\t// authentication perimeter — a conformant host checks auth before it\n\t\t// checks whether the record exists. Only 401/403 proves that: a 404\n\t\t// would also be returned by a host that serves reads with no auth at\n\t\t// all (there's simply no record at this probe URI to leak), and a 5xx\n\t\t// is a server fault, not a refusal — neither demonstrates enforcement.\n\t\tconst res = await xrpcGet(ctx, \"com.atproto.space.getRecord\", {\n\t\t\tspace: spaceUri(ctx.target.did, \"probe\"),\n\t\t\trepo: ctx.target.did,\n\t\t\tcollection: \"app.bsky.feed.post\",\n\t\t\trkey: \"whatever\",\n\t\t});\n\t\tif (res.status === 401 || res.status === 403) {\n\t\t\treturn pass(`refused with ${res.status}`);\n\t\t}\n\t\treturn fail(\n\t\t\t`unauthenticated read was not refused with 401/403 (got ${describe(res)})`,\n\t\t\tres.json,\n\t\t);\n\t},\n});\n\nconst credentialTokenlessUnknown = defineCheck({\n\tid: \"credential.tokenless-unknown-space\",\n\ttitle:\n\t\t\"A tokenless credential request for an unknown space gets SpaceNotFound\",\n\ttier: \"must\",\n\tcitations: [\n\t\tlexicon(\"com.atproto.space.authorizeSpaceSync@error:SpaceNotFound\"),\n\t],\n\tneeds: [],\n\tasync run(ctx) {\n\t\t// No delegation token, a space nobody created: there is nothing public\n\t\t// to issue for, and the declared answer is SpaceNotFound — the same\n\t\t// answer a non-public space gives, so existence is not disclosed.\n\t\tconst key = await createCredentialKey();\n\t\tconst res = await xrpcPost(ctx, \"com.atproto.space.authorizeSpaceSync\", {\n\t\t\tspace: unknownSpaceUri(ctx.target.did),\n\t\t\tcredentialKey: key.did,\n\t\t});\n\t\tif (res.status === 200)\n\t\t\treturn fail(\"issued a credential for an unknown space\");\n\t\treturn res.error === \"SpaceNotFound\"\n\t\t\t? pass(\"refused with SpaceNotFound\")\n\t\t\t: fail(`refused with ${describe(res)}, expected SpaceNotFound`, res.json);\n\t},\n});\n\n/** Checks that need no crypto and no session — safe in any transport. */\nexport const baseChecks: Check[] = [\n\tdiscoveryPdsService,\n\tdiscoverySigningKey,\n\tdiscoveryKemKey,\n\tdiscoveryLegacyEntries,\n\tauthGetRecordRequiresAuth,\n\tcredentialTokenlessUnknown,\n];\n","/**\n * Space management and the baseline policies: createSpace / updateSpace /\n * deleteSpace / getSpace / listSpaces, and the memberspace member list.\n * Operator-only and browser-safe.\n */\n\nimport { defineCheck } from \"../registry.js\";\nimport { asOperator, xrpcGet, xrpcPost } from \"../http.js\";\nimport { fail, pass, type Check, type CheckContext } from \"../model.js\";\nimport { bytesEqual, isTid, lexBytes, toBase32 } from \"../encoding.js\";\nimport {\n\tFOREIGN_DID,\n\tPROBE_TYPE,\n\tcreateProbeSpace,\n\tcredentialCall,\n\tdeleteProbeSpace,\n\tdescribe,\n\terrorIs,\n\texpectEach,\n\tmanagedspace,\n\tmemberspace,\n\tmustCreateRecord,\n\tobtainPublicCredential,\n\toperatorGetRecord,\n\tpersonalspace,\n\tprobeSkey,\n\tpublicRead,\n\tspaceUri,\n\tunknownSpaceUri,\n\ttype Policy,\n} from \"./probe.js\";\n\nconst L = (ref: string) => ({ source: \"lexicon\" as const, ref });\nconst C = (ref: string) => ({ source: \"changeset\" as const, ref });\nconst P = (ref: string) => ({ source: \"proposal\" as const, ref });\n\n/** A syntactically valid did:plc nobody registered — a member to list. */\nexport function fakeDid(): string {\n\treturn `did:plc:${toBase32(crypto.getRandomValues(new Uint8Array(15))).slice(0, 24)}`;\n}\n\nconst op = asOperator;\n\ntype Member = { did: string; read: boolean; write: boolean };\n\nexport const putMembers = (\n\tctx: CheckContext,\n\tspace: string,\n\tmembers: Member[],\n) =>\n\txrpcPost(op(ctx), \"com.atproto.memberspace.putMembers\", { space, members });\n\nconst removeMembers = (ctx: CheckContext, space: string, dids: string[]) =>\n\txrpcPost(op(ctx), \"com.atproto.memberspace.removeMembers\", { space, dids });\n\nasync function listMembers(\n\tctx: CheckContext,\n\tspace: string,\n): Promise<Member[]> {\n\tconst res = await xrpcGet(op(ctx), \"com.atproto.memberspace.listMembers\", {\n\t\tspace,\n\t\tlimit: \"100\",\n\t});\n\tif (res.status !== 200) throw new Error(`listMembers ${describe(res)}`);\n\treturn (res.json as { members?: Member[] }).members ?? [];\n}\n\n// --- create / get -------------------------------------------------------\n\nconst spaceCreateAndGet = defineCheck({\n\tid: \"space.create-and-get\",\n\ttitle:\n\t\t\"createSpace anchors the space on the operator at an at:space/ ref and getSpace describes it\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.space.createSpace\"),\n\t\tL(\"com.atproto.space.getSpace\"),\n\t\tP(\"0016#addressing\"),\n\t\tC(\"spaces-syntax\"),\n\t\tC(\"pds-space-uri-migration\"),\n\t],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst skey = probeSkey();\n\t\tconst res = await xrpcPost(op(ctx), \"com.atproto.space.createSpace\", {\n\t\t\tspaceType: PROBE_TYPE,\n\t\t\tskey,\n\t\t\tpolicy: memberspace(),\n\t\t});\n\t\tif (res.status !== 200)\n\t\t\treturn fail(`createSpace ${describe(res)}`, res.json);\n\t\tconst uri = (res.json as { space?: string }).space;\n\t\ttry {\n\t\t\t// Since the 2026-11-24 alpha a space is addressed as\n\t\t\t// at:space/{spaceDid}/{spaceType}/{skey}; hosts emit only that form.\n\t\t\tconst expected = spaceUri(ctx.target.did, skey);\n\t\t\tif (uri !== expected) {\n\t\t\t\treturn fail(\n\t\t\t\t\t`createSpace returned space ${uri}, expected ${expected}`,\n\t\t\t\t\tres.json,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst got = await xrpcGet(op(ctx), \"com.atproto.space.getSpace\", {\n\t\t\t\tspace: uri,\n\t\t\t});\n\t\t\tif (got.status !== 200)\n\t\t\t\treturn fail(`getSpace ${describe(got)}`, got.json);\n\t\t\tconst body = got.json as { space?: string; policy?: Policy };\n\t\t\tif (body.space !== uri)\n\t\t\t\treturn fail(`getSpace space was ${body.space}`, got.json);\n\t\t\tif (body.policy?.$type !== \"com.atproto.memberspace.policy\") {\n\t\t\t\treturn fail(`getSpace policy was ${body.policy?.$type}`, got.json);\n\t\t\t}\n\t\t\t// Defaults are false: an unset publicRead must not read as public.\n\t\t\treturn body.policy.publicRead === true\n\t\t\t\t? fail(\n\t\t\t\t\t\t\"a memberspace created without publicRead reports publicRead: true\",\n\t\t\t\t\t)\n\t\t\t\t: pass(\n\t\t\t\t\t\t\"created at the expected at:space/ ref; getSpace reports the memberspace policy\",\n\t\t\t\t\t);\n\t\t} finally {\n\t\t\tif (uri) await deleteProbeSpace(ctx, uri);\n\t\t}\n\t},\n});\n\nconst spaceGeneratedSkey = defineCheck({\n\tid: \"space.create-generates-skey\",\n\ttitle: \"createSpace without an skey generates a TID\",\n\ttier: \"must\",\n\tcitations: [L(\"com.atproto.space.createSpace\")],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst res = await xrpcPost(op(ctx), \"com.atproto.space.createSpace\", {\n\t\t\tspaceType: PROBE_TYPE,\n\t\t\tpolicy: personalspace(),\n\t\t});\n\t\tif (res.status !== 200)\n\t\t\treturn fail(`createSpace ${describe(res)}`, res.json);\n\t\tconst uri = (res.json as { space: string }).space;\n\t\tawait deleteProbeSpace(ctx, uri);\n\t\tconst skey = uri?.split(\"/\").at(-1);\n\t\treturn isTid(skey)\n\t\t\t? pass(`generated skey ${skey}`)\n\t\t\t: fail(`generated skey ${skey} is not a TID`);\n\t},\n});\n\nconst spaceDuplicate = defineCheck({\n\tid: \"space.duplicate-refused\",\n\ttitle: \"Creating an existing space is refused with SpaceAlreadyExists\",\n\ttier: \"must\",\n\tcitations: [L(\"com.atproto.space.createSpace@error:SpaceAlreadyExists\")],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst space = await createProbeSpace(ctx, personalspace());\n\t\ttry {\n\t\t\tconst again = await xrpcPost(op(ctx), \"com.atproto.space.createSpace\", {\n\t\t\t\tspaceType: PROBE_TYPE,\n\t\t\t\tskey: space.skey,\n\t\t\t\tpolicy: personalspace(),\n\t\t\t});\n\t\t\tif (again.status === 200)\n\t\t\t\treturn fail(\"a second createSpace at the same skey returned 200\");\n\t\t\treturn again.error === \"SpaceAlreadyExists\"\n\t\t\t\t? pass(\"refused with SpaceAlreadyExists\")\n\t\t\t\t: fail(\n\t\t\t\t\t\t`refused with ${describe(again)}, expected SpaceAlreadyExists`,\n\t\t\t\t\t\tagain.json,\n\t\t\t\t\t);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nconst spaceRecreate = defineCheck({\n\tid: \"space.recreate-after-delete\",\n\ttitle: \"A deleted space may be created again\",\n\ttier: \"must\",\n\tcitations: [P(\"0016#space-deletion\"), L(\"com.atproto.space.createSpace\")],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\t// \"An authority MAY recreate a deleted space with the same space type\n\t\t// and skey\" — so a host must let it.\n\t\tconst space = await createProbeSpace(ctx, personalspace());\n\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\tconst again = await xrpcPost(op(ctx), \"com.atproto.space.createSpace\", {\n\t\t\tspaceType: PROBE_TYPE,\n\t\t\tskey: space.skey,\n\t\t\tpolicy: personalspace(),\n\t\t});\n\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\treturn again.status === 200\n\t\t\t? pass(\"re-created the deleted space\")\n\t\t\t: fail(\n\t\t\t\t\t`re-creating a deleted space returned ${describe(again)}`,\n\t\t\t\t\tagain.json,\n\t\t\t\t);\n\t},\n});\n\nconst spaceUnsupportedPolicy = defineCheck({\n\tid: \"space.unsupported-policy-rejected\",\n\ttitle:\n\t\t\"createSpace and updateSpace refuse a policy the host does not implement\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.space.createSpace@error:UnsupportedPolicy\"),\n\t\tL(\"com.atproto.space.updateSpace@error:UnsupportedPolicy\"),\n\t\tP(\"0016#space-policy\"),\n\t],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst mystery = { $type: \"com.example.mysteryPolicy\" };\n\t\tconst space = await createProbeSpace(ctx, personalspace());\n\t\tlet created: string | undefined;\n\t\ttry {\n\t\t\tconst result = await expectEach([\n\t\t\t\t[\n\t\t\t\t\t\"createSpace\",\n\t\t\t\t\tasync () => {\n\t\t\t\t\t\tconst res = await xrpcPost(\n\t\t\t\t\t\t\top(ctx),\n\t\t\t\t\t\t\t\"com.atproto.space.createSpace\",\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tspaceType: PROBE_TYPE,\n\t\t\t\t\t\t\t\tskey: probeSkey(),\n\t\t\t\t\t\t\t\tpolicy: mystery,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (res.status === 200)\n\t\t\t\t\t\t\tcreated = (res.json as { space: string }).space;\n\t\t\t\t\t\treturn res;\n\t\t\t\t\t},\n\t\t\t\t\terrorIs(\"UnsupportedPolicy\"),\n\t\t\t\t],\n\t\t\t\t[\n\t\t\t\t\t\"updateSpace\",\n\t\t\t\t\t() =>\n\t\t\t\t\t\txrpcPost(op(ctx), \"com.atproto.space.updateSpace\", {\n\t\t\t\t\t\t\tspace: space.uri,\n\t\t\t\t\t\t\tpolicy: mystery,\n\t\t\t\t\t\t}),\n\t\t\t\t\terrorIs(\"UnsupportedPolicy\"),\n\t\t\t\t],\n\t\t\t]);\n\t\t\treturn result.ok\n\t\t\t\t? pass(\"both refused with UnsupportedPolicy\")\n\t\t\t\t: fail(`expected UnsupportedPolicy: ${result.detail}`, result.evidence);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t\tif (created) await deleteProbeSpace(ctx, created);\n\t\t}\n\t},\n});\n\nconst spaceUpdateReplaces = defineCheck({\n\tid: \"space.update-replaces-policy\",\n\ttitle:\n\t\t\"updateSpace replaces the policy wholesale; a type change discards member state\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.space.updateSpace\"),\n\t\tL(\"com.atproto.space.getSpace\"),\n\t\tL(\"com.atproto.memberspace.listMembers\"),\n\t\tP(\"0016#space-policy\"),\n\t],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst space = await createProbeSpace(ctx, memberspace());\n\t\tconst member = fakeDid();\n\t\tconst policyOf = async () =>\n\t\t\t(\n\t\t\t\t(\n\t\t\t\t\tawait xrpcGet(op(ctx), \"com.atproto.space.getSpace\", {\n\t\t\t\t\t\tspace: space.uri,\n\t\t\t\t\t})\n\t\t\t\t).json as { policy?: Policy } | undefined\n\t\t\t)?.policy;\n\t\tconst update = (policy: Policy) =>\n\t\t\txrpcPost(op(ctx), \"com.atproto.space.updateSpace\", {\n\t\t\t\tspace: space.uri,\n\t\t\t\tpolicy,\n\t\t\t});\n\t\ttry {\n\t\t\tawait putMembers(ctx, space.uri, [\n\t\t\t\t{ did: member, read: true, write: false },\n\t\t\t]);\n\t\t\t// Same type: a configuration change. The member list survives.\n\t\t\tconst same = await update(memberspace({ publicRead: true }));\n\t\t\tif (same.status !== 200)\n\t\t\t\treturn fail(`updateSpace (config) ${describe(same)}`, same.json);\n\t\t\tif ((await policyOf())?.publicRead !== true)\n\t\t\t\treturn fail(\"getSpace does not reflect publicRead: true\");\n\t\t\tif (!(await listMembers(ctx, space.uri)).some((m) => m.did === member)) {\n\t\t\t\treturn fail(\"a same-type update dropped the member list\");\n\t\t\t}\n\t\t\t// A different type migrates the space.\n\t\t\tconst migrate = await update(personalspace());\n\t\t\tif (migrate.status !== 200)\n\t\t\t\treturn fail(`updateSpace (migrate) ${describe(migrate)}`, migrate.json);\n\t\t\tconst p2 = await policyOf();\n\t\t\tif (p2?.$type !== \"com.atproto.personalspace.policy\") {\n\t\t\t\treturn fail(`after migration getSpace reports ${p2?.$type}`, p2);\n\t\t\t}\n\t\t\t// Migrating back does not restore the discarded member list.\n\t\t\tconst back = await update(memberspace());\n\t\t\tif (back.status !== 200)\n\t\t\t\treturn fail(`updateSpace (back) ${describe(back)}`, back.json);\n\t\t\treturn (await listMembers(ctx, space.uri)).some((m) => m.did === member)\n\t\t\t\t? fail(\"migrating away and back restored the old member list\")\n\t\t\t\t: pass(\n\t\t\t\t\t\t\"config update kept members; a type change replaced the policy and discarded them\",\n\t\t\t\t\t);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nconst spaceNotAuthority = defineCheck({\n\tid: \"space.not-authority-refused\",\n\ttitle:\n\t\t\"Managing a space anchored on another DID is refused with NotAuthorized\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.space.deleteSpace@error:NotAuthorized\"),\n\t\tL(\"com.atproto.space.updateSpace@error:NotAuthorized\"),\n\t\tL(\"com.atproto.space.getSpace@error:NotAuthorized\"),\n\t\tL(\"com.atproto.space.removeWriter@error:NotAuthorized\"),\n\t\tL(\"com.atproto.space.exportSpaceMeta@error:NotAuthorized\"),\n\t\tL(\"com.atproto.memberspace.putMembers@error:NotAuthorized\"),\n\t\tL(\"com.atproto.memberspace.removeMembers@error:NotAuthorized\"),\n\t\tL(\"com.atproto.memberspace.listMembers@error:NotAuthorized\"),\n\t],\n\tneeds: [\"operator\"],\n\tasync run(ctx) {\n\t\tconst space = unknownSpaceUri(FOREIGN_DID);\n\t\tconst did = fakeDid();\n\t\tconst na = errorIs(\"NotAuthorized\");\n\t\tconst result = await expectEach([\n\t\t\t[\n\t\t\t\t\"deleteSpace\",\n\t\t\t\t() => xrpcPost(op(ctx), \"com.atproto.space.deleteSpace\", { space }),\n\t\t\t\tna,\n\t\t\t],\n\t\t\t[\n\t\t\t\t\"updateSpace\",\n\t\t\t\t() =>\n\t\t\t\t\txrpcPost(op(ctx), \"com.atproto.space.updateSpace\", {\n\t\t\t\t\t\tspace,\n\t\t\t\t\t\tpolicy: personalspace(),\n\t\t\t\t\t}),\n\t\t\t\tna,\n\t\t\t],\n\t\t\t[\n\t\t\t\t\"getSpace\",\n\t\t\t\t() => xrpcGet(op(ctx), \"com.atproto.space.getSpace\", { space }),\n\t\t\t\tna,\n\t\t\t],\n\t\t\t[\n\t\t\t\t\"removeWriter\",\n\t\t\t\t() =>\n\t\t\t\t\txrpcPost(op(ctx), \"com.atproto.space.removeWriter\", {\n\t\t\t\t\t\tspace,\n\t\t\t\t\t\trepo: did,\n\t\t\t\t\t}),\n\t\t\t\tna,\n\t\t\t],\n\t\t\t[\n\t\t\t\t\"exportSpaceMeta\",\n\t\t\t\t() => xrpcGet(op(ctx), \"com.atproto.space.exportSpaceMeta\", { space }),\n\t\t\t\tna,\n\t\t\t],\n\t\t\t[\n\t\t\t\t\"putMembers\",\n\t\t\t\t() => putMembers(ctx, space, [{ did, read: true, write: true }]),\n\t\t\t\tna,\n\t\t\t],\n\t\t\t[\"removeMembers\", () => removeMembers(ctx, space, [did]), na],\n\t\t\t[\n\t\t\t\t\"listMembers\",\n\t\t\t\t() =>\n\t\t\t\t\txrpcGet(op(ctx), \"com.atproto.memberspace.listMembers\", { space }),\n\t\t\t\tna,\n\t\t\t],\n\t\t]);\n\t\treturn result.ok\n\t\t\t? pass(\"every authority-only method answered NotAuthorized\")\n\t\t\t: fail(`expected NotAuthorized: ${result.detail}`, result.evidence);\n\t},\n});\n\nconst spaceUnknown = defineCheck({\n\tid: \"space.unknown-space-not-found\",\n\ttitle: \"Managing an own space that does not exist answers SpaceNotFound\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.space.getSpace@error:SpaceNotFound\"),\n\t\tL(\"com.atproto.space.updateSpace@error:SpaceNotFound\"),\n\t\tL(\"com.atproto.space.deleteSpace@error:SpaceNotFound\"),\n\t\tL(\"com.atproto.space.exportSpaceMeta@error:SpaceNotFound\"),\n\t\tL(\"com.atproto.space.removeWriter@error:SpaceNotFound\"),\n\t\tL(\"com.atproto.memberspace.putMembers@error:SpaceNotFound\"),\n\t\tL(\"com.atproto.memberspace.removeMembers@error:SpaceNotFound\"),\n\t\tL(\"com.atproto.memberspace.listMembers@error:SpaceNotFound\"),\n\t],\n\tneeds: [\"operator\"],\n\tasync run(ctx) {\n\t\tconst space = unknownSpaceUri(ctx.target.did);\n\t\tconst did = fakeDid();\n\t\tconst nf = errorIs(\"SpaceNotFound\");\n\t\tconst result = await expectEach([\n\t\t\t[\n\t\t\t\t\"getSpace\",\n\t\t\t\t() => xrpcGet(op(ctx), \"com.atproto.space.getSpace\", { space }),\n\t\t\t\tnf,\n\t\t\t],\n\t\t\t[\n\t\t\t\t\"updateSpace\",\n\t\t\t\t() =>\n\t\t\t\t\txrpcPost(op(ctx), \"com.atproto.space.updateSpace\", {\n\t\t\t\t\t\tspace,\n\t\t\t\t\t\tpolicy: personalspace(),\n\t\t\t\t\t}),\n\t\t\t\tnf,\n\t\t\t],\n\t\t\t[\n\t\t\t\t\"deleteSpace\",\n\t\t\t\t() => xrpcPost(op(ctx), \"com.atproto.space.deleteSpace\", { space }),\n\t\t\t\tnf,\n\t\t\t],\n\t\t\t[\n\t\t\t\t\"exportSpaceMeta\",\n\t\t\t\t() => xrpcGet(op(ctx), \"com.atproto.space.exportSpaceMeta\", { space }),\n\t\t\t\tnf,\n\t\t\t],\n\t\t\t[\n\t\t\t\t\"removeWriter\",\n\t\t\t\t() =>\n\t\t\t\t\txrpcPost(op(ctx), \"com.atproto.space.removeWriter\", {\n\t\t\t\t\t\tspace,\n\t\t\t\t\t\trepo: did,\n\t\t\t\t\t}),\n\t\t\t\tnf,\n\t\t\t],\n\t\t\t[\n\t\t\t\t\"putMembers\",\n\t\t\t\t() => putMembers(ctx, space, [{ did, read: true, write: false }]),\n\t\t\t\tnf,\n\t\t\t],\n\t\t\t[\"removeMembers\", () => removeMembers(ctx, space, [did]), nf],\n\t\t\t[\n\t\t\t\t\"listMembers\",\n\t\t\t\t() =>\n\t\t\t\t\txrpcGet(op(ctx), \"com.atproto.memberspace.listMembers\", { space }),\n\t\t\t\tnf,\n\t\t\t],\n\t\t]);\n\t\treturn result.ok\n\t\t\t? pass(\"every method answered SpaceNotFound\")\n\t\t\t: fail(`expected SpaceNotFound: ${result.detail}`, result.evidence);\n\t},\n});\n\nconst spaceDeleteIdempotent = defineCheck({\n\tid: \"space.delete-idempotent\",\n\ttitle: \"Deleting an already-deleted space succeeds\",\n\ttier: \"should\",\n\tcitations: [\n\t\t{\n\t\t\tsource: \"reference\",\n\t\t\tref: \"pds deleteSpace returns early for a tombstoned space\",\n\t\t},\n\t\tL(\"com.atproto.space.deleteSpace\"),\n\t],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\t// The 1105 lexicon called deleteSpace idempotent; 1112 dropped the\n\t\t// sentence, so this is now calibrated against the reference.\n\t\tconst space = await createProbeSpace(ctx, personalspace());\n\t\tconst first = await xrpcPost(op(ctx), \"com.atproto.space.deleteSpace\", {\n\t\t\tspace: space.uri,\n\t\t});\n\t\tconst second = await xrpcPost(op(ctx), \"com.atproto.space.deleteSpace\", {\n\t\t\tspace: space.uri,\n\t\t});\n\t\treturn first.status === 200 && second.status === 200\n\t\t\t? pass(\"both deletes returned 200\")\n\t\t\t: fail(`deletes returned ${describe(first)} then ${describe(second)}`);\n\t},\n});\n\nconst spaceListSpaces = defineCheck({\n\tid: \"space.listspaces-filters\",\n\ttitle:\n\t\t\"listSpaces lists the operator's spaces with its repo state, honouring spaceType and spaceDid\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.space.listSpaces\"),\n\t\tL(\"com.atproto.space.listSpaces#spaceView\"),\n\t\tC(\"pds-space-uri-migration\"),\n\t],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst space = await createProbeSpace(ctx, personalspace());\n\t\ttry {\n\t\t\tawait mustCreateRecord(ctx, space.uri, \"a\");\n\t\t\t// Filter on both: an OAuth grant scoped to the probe type under the\n\t\t\t// operator's authority covers exactly this listing.\n\t\t\tconst seen: Array<{\n\t\t\t\tspace: string;\n\t\t\t\trepoRev?: string;\n\t\t\t\tdata?: unknown;\n\t\t\t\tspaceRev?: string;\n\t\t\t}> = [];\n\t\t\tlet cursor: string | undefined;\n\t\t\tfor (let page = 0; page < 20; page++) {\n\t\t\t\tconst res = await xrpcGet(op(ctx), \"com.atproto.space.listSpaces\", {\n\t\t\t\t\tspaceType: PROBE_TYPE,\n\t\t\t\t\tspaceDid: ctx.target.did,\n\t\t\t\t\tlimit: \"100\",\n\t\t\t\t\tcursor,\n\t\t\t\t});\n\t\t\t\tif (res.status !== 200)\n\t\t\t\t\treturn fail(`listSpaces ${describe(res)}`, res.json);\n\t\t\t\tconst body = res.json as { spaces?: typeof seen; cursor?: string };\n\t\t\t\tseen.push(...(body.spaces ?? []));\n\t\t\t\tcursor = body.cursor;\n\t\t\t\tif (!cursor || seen.some((s) => s.space === space.uri)) break;\n\t\t\t}\n\t\t\tconst entry = seen.find((s) => s.space === space.uri);\n\t\t\tif (!entry) return fail(\"listSpaces did not list the new space\");\n\t\t\t// Every entry is an at:space/ ref under the filtered authority and\n\t\t\t// type — an entry in any other form is outside the filter too.\n\t\t\tconst stray = seen.filter(\n\t\t\t\t(s) => !s.space.startsWith(spaceUri(ctx.target.did, \"\")),\n\t\t\t);\n\t\t\tif (stray.length)\n\t\t\t\treturn fail(\n\t\t\t\t\t`listing included spaces outside the filter (or not as at:space/${ctx.target.did}/${PROBE_TYPE}/… refs): ${stray.map((s) => s.space).join(\", \")}`,\n\t\t\t\t);\n\t\t\t// The entry carries the operator's repo state, and — as authority — the spaceRev.\n\t\t\tconst latest = await xrpcGet(\n\t\t\t\top(ctx),\n\t\t\t\t\"com.atproto.space.getLatestCommit\",\n\t\t\t\t{\n\t\t\t\t\tspace: space.uri,\n\t\t\t\t\trepo: ctx.target.did,\n\t\t\t\t},\n\t\t\t);\n\t\t\tconst commit = (\n\t\t\t\tlatest.json as { commit?: { rev?: string; data?: unknown } } | undefined\n\t\t\t)?.commit;\n\t\t\tconst a = lexBytes(entry.data);\n\t\t\tconst b = lexBytes(commit?.data);\n\t\t\tconst problems: string[] = [];\n\t\t\tif (entry.repoRev !== commit?.rev)\n\t\t\t\tproblems.push(`repoRev ${entry.repoRev} ≠ commit rev ${commit?.rev}`);\n\t\t\tif (!a || !b || !bytesEqual(a, b))\n\t\t\t\tproblems.push(\"data does not match the commit\");\n\t\t\tif (!isTid(entry.spaceRev))\n\t\t\t\tproblems.push(`no spaceRev for a space the caller is authority of`);\n\t\t\treturn problems.length\n\t\t\t\t? fail(problems.join(\"; \"), entry)\n\t\t\t\t: pass(\"listed with the operator's repoRev, data and the spaceRev\");\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nconst spaceOwnerStateNotByCredential = defineCheck({\n\tid: \"space.owner-state-not-by-credential\",\n\ttitle:\n\t\t\"A space credential does not reach getSpace, listMembers or exportSpaceMeta\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.space.getSpace\"),\n\t\tL(\"com.atproto.memberspace.listMembers\"),\n\t\tL(\"com.atproto.space.exportSpaceMeta\"),\n\t],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\t// Each requires auth as the space authority: the policy and member list\n\t\t// are its own state, and a credential — which any reader of a public\n\t\t// space can hold — must not expose them.\n\t\tconst space = await createProbeSpace(ctx, publicRead());\n\t\ttry {\n\t\t\tconst credential = await obtainPublicCredential(ctx, space.uri);\n\t\t\tconst call = (nsid: string) =>\n\t\t\t\tcredentialCall(ctx, credential, nsid, {\n\t\t\t\t\tparams: { space: space.uri },\n\t\t\t\t\taudience: ctx.target.did,\n\t\t\t\t});\n\t\t\t// A refusal, not a 5xx. Each declares NotAuthorized for a caller who\n\t\t\t// is not the authority, but a credential is no account session at\n\t\t\t// all, so the auth layer may refuse it first — the reference answers\n\t\t\t// 400 InvalidToken — and a must can't insist on the error name.\n\t\t\tconst isRefusal = (r: { status: number }) =>\n\t\t\t\tr.status >= 400 && r.status < 500;\n\t\t\tconst result = await expectEach([\n\t\t\t\t[\"getSpace\", () => call(\"com.atproto.space.getSpace\"), isRefusal],\n\t\t\t\t[\n\t\t\t\t\t\"listMembers\",\n\t\t\t\t\t() => call(\"com.atproto.memberspace.listMembers\"),\n\t\t\t\t\tisRefusal,\n\t\t\t\t],\n\t\t\t\t[\n\t\t\t\t\t\"exportSpaceMeta\",\n\t\t\t\t\t() => call(\"com.atproto.space.exportSpaceMeta\"),\n\t\t\t\t\tisRefusal,\n\t\t\t\t],\n\t\t\t]);\n\t\t\treturn result.ok\n\t\t\t\t? pass(`all refused (${Object.values(result.evidence).join(\", \")})`)\n\t\t\t\t: fail(`expected a 4xx refusal: ${result.detail}`, result.evidence);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nconst managedBareDid = defineCheck({\n\tid: \"managedspace.bare-did-rejected\",\n\ttitle:\n\t\t\"A managedspace whose managingApp is not a did#serviceId reference is refused\",\n\ttier: \"must\",\n\tcitations: [L(\"com.atproto.managedspace.policy\"), C(\"tidy-spaces-settle\")],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst create = (managingApp: string) =>\n\t\t\txrpcPost(op(ctx), \"com.atproto.space.createSpace\", {\n\t\t\t\tspaceType: PROBE_TYPE,\n\t\t\t\tskey: probeSkey(),\n\t\t\t\tpolicy: managedspace(managingApp),\n\t\t\t});\n\t\t// Control: the same policy naming a did#serviceId is accepted, so the\n\t\t// refusal is of the bare DID, not of managedspaces.\n\t\tconst ok = await create(`${FOREIGN_DID}#managing_app`);\n\t\tif (ok.status !== 200)\n\t\t\treturn fail(\n\t\t\t\t`positive control failed: a managedspace naming a did#serviceId was refused (${describe(ok)})`,\n\t\t\t\tok.json,\n\t\t\t);\n\t\tawait deleteProbeSpace(ctx, (ok.json as { space: string }).space);\n\t\tconst res = await create(FOREIGN_DID);\n\t\tif (res.status === 200) {\n\t\t\tawait deleteProbeSpace(ctx, (res.json as { space: string }).space);\n\t\t\treturn fail(\"created a managedspace whose managingApp is a bare DID\");\n\t\t}\n\t\t// createSpace declares no error for it: a malformed input is XRPC's\n\t\t// generic InvalidRequest.\n\t\treturn res.status === 400 && res.error === \"InvalidRequest\"\n\t\t\t? pass(\n\t\t\t\t\t\"a did#serviceId was accepted; a bare DID refused with InvalidRequest\",\n\t\t\t\t)\n\t\t\t: fail(\n\t\t\t\t\t`answered ${describe(res)}, expected 400 InvalidRequest`,\n\t\t\t\t\tres.json,\n\t\t\t\t);\n\t},\n});\n\n// --- memberspace ------------------------------------------------------\n\nconst memberRoundTrip = defineCheck({\n\tid: \"memberspace.member-round-trip\",\n\ttitle: \"putMembers and removeMembers apply batches; listMembers follows\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.memberspace.putMembers\"),\n\t\tL(\"com.atproto.memberspace.listMembers\"),\n\t\tL(\"com.atproto.memberspace.removeMembers\"),\n\t\tL(\"com.atproto.memberspace.defs#member\"),\n\t\tC(\"tidy-spaces-settle\"),\n\t],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst space = await createProbeSpace(ctx, memberspace());\n\t\tconst [a, b] = [fakeDid(), fakeDid()];\n\t\tconst find = (members: Member[], did: string) =>\n\t\t\tmembers.find((m) => m.did === did);\n\t\ttry {\n\t\t\t// One batch; `a` appears twice and its last entry wins.\n\t\t\tconst put = await putMembers(ctx, space.uri, [\n\t\t\t\t{ did: a, read: false, write: false },\n\t\t\t\t{ did: b, read: true, write: true },\n\t\t\t\t{ did: a, read: true, write: false },\n\t\t\t]);\n\t\t\tif (put.status !== 200)\n\t\t\t\treturn fail(`putMembers ${describe(put)}`, put.json);\n\t\t\tconst listed = await listMembers(ctx, space.uri);\n\t\t\tconst ma = find(listed, a);\n\t\t\tconst mb = find(listed, b);\n\t\t\tif (!ma || ma.read !== true || ma.write !== false)\n\t\t\t\treturn fail(\n\t\t\t\t\t`a duplicated DID did not take its last entry: ${JSON.stringify(ma)}`,\n\t\t\t\t);\n\t\t\tif (!mb || mb.read !== true || mb.write !== true)\n\t\t\t\treturn fail(`second member: ${JSON.stringify(mb)}`);\n\t\t\t// Replace one member's access.\n\t\t\tawait putMembers(ctx, space.uri, [{ did: b, read: false, write: true }]);\n\t\t\tconst mb2 = find(await listMembers(ctx, space.uri), b);\n\t\t\tif (!mb2 || mb2.read !== false || mb2.write !== true)\n\t\t\t\treturn fail(\n\t\t\t\t\t`putMembers did not replace access: ${JSON.stringify(mb2)}`,\n\t\t\t\t);\n\t\t\t// removeMembers ignores DIDs that are not members.\n\t\t\tconst removed = await removeMembers(ctx, space.uri, [a, b, fakeDid()]);\n\t\t\tif (removed.status !== 200)\n\t\t\t\treturn fail(`removeMembers ${describe(removed)}`, removed.json);\n\t\t\tconst left = await listMembers(ctx, space.uri);\n\t\t\treturn find(left, a) || find(left, b)\n\t\t\t\t? fail(`removeMembers left ${JSON.stringify(left)}`)\n\t\t\t\t: pass(\n\t\t\t\t\t\t\"batched put (last entry wins), replace, and remove (ignoring a non-member)\",\n\t\t\t\t\t);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nconst memberPolicyMismatch = defineCheck({\n\tid: \"memberspace.policy-mismatch\",\n\ttitle: \"Member methods on a non-memberspace answer PolicyMismatch\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.memberspace.putMembers@error:PolicyMismatch\"),\n\t\tL(\"com.atproto.memberspace.removeMembers@error:PolicyMismatch\"),\n\t\tL(\"com.atproto.memberspace.listMembers@error:PolicyMismatch\"),\n\t],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst space = await createProbeSpace(ctx, personalspace());\n\t\tconst did = fakeDid();\n\t\tconst mm = errorIs(\"PolicyMismatch\");\n\t\ttry {\n\t\t\tconst result = await expectEach([\n\t\t\t\t[\n\t\t\t\t\t\"putMembers\",\n\t\t\t\t\t() => putMembers(ctx, space.uri, [{ did, read: true, write: true }]),\n\t\t\t\t\tmm,\n\t\t\t\t],\n\t\t\t\t[\"removeMembers\", () => removeMembers(ctx, space.uri, [did]), mm],\n\t\t\t\t[\n\t\t\t\t\t\"listMembers\",\n\t\t\t\t\t() =>\n\t\t\t\t\t\txrpcGet(op(ctx), \"com.atproto.memberspace.listMembers\", {\n\t\t\t\t\t\t\tspace: space.uri,\n\t\t\t\t\t\t}),\n\t\t\t\t\tmm,\n\t\t\t\t],\n\t\t\t]);\n\t\t\treturn result.ok\n\t\t\t\t? pass(\"all three answered PolicyMismatch on a personalspace\")\n\t\t\t\t: fail(`expected PolicyMismatch: ${result.detail}`, result.evidence);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nconst memberPublish = defineCheck({\n\tid: \"memberspace.publish-policy-and-members\",\n\ttitle:\n\t\t\"publishPolicy / publishMembers keep policy and member records in the authority's repo\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.memberspace.policy\"),\n\t\tL(\"com.atproto.space.policy\"),\n\t\tL(\"com.atproto.memberspace.member\"),\n\t\tP(\"0016#publishing-to-readers\"),\n\t],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst space = await createProbeSpace(\n\t\t\tctx,\n\t\t\tmemberspace({ publishPolicy: true, publishMembers: true }),\n\t\t);\n\t\tconst member = fakeDid();\n\t\ttry {\n\t\t\tconst policy = await operatorGetRecord(\n\t\t\t\tctx,\n\t\t\t\tspace.uri,\n\t\t\t\t\"self\",\n\t\t\t\t\"com.atproto.space.policy\",\n\t\t\t);\n\t\t\tif (policy.status !== 200)\n\t\t\t\treturn fail(\n\t\t\t\t\t`no com.atproto.space.policy/self record: ${describe(policy)}`,\n\t\t\t\t\tpolicy.json,\n\t\t\t\t);\n\t\t\tconst published = (policy.json as { value?: { policy?: Policy } }).value\n\t\t\t\t?.policy;\n\t\t\tif (\n\t\t\t\tpublished?.$type !== \"com.atproto.memberspace.policy\" ||\n\t\t\t\tpublished.publishMembers !== true\n\t\t\t) {\n\t\t\t\treturn fail(\n\t\t\t\t\t\"the published policy record does not carry the space's policy\",\n\t\t\t\t\tpolicy.json,\n\t\t\t\t);\n\t\t\t}\n\t\t\tawait putMembers(ctx, space.uri, [\n\t\t\t\t{ did: member, read: true, write: false },\n\t\t\t]);\n\t\t\tconst rec = await operatorGetRecord(\n\t\t\t\tctx,\n\t\t\t\tspace.uri,\n\t\t\t\tmember,\n\t\t\t\t\"com.atproto.memberspace.member\",\n\t\t\t);\n\t\t\tconst value = (\n\t\t\t\trec.json as { value?: { read?: boolean; write?: boolean } } | undefined\n\t\t\t)?.value;\n\t\t\tif (rec.status !== 200 || value?.read !== true || value.write !== false) {\n\t\t\t\treturn fail(\n\t\t\t\t\t`member record after putMembers: ${describe(rec)}`,\n\t\t\t\t\trec.json,\n\t\t\t\t);\n\t\t\t}\n\t\t\tawait removeMembers(ctx, space.uri, [member]);\n\t\t\tconst gone = await operatorGetRecord(\n\t\t\t\tctx,\n\t\t\t\tspace.uri,\n\t\t\t\tmember,\n\t\t\t\t\"com.atproto.memberspace.member\",\n\t\t\t);\n\t\t\treturn gone.status === 200\n\t\t\t\t? fail(\"the member record outlived removeMembers\", gone.json)\n\t\t\t\t: pass(\n\t\t\t\t\t\t\"policy record published; member record tracked putMembers and removeMembers\",\n\t\t\t\t\t);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nexport const spaceChecks: Check[] = [\n\tspaceCreateAndGet,\n\tspaceGeneratedSkey,\n\tspaceDuplicate,\n\tspaceRecreate,\n\tspaceUnsupportedPolicy,\n\tspaceUpdateReplaces,\n\tspaceNotAuthority,\n\tspaceUnknown,\n\tspaceDeleteIdempotent,\n\tspaceListSpaces,\n\tspaceOwnerStateNotByCredential,\n\tmanagedBareDid,\n\tmemberRoundTrip,\n\tmemberPolicyMismatch,\n\tmemberPublish,\n];\n","/**\n * Space credentials, operator-side: issuance through authorizeSpaceSync\n * (tokenless for public-read spaces, via the target's own delegation\n * tokens otherwise), the refusals it declares, and presentation — the\n * HTTP message signature, the audience binding and the MAC request every\n * credentialed read of a commit or record must carry.\n *\n * All browser-safe: credential keys, signatures and HPKE key shares are\n * WebCrypto (see ../space-auth.ts). Verifying the MACs that come back\n * needs the reference library and lives in ../full/checks.ts.\n */\n\nimport { defineCheck } from \"../registry.js\";\nimport { asOperator, xrpcGet, xrpcPost } from \"../http.js\";\nimport { fail, pass, type Check, type CheckContext } from \"../model.js\";\nimport { decodeJwt, isTid, rawCid, toBase64Url, utf8 } from \"../encoding.js\";\nimport {\n\tCOMMIT_MAC_PROFILE,\n\tRECORD_MAC_PROFILE,\n\tcreateCredentialKey,\n\tcredentialSigMembers,\n\tformatDidKey,\n\tformatMacRequest,\n\tsignClientAttestation,\n\tspaceHostAud,\n} from \"../space-auth.js\";\nimport {\n\tFOREIGN_DID,\n\tPOST,\n\tcreateProbeSpace,\n\tcredentialCall,\n\tcredentialGet,\n\tdeleteProbeSpace,\n\tdescribe,\n\terrorIs,\n\tmemberspace,\n\tmustCreateRecord,\n\tobtainCredentialViaDelegation,\n\tobtainPublicCredential,\n\tpersonalspace,\n\tpublicRead,\n\trequestCredential,\n\tspaceUri,\n\ttype Credential,\n\ttype CredentialCallOptions,\n\ttype ProbeSpace,\n} from \"./probe.js\";\nimport { fakeDid } from \"./space.js\";\n\nconst L = (ref: string) => ({ source: \"lexicon\" as const, ref });\nconst P = (ref: string) => ({ source: \"proposal\" as const, ref });\nconst C = (ref: string) => ({ source: \"changeset\" as const, ref });\n\n/** Refusals the lexicon allows for an account the policy does not authorise. */\nexport const ACCOUNT_REFUSALS = [\n\t\"SpaceNotFound\",\n\t\"AccountNotAuthorized\",\n\t\"NotAuthorized\",\n];\n\n/** A public-read probe space holding one record, plus a tokenless credential for it. */\nasync function withPublicSpace<T>(\n\tctx: CheckContext,\n\tfn: (space: ProbeSpace, credential: Credential) => Promise<T>,\n): Promise<T> {\n\tconst space = await createProbeSpace(ctx, publicRead());\n\ttry {\n\t\tawait mustCreateRecord(ctx, space.uri, \"shared\", \"visible\");\n\t\tconst credential = await obtainPublicCredential(ctx, space.uri);\n\t\treturn await fn(space, credential);\n\t} finally {\n\t\tawait deleteProbeSpace(ctx, space.uri);\n\t}\n}\n\nconst recordParams = (ctx: CheckContext, space: string) => ({\n\tspace,\n\trepo: ctx.target.did,\n\tcollection: POST,\n\trkey: \"shared\",\n});\n\n/** Read the shared record with a credential, varying one aspect of presentation. */\nconst readShared = (\n\tctx: CheckContext,\n\tcredential: Credential,\n\tspace: string,\n\topts: Omit<CredentialCallOptions, \"params\"> = {},\n) =>\n\tcredentialCall(ctx, credential, \"com.atproto.space.getRecord\", {\n\t\t...opts,\n\t\tparams: recordParams(ctx, space),\n\t});\n\nconst refused = (status: number) => status >= 400 && status < 500;\n\n// --- issuance ----------------------------------------------------------\n\nconst credentialTokenlessPolicies = defineCheck({\n\tid: \"credential.tokenless-by-policy\",\n\ttitle:\n\t\t\"Without a delegation token only a public-read space issues a credential\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.space.authorizeSpaceSync\"),\n\t\tL(\"com.atproto.space.authorizeSpaceSync@error:SpaceNotFound\"),\n\t\tL(\"com.atproto.memberspace.policy\"),\n\t\tL(\"com.atproto.personalspace.policy\"),\n\t\tP(\"0016#memberspace\"),\n\t],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst open = await createProbeSpace(ctx, publicRead());\n\t\tconst closed = await createProbeSpace(ctx, memberspace());\n\t\tconst personal = await createProbeSpace(ctx, personalspace());\n\t\ttry {\n\t\t\tconst a = await requestCredential(ctx, open.uri);\n\t\t\tif (!a.credential)\n\t\t\t\treturn fail(\n\t\t\t\t\t`public-read space refused a tokenless request: ${describe(a.result)}`,\n\t\t\t\t\ta.result.json,\n\t\t\t\t);\n\t\t\tconst misses: string[] = [];\n\t\t\tfor (const [label, space] of [\n\t\t\t\t[\"memberspace\", closed],\n\t\t\t\t[\"personalspace\", personal],\n\t\t\t] as const) {\n\t\t\t\tconst res = await requestCredential(ctx, space.uri);\n\t\t\t\tif (res.credential || !errorIs(...ACCOUNT_REFUSALS)(res.result))\n\t\t\t\t\tmisses.push(`${label} → ${describe(res.result)}`);\n\t\t\t}\n\t\t\treturn misses.length\n\t\t\t\t? fail(`expected ${ACCOUNT_REFUSALS.join(\" / \")}: ${misses.join(\"; \")}`)\n\t\t\t\t: pass(\n\t\t\t\t\t\t\"public-read issued; a closed memberspace and a personalspace refused\",\n\t\t\t\t\t);\n\t\t} finally {\n\t\t\tfor (const s of [open, closed, personal])\n\t\t\t\tawait deleteProbeSpace(ctx, s.uri);\n\t\t}\n\t},\n});\n\nconst credentialClaims = defineCheck({\n\tid: \"credential.claims\",\n\ttitle:\n\t\t\"A credential is signed by the authority for the space, bound to the requested key\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.space.authorizeSpaceSync\"),\n\t\tP(\"0016#space-credential\"),\n\t\tC(\"pds-space-uri-migration\"),\n\t],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst space = await createProbeSpace(ctx, publicRead());\n\t\ttry {\n\t\t\tconst credential = await obtainPublicCredential(ctx, space.uri);\n\t\t\tconst { header, payload } = decodeJwt(credential.credential);\n\t\t\tconst cnf = payload.cnf as { kid?: unknown } | undefined;\n\t\t\tconst problems: string[] = [];\n\t\t\tif (header.typ !== \"atproto-space-credential+jwt\")\n\t\t\t\tproblems.push(`typ ${String(header.typ)}`);\n\t\t\tif (header.kid !== \"#atproto\") problems.push(`kid ${String(header.kid)}`);\n\t\t\tif (payload.iss !== ctx.target.did)\n\t\t\t\tproblems.push(`iss ${String(payload.iss)}`);\n\t\t\t// `sub` is the space-ref in its at:space/ form, compared exactly.\n\t\t\tif (payload.sub !== spaceUri(ctx.target.did, space.skey))\n\t\t\t\tproblems.push(`sub ${String(payload.sub)}`);\n\t\t\tif (cnf?.kid !== credential.key.did)\n\t\t\t\tproblems.push(`cnf.kid ${String(cnf?.kid)}`);\n\t\t\t// Credentials carry no audience: each use is bound to one by its signature.\n\t\t\tif (\"aud\" in payload) problems.push(`has aud ${String(payload.aud)}`);\n\t\t\tif (typeof payload.jti !== \"string\" || !payload.jti)\n\t\t\t\tproblems.push(\"no jti\");\n\t\t\tconst iat = Number(payload.iat);\n\t\t\tconst exp = Number(payload.exp);\n\t\t\tif (!(exp > iat) || exp - iat > 3600)\n\t\t\t\tproblems.push(`lifetime ${exp - iat}s (max 3600)`);\n\t\t\treturn problems.length\n\t\t\t\t? fail(`credential claims: ${problems.join(\", \")}`, { header, payload })\n\t\t\t\t: pass(\n\t\t\t\t\t\t`typ/kid/iss/sub (at:space/ ref)/cnf correct, no aud, ${exp - iat}s lifetime`,\n\t\t\t\t\t);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nconst credentialDefaultLifetime = defineCheck({\n\tid: \"credential.default-lifetime\",\n\ttitle: \"Credentials live 600 seconds, the default\",\n\ttier: \"should\",\n\tcitations: [P(\"0016#space-credential\")],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst space = await createProbeSpace(ctx, publicRead());\n\t\ttry {\n\t\t\tconst { payload } = decodeJwt(\n\t\t\t\t(await obtainPublicCredential(ctx, space.uri)).credential,\n\t\t\t);\n\t\t\tconst lifetime = Number(payload.exp) - Number(payload.iat);\n\t\t\treturn lifetime === 600 ? pass(\"600s\") : fail(`${lifetime}s`);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nconst credentialSpaceRev = defineCheck({\n\tid: \"credential.space-rev\",\n\ttitle:\n\t\t\"authorizeSpaceSync reports the space's current revision, omitted before its first update\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.space.authorizeSpaceSync\"),\n\t\tP(\"0016#authorizing-space-sync\"),\n\t],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst space = await createProbeSpace(ctx, publicRead());\n\t\ttry {\n\t\t\tconst fresh = await requestCredential(ctx, space.uri);\n\t\t\tif (!fresh.credential)\n\t\t\t\treturn fail(\n\t\t\t\t\t`authorizeSpaceSync ${describe(fresh.result)}`,\n\t\t\t\t\tfresh.result.json,\n\t\t\t\t);\n\t\t\tif (fresh.spaceRev !== undefined)\n\t\t\t\treturn fail(\n\t\t\t\t\t`a space with no updates reported spaceRev ${fresh.spaceRev}`,\n\t\t\t\t);\n\t\t\tawait mustCreateRecord(ctx, space.uri, \"a\");\n\t\t\tconst after = await requestCredential(ctx, space.uri);\n\t\t\tif (!isTid(after.spaceRev))\n\t\t\t\treturn fail(\n\t\t\t\t\t`after a write, spaceRev is ${String(after.spaceRev)}`,\n\t\t\t\t\tafter.result.json,\n\t\t\t\t);\n\t\t\t// The space's current revision is the latest one listWriters sequenced.\n\t\t\tconst list = await credentialCall(\n\t\t\t\tctx,\n\t\t\t\tafter.credential!,\n\t\t\t\t\"com.atproto.space.listWriters\",\n\t\t\t\t{\n\t\t\t\t\tparams: { space: space.uri },\n\t\t\t\t\taudience: ctx.target.did,\n\t\t\t\t},\n\t\t\t);\n\t\t\tconst revs = (\n\t\t\t\t(list.json as { repos?: Array<{ spaceRev?: string }> } | undefined)\n\t\t\t\t\t?.repos ?? []\n\t\t\t).map((r) => r.spaceRev);\n\t\t\treturn revs.at(-1) === after.spaceRev\n\t\t\t\t? pass(\n\t\t\t\t\t\t`omitted before the first update; then ${after.spaceRev}, the latest sequenced revision`,\n\t\t\t\t\t)\n\t\t\t\t: fail(\n\t\t\t\t\t\t`spaceRev ${after.spaceRev} is not the latest listWriters revision ${revs.at(-1)}`,\n\t\t\t\t\t);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nconst credentialKeyP256 = defineCheck({\n\tid: \"credential.key-must-be-p256\",\n\ttitle:\n\t\t\"authorizeSpaceSync refuses a credentialKey that is not a P-256 did:key\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.space.authorizeSpaceSync\"),\n\t\tP(\"0016#credential-key-binding\"),\n\t],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst space = await createProbeSpace(ctx, publicRead());\n\t\ttry {\n\t\t\t// A well-formed secp256k1 did:key: valid syntax, wrong curve.\n\t\t\tconst k256 = formatDidKey(\n\t\t\t\t\"ES256K\",\n\t\t\t\tnew Uint8Array([0x02, ...crypto.getRandomValues(new Uint8Array(32))]),\n\t\t\t);\n\t\t\tconst bad = await requestCredential(ctx, space.uri, {\n\t\t\t\tcredentialKey: k256,\n\t\t\t});\n\t\t\tif (bad.credential)\n\t\t\t\treturn fail(\"issued a credential bound to a secp256k1 key\");\n\t\t\tconst notKey = await requestCredential(ctx, space.uri, {\n\t\t\t\tcredentialKey: ctx.target.did,\n\t\t\t});\n\t\t\tif (notKey.credential)\n\t\t\t\treturn fail(\"issued a credential bound to a non-key DID\");\n\t\t\tconst good = await requestCredential(ctx, space.uri);\n\t\t\treturn good.credential\n\t\t\t\t? pass(\n\t\t\t\t\t\t`refused secp256k1 (${describe(bad.result)}) and non-key (${describe(notKey.result)}); P-256 issued`,\n\t\t\t\t\t)\n\t\t\t\t: fail(\n\t\t\t\t\t\t`positive control failed: ${describe(good.result)}`,\n\t\t\t\t\t\tgood.result.json,\n\t\t\t\t\t);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nconst credentialGarbageDelegation = defineCheck({\n\tid: \"credential.garbage-delegation-refused\",\n\ttitle: \"A malformed delegation token is refused with InvalidDelegationToken\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.space.authorizeSpaceSync@error:InvalidDelegationToken\"),\n\t],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst space = await createProbeSpace(ctx, memberspace());\n\t\ttry {\n\t\t\tconst res = await requestCredential(ctx, space.uri, {\n\t\t\t\tdelegationToken: \"not.a.token\",\n\t\t\t});\n\t\t\tif (res.credential)\n\t\t\t\treturn fail(\"issued a credential for a garbage delegation token\");\n\t\t\treturn res.result.error === \"InvalidDelegationToken\"\n\t\t\t\t? pass(\"refused with InvalidDelegationToken\")\n\t\t\t\t: fail(\n\t\t\t\t\t\t`refused with ${describe(res.result)}, expected InvalidDelegationToken`,\n\t\t\t\t\t\tres.result.json,\n\t\t\t\t\t);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\n/** A client_id no host serves: an app the target can never resolve. */\nconst UNRESOLVABLE_CLIENT =\n\t\"https://app.space-conformance.invalid/client-metadata.json\";\n\n/**\n * A structurally valid client attestation for a client nobody can resolve:\n * typed, addressed to the space host, iss = sub = an unresolvable\n * client_id, signed by a throwaway key. Only verification can refuse it.\n */\nasync function unverifiableAttestation(authority: string): Promise<string> {\n\tconst key = await createCredentialKey();\n\treturn signClientAttestation({\n\t\tclientId: UNRESOLVABLE_CLIENT,\n\t\taud: spaceHostAud(authority),\n\t\tkid: \"key-1\",\n\t\tsign: (bytes) => key.sign(bytes),\n\t});\n}\n\nconst attestationCitations = [\n\tL(\"com.atproto.space.authorizeSpaceSync@error:InvalidClientAttestation\"),\n\tP(\"0016#client-attestation\"),\n];\n\n/** Said by a refusal check that could not run its success-path control. */\nconst NO_VERIFIABLE_CLIENT =\n\t\"the success path was not checked: no syncer inbox to publish a verifiable client\";\n\n/**\n * The attestation success path, when the harness serves a syncer inbox: an\n * attestation signed by the inbox's published client key, for `space`,\n * must issue a credential. A refusal check runs it first, so a host that\n * refuses every attestation — verification broken — fails rather than\n * passing on the refusals alone. Returns the control's detail, or a failure.\n */\nasync function attestationControl(\n\tctx: CheckContext,\n\tspace: string,\n): Promise<{ detail: string } | { failure: ReturnType<typeof fail> }> {\n\tconst inbox = ctx.syncerInbox;\n\tif (!inbox) return { detail: NO_VERIFIABLE_CLIENT };\n\tconst res = await requestCredential(ctx, space, {\n\t\tclientAttestation: await inbox.attest(spaceHostAud(ctx.target.did)),\n\t});\n\treturn res.credential\n\t\t? { detail: `a valid attestation from ${inbox.clientId} issued` }\n\t\t: {\n\t\t\t\tfailure: fail(\n\t\t\t\t\t`positive control failed: a valid attestation from ${inbox.clientId} was refused (${describe(res.result)}), so a refusal proves nothing about verification`,\n\t\t\t\t\tres.result.json,\n\t\t\t\t),\n\t\t\t};\n}\n\nconst credentialUnverifiableAttestation = defineCheck({\n\tid: \"credential.unverifiable-attestation-refused\",\n\ttitle:\n\t\t\"A client attestation that cannot be verified is refused with InvalidClientAttestation\",\n\ttier: \"must\",\n\tcitations: attestationCitations,\n\tneeds: [\"operator\"],\n\tuses: [\"syncer-inbox\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\t// A public-read space would issue without it, so the refusal can only\n\t\t// be the attestation's.\n\t\tconst space = await createProbeSpace(ctx, publicRead());\n\t\ttry {\n\t\t\tconst control = await attestationControl(ctx, space.uri);\n\t\t\tif (\"failure\" in control) return control.failure;\n\t\t\tconst res = await requestCredential(ctx, space.uri, {\n\t\t\t\tclientAttestation: await unverifiableAttestation(ctx.target.did),\n\t\t\t});\n\t\t\tif (res.credential)\n\t\t\t\treturn fail(\n\t\t\t\t\t\"issued a credential on an unverifiable client attestation\",\n\t\t\t\t);\n\t\t\treturn res.result.error === \"InvalidClientAttestation\"\n\t\t\t\t? pass(`refused with InvalidClientAttestation; ${control.detail}`)\n\t\t\t\t: fail(\n\t\t\t\t\t\t`refused with ${describe(res.result)}, expected InvalidClientAttestation`,\n\t\t\t\t\t\tres.result.json,\n\t\t\t\t\t);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nconst credentialGarbageAttestation = defineCheck({\n\tid: \"credential.garbage-attestation-refused\",\n\ttitle:\n\t\t\"A malformed client attestation is refused with InvalidClientAttestation\",\n\ttier: \"must\",\n\tcitations: attestationCitations,\n\tneeds: [\"operator\"],\n\tuses: [\"syncer-inbox\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst space = await createProbeSpace(ctx, publicRead());\n\t\ttry {\n\t\t\tconst control = await attestationControl(ctx, space.uri);\n\t\t\tif (\"failure\" in control) return control.failure;\n\t\t\tconst res = await requestCredential(ctx, space.uri, {\n\t\t\t\tclientAttestation: \"not.an.attestation\",\n\t\t\t});\n\t\t\tif (res.credential)\n\t\t\t\treturn fail(\"issued a credential despite a garbage client attestation\");\n\t\t\treturn res.result.error === \"InvalidClientAttestation\"\n\t\t\t\t? pass(`refused with InvalidClientAttestation; ${control.detail}`)\n\t\t\t\t: fail(\n\t\t\t\t\t\t`refused with ${describe(res.result)}, expected InvalidClientAttestation`,\n\t\t\t\t\t\tres.result.json,\n\t\t\t\t\t);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nconst allowedAppsCitations = [\n\tL(\"com.atproto.space.authorizeSpaceSync@error:AppNotAuthorized\"),\n\tL(\"com.atproto.memberspace.policy\"),\n\tP(\"0016#memberspace\"),\n\tP(\"0016#client-attestation\"),\n];\n\nconst credentialAllowedApps = defineCheck({\n\tid: \"credential.allowed-apps-gate\",\n\ttitle: \"A memberspace with allowedApps refuses an unattested app\",\n\ttier: \"must\",\n\tcitations: allowedAppsCitations,\n\tneeds: [\"operator\"],\n\tuses: [\"syncer-inbox\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\t// publicRead clears the account perimeter, so only the app perimeter is\n\t\t// left to refuse; NotAuthorized may stand in for AppNotAuthorized. With\n\t\t// an inbox its client is listed too, and must get in — so a gate that\n\t\t// refuses everyone does not pass.\n\t\tconst inbox = ctx.syncerInbox;\n\t\tconst space = await createProbeSpace(\n\t\t\tctx,\n\t\t\tmemberspace({\n\t\t\t\tpublicRead: true,\n\t\t\t\tallowedApps: [UNRESOLVABLE_CLIENT, ...(inbox ? [inbox.clientId] : [])],\n\t\t\t}),\n\t\t);\n\t\ttry {\n\t\t\tconst res = await requestCredential(ctx, space.uri);\n\t\t\tif (res.credential)\n\t\t\t\treturn fail(\"issued a credential to an app outside allowedApps\");\n\t\t\tif (!errorIs(\"AppNotAuthorized\", \"NotAuthorized\")(res.result))\n\t\t\t\treturn fail(\n\t\t\t\t\t`refused with ${describe(res.result)}, expected AppNotAuthorized`,\n\t\t\t\t\tres.result.json,\n\t\t\t\t);\n\t\t\tconst control = await attestationControl(ctx, space.uri);\n\t\t\tif (\"failure\" in control) return control.failure;\n\t\t\treturn pass(\n\t\t\t\t`unattested request refused with ${res.result.error}; ${inbox ? \"a valid attestation from a listed app issued\" : control.detail}`,\n\t\t\t);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nconst credentialValidAttestation = defineCheck({\n\tid: \"credential.valid-attestation-issues\",\n\ttitle:\n\t\t\"A verifiable client attestation from an app in allowedApps obtains a credential\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.space.authorizeSpaceSync\"),\n\t\tL(\"com.atproto.memberspace.policy\"),\n\t\tP(\"0016#client-attestation\"),\n\t\tP(\"0016#memberspace\"),\n\t],\n\tneeds: [\"operator\", \"syncer-inbox\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\t// The host must fetch the inbox's client metadata, take the key its\n\t\t// jwks publishes and verify the signature: the one path no refusal\n\t\t// exercises. publicRead clears the account perimeter, so only the\n\t\t// app perimeter decides.\n\t\tconst inbox = ctx.syncerInbox!;\n\t\tconst space = await createProbeSpace(\n\t\t\tctx,\n\t\t\tmemberspace({ publicRead: true, allowedApps: [inbox.clientId] }),\n\t\t);\n\t\ttry {\n\t\t\tconst unattested = await requestCredential(ctx, space.uri);\n\t\t\tif (unattested.credential)\n\t\t\t\treturn fail(\n\t\t\t\t\t\"issued without an attestation, so allowedApps is not enforced and issuance proves nothing\",\n\t\t\t\t);\n\t\t\tconst res = await requestCredential(ctx, space.uri, {\n\t\t\t\tclientAttestation: await inbox.attest(spaceHostAud(ctx.target.did)),\n\t\t\t});\n\t\t\treturn res.credential\n\t\t\t\t? pass(\n\t\t\t\t\t\t`unattested refused (${describe(unattested.result)}); attested as ${inbox.clientId}, issued`,\n\t\t\t\t\t)\n\t\t\t\t: fail(\n\t\t\t\t\t\t`a valid attestation from the listed ${inbox.clientId} was refused: ${describe(res.result)}`,\n\t\t\t\t\t\tres.result.json,\n\t\t\t\t\t);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nconst credentialUnlistedAttestation = defineCheck({\n\tid: \"credential.valid-attestation-unlisted-refused\",\n\ttitle:\n\t\t\"A verifiable client attestation from an app outside allowedApps is refused with AppNotAuthorized\",\n\ttier: \"must\",\n\tcitations: allowedAppsCitations,\n\tneeds: [\"operator\", \"syncer-inbox\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\t// The same valid attestation that gets into a space listing the app\n\t\t// is refused by one listing only another: the refusal is the\n\t\t// allow-list's, not a verification failure.\n\t\tconst inbox = ctx.syncerInbox!;\n\t\tconst listed = await createProbeSpace(\n\t\t\tctx,\n\t\t\tmemberspace({ publicRead: true, allowedApps: [inbox.clientId] }),\n\t\t);\n\t\tconst unlisted = await createProbeSpace(\n\t\t\tctx,\n\t\t\tmemberspace({ publicRead: true, allowedApps: [UNRESOLVABLE_CLIENT] }),\n\t\t);\n\t\ttry {\n\t\t\tconst aud = spaceHostAud(ctx.target.did);\n\t\t\tconst ok = await requestCredential(ctx, listed.uri, {\n\t\t\t\tclientAttestation: await inbox.attest(aud),\n\t\t\t});\n\t\t\tif (!ok.credential)\n\t\t\t\treturn fail(\n\t\t\t\t\t`positive control failed: the space listing ${inbox.clientId} refused its valid attestation (${describe(ok.result)})`,\n\t\t\t\t\tok.result.json,\n\t\t\t\t);\n\t\t\tconst res = await requestCredential(ctx, unlisted.uri, {\n\t\t\t\tclientAttestation: await inbox.attest(aud),\n\t\t\t});\n\t\t\tif (res.credential)\n\t\t\t\treturn fail(\n\t\t\t\t\t\"issued a credential to a verified app outside allowedApps\",\n\t\t\t\t);\n\t\t\treturn res.result.error === \"AppNotAuthorized\"\n\t\t\t\t? pass(\n\t\t\t\t\t\t\"issued where the app is listed; refused with AppNotAuthorized where it is not\",\n\t\t\t\t\t)\n\t\t\t\t: fail(\n\t\t\t\t\t\t`refused with ${describe(res.result)}, expected AppNotAuthorized`,\n\t\t\t\t\t\tres.result.json,\n\t\t\t\t\t);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, listed.uri);\n\t\t\tawait deleteProbeSpace(ctx, unlisted.uri);\n\t\t}\n\t},\n});\n\nconst credentialDeletedSpace = defineCheck({\n\tid: \"credential.deleted-space\",\n\ttitle:\n\t\t\"deleteSpace removes the authority's repo, and authorizeSpaceSync then answers SpaceDeleted\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.space.deleteSpace\"),\n\t\tL(\"com.atproto.space.authorizeSpaceSync@error:SpaceDeleted\"),\n\t\tP(\"0016#space-deletion\"),\n\t],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst space = await createProbeSpace(ctx, publicRead());\n\t\tawait mustCreateRecord(ctx, space.uri, \"mine\");\n\t\tconst before = await requestCredential(ctx, space.uri);\n\t\tif (!before.credential) {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t\treturn fail(\n\t\t\t\t`could not obtain a credential before deletion (${describe(before.result)})`,\n\t\t\t);\n\t\t}\n\t\tconst del = await xrpcPost(\n\t\t\tasOperator(ctx),\n\t\t\t\"com.atproto.space.deleteSpace\",\n\t\t\t{ space: space.uri },\n\t\t);\n\t\tif (del.status !== 200)\n\t\t\treturn fail(`deleteSpace ${describe(del)}`, del.json);\n\t\t// \"Delete a space, along with the authority's space repo.\"\n\t\tconst own = await xrpcGet(asOperator(ctx), \"com.atproto.space.getRecord\", {\n\t\t\tspace: space.uri,\n\t\t\trepo: ctx.target.did,\n\t\t\tcollection: POST,\n\t\t\trkey: \"mine\",\n\t\t});\n\t\tif (own.status === 200)\n\t\t\treturn fail(\"the authority's own record survived deleteSpace\", own.json);\n\t\t// \"regardless of the request's authorization\": tokenless, and with a\n\t\t// garbage delegation token.\n\t\tconst tokenless = await requestCredential(ctx, space.uri);\n\t\tconst garbage = await requestCredential(ctx, space.uri, {\n\t\t\tdelegationToken: \"not.a.token\",\n\t\t});\n\t\tif (tokenless.credential)\n\t\t\treturn fail(\"a deleted space still issued a credential\");\n\t\treturn tokenless.result.error === \"SpaceDeleted\" &&\n\t\t\tgarbage.result.error === \"SpaceDeleted\"\n\t\t\t? pass(\n\t\t\t\t\t\"own records gone; answered SpaceDeleted, tokenless and with a bad token\",\n\t\t\t\t)\n\t\t\t: fail(\n\t\t\t\t\t`answered ${describe(tokenless.result)} tokenless, ${describe(garbage.result)} with a bad token; expected SpaceDeleted`,\n\t\t\t\t);\n\t},\n});\n\nconst credentialUnconfirmedRegistration = defineCheck({\n\tid: \"credential.unconfirmed-registration-refused\",\n\ttitle:\n\t\t\"A notify endpoint that does not confirm the registration gets RegistrationNotConfirmed\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.space.authorizeSpaceSync@error:RegistrationNotConfirmed\"),\n\t\tP(\"0016#registering-for-notifications\"),\n\t],\n\tneeds: [\"operator\"],\n\tuses: [\"syncer-inbox\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst inbox = ctx.syncerInbox;\n\t\tconst space = await createProbeSpace(ctx, publicRead());\n\t\tconst randomToken = () =>\n\t\t\ttoBase64Url(crypto.getRandomValues(new Uint8Array(32)));\n\t\ttry {\n\t\t\t// With an inbox, the success path first: a host whose\n\t\t\t// confirmRegistration never succeeds would refuse every\n\t\t\t// registration, and pass on the refusals alone.\n\t\t\tconst refusals: Array<[string, { endpoint: string; token: string }]> = [\n\t\t\t\t// An endpoint nobody serves can't echo the challenge.\n\t\t\t\t[\n\t\t\t\t\t\"an unreachable endpoint\",\n\t\t\t\t\t{\n\t\t\t\t\t\tendpoint: \"https://syncer.space-conformance.invalid\",\n\t\t\t\t\t\ttoken: randomToken(),\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t];\n\t\t\tif (inbox) {\n\t\t\t\tconst ok = await requestCredential(ctx, space.uri, {\n\t\t\t\t\tnotify: {\n\t\t\t\t\t\tendpoint: inbox.endpoint,\n\t\t\t\t\t\ttoken: inbox.issueToken(space.uri),\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\tif (!ok.credential)\n\t\t\t\t\treturn fail(\n\t\t\t\t\t\t`positive control failed: a registration the inbox confirms was refused (${describe(ok.result)})`,\n\t\t\t\t\t\tok.result.json,\n\t\t\t\t\t);\n\t\t\t\t// Reachable, but refusing to confirm a token it never issued.\n\t\t\t\trefusals.push([\n\t\t\t\t\t\"a token the endpoint did not issue\",\n\t\t\t\t\t{ endpoint: inbox.endpoint, token: randomToken() },\n\t\t\t\t]);\n\t\t\t}\n\t\t\tconst misses: string[] = [];\n\t\t\tfor (const [label, notify] of refusals) {\n\t\t\t\tconst res = await requestCredential(ctx, space.uri, { notify });\n\t\t\t\tif (res.credential) misses.push(`${label} → issued`);\n\t\t\t\telse if (res.result.error !== \"RegistrationNotConfirmed\")\n\t\t\t\t\tmisses.push(`${label} → ${describe(res.result)}`);\n\t\t\t}\n\t\t\tif (misses.length)\n\t\t\t\treturn fail(`expected RegistrationNotConfirmed: ${misses.join(\"; \")}`);\n\t\t\treturn pass(\n\t\t\t\tinbox\n\t\t\t\t\t? \"a confirmed registration issued; an unreachable endpoint and an unissued token were refused with RegistrationNotConfirmed\"\n\t\t\t\t\t: \"an unreachable endpoint was refused with RegistrationNotConfirmed; the success path was not checked (no syncer inbox)\",\n\t\t\t);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\n// --- delegation (the target's own tokens) --------------------------------\n\nconst credentialSelfRoundTrip = defineCheck({\n\tid: \"credential.self-round-trip\",\n\ttitle:\n\t\t\"Operator obtains a credential via getDelegationToken and reads with it\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.space.getDelegationToken\"),\n\t\tL(\"com.atproto.space.authorizeSpaceSync\"),\n\t\tL(\"com.atproto.space.getRecord\"),\n\t\tP(\"0016#credential-flow\"),\n\t],\n\tneeds: [\"operator\", \"pds-delegation\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\t// A closed memberspace: only the delegation token can get the operator in.\n\t\tconst space = await createProbeSpace(ctx, memberspace());\n\t\ttry {\n\t\t\tawait mustCreateRecord(ctx, space.uri, \"shared\", \"mine\");\n\t\t\tconst { result, credential, delegation } =\n\t\t\t\tawait obtainCredentialViaDelegation(ctx, space.uri);\n\t\t\tif (delegation.status !== 200)\n\t\t\t\treturn fail(\n\t\t\t\t\t`getDelegationToken ${describe(delegation)}`,\n\t\t\t\t\tdelegation.json,\n\t\t\t\t);\n\t\t\tif (!credential)\n\t\t\t\treturn fail(`authorizeSpaceSync ${describe(result)}`, result.json);\n\t\t\tconst read = await readShared(ctx, credential, space.uri);\n\t\t\tif (read.status !== 200)\n\t\t\t\treturn fail(`credential read failed: ${describe(read)}`, read.json);\n\t\t\treturn read.headers.get(\"atproto-space-record\") &&\n\t\t\t\tread.headers.get(\"signature\")\n\t\t\t\t? pass(\n\t\t\t\t\t\t\"delegation → credential → read carrying an Atproto-Space-Record MAC (presence only here; mac.record-verifies checks it with the alpha libs)\",\n\t\t\t\t\t)\n\t\t\t\t: fail(\"the credentialed read carried no Atproto-Space-Record MAC\");\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nconst credentialPersonalOwner = defineCheck({\n\tid: \"policy.personalspace-owner-admitted\",\n\ttitle:\n\t\t\"A personalspace issues its authority a credential through a delegation token\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.personalspace.policy\"),\n\t\tL(\"com.atproto.space.authorizeSpaceSync\"),\n\t\tP(\"0016#personalspace\"),\n\t],\n\tneeds: [\"operator\", \"pds-delegation\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\t// The other half of policy.personalspace-owner-only: a personalspace\n\t\t// that refuses everyone, its authority included, passes that check.\n\t\tconst space = await createProbeSpace(ctx, personalspace());\n\t\ttry {\n\t\t\tawait mustCreateRecord(ctx, space.uri, \"shared\", \"mine\");\n\t\t\tconst tokenless = await requestCredential(ctx, space.uri);\n\t\t\tif (tokenless.credential)\n\t\t\t\treturn fail(\n\t\t\t\t\t\"a personalspace issued a credential with no delegation token\",\n\t\t\t\t);\n\t\t\tconst { result, credential, delegation } =\n\t\t\t\tawait obtainCredentialViaDelegation(ctx, space.uri);\n\t\t\tif (delegation.status !== 200)\n\t\t\t\treturn fail(\n\t\t\t\t\t`getDelegationToken ${describe(delegation)}`,\n\t\t\t\t\tdelegation.json,\n\t\t\t\t);\n\t\t\tif (!credential)\n\t\t\t\treturn fail(\n\t\t\t\t\t`the authority was refused its own personalspace: ${describe(result)}`,\n\t\t\t\t\tresult.json,\n\t\t\t\t);\n\t\t\tconst read = await readShared(ctx, credential, space.uri);\n\t\t\treturn read.status === 200\n\t\t\t\t? pass(\n\t\t\t\t\t\t`tokenless refused (${describe(tokenless.result)}); the authority's delegation token issued, and the credential reads`,\n\t\t\t\t\t)\n\t\t\t\t: fail(\n\t\t\t\t\t\t`the authority's credential could not read: ${describe(read)}`,\n\t\t\t\t\t\tread.json,\n\t\t\t\t\t);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nconst delegationClaims = defineCheck({\n\tid: \"delegation.token-claims\",\n\ttitle:\n\t\t\"getDelegationToken mints a token for the space's #atproto_pds, signed by #atproto\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.space.getDelegationToken\"),\n\t\tP(\"0016#delegation-token\"),\n\t\tC(\"pds-space-uri-migration\"),\n\t],\n\tneeds: [\"operator\", \"pds-delegation\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst space = await createProbeSpace(ctx, memberspace());\n\t\ttry {\n\t\t\tconst res = await xrpcGet(\n\t\t\t\tasOperator(ctx),\n\t\t\t\t\"com.atproto.space.getDelegationToken\",\n\t\t\t\t{ space: space.uri },\n\t\t\t);\n\t\t\tif (res.status !== 200)\n\t\t\t\treturn fail(`getDelegationToken ${describe(res)}`, res.json);\n\t\t\tconst { header, payload } = decodeJwt(\n\t\t\t\t(res.json as { token: string }).token,\n\t\t\t);\n\t\t\tconst problems: string[] = [];\n\t\t\tif (header.typ !== \"atproto-space-delegation+jwt\")\n\t\t\t\tproblems.push(`typ ${String(header.typ)}`);\n\t\t\tif (header.kid !== \"#atproto\") problems.push(`kid ${String(header.kid)}`);\n\t\t\tif (payload.iss !== ctx.target.did)\n\t\t\t\tproblems.push(`iss ${String(payload.iss)}`);\n\t\t\t// `sub` is the space-ref in its at:space/ form, compared exactly.\n\t\t\tif (payload.sub !== spaceUri(ctx.target.did, space.skey))\n\t\t\t\tproblems.push(`sub ${String(payload.sub)}`);\n\t\t\tif (payload.aud !== `${ctx.target.did}#atproto_pds`)\n\t\t\t\tproblems.push(`aud ${String(payload.aud)}`);\n\t\t\tif (\"lxm\" in payload) problems.push(\"has an lxm claim\");\n\t\t\tif (typeof payload.jti !== \"string\" || !payload.jti)\n\t\t\t\tproblems.push(\"no jti\");\n\t\t\tif (!(Number(payload.exp) > Math.floor(Date.now() / 1000) - 5))\n\t\t\t\tproblems.push(\"already expired\");\n\t\t\treturn problems.length\n\t\t\t\t? fail(`delegation token: ${problems.join(\", \")}`, { header, payload })\n\t\t\t\t: pass(\"typ/kid/iss/sub (at:space/ ref)/aud as specified, no lxm\");\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nconst delegationReplay = defineCheck({\n\tid: \"delegation.replay-refused\",\n\ttitle: \"A delegation token cannot be used twice\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.space.authorizeSpaceSync@error:InvalidDelegationToken\"),\n\t\tP(\"0016#delegation-token\"),\n\t],\n\tneeds: [\"operator\", \"pds-delegation\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst space = await createProbeSpace(ctx, memberspace());\n\t\ttry {\n\t\t\tconst res = await xrpcGet(\n\t\t\t\tasOperator(ctx),\n\t\t\t\t\"com.atproto.space.getDelegationToken\",\n\t\t\t\t{ space: space.uri },\n\t\t\t);\n\t\t\tif (res.status !== 200)\n\t\t\t\treturn fail(`getDelegationToken ${describe(res)}`, res.json);\n\t\t\tconst delegationToken = (res.json as { token: string }).token;\n\t\t\tconst first = await requestCredential(ctx, space.uri, {\n\t\t\t\tdelegationToken,\n\t\t\t});\n\t\t\tif (!first.credential)\n\t\t\t\treturn fail(\n\t\t\t\t\t`first exchange failed (${describe(first.result)}); cannot test replay`,\n\t\t\t\t);\n\t\t\tconst second = await requestCredential(ctx, space.uri, {\n\t\t\t\tdelegationToken,\n\t\t\t});\n\t\t\tif (second.credential)\n\t\t\t\treturn fail(\"a replayed delegation token was accepted\");\n\t\t\treturn second.result.error === \"InvalidDelegationToken\"\n\t\t\t\t? pass(\"replay refused with InvalidDelegationToken\")\n\t\t\t\t: fail(\n\t\t\t\t\t\t`replay refused with ${describe(second.result)}, expected InvalidDelegationToken`,\n\t\t\t\t\t);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nconst delegationWrongSpace = defineCheck({\n\tid: \"delegation.wrong-space-refused\",\n\ttitle: \"A delegation token for one space is refused for another\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.space.authorizeSpaceSync@error:InvalidDelegationToken\"),\n\t\tP(\"0016#delegation-token\"),\n\t],\n\tneeds: [\"operator\", \"pds-delegation\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst a = await createProbeSpace(ctx, memberspace());\n\t\tconst b = await createProbeSpace(ctx, memberspace());\n\t\ttry {\n\t\t\tconst res = await xrpcGet(\n\t\t\t\tasOperator(ctx),\n\t\t\t\t\"com.atproto.space.getDelegationToken\",\n\t\t\t\t{ space: a.uri },\n\t\t\t);\n\t\t\tif (res.status !== 200)\n\t\t\t\treturn fail(`getDelegationToken ${describe(res)}`, res.json);\n\t\t\tconst cross = await requestCredential(ctx, b.uri, {\n\t\t\t\tdelegationToken: (res.json as { token: string }).token,\n\t\t\t});\n\t\t\tif (cross.credential)\n\t\t\t\treturn fail(\"a token for space A issued a credential for space B\");\n\t\t\treturn cross.result.error === \"InvalidDelegationToken\"\n\t\t\t\t? pass(\"refused with InvalidDelegationToken\")\n\t\t\t\t: fail(\n\t\t\t\t\t\t`refused with ${describe(cross.result)}, expected InvalidDelegationToken`,\n\t\t\t\t\t);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, a.uri);\n\t\t\tawait deleteProbeSpace(ctx, b.uri);\n\t\t}\n\t},\n});\n\n// --- presentation -----------------------------------------------------\n\nconst presentationCitations = [\n\tL(\"com.atproto.space.getRecord\"),\n\tL(\"com.atproto.space.listWriters\"),\n\tP(\"0016#presenting-a-space-credential\"),\n];\n\nconst credentialSignatureRequired = defineCheck({\n\tid: \"credential.signature-required\",\n\ttitle: \"A credential presented without its HTTP signature is refused\",\n\ttier: \"must\",\n\tcitations: presentationCitations,\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\treturn withPublicSpace(ctx, async (space, credential) => {\n\t\t\tconst ok = await readShared(ctx, credential, space.uri);\n\t\t\tif (ok.status !== 200)\n\t\t\t\treturn fail(`positive control failed: ${describe(ok)}`, ok.json);\n\t\t\tconst bare = await readShared(ctx, credential, space.uri, {\n\t\t\t\tunsigned: true,\n\t\t\t});\n\t\t\treturn refused(bare.status)\n\t\t\t\t? pass(`signed read 200; unsigned read refused (${describe(bare)})`)\n\t\t\t\t: fail(\n\t\t\t\t\t\t`an unsigned credential read returned ${describe(bare)}`,\n\t\t\t\t\t\tbare.json,\n\t\t\t\t\t);\n\t\t});\n\t},\n});\n\nconst credentialSignatureByTag = defineCheck({\n\tid: \"credential.signature-found-by-tag\",\n\ttitle:\n\t\t\"The credential signature is found by its tag under any label; other parameters are ignored\",\n\ttier: \"must\",\n\tcitations: presentationCitations,\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\treturn withPublicSpace(ctx, async (space, credential) => {\n\t\t\tconst now = Math.floor(Date.now() / 1000);\n\t\t\tconst variants: Array<[string, CredentialCallOptions[\"signature\"]]> = [\n\t\t\t\t[\"label 'x7'\", { label: \"x7\" }],\n\t\t\t\t[\n\t\t\t\t\t\"created and nonce parameters\",\n\t\t\t\t\t{\n\t\t\t\t\t\tparams: [\n\t\t\t\t\t\t\t[\"created\", now],\n\t\t\t\t\t\t\t[\"nonce\", \"abc\"],\n\t\t\t\t\t\t],\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\t[\n\t\t\t\t\t\"keyid = cnf.kid and alg = ecdsa-p256-sha256\",\n\t\t\t\t\t{\n\t\t\t\t\t\tparams: [\n\t\t\t\t\t\t\t[\"keyid\", credential.key.did],\n\t\t\t\t\t\t\t[\"alg\", \"ecdsa-p256-sha256\"],\n\t\t\t\t\t\t],\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t];\n\t\t\tconst misses: string[] = [];\n\t\t\tfor (const [label, signature] of variants) {\n\t\t\t\tconst res = await readShared(ctx, credential, space.uri, { signature });\n\t\t\t\tif (res.status !== 200) misses.push(`${label} → ${describe(res)}`);\n\t\t\t}\n\t\t\t// A second, unrelated signature with another tag alongside is ignored.\n\t\t\tconst extra = await readShared(ctx, credential, space.uri, {\n\t\t\t\tsignatureHeaders: async (h) => {\n\t\t\t\t\tconst other = await credentialSigMembers(credential.key, {\n\t\t\t\t\t\tauthorization: h.authorization!,\n\t\t\t\t\t\taudience: h[\"atproto-space-audience\"]!,\n\t\t\t\t\t\tlabel: \"other\",\n\t\t\t\t\t\ttag: \"some-other-app\",\n\t\t\t\t\t});\n\t\t\t\t\treturn {\n\t\t\t\t\t\t...h,\n\t\t\t\t\t\t\"signature-input\": `${h[\"signature-input\"]}, ${other.input}`,\n\t\t\t\t\t\tsignature: `${h.signature}, ${other.signature}`,\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t});\n\t\t\tif (extra.status !== 200)\n\t\t\t\tmisses.push(\n\t\t\t\t\t`with an extra differently-tagged signature → ${describe(extra)}`,\n\t\t\t\t);\n\t\t\treturn misses.length\n\t\t\t\t? fail(`refused a valid signature: ${misses.join(\"; \")}`)\n\t\t\t\t: pass(\n\t\t\t\t\t\t\"accepted under another label, with extra parameters, and beside another tag's signature\",\n\t\t\t\t\t);\n\t\t});\n\t},\n});\n\nconst credentialSignatureRequirements = defineCheck({\n\tid: \"credential.signature-requirements\",\n\ttitle:\n\t\t\"A credential signature with the wrong components, keyid, alg or count is refused\",\n\ttier: \"must\",\n\tcitations: presentationCitations,\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\treturn withPublicSpace(ctx, async (space, credential) => {\n\t\t\tconst ok = await readShared(ctx, credential, space.uri);\n\t\t\tif (ok.status !== 200)\n\t\t\t\treturn fail(`positive control failed: ${describe(ok)}`, ok.json);\n\t\t\tconst other = await createCredentialKey();\n\t\t\tconst variants: Array<[string, Omit<CredentialCallOptions, \"params\">]> = [\n\t\t\t\t[\n\t\t\t\t\t\"covers only authorization\",\n\t\t\t\t\t{ signature: { components: [\"authorization\"] } },\n\t\t\t\t],\n\t\t\t\t[\n\t\t\t\t\t\"components out of order\",\n\t\t\t\t\t{\n\t\t\t\t\t\tsignature: {\n\t\t\t\t\t\t\tcomponents: [\"atproto-space-audience\", \"authorization\"],\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\t[\n\t\t\t\t\t\"keyid of another key\",\n\t\t\t\t\t{ signature: { params: [[\"keyid\", other.did]] } },\n\t\t\t\t],\n\t\t\t\t[\n\t\t\t\t\t\"alg hmac-sha256\",\n\t\t\t\t\t{ signature: { params: [[\"alg\", \"hmac-sha256\"]] } },\n\t\t\t\t],\n\t\t\t\t[\n\t\t\t\t\t\"no atproto-space-credential tag\",\n\t\t\t\t\t{ signature: { tag: \"something-else\" } },\n\t\t\t\t],\n\t\t\t\t[\n\t\t\t\t\t\"two tagged signatures\",\n\t\t\t\t\t{\n\t\t\t\t\t\tsignatureHeaders: async (h) => {\n\t\t\t\t\t\t\tconst dup = await credentialSigMembers(credential.key, {\n\t\t\t\t\t\t\t\tauthorization: h.authorization!,\n\t\t\t\t\t\t\t\taudience: h[\"atproto-space-audience\"]!,\n\t\t\t\t\t\t\t\tlabel: \"dup\",\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t...h,\n\t\t\t\t\t\t\t\t\"signature-input\": `${h[\"signature-input\"]}, ${dup.input}`,\n\t\t\t\t\t\t\t\tsignature: `${h.signature}, ${dup.signature}`,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t];\n\t\t\tconst misses: string[] = [];\n\t\t\tfor (const [label, opts] of variants) {\n\t\t\t\tconst res = await readShared(ctx, credential, space.uri, opts);\n\t\t\t\tif (!refused(res.status)) misses.push(`${label} → ${describe(res)}`);\n\t\t\t}\n\t\t\treturn misses.length\n\t\t\t\t? fail(`accepted: ${misses.join(\"; \")}`)\n\t\t\t\t: pass(\"every malformed signature was refused\");\n\t\t});\n\t},\n});\n\nconst credentialAudienceBound = defineCheck({\n\tid: \"credential.audience-bound\",\n\ttitle: \"A credential signed for another audience is refused\",\n\ttier: \"must\",\n\tcitations: presentationCitations,\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\treturn withPublicSpace(ctx, async (space, credential) => {\n\t\t\tconst ok = await readShared(ctx, credential, space.uri);\n\t\t\tif (ok.status !== 200)\n\t\t\t\treturn fail(`positive control failed: ${describe(ok)}`, ok.json);\n\t\t\tconst misaddressed = await readShared(ctx, credential, space.uri, {\n\t\t\t\taudience: FOREIGN_DID,\n\t\t\t});\n\t\t\tif (!refused(misaddressed.status))\n\t\t\t\treturn fail(\n\t\t\t\t\t`a misaddressed repo-host read returned ${describe(misaddressed)}`,\n\t\t\t\t\tmisaddressed.json,\n\t\t\t\t);\n\t\t\t// The same at the space host, whose audience is the authority.\n\t\t\tconst listWriters = (audience: string) =>\n\t\t\t\tcredentialCall(ctx, credential, \"com.atproto.space.listWriters\", {\n\t\t\t\t\tparams: { space: space.uri },\n\t\t\t\t\taudience,\n\t\t\t\t});\n\t\t\tconst hostOk = await listWriters(ctx.target.did);\n\t\t\tif (hostOk.status !== 200)\n\t\t\t\treturn fail(\n\t\t\t\t\t`listWriters positive control failed: ${describe(hostOk)}`,\n\t\t\t\t\thostOk.json,\n\t\t\t\t);\n\t\t\tconst hostWrong = await listWriters(FOREIGN_DID);\n\t\t\treturn refused(hostWrong.status)\n\t\t\t\t? pass(\n\t\t\t\t\t\t`refused other audiences at the repo host (${describe(misaddressed)}) and space host (${describe(hostWrong)})`,\n\t\t\t\t\t)\n\t\t\t\t: fail(\n\t\t\t\t\t\t`a misaddressed listWriters returned ${describe(hostWrong)}`,\n\t\t\t\t\t\thostWrong.json,\n\t\t\t\t\t);\n\t\t});\n\t},\n});\n\nconst credentialWrongKey = defineCheck({\n\tid: \"credential.wrong-key-refused\",\n\ttitle: \"A credential signed by a key other than its cnf.kid is refused\",\n\ttier: \"must\",\n\tcitations: presentationCitations,\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\treturn withPublicSpace(ctx, async (space, credential) => {\n\t\t\tconst ok = await readShared(ctx, credential, space.uri);\n\t\t\tif (ok.status !== 200)\n\t\t\t\treturn fail(`positive control failed: ${describe(ok)}`, ok.json);\n\t\t\tconst thief = await readShared(ctx, credential, space.uri, {\n\t\t\t\tsignWith: await createCredentialKey(),\n\t\t\t});\n\t\t\treturn refused(thief.status)\n\t\t\t\t? pass(`refused a signature by the wrong key (${describe(thief)})`)\n\t\t\t\t: fail(\n\t\t\t\t\t\t`a credential signed by a stranger's key returned ${describe(thief)}`,\n\t\t\t\t\t\tthief.json,\n\t\t\t\t\t);\n\t\t});\n\t},\n});\n\nconst credentialSchemeCase = defineCheck({\n\tid: \"credential.scheme-case-insensitive\",\n\ttitle: \"The Atproto-Space-Credential scheme is recognised regardless of case\",\n\ttier: \"must\",\n\tcitations: [\n\t\tP(\"0016#presenting-a-space-credential\"),\n\t\tL(\"com.atproto.space.getRecord\"),\n\t],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\treturn withPublicSpace(ctx, async (space, credential) => {\n\t\t\tconst lower = await readShared(ctx, credential, space.uri, {\n\t\t\t\tscheme: \"atproto-space-credential\",\n\t\t\t});\n\t\t\treturn lower.status === 200\n\t\t\t\t? pass(\"a lowercase scheme was accepted\")\n\t\t\t\t: fail(`a lowercase scheme returned ${describe(lower)}`, lower.json);\n\t\t});\n\t},\n});\n\nconst credentialCrossSpace = defineCheck({\n\tid: \"credential.cross-space-refused\",\n\ttitle: \"A credential for one space cannot read another\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.space.getRecord\"),\n\t\tP(\"0016#presenting-a-space-credential\"),\n\t],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst other = await createProbeSpace(ctx, publicRead());\n\t\ttry {\n\t\t\tawait mustCreateRecord(ctx, other.uri, \"shared\", \"b\");\n\t\t\treturn await withPublicSpace(ctx, async (space, credential) => {\n\t\t\t\tconst ok = await readShared(ctx, credential, space.uri);\n\t\t\t\tif (ok.status !== 200)\n\t\t\t\t\treturn fail(`positive control failed: ${describe(ok)}`, ok.json);\n\t\t\t\tconst cross = await readShared(ctx, credential, other.uri);\n\t\t\t\tif (cross.status === 200)\n\t\t\t\t\treturn fail(\"a space-A credential read space B\", cross.json);\n\t\t\t\treturn refused(cross.status)\n\t\t\t\t\t? pass(`cross-space read refused (${describe(cross)})`)\n\t\t\t\t\t: fail(\n\t\t\t\t\t\t\t`cross-space read answered ${describe(cross)}, expected a 4xx refusal`,\n\t\t\t\t\t\t\tcross.json,\n\t\t\t\t\t\t);\n\t\t\t});\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, other.uri);\n\t\t}\n\t},\n});\n\nconst credentialUnhostedRepo = defineCheck({\n\tid: \"credential.unhosted-repo-not-found\",\n\ttitle:\n\t\t\"Credentialed reads of a repo the host does not hold answer RepoNotFound\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.space.getRecord@error:RepoNotFound\"),\n\t\tL(\"com.atproto.space.getLatestCommit@error:RepoNotFound\"),\n\t\tL(\"com.atproto.space.getRepo@error:RepoNotFound\"),\n\t\tL(\"com.atproto.space.listRecords@error:RepoNotFound\"),\n\t\tL(\"com.atproto.space.listRepoOps@error:RepoNotFound\"),\n\t\tL(\"com.atproto.space.listBlobs@error:RepoNotFound\"),\n\t\tL(\"com.atproto.space.getBlob@error:RepoNotFound\"),\n\t],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\treturn withPublicSpace(ctx, async (space, credential) => {\n\t\t\t// A DID no host serves. Its KEM key can't be resolved, so the MAC\n\t\t\t// request carries a well-formed but unanswerable key share — the\n\t\t\t// host must find no repo before it could use one.\n\t\t\tconst repo = fakeDid();\n\t\t\tconst base = { space: space.uri, repo };\n\t\t\tconst reads: Array<[string, Record<string, string>]> = [\n\t\t\t\t[\"getRecord\", { ...base, collection: POST, rkey: \"shared\" }],\n\t\t\t\t[\"getLatestCommit\", base],\n\t\t\t\t[\"getRepo\", base],\n\t\t\t\t[\"listRepoOps\", base],\n\t\t\t\t[\"listRecords\", base],\n\t\t\t\t[\"listBlobs\", base],\n\t\t\t\t[\"getBlob\", { ...base, cid: await rawCid(utf8(\"no such blob\")) }],\n\t\t\t];\n\t\t\tconst misses: string[] = [];\n\t\t\tfor (const [name, params] of reads) {\n\t\t\t\tconst res = await credentialCall(\n\t\t\t\t\tctx,\n\t\t\t\t\tcredential,\n\t\t\t\t\t`com.atproto.space.${name}`,\n\t\t\t\t\t{ params },\n\t\t\t\t);\n\t\t\t\tif (res.error !== \"RepoNotFound\")\n\t\t\t\t\tmisses.push(`${name} → ${describe(res)}`);\n\t\t\t}\n\t\t\treturn misses.length\n\t\t\t\t? fail(`expected RepoNotFound: ${misses.join(\"; \")}`)\n\t\t\t\t: pass(\"all seven reads answered RepoNotFound\");\n\t\t});\n\t},\n});\n\nconst macRequired = defineCheck({\n\tid: \"mac.mac-request-required\",\n\ttitle:\n\t\t\"Credentialed reads of a commit or record without a MAC request answer InvalidSpaceMac\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.space.getLatestCommit@error:InvalidSpaceMac\"),\n\t\tL(\"com.atproto.space.getRecord@error:InvalidSpaceMac\"),\n\t\tL(\"com.atproto.space.getRepo@error:InvalidSpaceMac\"),\n\t\tL(\"com.atproto.space.listRepoOps@error:InvalidSpaceMac\"),\n\t\tP(\"0016#requesting-a-mac\"),\n\t],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\treturn withPublicSpace(ctx, async (space, credential) => {\n\t\t\tconst base = { space: space.uri, repo: ctx.target.did };\n\t\t\tconst reads: Array<[string, Record<string, string>]> = [\n\t\t\t\t[\"getLatestCommit\", base],\n\t\t\t\t[\"getRecord\", recordParams(ctx, space.uri)],\n\t\t\t\t[\"getRepo\", base],\n\t\t\t\t[\"listRepoOps\", base],\n\t\t\t];\n\t\t\tconst misses: string[] = [];\n\t\t\tfor (const [name, params] of reads) {\n\t\t\t\tconst nsid = `com.atproto.space.${name}`;\n\t\t\t\tconst ok = await credentialGet(ctx, credential, nsid, params);\n\t\t\t\tif (ok.status !== 200) {\n\t\t\t\t\tmisses.push(`${name} with a MAC request → ${describe(ok)}`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst none = await credentialCall(ctx, credential, nsid, {\n\t\t\t\t\tparams,\n\t\t\t\t\tmac: false,\n\t\t\t\t});\n\t\t\t\tif (none.error !== \"InvalidSpaceMac\")\n\t\t\t\t\tmisses.push(`${name} without → ${describe(none)}`);\n\t\t\t\t// A request only for another tag is ignored, leaving none.\n\t\t\t\tconst profile =\n\t\t\t\t\tname === \"getRecord\" ? RECORD_MAC_PROFILE : COMMIT_MAC_PROFILE;\n\t\t\t\tconst otherTag = await credentialCall(ctx, credential, nsid, {\n\t\t\t\t\tparams,\n\t\t\t\t\tmac: {\n\t\t\t\t\t\tprofile,\n\t\t\t\t\t\theader: (k) =>\n\t\t\t\t\t\t\tformatMacRequest(profile, k).replace(\n\t\t\t\t\t\t\t\t`tag=\"${profile}\"`,\n\t\t\t\t\t\t\t\t'tag=\"some-other-profile\"',\n\t\t\t\t\t\t\t),\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\tif (otherTag.error !== \"InvalidSpaceMac\")\n\t\t\t\t\tmisses.push(`${name} with only another tag → ${describe(otherTag)}`);\n\t\t\t}\n\t\t\treturn misses.length\n\t\t\t\t? fail(misses.join(\"; \"))\n\t\t\t\t: pass(\n\t\t\t\t\t\t\"each served with a MAC request (not verified here: mac.commit-verifies and mac.record-verifies need the alpha libs) and answered InvalidSpaceMac without one\",\n\t\t\t\t\t);\n\t\t});\n\t},\n});\n\nconst macMalformed = defineCheck({\n\tid: \"mac.malformed-request-rejected\",\n\ttitle: \"A malformed MAC request answers InvalidSpaceMac\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.space.getLatestCommit@error:InvalidSpaceMac\"),\n\t\tL(\"com.atproto.space.getRecord@error:InvalidSpaceMac\"),\n\t\tP(\"0016#requesting-a-mac\"),\n\t],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\treturn withPublicSpace(ctx, async (space, credential) => {\n\t\t\tconst commit = { space: space.uri, repo: ctx.target.did };\n\t\t\tconst c = COMMIT_MAC_PROFILE;\n\t\t\tconst probes: Array<\n\t\t\t\t[string, Record<string, string>, (k: string) => string]\n\t\t\t> = [\n\t\t\t\t[\n\t\t\t\t\t\"invalid keyid\",\n\t\t\t\t\tcommit,\n\t\t\t\t\t() => formatMacRequest(c, \"did:key:zNotAKey\"),\n\t\t\t\t],\n\t\t\t\t[\n\t\t\t\t\t\"keyid not a P-256 key\",\n\t\t\t\t\tcommit,\n\t\t\t\t\t() =>\n\t\t\t\t\t\tformatMacRequest(\n\t\t\t\t\t\t\tc,\n\t\t\t\t\t\t\tformatDidKey(\n\t\t\t\t\t\t\t\t\"ES256K\",\n\t\t\t\t\t\t\t\tnew Uint8Array([\n\t\t\t\t\t\t\t\t\t2,\n\t\t\t\t\t\t\t\t\t...crypto.getRandomValues(new Uint8Array(32)),\n\t\t\t\t\t\t\t\t]),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t),\n\t\t\t\t],\n\t\t\t\t[\n\t\t\t\t\t\"two requests with the tag\",\n\t\t\t\t\tcommit,\n\t\t\t\t\t(k) =>\n\t\t\t\t\t\t`${formatMacRequest(c, k)}, ${formatMacRequest(c, k, { label: \"mac2\" })}`,\n\t\t\t\t],\n\t\t\t\t[\n\t\t\t\t\t\"an extra parameter\",\n\t\t\t\t\tcommit,\n\t\t\t\t\t(k) =>\n\t\t\t\t\t\tformatMacRequest(c, k, {\n\t\t\t\t\t\t\tparams: [[\"created\", Math.floor(Date.now() / 1000)]],\n\t\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t\t[\n\t\t\t\t\t\"alg other than hmac-sha256\",\n\t\t\t\t\tcommit,\n\t\t\t\t\t(k) =>\n\t\t\t\t\t\tformatMacRequest(c, k, { params: [[\"alg\", \"ecdsa-p256-sha256\"]] }),\n\t\t\t\t],\n\t\t\t\t[\n\t\t\t\t\t\"wrong covered header\",\n\t\t\t\t\tcommit,\n\t\t\t\t\t(k) =>\n\t\t\t\t\t\tformatMacRequest(c, k).replace(\n\t\t\t\t\t\t\t'(\"atproto-space-commit\";sf)',\n\t\t\t\t\t\t\t'(\"atproto-space-record\";sf)',\n\t\t\t\t\t\t),\n\t\t\t\t],\n\t\t\t\t[\n\t\t\t\t\t\"not a structured field\",\n\t\t\t\t\trecordParams(ctx, space.uri),\n\t\t\t\t\t() => \"please\",\n\t\t\t\t],\n\t\t\t];\n\t\t\tconst misses: string[] = [];\n\t\t\tfor (const [label, params, header] of probes) {\n\t\t\t\tconst nsid = params.rkey\n\t\t\t\t\t? \"com.atproto.space.getRecord\"\n\t\t\t\t\t: \"com.atproto.space.getLatestCommit\";\n\t\t\t\tconst profile = params.rkey ? RECORD_MAC_PROFILE : COMMIT_MAC_PROFILE;\n\t\t\t\tconst res = await credentialCall(ctx, credential, nsid, {\n\t\t\t\t\tparams,\n\t\t\t\t\tmac: { profile, header },\n\t\t\t\t});\n\t\t\t\tif (res.error !== \"InvalidSpaceMac\")\n\t\t\t\t\tmisses.push(`${label} → ${describe(res)}`);\n\t\t\t}\n\t\t\treturn misses.length\n\t\t\t\t? fail(`expected InvalidSpaceMac: ${misses.join(\"; \")}`)\n\t\t\t\t: pass(\"every malformed MAC request answered InvalidSpaceMac\");\n\t\t});\n\t},\n});\n\nexport const credentialChecks: Check[] = [\n\tcredentialTokenlessPolicies,\n\tcredentialClaims,\n\tcredentialDefaultLifetime,\n\tcredentialSpaceRev,\n\tcredentialKeyP256,\n\tcredentialGarbageDelegation,\n\tcredentialUnverifiableAttestation,\n\tcredentialGarbageAttestation,\n\tcredentialAllowedApps,\n\tcredentialValidAttestation,\n\tcredentialUnlistedAttestation,\n\tcredentialDeletedSpace,\n\tcredentialUnconfirmedRegistration,\n\tcredentialSelfRoundTrip,\n\tcredentialPersonalOwner,\n\tdelegationClaims,\n\tdelegationReplay,\n\tdelegationWrongSpace,\n\tcredentialSignatureRequired,\n\tcredentialSignatureByTag,\n\tcredentialSignatureRequirements,\n\tcredentialAudienceBound,\n\tcredentialWrongKey,\n\tcredentialSchemeCase,\n\tcredentialCrossSpace,\n\tcredentialUnhostedRepo,\n\tmacRequired,\n\tmacMalformed,\n];\n","/**\n * The space-host role: the writer set (listWriters, removeWriter) and,\n * when the harness serves a syncer inbox, the notifications the host sends\n * through `authorizeSpaceSync`'s `notify` registration —\n * confirmRegistration, then notifySpaceUpdate for writes, removals and\n * deletion. Browser-safe; the inbox checks need a harness the target can\n * reach.\n */\n\nimport { defineCheck } from \"../registry.js\";\nimport { asOperator, xrpcGet, xrpcPost } from \"../http.js\";\nimport {\n\tfail,\n\tpass,\n\ttype Check,\n\ttype CheckContext,\n\ttype InboxDelivery,\n\ttype SyncerInbox,\n} from \"../model.js\";\nimport { bytesEqual, decodeJwt, isTid, lexBytes } from \"../encoding.js\";\nimport {\n\tcreateProbeSpace,\n\tmanagedspace,\n\tcredentialCall,\n\tdeleteProbeSpace,\n\tdescribe,\n\tmustCreateRecord,\n\tobtainPublicCredential,\n\tpublicRead,\n\trequestCredential,\n\ttype Credential,\n} from \"./probe.js\";\nimport { fakeDid } from \"./space.js\";\n\nconst L = (ref: string) => ({ source: \"lexicon\" as const, ref });\nconst P = (ref: string) => ({ source: \"proposal\" as const, ref });\n\nconst REPO_WRITE = \"com.atproto.space.defs#repoWrite\";\nconst REPO_REMOVED = \"com.atproto.space.defs#repoRemoved\";\nconst SPACE_DELETED = \"com.atproto.space.notifySpaceUpdate#spaceDeleted\";\n\ninterface WriterEntry {\n\t$type?: string;\n\trepo?: string;\n\trepoRev?: unknown;\n\tdata?: unknown;\n\tspaceRev?: unknown;\n}\n\nexport async function listWriters(\n\tctx: CheckContext,\n\tcredential: Credential,\n\tparams: Record<string, string> = {},\n) {\n\tconst res = await credentialCall(\n\t\tctx,\n\t\tcredential,\n\t\t\"com.atproto.space.listWriters\",\n\t\t{\n\t\t\tparams: { space: credential.space, ...params },\n\t\t\taudience: ctx.target.did,\n\t\t},\n\t);\n\tconst body = res.json as\n\t\t| { repos?: WriterEntry[]; cursor?: string }\n\t\t| undefined;\n\treturn { res, repos: body?.repos ?? [], cursor: body?.cursor };\n}\n\n/** The latest entry for `repo` in the whole writer set. */\nasync function writerEntry(\n\tctx: CheckContext,\n\tcredential: Credential,\n\trepo: string,\n) {\n\tconst { repos } = await listWriters(ctx, credential, { limit: \"1000\" });\n\treturn repos.filter((r) => r.repo === repo).at(-1);\n}\n\nconst hostRequiresCredential = defineCheck({\n\tid: \"host.listwriters-requires-credential\",\n\ttitle: \"listWriters refuses an unauthenticated caller\",\n\ttier: \"must\",\n\tcitations: [L(\"com.atproto.space.listWriters\")],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst space = await createProbeSpace(ctx, publicRead());\n\t\ttry {\n\t\t\tconst res = await xrpcGet(ctx, \"com.atproto.space.listWriters\", {\n\t\t\t\tspace: space.uri,\n\t\t\t});\n\t\t\treturn res.status === 401 || res.status === 403\n\t\t\t\t? pass(`refused with ${res.status}`)\n\t\t\t\t: fail(\n\t\t\t\t\t\t`unauthenticated listWriters returned ${describe(res)}`,\n\t\t\t\t\t\tres.json,\n\t\t\t\t\t);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nconst listWritersShape = defineCheck({\n\tid: \"sync.listwriters-shape\",\n\ttitle:\n\t\t\"listWriters lists typed repoWrite entries by ascending spaceRev, resumable by cursor\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.space.listWriters\"),\n\t\tL(\"com.atproto.space.defs#repoWrite\"),\n\t\tP(\"0016#the-sync-boundary-writer-set\"),\n\t],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst space = await createProbeSpace(ctx, publicRead());\n\t\ttry {\n\t\t\tawait mustCreateRecord(ctx, space.uri, \"a\");\n\t\t\tawait mustCreateRecord(ctx, space.uri, \"b\");\n\t\t\tconst credential = await obtainPublicCredential(ctx, space.uri);\n\t\t\tconst page = await listWriters(ctx, credential);\n\t\t\tif (page.res.status !== 200)\n\t\t\t\treturn fail(`listWriters ${describe(page.res)}`, page.res.json);\n\t\t\tconst problems: string[] = [];\n\t\t\tfor (const entry of page.repos) {\n\t\t\t\tif (entry.$type !== REPO_WRITE && entry.$type !== REPO_REMOVED)\n\t\t\t\t\tproblems.push(`entry $type ${String(entry.$type)}`);\n\t\t\t\tif (!isTid(entry.spaceRev))\n\t\t\t\t\tproblems.push(`${entry.repo} spaceRev ${String(entry.spaceRev)}`);\n\t\t\t\tif (entry.$type === REPO_WRITE) {\n\t\t\t\t\tif (!isTid(entry.repoRev))\n\t\t\t\t\t\tproblems.push(`${entry.repo} repoRev ${String(entry.repoRev)}`);\n\t\t\t\t\tif (lexBytes(entry.data)?.length !== 32)\n\t\t\t\t\t\tproblems.push(`${entry.repo} data is not 32 bytes`);\n\t\t\t\t}\n\t\t\t\tif (\"prevSpaceRev\" in entry)\n\t\t\t\t\tproblems.push(\"listWriters entries carry prevSpaceRev\");\n\t\t\t}\n\t\t\tconst revs = page.repos.map((r) => String(r.spaceRev));\n\t\t\tif (revs.some((rev, i) => i > 0 && rev <= revs[i - 1]!))\n\t\t\t\tproblems.push(`not ascending: ${revs.join(\",\")}`);\n\t\t\tif (\n\t\t\t\t!page.repos.some(\n\t\t\t\t\t(r) => r.repo === ctx.target.did && r.$type === REPO_WRITE,\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\tproblems.push(\"the authority's own repo is not listed as a repoWrite\");\n\t\t\t}\n\t\t\tif (!page.cursor) problems.push(\"a non-empty page carried no cursor\");\n\t\t\tif (problems.length) return fail(problems.join(\"; \"), page.res.json);\n\t\t\t// Resuming from the cursor reaches only later updates — here, none.\n\t\t\tconst next = await listWriters(ctx, credential, { cursor: page.cursor! });\n\t\t\tif (next.res.status !== 200)\n\t\t\t\treturn fail(`listWriters(cursor) ${describe(next.res)}`, next.res.json);\n\t\t\treturn next.repos.length === 0\n\t\t\t\t? pass(\n\t\t\t\t\t\t`${page.repos.length} writer(s), typed and ascending; the cursor resumes after them`,\n\t\t\t\t\t)\n\t\t\t\t: fail(\n\t\t\t\t\t\t`after the last cursor: ${next.repos.length} repo(s) again`,\n\t\t\t\t\t\tnext.res.json,\n\t\t\t\t\t);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nconst listWritersReflects = defineCheck({\n\tid: \"sync.listwriters-reflects-writes\",\n\ttitle: \"The authority's listWriters entry matches its latest commit\",\n\ttier: \"should\",\n\tcitations: [\n\t\t{\n\t\t\tsource: \"reference\",\n\t\t\tref: \"authority repo notifies its own space host synchronously\",\n\t\t},\n\t\tL(\"com.atproto.space.listWriters\"),\n\t],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\t// The proposal lets the entry lag (\"current as far as the authority's\n\t\t// notifications have kept it\"), so this is calibrated on the reference.\n\t\tconst space = await createProbeSpace(ctx, publicRead());\n\t\ttry {\n\t\t\tawait mustCreateRecord(ctx, space.uri, \"a\");\n\t\t\tconst credential = await obtainPublicCredential(ctx, space.uri);\n\t\t\tconst mine = await writerEntry(ctx, credential, ctx.target.did);\n\t\t\tconst latest = await xrpcGet(\n\t\t\t\tasOperator(ctx),\n\t\t\t\t\"com.atproto.space.getLatestCommit\",\n\t\t\t\t{\n\t\t\t\t\tspace: space.uri,\n\t\t\t\t\trepo: ctx.target.did,\n\t\t\t\t},\n\t\t\t);\n\t\t\tconst commit = (\n\t\t\t\tlatest.json as { commit?: { rev?: string; data?: unknown } } | undefined\n\t\t\t)?.commit;\n\t\t\tconst a = lexBytes(mine?.data);\n\t\t\tconst b = lexBytes(commit?.data);\n\t\t\treturn mine &&\n\t\t\t\tcommit &&\n\t\t\t\tmine.repoRev === commit.rev &&\n\t\t\t\ta &&\n\t\t\t\tb &&\n\t\t\t\tbytesEqual(a, b)\n\t\t\t\t? pass(\"repoRev and data match getLatestCommit\")\n\t\t\t\t: fail(\"listWriters entry differs from the latest commit\", {\n\t\t\t\t\t\tlisted: mine,\n\t\t\t\t\t\tcommit,\n\t\t\t\t\t});\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nconst removeWriter = defineCheck({\n\tid: \"host.removewriter\",\n\ttitle: \"removeWriter lists the repo as repoRemoved until it writes again\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.space.removeWriter\"),\n\t\tL(\"com.atproto.space.listWriters\"),\n\t\tL(\"com.atproto.space.defs#repoRemoved\"),\n\t\tP(\"0016#the-sync-boundary-writer-set\"),\n\t],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst space = await createProbeSpace(ctx, publicRead());\n\t\tconst remove = (repo: string) =>\n\t\t\txrpcPost(asOperator(ctx), \"com.atproto.space.removeWriter\", {\n\t\t\t\tspace: space.uri,\n\t\t\t\trepo,\n\t\t\t});\n\t\ttry {\n\t\t\tawait mustCreateRecord(ctx, space.uri, \"a\");\n\t\t\tconst credential = await obtainPublicCredential(ctx, space.uri);\n\t\t\tconst before = await writerEntry(ctx, credential, ctx.target.did);\n\t\t\tif (before?.$type !== REPO_WRITE)\n\t\t\t\treturn fail(\n\t\t\t\t\t\"the authority's repo was not in the writer set to begin with\",\n\t\t\t\t);\n\t\t\tconst removed = await remove(ctx.target.did);\n\t\t\tif (removed.status !== 200)\n\t\t\t\treturn fail(`removeWriter ${describe(removed)}`, removed.json);\n\t\t\tconst gone = await writerEntry(ctx, credential, ctx.target.did);\n\t\t\tif (gone?.$type !== REPO_REMOVED)\n\t\t\t\treturn fail(`after removeWriter the entry is ${JSON.stringify(gone)}`);\n\t\t\tif (!(String(gone.spaceRev) > String(before.spaceRev)))\n\t\t\t\treturn fail(\"the removal was not sequenced after the write\");\n\t\t\t// \"Does nothing if the account is not in the writer set.\"\n\t\t\tconst absent = await remove(fakeDid());\n\t\t\tif (absent.status !== 200)\n\t\t\t\treturn fail(\n\t\t\t\t\t`removeWriter of a non-writer returned ${describe(absent)}`,\n\t\t\t\t\tabsent.json,\n\t\t\t\t);\n\t\t\tawait mustCreateRecord(ctx, space.uri, \"b\");\n\t\t\tconst back = await writerEntry(ctx, credential, ctx.target.did);\n\t\t\treturn back?.$type === REPO_WRITE\n\t\t\t\t? pass(\n\t\t\t\t\t\t\"listed as repoRemoved at a later spaceRev; no-op for a non-writer; a new write re-added it\",\n\t\t\t\t\t)\n\t\t\t\t: fail(`after a new write the entry is ${JSON.stringify(back)}`);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nconst hostAfterDelete = defineCheck({\n\tid: \"host.deleted-space-not-found\",\n\ttitle: \"listWriters on a deleted space answers SpaceNotFound\",\n\ttier: \"must\",\n\tcitations: [L(\"com.atproto.space.listWriters@error:SpaceNotFound\")],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\t// A credential issued before deletion is still well-formed and\n\t\t// unexpired; what has gone is the space.\n\t\tconst space = await createProbeSpace(ctx, publicRead());\n\t\tconst credential = await obtainPublicCredential(ctx, space.uri);\n\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\tconst { res } = await listWriters(ctx, credential);\n\t\treturn res.error === \"SpaceNotFound\"\n\t\t\t? pass(\"answered SpaceNotFound\")\n\t\t\t: fail(`answered ${describe(res)}, expected SpaceNotFound`, res.json);\n\t},\n});\n\n// --- notifications to a harness syncer ------------------------------------\n\nconst NOTIFY_TIMEOUT_MS = 10_000;\n\n/** Authorise with a fresh notify registration at the inbox. */\nasync function register(ctx: CheckContext, inbox: SyncerInbox, space: string) {\n\tconst token = inbox.issueToken(space);\n\tconst since = Date.now();\n\tconst res = await requestCredential(ctx, space, {\n\t\tnotify: { endpoint: inbox.endpoint, token },\n\t});\n\treturn { token, since, ...res };\n}\n\nconst updatesFor =\n\t(space: string, token: string, type: string, since: number) =>\n\t(d: InboxDelivery) => {\n\t\tconst body = d.body as\n\t\t\t| { space?: string; token?: string; update?: { $type?: string } }\n\t\t\t| undefined;\n\t\treturn (\n\t\t\td.lxm === \"com.atproto.space.notifySpaceUpdate\" &&\n\t\t\td.receivedAt >= since &&\n\t\t\tbody?.space === space &&\n\t\t\tbody.token === token &&\n\t\t\tbody.update?.$type === type\n\t\t);\n\t};\n\nconst notifyConfirmed = defineCheck({\n\tid: \"notify.registration-confirmed\",\n\ttitle:\n\t\t\"A notify registration is confirmed with a challenge before the credential is issued\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.space.confirmRegistration\"),\n\t\tL(\"com.atproto.space.authorizeSpaceSync#notify\"),\n\t\tP(\"0016#registering-for-notifications\"),\n\t],\n\tneeds: [\"operator\", \"syncer-inbox\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst inbox = ctx.syncerInbox!;\n\t\tconst space = await createProbeSpace(ctx, publicRead());\n\t\ttry {\n\t\t\tconst reg = await register(ctx, inbox, space.uri);\n\t\t\tif (!reg.credential)\n\t\t\t\treturn fail(\n\t\t\t\t\t`authorizeSpaceSync with notify ${describe(reg.result)}`,\n\t\t\t\t\treg.result.json,\n\t\t\t\t);\n\t\t\tconst confirm = await inbox.waitFor(\n\t\t\t\t(d) =>\n\t\t\t\t\td.lxm === \"com.atproto.space.confirmRegistration\" &&\n\t\t\t\t\td.receivedAt >= reg.since &&\n\t\t\t\t\t(d.body as { token?: string } | undefined)?.token === reg.token,\n\t\t\t\t1_000,\n\t\t\t);\n\t\t\tif (!confirm)\n\t\t\t\treturn fail(\n\t\t\t\t\t\"the credential was issued without calling confirmRegistration\",\n\t\t\t\t);\n\t\t\tconst body = confirm.body as { space?: string; challenge?: unknown };\n\t\t\tif (body.space !== space.uri)\n\t\t\t\treturn fail(`confirmRegistration named space ${body.space}`);\n\t\t\tif (typeof body.challenge !== \"string\" || body.challenge.length < 8)\n\t\t\t\treturn fail(\"confirmRegistration carried no real challenge\", body);\n\t\t\treturn pass(\n\t\t\t\t\"confirmRegistration (space, token, challenge) preceded the credential\",\n\t\t\t);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nconst notifyRenewal = defineCheck({\n\tid: \"notify.renewal-not-reconfirmed\",\n\ttitle:\n\t\t\"Reauthorizing with the same notify pair renews without confirming again\",\n\ttier: \"should\",\n\tcitations: [\n\t\t{\n\t\t\tsource: \"reference\",\n\t\t\tref: \"pds authorizeSpaceSync confirms only unregistered pairs\",\n\t\t},\n\t\tP(\"0016#registering-for-notifications\"),\n\t],\n\tneeds: [\"operator\", \"syncer-inbox\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst inbox = ctx.syncerInbox!;\n\t\tconst space = await createProbeSpace(ctx, publicRead());\n\t\ttry {\n\t\t\tconst first = await register(ctx, inbox, space.uri);\n\t\t\tif (!first.credential)\n\t\t\t\treturn fail(`authorizeSpaceSync ${describe(first.result)}`);\n\t\t\t// The absence of a second confirmation means something only if the\n\t\t\t// first registration was confirmed at all.\n\t\t\tconst confirmed = await inbox.waitFor(\n\t\t\t\t(d) =>\n\t\t\t\t\td.lxm === \"com.atproto.space.confirmRegistration\" &&\n\t\t\t\t\td.receivedAt >= first.since &&\n\t\t\t\t\t(d.body as { token?: string })?.token === first.token,\n\t\t\t\t1_000,\n\t\t\t);\n\t\t\tif (!confirmed)\n\t\t\t\treturn fail(\n\t\t\t\t\t\"the first registration was never confirmed, so the renewal's lack of one proves nothing\",\n\t\t\t\t);\n\t\t\tconst since = Date.now();\n\t\t\tconst again = await requestCredential(ctx, space.uri, {\n\t\t\t\tnotify: { endpoint: inbox.endpoint, token: first.token },\n\t\t\t});\n\t\t\tif (!again.credential)\n\t\t\t\treturn fail(`reauthorizing ${describe(again.result)}`);\n\t\t\tconst reconfirmed = await inbox.waitFor(\n\t\t\t\t(d) =>\n\t\t\t\t\td.lxm === \"com.atproto.space.confirmRegistration\" &&\n\t\t\t\t\td.receivedAt >= since &&\n\t\t\t\t\t(d.body as { token?: string })?.token === first.token,\n\t\t\t\t500,\n\t\t\t);\n\t\t\treturn reconfirmed\n\t\t\t\t? fail(\"the renewal was confirmed again\")\n\t\t\t\t: pass(\n\t\t\t\t\t\t\"the first registration was confirmed; the renewal was not confirmed again\",\n\t\t\t\t\t);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nconst notifyRepoWrite = defineCheck({\n\tid: \"notify.repo-write-delivered\",\n\ttitle: \"A registered syncer receives sequenced repoWrite updates\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.space.notifySpaceUpdate\"),\n\t\tL(\"com.atproto.space.defs#repoWrite\"),\n\t\tP(\"0016#write-notifications\"),\n\t],\n\tneeds: [\"operator\", \"syncer-inbox\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst inbox = ctx.syncerInbox!;\n\t\tconst space = await createProbeSpace(ctx, publicRead());\n\t\ttry {\n\t\t\tawait mustCreateRecord(ctx, space.uri, \"before\");\n\t\t\tconst reg = await register(ctx, inbox, space.uri);\n\t\t\tif (!reg.credential)\n\t\t\t\treturn fail(\n\t\t\t\t\t`authorizeSpaceSync with notify ${describe(reg.result)}`,\n\t\t\t\t\treg.result.json,\n\t\t\t\t);\n\t\t\tconst since = Date.now();\n\t\t\tawait mustCreateRecord(ctx, space.uri, \"one\");\n\t\t\tconst first = await inbox.waitFor(\n\t\t\t\tupdatesFor(space.uri, reg.token, REPO_WRITE, since),\n\t\t\t\tNOTIFY_TIMEOUT_MS,\n\t\t\t);\n\t\t\tif (!first) return fail(\"no repoWrite reached the syncer after a write\");\n\t\t\tconst a = (first.body as { update: Record<string, unknown> }).update;\n\t\t\tawait mustCreateRecord(ctx, space.uri, \"two\");\n\t\t\tconst second = await inbox.waitFor(\n\t\t\t\t(d) =>\n\t\t\t\t\tupdatesFor(space.uri, reg.token, REPO_WRITE, first.receivedAt)(d) &&\n\t\t\t\t\t(d.body as { update: { spaceRev?: unknown } }).update.spaceRev !==\n\t\t\t\t\t\ta.spaceRev,\n\t\t\t\tNOTIFY_TIMEOUT_MS,\n\t\t\t);\n\t\t\tif (!second)\n\t\t\t\treturn fail(\"no repoWrite reached the syncer after a second write\");\n\t\t\tconst b = (second.body as { update: Record<string, unknown> }).update;\n\t\t\tconst problems: string[] = [];\n\t\t\tfor (const [label, u] of [\n\t\t\t\t[\"first\", a],\n\t\t\t\t[\"second\", b],\n\t\t\t] as const) {\n\t\t\t\tif (u.repo !== ctx.target.did)\n\t\t\t\t\tproblems.push(`${label} repo ${String(u.repo)}`);\n\t\t\t\tif (!isTid(u.repoRev))\n\t\t\t\t\tproblems.push(`${label} repoRev ${String(u.repoRev)}`);\n\t\t\t\tif (!isTid(u.spaceRev)) problems.push(`${label} has no spaceRev`);\n\t\t\t\tif (lexBytes(u.data)?.length !== 32)\n\t\t\t\t\tproblems.push(`${label} data is not 32 bytes`);\n\t\t\t}\n\t\t\t// The first write in the space preceded registration, so both carry one.\n\t\t\tif (a.prevSpaceRev === undefined)\n\t\t\t\tproblems.push(\"first update has no prevSpaceRev\");\n\t\t\tif (b.prevSpaceRev !== a.spaceRev)\n\t\t\t\tproblems.push(\n\t\t\t\t\t`second prevSpaceRev ${String(b.prevSpaceRev)} ≠ first spaceRev ${String(a.spaceRev)}`,\n\t\t\t\t);\n\t\t\treturn problems.length\n\t\t\t\t? fail(problems.join(\"; \"), { first: a, second: b })\n\t\t\t\t: pass(\"two repoWrite updates carrying the token; prevSpaceRev chains\");\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nconst notifyRepoRemoved = defineCheck({\n\tid: \"notify.repo-removed-delivered\",\n\ttitle: \"removeWriter is announced to registered syncers as repoRemoved\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.space.removeWriter\"),\n\t\tL(\"com.atproto.space.defs#repoRemoved\"),\n\t\tL(\"com.atproto.space.notifySpaceUpdate\"),\n\t\tP(\"0016#the-sync-boundary-writer-set\"),\n\t],\n\tneeds: [\"operator\", \"syncer-inbox\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst inbox = ctx.syncerInbox!;\n\t\tconst space = await createProbeSpace(ctx, publicRead());\n\t\ttry {\n\t\t\tawait mustCreateRecord(ctx, space.uri, \"a\");\n\t\t\tconst reg = await register(ctx, inbox, space.uri);\n\t\t\tif (!reg.credential)\n\t\t\t\treturn fail(\n\t\t\t\t\t`authorizeSpaceSync with notify ${describe(reg.result)}`,\n\t\t\t\t\treg.result.json,\n\t\t\t\t);\n\t\t\tconst since = Date.now();\n\t\t\tconst removed = await xrpcPost(\n\t\t\t\tasOperator(ctx),\n\t\t\t\t\"com.atproto.space.removeWriter\",\n\t\t\t\t{ space: space.uri, repo: ctx.target.did },\n\t\t\t);\n\t\t\tif (removed.status !== 200)\n\t\t\t\treturn fail(`removeWriter ${describe(removed)}`, removed.json);\n\t\t\tconst got = await inbox.waitFor(\n\t\t\t\tupdatesFor(space.uri, reg.token, REPO_REMOVED, since),\n\t\t\t\tNOTIFY_TIMEOUT_MS,\n\t\t\t);\n\t\t\tif (!got) return fail(\"no repoRemoved reached the syncer\");\n\t\t\tconst u = (got.body as { update: Record<string, unknown> }).update;\n\t\t\treturn u.repo === ctx.target.did &&\n\t\t\t\tisTid(u.spaceRev) &&\n\t\t\t\tisTid(u.prevSpaceRev)\n\t\t\t\t? pass(\"repoRemoved delivered with spaceRev and prevSpaceRev\")\n\t\t\t\t: fail(\"repoRemoved fields wrong\", u);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nconst notifySpaceDeleted = defineCheck({\n\tid: \"notify.space-deleted-delivered\",\n\ttitle: \"A registered syncer is sent spaceDeleted when the space is deleted\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.space.notifySpaceUpdate#spaceDeleted\"),\n\t\tP(\"0016#space-deletion\"),\n\t],\n\tneeds: [\"operator\", \"syncer-inbox\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst inbox = ctx.syncerInbox!;\n\t\tconst space = await createProbeSpace(ctx, publicRead());\n\t\tlet deleted = false;\n\t\ttry {\n\t\t\tconst reg = await register(ctx, inbox, space.uri);\n\t\t\tif (!reg.credential)\n\t\t\t\treturn fail(\n\t\t\t\t\t`authorizeSpaceSync with notify ${describe(reg.result)}`,\n\t\t\t\t\treg.result.json,\n\t\t\t\t);\n\t\t\tconst since = Date.now();\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t\tdeleted = true;\n\t\t\tconst got = await inbox.waitFor(\n\t\t\t\tupdatesFor(space.uri, reg.token, SPACE_DELETED, since),\n\t\t\t\tNOTIFY_TIMEOUT_MS,\n\t\t\t);\n\t\t\treturn got\n\t\t\t\t? pass(\"spaceDeleted delivered\")\n\t\t\t\t: fail(`no spaceDeleted within ${NOTIFY_TIMEOUT_MS / 1000}s`);\n\t\t} finally {\n\t\t\tif (!deleted) await deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nconst notifyExpired = defineCheck({\n\tid: \"notify.registration-expired\",\n\ttitle:\n\t\t\"Once its credential expires, a registration is sent registrationExpired in place of the next update\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.space.notifySpaceUpdate#registrationExpired\"),\n\t\tP(\"0016#registering-for-notifications\"),\n\t],\n\tneeds: [\"operator\", \"syncer-inbox\"],\n\tdestructive: true,\n\t// Waits out a real credential lifetime (10 minutes by default).\n\tslow: true,\n\ttimeoutMs: 65 * 60_000,\n\tasync run(ctx) {\n\t\tconst inbox = ctx.syncerInbox!;\n\t\tconst space = await createProbeSpace(ctx, publicRead());\n\t\ttry {\n\t\t\tconst reg = await register(ctx, inbox, space.uri);\n\t\t\tif (!reg.credential)\n\t\t\t\treturn fail(\n\t\t\t\t\t`authorizeSpaceSync with notify ${describe(reg.result)}`,\n\t\t\t\t\treg.result.json,\n\t\t\t\t);\n\t\t\tconst exp =\n\t\t\t\tNumber(decodeJwt(reg.credential.credential).payload.exp) * 1000;\n\t\t\tawait new Promise((r) =>\n\t\t\t\tsetTimeout(r, Math.max(0, exp - Date.now()) + 5_000),\n\t\t\t);\n\t\t\tconst since = Date.now();\n\t\t\tawait mustCreateRecord(ctx, space.uri, \"late\");\n\t\t\tconst got = await inbox.waitFor(\n\t\t\t\t(d) =>\n\t\t\t\t\tupdatesFor(\n\t\t\t\t\t\tspace.uri,\n\t\t\t\t\t\treg.token,\n\t\t\t\t\t\t\"com.atproto.space.notifySpaceUpdate#registrationExpired\",\n\t\t\t\t\t\tsince,\n\t\t\t\t\t)(d),\n\t\t\t\tNOTIFY_TIMEOUT_MS,\n\t\t\t);\n\t\t\tif (!got)\n\t\t\t\treturn fail(\"no registrationExpired after the credential lapsed\");\n\t\t\tconst update = (got.body as { update: { spaceRev?: unknown } }).update;\n\t\t\tconst write = await inbox.waitFor(\n\t\t\t\tupdatesFor(space.uri, reg.token, REPO_WRITE, since),\n\t\t\t\t2_000,\n\t\t\t);\n\t\t\tif (write)\n\t\t\t\treturn fail(\"a lapsed registration still received the repoWrite\");\n\t\t\treturn isTid(update.spaceRev)\n\t\t\t\t? pass(\"registrationExpired sent in place of the update\")\n\t\t\t\t: fail(\"registrationExpired has no spaceRev\", update);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\n// --- managedspace ------------------------------------------------------\n\nconst CHECK_ACCESS = \"com.atproto.managedspace.checkAccess\";\n\nconst managedTokenless = defineCheck({\n\tid: \"managedspace.check-access-tokenless\",\n\ttitle:\n\t\t\"Without a delegation token a managedspace asks its managing app, with no repo\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.managedspace.checkAccess\"),\n\t\tL(\"com.atproto.managedspace.policy\"),\n\t\tP(\"0016#managedspace\"),\n\t],\n\tneeds: [\"operator\", \"syncer-inbox\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst inbox = ctx.syncerInbox!;\n\t\tlet answer = { read: false, write: false };\n\t\tinbox.respond(CHECK_ACCESS, () => answer);\n\t\tconst space = await createProbeSpace(ctx, managedspace(inbox.service));\n\t\ttry {\n\t\t\tconst since = Date.now();\n\t\t\tconst denied = await requestCredential(ctx, space.uri);\n\t\t\tif (denied.credential)\n\t\t\t\treturn fail(\"issued a credential the managing app refused\");\n\t\t\tconst asked = await inbox.waitFor(\n\t\t\t\t(d) => d.lxm === CHECK_ACCESS && d.receivedAt >= since,\n\t\t\t\t5_000,\n\t\t\t);\n\t\t\tif (!asked)\n\t\t\t\treturn fail(\n\t\t\t\t\t`the managing app was never asked (${describe(denied.result)})`,\n\t\t\t\t);\n\t\t\tconst p = asked.params ?? {};\n\t\t\tif (p.space !== space.uri || \"repo\" in p || \"access\" in p)\n\t\t\t\treturn fail(\"checkAccess params wrong for a tokenless request\", p);\n\t\t\tconst jwt = asked.authorization?.replace(/^Bearer /, \"\");\n\t\t\tconst claims = jwt ? decodeJwt(jwt).payload : undefined;\n\t\t\tif (\n\t\t\t\tclaims?.lxm !== CHECK_ACCESS ||\n\t\t\t\tclaims.iss !== ctx.target.did ||\n\t\t\t\tclaims.aud !== inbox.service\n\t\t\t) {\n\t\t\t\treturn fail(\n\t\t\t\t\t\"checkAccess service auth does not name the method, the authority and the managing app\",\n\t\t\t\t\tclaims,\n\t\t\t\t);\n\t\t\t}\n\t\t\tanswer = { read: true, write: false };\n\t\t\tconst allowed = await requestCredential(ctx, space.uri);\n\t\t\treturn allowed.credential\n\t\t\t\t? pass(\n\t\t\t\t\t\t`asked with no repo under service auth; refused on read:false (${denied.result.error}), issued on read:true`,\n\t\t\t\t\t)\n\t\t\t\t: fail(\n\t\t\t\t\t\t`the managing app allowed reading but the credential was refused: ${describe(allowed.result)}`,\n\t\t\t\t\t);\n\t\t} finally {\n\t\t\tinbox.respond(CHECK_ACCESS, undefined);\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\n/** A managing app no host can resolve, let alone reach. */\nconst UNREACHABLE_APP = \"did:web:app.space-conformance.invalid#managing_app\";\n\n/**\n * Ask for a tokenless credential from a managedspace whose managing app\n * cannot answer, two ways — unresolvable, and the inbox answering\n * checkAccess with an error — after a same-run control: the inbox, answering\n * `{read: true}`, gets one issued. Without the control a host that refuses\n * every managedspace would pass for failing closed.\n */\nasync function unansweredManagingApp(\n\tctx: CheckContext,\n): Promise<\n\t| { failure: ReturnType<typeof fail> }\n\t| { results: Array<[string, Awaited<ReturnType<typeof requestCredential>>]> }\n> {\n\tconst inbox = ctx.syncerInbox!;\n\tconst reachable = await createProbeSpace(ctx, managedspace(inbox.service));\n\tconst erroring = await createProbeSpace(ctx, managedspace(inbox.service));\n\tconst unreachable = await createProbeSpace(\n\t\tctx,\n\t\tmanagedspace(UNREACHABLE_APP),\n\t);\n\ttry {\n\t\tinbox.respond(CHECK_ACCESS, () => ({ read: true, write: false }));\n\t\tconst ok = await requestCredential(ctx, reachable.uri);\n\t\tif (!ok.credential)\n\t\t\treturn {\n\t\t\t\tfailure: fail(\n\t\t\t\t\t`positive control failed: a managing app answering read:true got no credential issued (${describe(ok.result)})`,\n\t\t\t\t\tok.result.json,\n\t\t\t\t),\n\t\t\t};\n\t\t// With no responder the inbox answers checkAccess 501.\n\t\tinbox.respond(CHECK_ACCESS, undefined);\n\t\treturn {\n\t\t\tresults: [\n\t\t\t\t[\"unresolvable app\", await requestCredential(ctx, unreachable.uri)],\n\t\t\t\t[\n\t\t\t\t\t\"app answering with an error\",\n\t\t\t\t\tawait requestCredential(ctx, erroring.uri),\n\t\t\t\t],\n\t\t\t],\n\t\t};\n\t} finally {\n\t\tinbox.respond(CHECK_ACCESS, undefined);\n\t\tfor (const s of [reachable, erroring, unreachable])\n\t\t\tawait deleteProbeSpace(ctx, s.uri);\n\t}\n}\n\nconst managedFailsClosed = defineCheck({\n\tid: \"managedspace.unreachable-app-fails-closed\",\n\ttitle:\n\t\t\"A managedspace whose managing app cannot be reached issues no credential\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.managedspace.policy\"),\n\t\tP(\"0016#managedspace\"),\n\t\t{ source: \"changeset\", ref: \"patient-managers-answer\" },\n\t],\n\tneeds: [\"operator\", \"syncer-inbox\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\t// authorizeSpaceSync declares no error for this, so any error response\n\t\t// fails closed here; managedspace.unreachable-app-upstream-failure\n\t\t// asks for the changeset's UpstreamFailure.\n\t\tconst outcome = await unansweredManagingApp(ctx);\n\t\tif (\"failure\" in outcome) return outcome.failure;\n\t\tconst misses = outcome.results\n\t\t\t.filter(([, r]) => r.credential || r.result.status < 400)\n\t\t\t.map(([label, r]) =>\n\t\t\t\tr.credential ? `${label} → issued` : `${label} → ${describe(r.result)}`,\n\t\t\t);\n\t\treturn misses.length\n\t\t\t? fail(`did not fail closed: ${misses.join(\"; \")}`)\n\t\t\t: pass(\n\t\t\t\t\t`a managing app answering read:true issued; without an answer refused (${outcome.results.map(([l, r]) => `${l}: ${describe(r.result)}`).join(\", \")})`,\n\t\t\t\t);\n\t},\n});\n\nconst managedUpstreamFailure = defineCheck({\n\tid: \"managedspace.unreachable-app-upstream-failure\",\n\ttitle:\n\t\t\"An unreachable managing app is reported as UpstreamFailure, not a refusal\",\n\ttier: \"should\",\n\tcitations: [{ source: \"changeset\", ref: \"patient-managers-answer\" }],\n\tneeds: [\"operator\", \"syncer-inbox\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\t// Distinct from a denial: a syncer keeps its registration and a repo\n\t\t// host retries, rather than reading the failure as lost access.\n\t\tconst outcome = await unansweredManagingApp(ctx);\n\t\tif (\"failure\" in outcome) return outcome.failure;\n\t\tconst misses = outcome.results\n\t\t\t.filter(([, r]) => r.result.error !== \"UpstreamFailure\")\n\t\t\t.map(([label, r]) => `${label} → ${describe(r.result)}`);\n\t\treturn misses.length\n\t\t\t? fail(`expected UpstreamFailure: ${misses.join(\"; \")}`)\n\t\t\t: pass(\n\t\t\t\t\t\"a managing app answering read:true issued; unresolvable and erroring apps answered UpstreamFailure\",\n\t\t\t\t);\n\t},\n});\n\nexport const hostChecks: Check[] = [\n\thostRequiresCredential,\n\tlistWritersShape,\n\tlistWritersReflects,\n\tremoveWriter,\n\thostAfterDelete,\n\tnotifyConfirmed,\n\tnotifyRenewal,\n\tnotifyRepoWrite,\n\tnotifyRepoRemoved,\n\tnotifySpaceDeleted,\n\tnotifyExpired,\n\tmanagedTokenless,\n\tmanagedFailsClosed,\n\tmanagedUpstreamFailure,\n];\n","/**\n * Record writes and the owner's own reads: create/put/delete/applyWrites,\n * clearRecords, listRecords, blobs, and the SpaceNotFound perimeter around\n * spaces that do not exist or were deleted. Operator-only, browser-safe.\n */\n\nimport { defineCheck } from \"../registry.js\";\nimport {\n\tasOperator,\n\toperatorFetch,\n\txrpcGet,\n\txrpcPost,\n\ttype XrpcResult,\n} from \"../http.js\";\nimport { fail, pass, type Check, type CheckContext } from \"../model.js\";\nimport { bytesEqual, lexBytes, rawCid, sha256 } from \"../encoding.js\";\nimport {\n\tPOST,\n\tPROBE_TYPE,\n\tcreateProbeSpace,\n\tdeleteProbeSpace,\n\tdescribe,\n\tmemberspace,\n\tmustCreateRecord,\n\tnote,\n\toperatorCreateRecord,\n\toperatorGetRecord,\n\terrorIs,\n\texpectEach,\n\tlegacySpaceUri,\n\tpersonalspace,\n\tprobeSkey,\n\tspaceRecordUri,\n\tspaceUri,\n\tunknownSpaceUri,\n} from \"./probe.js\";\nimport { resolveDidDocument } from \"../did.js\";\n\nconst L = (ref: string) => ({ source: \"lexicon\" as const, ref });\nconst C = (ref: string) => ({ source: \"changeset\" as const, ref });\nconst P = (ref: string) => ({ source: \"proposal\" as const, ref });\nconst op = asOperator;\n\nconst writesCreateRead = defineCheck({\n\tid: \"writes.create-and-read\",\n\ttitle:\n\t\t\"Operator creates a record and reads it back, addressed by its at:space/ uri\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.space.createRecord\"),\n\t\tL(\"com.atproto.space.getRecord\"),\n\t\tC(\"spaces-syntax\"),\n\t\tC(\"pds-space-uri-migration\"),\n\t],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst space = await createProbeSpace(ctx);\n\t\ttry {\n\t\t\tconst created = await operatorCreateRecord(\n\t\t\t\tctx,\n\t\t\t\tspace.uri,\n\t\t\t\tPOST,\n\t\t\t\t\"rec1\",\n\t\t\t\tnote(\"hello\"),\n\t\t\t);\n\t\t\tif (created.status !== 200)\n\t\t\t\treturn fail(`createRecord ${describe(created)}`, created.json);\n\t\t\tconst read = await operatorGetRecord(ctx, space.uri, \"rec1\");\n\t\t\tif (read.status !== 200)\n\t\t\t\treturn fail(`getRecord ${describe(read)}`, read.json);\n\t\t\tconst body = read.json as {\n\t\t\t\turi?: string;\n\t\t\t\tcid?: string;\n\t\t\t\tvalue?: { text?: string };\n\t\t\t};\n\t\t\tif (body.cid !== (created.json as { cid?: string }).cid) {\n\t\t\t\treturn fail(\n\t\t\t\t\t\"getRecord cid differs from the createRecord cid\",\n\t\t\t\t\tread.json,\n\t\t\t\t);\n\t\t\t}\n\t\t\t// Both uris are the record's at:space/ uri: the space-ref, then\n\t\t\t// author, collection and rkey.\n\t\t\tconst uri = spaceRecordUri(\n\t\t\t\tspaceUri(ctx.target.did, space.skey),\n\t\t\t\tctx.target.did,\n\t\t\t\tPOST,\n\t\t\t\t\"rec1\",\n\t\t\t);\n\t\t\tconst createdUri = (created.json as { uri?: string }).uri;\n\t\t\tif (createdUri !== uri || body.uri !== uri)\n\t\t\t\treturn fail(\n\t\t\t\t\t`record uri was ${createdUri} (createRecord) / ${body.uri} (getRecord), expected ${uri}`,\n\t\t\t\t\t{ created: created.json, read: read.json },\n\t\t\t\t);\n\t\t\treturn body.value?.text === \"hello\"\n\t\t\t\t? pass(\"round-tripped the record value and cid, at its at:space/ uri\")\n\t\t\t\t: fail(\"record value did not round-trip\", read.json);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nconst writesUnauthReadRefused = defineCheck({\n\tid: \"auth.existing-record-unauth-refused\",\n\ttitle: \"An existing space record is not readable without auth\",\n\ttier: \"must\",\n\tcitations: [L(\"com.atproto.space.getRecord\")],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\t// The browser-safe auth.getrecord-unauthenticated-refused can only\n\t\t// probe a *nonexistent* space, so on its own it cannot distinguish a\n\t\t// host that enforces auth from one that 401s missing spaces but serves\n\t\t// existing records to anyone. This is the other half.\n\t\tconst space = await createProbeSpace(ctx);\n\t\ttry {\n\t\t\tawait mustCreateRecord(ctx, space.uri, \"private\", \"not for you\");\n\t\t\tconst res = await xrpcGet(ctx, \"com.atproto.space.getRecord\", {\n\t\t\t\tspace: space.uri,\n\t\t\t\trepo: ctx.target.did,\n\t\t\t\tcollection: POST,\n\t\t\t\trkey: \"private\",\n\t\t\t});\n\t\t\tif (res.status === 200)\n\t\t\t\treturn fail(\n\t\t\t\t\t\"an existing space record was served with no auth\",\n\t\t\t\t\tres.json,\n\t\t\t\t);\n\t\t\treturn res.status === 401 || res.status === 403\n\t\t\t\t? pass(`unauthenticated read of a real record refused (${res.status})`)\n\t\t\t\t: fail(\n\t\t\t\t\t\t`refused, but with ${describe(res)} rather than 401/403`,\n\t\t\t\t\t\tres.json,\n\t\t\t\t\t);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nconst writesDuplicate = defineCheck({\n\tid: \"writes.duplicate-rejected\",\n\ttitle: \"A second create at the same key is refused with RecordAlreadyExists\",\n\ttier: \"must\",\n\tcitations: [L(\"com.atproto.space.createRecord@error:RecordAlreadyExists\")],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst space = await createProbeSpace(ctx);\n\t\ttry {\n\t\t\tawait mustCreateRecord(ctx, space.uri, \"dup\", \"one\");\n\t\t\tconst second = await operatorCreateRecord(\n\t\t\t\tctx,\n\t\t\t\tspace.uri,\n\t\t\t\tPOST,\n\t\t\t\t\"dup\",\n\t\t\t\tnote(\"two\"),\n\t\t\t);\n\t\t\tif (second.status === 200) return fail(\"duplicate create returned 200\");\n\t\t\treturn second.error === \"RecordAlreadyExists\"\n\t\t\t\t? pass(\"refused with RecordAlreadyExists\")\n\t\t\t\t: fail(`refused but error was ${describe(second)}`, second.json);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nconst writesPutRecord = defineCheck({\n\tid: \"writes.putrecord-upsert\",\n\ttitle: \"putRecord creates a record and then replaces it\",\n\ttier: \"must\",\n\tcitations: [L(\"com.atproto.space.putRecord\")],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst space = await createProbeSpace(ctx);\n\t\tconst put = (text: string) =>\n\t\t\txrpcPost(op(ctx), \"com.atproto.space.putRecord\", {\n\t\t\t\tspace: space.uri,\n\t\t\t\trepo: ctx.target.did,\n\t\t\t\tcollection: POST,\n\t\t\t\trkey: \"upsert\",\n\t\t\t\trecord: note(text),\n\t\t\t});\n\t\ttry {\n\t\t\tconst first = await put(\"v1\");\n\t\t\tif (first.status !== 200)\n\t\t\t\treturn fail(`putRecord (create) ${describe(first)}`, first.json);\n\t\t\tconst second = await put(\"v2\");\n\t\t\tif (second.status !== 200)\n\t\t\t\treturn fail(`putRecord (update) ${describe(second)}`, second.json);\n\t\t\tconst read = await operatorGetRecord(ctx, space.uri, \"upsert\");\n\t\t\tconst text = (read.json as { value?: { text?: string } } | undefined)\n\t\t\t\t?.value?.text;\n\t\t\treturn text === \"v2\"\n\t\t\t\t? pass(\"created then replaced the record\")\n\t\t\t\t: fail(\n\t\t\t\t\t\t`after two puts the record reads ${describe(read)} ${text}`,\n\t\t\t\t\t\tread.json,\n\t\t\t\t\t);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nconst writesGetRecordMissing = defineCheck({\n\tid: \"writes.getrecord-missing\",\n\ttitle: \"getRecord of an absent rkey answers RecordNotFound\",\n\ttier: \"must\",\n\tcitations: [L(\"com.atproto.space.getRecord@error:RecordNotFound\")],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst space = await createProbeSpace(ctx);\n\t\ttry {\n\t\t\t// The repo exists (one record), so the absence is the record's.\n\t\t\tawait mustCreateRecord(ctx, space.uri, \"present\");\n\t\t\tconst res = await operatorGetRecord(ctx, space.uri, \"absent\");\n\t\t\treturn res.error === \"RecordNotFound\"\n\t\t\t\t? pass(\"answered RecordNotFound\")\n\t\t\t\t: fail(`answered ${describe(res)}, expected RecordNotFound`, res.json);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nconst writesDeleteIdempotent = defineCheck({\n\tid: \"writes.delete-idempotent\",\n\ttitle: \"deleteRecord removes the record and is idempotent\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.space.deleteRecord\"),\n\t\tL(\"com.atproto.space.getRecord\"),\n\t],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst space = await createProbeSpace(ctx);\n\t\ttry {\n\t\t\tconst del = (rkey: string) =>\n\t\t\t\txrpcPost(op(ctx), \"com.atproto.space.deleteRecord\", {\n\t\t\t\t\tspace: space.uri,\n\t\t\t\t\trepo: ctx.target.did,\n\t\t\t\t\tcollection: POST,\n\t\t\t\t\trkey,\n\t\t\t\t});\n\t\t\t// Effect first: without it a deleteRecord that is a no-op (200,\n\t\t\t// nothing happens) would pass on idempotency alone.\n\t\t\tawait mustCreateRecord(ctx, space.uri, \"doomed\", \"bye\");\n\t\t\tconst removed = await del(\"doomed\");\n\t\t\tif (removed.status !== 200)\n\t\t\t\treturn fail(\n\t\t\t\t\t`delete of an existing record returned ${describe(removed)}`,\n\t\t\t\t\tremoved.json,\n\t\t\t\t);\n\t\t\tconst after = await operatorGetRecord(ctx, space.uri, \"doomed\");\n\t\t\tif (after.status === 200)\n\t\t\t\treturn fail(\"a deleted record was still readable\", after.json);\n\t\t\tconst again = await del(\"doomed\");\n\t\t\tconst ghost = await del(\"ghost\");\n\t\t\tif (again.status !== 200 || ghost.status !== 200) {\n\t\t\t\treturn fail(\n\t\t\t\t\t`repeat delete returned ${describe(again)}, absent-key delete returned ${describe(ghost)}`,\n\t\t\t\t\t{\n\t\t\t\t\t\tagain: again.json,\n\t\t\t\t\t\tghost: ghost.json,\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn pass(\"delete removed the record; repeat and absent deletes 200\");\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nconst create = (rkey: string, text: string) => ({\n\t$type: \"com.atproto.space.applyWrites#create\",\n\tcollection: POST,\n\trkey,\n\tvalue: note(text),\n});\n\nconst writesApplyWritesAtomic = defineCheck({\n\tid: \"writes.applywrites-atomic\",\n\ttitle: \"A failing applyWrites batch commits nothing\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.space.applyWrites\"),\n\t\tL(\"com.atproto.space.applyWrites@error:RecordAlreadyExists\"),\n\t],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst space = await createProbeSpace(ctx);\n\t\ttry {\n\t\t\tawait mustCreateRecord(ctx, space.uri, \"exists\", \"here\");\n\t\t\t// Positive control: a target with no applyWrites at all would\n\t\t\t// otherwise pass the rollback assertion vacuously.\n\t\t\tconst ok = await xrpcPost(op(ctx), \"com.atproto.space.applyWrites\", {\n\t\t\t\tspace: space.uri,\n\t\t\t\trepo: ctx.target.did,\n\t\t\t\twrites: [create(\"ok1\", \"1\"), create(\"ok2\", \"2\")],\n\t\t\t});\n\t\t\tif (ok.status !== 200)\n\t\t\t\treturn fail(\n\t\t\t\t\t`applyWrites did not accept a valid batch (${describe(ok)})`,\n\t\t\t\t\tok.json,\n\t\t\t\t);\n\t\t\tconst batch = await xrpcPost(op(ctx), \"com.atproto.space.applyWrites\", {\n\t\t\t\tspace: space.uri,\n\t\t\t\trepo: ctx.target.did,\n\t\t\t\twrites: [create(\"fresh\", \"new\"), create(\"exists\", \"collide\")],\n\t\t\t});\n\t\t\tif (batch.status === 200) return fail(\"colliding batch returned 200\");\n\t\t\tif (batch.error !== \"RecordAlreadyExists\") {\n\t\t\t\treturn fail(\n\t\t\t\t\t`colliding batch refused with ${describe(batch)}, expected RecordAlreadyExists`,\n\t\t\t\t\tbatch.json,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst check = await operatorGetRecord(ctx, space.uri, \"fresh\");\n\t\t\treturn check.status !== 200\n\t\t\t\t? pass(\"a failed batch committed nothing\")\n\t\t\t\t: fail(\"a failed batch left its first op committed\", check.json);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nconst writesApplyWritesMissing = defineCheck({\n\tid: \"writes.applywrites-update-missing\",\n\ttitle: \"An applyWrites update of an absent record answers RecordNotFound\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.space.applyWrites\"),\n\t\tL(\"com.atproto.space.applyWrites@error:RecordNotFound\"),\n\t],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst space = await createProbeSpace(ctx);\n\t\tconst update = (rkey: string, text: string) =>\n\t\t\txrpcPost(op(ctx), \"com.atproto.space.applyWrites\", {\n\t\t\t\tspace: space.uri,\n\t\t\t\trepo: ctx.target.did,\n\t\t\t\twrites: [\n\t\t\t\t\t{\n\t\t\t\t\t\t$type: \"com.atproto.space.applyWrites#update\",\n\t\t\t\t\t\tcollection: POST,\n\t\t\t\t\t\trkey,\n\t\t\t\t\t\tvalue: note(text),\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t});\n\t\ttry {\n\t\t\tawait mustCreateRecord(ctx, space.uri, \"present\");\n\t\t\t// Control: an update of a record that exists succeeds and takes\n\t\t\t// effect, so the refusal below is of the absent record, not of\n\t\t\t// #update itself.\n\t\t\tconst ok = await update(\"present\", \"updated\");\n\t\t\tif (ok.status !== 200)\n\t\t\t\treturn fail(\n\t\t\t\t\t`positive control failed: updating an existing record answered ${describe(ok)}`,\n\t\t\t\t\tok.json,\n\t\t\t\t);\n\t\t\tconst read = await operatorGetRecord(ctx, space.uri, \"present\");\n\t\t\tconst text = (read.json as { value?: { text?: unknown } } | undefined)\n\t\t\t\t?.value?.text;\n\t\t\tif (text !== \"updated\")\n\t\t\t\treturn fail(\n\t\t\t\t\t`the update of an existing record answered 200 but the record reads ${JSON.stringify(text)}`,\n\t\t\t\t\tread.json,\n\t\t\t\t);\n\t\t\tconst res = await update(\"absent\", \"nope\");\n\t\t\treturn res.error === \"RecordNotFound\"\n\t\t\t\t? pass(\n\t\t\t\t\t\t\"an existing record updated; an absent one refused with RecordNotFound\",\n\t\t\t\t\t)\n\t\t\t\t: fail(`answered ${describe(res)}, expected RecordNotFound`, res.json);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\n/** The creating writes, each aimed at `space` (deleteRecord has its own check). */\nfunction writeProbes(ctx: CheckContext, space: string) {\n\tconst repo = ctx.target.did;\n\treturn [\n\t\t[\n\t\t\t\"createRecord\",\n\t\t\t() =>\n\t\t\t\txrpcPost(op(ctx), \"com.atproto.space.createRecord\", {\n\t\t\t\t\tspace,\n\t\t\t\t\trepo,\n\t\t\t\t\tcollection: POST,\n\t\t\t\t\trkey: \"w\",\n\t\t\t\t\trecord: note(\"w\"),\n\t\t\t\t}),\n\t\t],\n\t\t[\n\t\t\t\"putRecord\",\n\t\t\t() =>\n\t\t\t\txrpcPost(op(ctx), \"com.atproto.space.putRecord\", {\n\t\t\t\t\tspace,\n\t\t\t\t\trepo,\n\t\t\t\t\tcollection: POST,\n\t\t\t\t\trkey: \"w\",\n\t\t\t\t\trecord: note(\"w\"),\n\t\t\t\t}),\n\t\t],\n\t\t[\n\t\t\t\"applyWrites\",\n\t\t\t() =>\n\t\t\t\txrpcPost(op(ctx), \"com.atproto.space.applyWrites\", {\n\t\t\t\t\tspace,\n\t\t\t\t\trepo,\n\t\t\t\t\twrites: [create(\"w\", \"w\")],\n\t\t\t\t}),\n\t\t],\n\t] as Array<[string, () => Promise<XrpcResult>]>;\n}\n\nasync function expectNotFound(\n\tprobes: Array<[string, () => Promise<XrpcResult>]>,\n\tlabel: string,\n): Promise<string[]> {\n\tconst misses: string[] = [];\n\tfor (const [name, call] of probes) {\n\t\tconst res = await call();\n\t\tif (res.error !== \"SpaceNotFound\")\n\t\t\tmisses.push(`${label} ${name} → ${describe(res)}`);\n\t}\n\treturn misses;\n}\n\nconst writesSpaceNotFound = defineCheck({\n\tid: \"writes.space-not-found\",\n\ttitle:\n\t\t\"The authority's writes to a missing or deleted space answer SpaceNotFound\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.space.createRecord@error:SpaceNotFound\"),\n\t\tL(\"com.atproto.space.putRecord@error:SpaceNotFound\"),\n\t\tL(\"com.atproto.space.applyWrites@error:SpaceNotFound\"),\n\t\tP(\"0016#repo-lifecycle\"),\n\t\tC(\"brave-spaces-exist\"),\n\t],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\t// A write must neither conjure an ungoverned space nor revive a\n\t\t// deleted one. (Writes into *another* authority's space are a\n\t\t// different matter: a member's host cannot know whether it exists.)\n\t\tconst deleted = await createProbeSpace(ctx, personalspace());\n\t\tawait mustCreateRecord(ctx, deleted.uri, \"before\");\n\t\tawait deleteProbeSpace(ctx, deleted.uri);\n\t\tconst misses = [\n\t\t\t...(await expectNotFound(\n\t\t\t\twriteProbes(ctx, unknownSpaceUri(ctx.target.did)),\n\t\t\t\t\"unknown:\",\n\t\t\t)),\n\t\t\t...(await expectNotFound(writeProbes(ctx, deleted.uri), \"deleted:\")),\n\t\t];\n\t\treturn misses.length\n\t\t\t? fail(`expected SpaceNotFound: ${misses.join(\"; \")}`)\n\t\t\t: pass(\n\t\t\t\t\t\"create, put and applyWrites answered SpaceNotFound for a missing and a deleted space\",\n\t\t\t\t);\n\t},\n});\n\nconst writesDeleteSpaceNotFound = defineCheck({\n\tid: \"writes.delete-in-missing-space\",\n\ttitle:\n\t\t\"The authority's deleteRecord in a missing or deleted space answers SpaceNotFound\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.space.deleteRecord@error:SpaceNotFound\"),\n\t\tP(\"0016#repo-lifecycle\"),\n\t\tC(\"brave-spaces-exist\"),\n\t],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\t// Separate from writes.space-not-found because deleteRecord is also\n\t\t// idempotent (\"or ensure it doesn't exist\"). That speaks to the record,\n\t\t// not the space: deleteRecord declares SpaceNotFound, and when the\n\t\t// writer is the authority \"the space must already exist\" (proposal,\n\t\t// Repo lifecycle).\n\t\tconst deleted = await createProbeSpace(ctx, personalspace());\n\t\tawait mustCreateRecord(ctx, deleted.uri, \"w\");\n\t\tawait deleteProbeSpace(ctx, deleted.uri);\n\t\tconst misses: string[] = [];\n\t\tfor (const [label, space] of [\n\t\t\t[\"unknown\", unknownSpaceUri(ctx.target.did)],\n\t\t\t[\"deleted\", deleted.uri],\n\t\t]) {\n\t\t\tconst res = await xrpcPost(op(ctx), \"com.atproto.space.deleteRecord\", {\n\t\t\t\tspace,\n\t\t\t\trepo: ctx.target.did,\n\t\t\t\tcollection: POST,\n\t\t\t\trkey: \"w\",\n\t\t\t});\n\t\t\tif (res.error !== \"SpaceNotFound\")\n\t\t\t\tmisses.push(`${label} → ${describe(res)}`);\n\t\t}\n\t\treturn misses.length\n\t\t\t? fail(`expected SpaceNotFound: ${misses.join(\"; \")}`)\n\t\t\t: pass(\"answered SpaceNotFound for a missing and a deleted space\");\n\t},\n});\n\nconst writesPublishedRefused = defineCheck({\n\tid: \"writes.published-collections-refused\",\n\ttitle: \"Direct writes to the policy and member collections are refused\",\n\ttier: \"should\",\n\tcitations: [\n\t\tP(\"0016#publishing-to-readers\"),\n\t\tC(\"baseline-space-policies\"),\n\t\tL(\"com.atproto.space.policy\"),\n\t\tL(\"com.atproto.memberspace.member\"),\n\t],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\t// Those records are the PDS's copy of the space's configuration; a\n\t\t// forged one would mislead every reader that trusts it.\n\t\tconst space = await createProbeSpace(ctx, memberspace());\n\t\ttry {\n\t\t\tconst attempts: Array<[string, string, Record<string, unknown>]> = [\n\t\t\t\t[\n\t\t\t\t\t\"com.atproto.space.policy\",\n\t\t\t\t\t\"self\",\n\t\t\t\t\t{\n\t\t\t\t\t\t$type: \"com.atproto.space.policy\",\n\t\t\t\t\t\tpolicy: memberspace({ publicRead: true }),\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\t[\n\t\t\t\t\t\"com.atproto.memberspace.member\",\n\t\t\t\t\t\"did:plc:aaaaaaaaaaaaaaaaaaaaaaaa\",\n\t\t\t\t\t{ $type: \"com.atproto.memberspace.member\", read: true, write: true },\n\t\t\t\t],\n\t\t\t];\n\t\t\tconst accepted: string[] = [];\n\t\t\tconst misanswered: string[] = [];\n\t\t\tfor (const [collection, rkey, record] of attempts) {\n\t\t\t\tfor (const nsid of [\"createRecord\", \"putRecord\"]) {\n\t\t\t\t\tconst res = await xrpcPost(op(ctx), `com.atproto.space.${nsid}`, {\n\t\t\t\t\t\tspace: space.uri,\n\t\t\t\t\t\trepo: ctx.target.did,\n\t\t\t\t\t\tcollection,\n\t\t\t\t\t\trkey,\n\t\t\t\t\t\trecord,\n\t\t\t\t\t});\n\t\t\t\t\tif (res.status === 200) accepted.push(`${nsid} ${collection}`);\n\t\t\t\t\t// No declared error names this; a refusal is a 4xx, not a 5xx.\n\t\t\t\t\telse if (res.status < 400 || res.status >= 500)\n\t\t\t\t\t\tmisanswered.push(`${nsid} ${collection} → ${describe(res)}`);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (accepted.length) return fail(`accepted: ${accepted.join(\", \")}`);\n\t\t\treturn misanswered.length\n\t\t\t\t? fail(`expected a 4xx refusal: ${misanswered.join(\", \")}`)\n\t\t\t\t: pass(\n\t\t\t\t\t\t\"createRecord and putRecord refused both published collections with a 4xx\",\n\t\t\t\t\t);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\n/** sha256 of an all-zero LtHash state: the commit data of an empty repo. */\nconst emptyRepoData = () => sha256(new Uint8Array(2048));\n\nasync function latestCommit(ctx: CheckContext, space: string) {\n\tconst res = await xrpcGet(op(ctx), \"com.atproto.space.getLatestCommit\", {\n\t\tspace,\n\t\trepo: ctx.target.did,\n\t});\n\tconst commit = (\n\t\tres.json as { commit?: { rev?: string; data?: unknown } } | undefined\n\t)?.commit;\n\treturn { res, rev: commit?.rev, data: lexBytes(commit?.data) };\n}\n\nasync function listRecords(\n\tctx: CheckContext,\n\tspace: string,\n\textra: Record<string, string> = {},\n) {\n\tconst res = await xrpcGet(op(ctx), \"com.atproto.space.listRecords\", {\n\t\tspace,\n\t\trepo: ctx.target.did,\n\t\t...extra,\n\t});\n\treturn {\n\t\tres,\n\t\trecords:\n\t\t\t(res.json as { records?: Array<Record<string, unknown>> } | undefined)\n\t\t\t\t?.records ?? [],\n\t};\n}\n\nconst writesClearRecords = defineCheck({\n\tid: \"writes.clearrecords\",\n\ttitle:\n\t\t\"clearRecords empties the repo at a new rev with the empty-repo digest\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.space.clearRecords\"),\n\t\tL(\"com.atproto.space.listRecords\"),\n\t\tP(\"0016#repo-lifecycle\"),\n\t\tC(\"clear-spaces-sweep\"),\n\t],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst space = await createProbeSpace(ctx);\n\t\tconst clear = () =>\n\t\t\txrpcPost(op(ctx), \"com.atproto.space.clearRecords\", {\n\t\t\t\tspace: space.uri,\n\t\t\t\trepo: ctx.target.did,\n\t\t\t});\n\t\ttry {\n\t\t\tawait mustCreateRecord(ctx, space.uri, \"a\");\n\t\t\tawait mustCreateRecord(ctx, space.uri, \"b\");\n\t\t\tconst before = await latestCommit(ctx, space.uri);\n\t\t\tconst cleared = await clear();\n\t\t\tif (cleared.status !== 200)\n\t\t\t\treturn fail(`clearRecords ${describe(cleared)}`, cleared.json);\n\t\t\tconst { records } = await listRecords(ctx, space.uri);\n\t\t\tif (records.length)\n\t\t\t\treturn fail(\n\t\t\t\t\t`${records.length} record(s) survived clearRecords`,\n\t\t\t\t\trecords,\n\t\t\t\t);\n\t\t\tconst after = await latestCommit(ctx, space.uri);\n\t\t\tif (!after.rev || !before.rev || after.rev <= before.rev) {\n\t\t\t\treturn fail(\n\t\t\t\t\t`rev did not advance (${before.rev} → ${after.rev})`,\n\t\t\t\t\tafter.res.json,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!after.data || !bytesEqual(after.data, await emptyRepoData())) {\n\t\t\t\treturn fail(\n\t\t\t\t\t\"commit data after clearRecords is not the empty repo's digest\",\n\t\t\t\t\tafter.res.json,\n\t\t\t\t);\n\t\t\t}\n\t\t\t// \"Clearing a repo with nothing to delete is a no-op.\" (clear-spaces-sweep)\n\t\t\tconst again = await clear();\n\t\t\treturn again.status === 200\n\t\t\t\t? pass(\n\t\t\t\t\t\t\"cleared at a new rev with the empty digest; clearing again is a no-op\",\n\t\t\t\t\t)\n\t\t\t\t: fail(\n\t\t\t\t\t\t`clearing an empty repo returned ${describe(again)}`,\n\t\t\t\t\t\tagain.json,\n\t\t\t\t\t);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nconst writesClearKeepsPublished = defineCheck({\n\tid: \"writes.clearrecords-keeps-published\",\n\ttitle:\n\t\t\"clearRecords in the authority's repo keeps the published policy record\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.space.clearRecords\"),\n\t\tP(\"0016#publishing-to-readers\"),\n\t],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst space = await createProbeSpace(\n\t\t\tctx,\n\t\t\tmemberspace({ publishPolicy: true }),\n\t\t);\n\t\ttry {\n\t\t\tawait mustCreateRecord(ctx, space.uri, \"mine\");\n\t\t\tconst cleared = await xrpcPost(\n\t\t\t\top(ctx),\n\t\t\t\t\"com.atproto.space.clearRecords\",\n\t\t\t\t{\n\t\t\t\t\tspace: space.uri,\n\t\t\t\t\trepo: ctx.target.did,\n\t\t\t\t},\n\t\t\t);\n\t\t\tif (cleared.status !== 200)\n\t\t\t\treturn fail(`clearRecords ${describe(cleared)}`, cleared.json);\n\t\t\tconst own = await operatorGetRecord(ctx, space.uri, \"mine\");\n\t\t\tif (own.status === 200)\n\t\t\t\treturn fail(\"the operator's own record survived clearRecords\");\n\t\t\tconst policy = await operatorGetRecord(\n\t\t\t\tctx,\n\t\t\t\tspace.uri,\n\t\t\t\t\"self\",\n\t\t\t\t\"com.atproto.space.policy\",\n\t\t\t);\n\t\t\treturn policy.status === 200\n\t\t\t\t? pass(\"own record cleared; the published policy record kept\")\n\t\t\t\t: fail(\n\t\t\t\t\t\t`the published policy record was cleared too (${describe(policy)})`,\n\t\t\t\t\t\tpolicy.json,\n\t\t\t\t\t);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nconst syncListRecords = defineCheck({\n\tid: \"sync.listrecords-lists\",\n\ttitle: \"listRecords lists records with values, and excludeValues omits them\",\n\ttier: \"must\",\n\tcitations: [L(\"com.atproto.space.listRecords\"), P(\"0016#xrpc-api\")],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst space = await createProbeSpace(ctx);\n\t\ttry {\n\t\t\tconst a = await mustCreateRecord(ctx, space.uri, \"aaa\", \"first\");\n\t\t\tawait mustCreateRecord(ctx, space.uri, \"bbb\", \"second\");\n\t\t\tconst full = await listRecords(ctx, space.uri, { collection: POST });\n\t\t\tif (full.res.status !== 200)\n\t\t\t\treturn fail(`listRecords ${describe(full.res)}`, full.res.json);\n\t\t\tconst entry = full.records.find((r) => r.rkey === \"aaa\");\n\t\t\tif (full.records.length !== 2 || !entry)\n\t\t\t\treturn fail(`listed ${full.records.length} record(s)`, full.records);\n\t\t\tif (\n\t\t\t\tentry.collection !== POST ||\n\t\t\t\tentry.cid !== a.cid ||\n\t\t\t\t(entry.value as { text?: string })?.text !== \"first\"\n\t\t\t) {\n\t\t\t\treturn fail(\"listed entry does not match the written record\", entry);\n\t\t\t}\n\t\t\tconst bare = await listRecords(ctx, space.uri, {\n\t\t\t\tcollection: POST,\n\t\t\t\texcludeValues: \"true\",\n\t\t\t});\n\t\t\tif (bare.records.length !== 2)\n\t\t\t\treturn fail(\n\t\t\t\t\t`excludeValues listed ${bare.records.length} record(s)`,\n\t\t\t\t\tbare.records,\n\t\t\t\t);\n\t\t\treturn bare.records.some((r) => \"value\" in r)\n\t\t\t\t? fail(\"excludeValues still inlined values\", bare.records)\n\t\t\t\t: pass(\n\t\t\t\t\t\t\"listed both records with values; excludeValues listed metadata only\",\n\t\t\t\t\t);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nconst syncListRecordsDescending = defineCheck({\n\tid: \"sync.listrecords-descending-default\",\n\ttitle: \"listRecords defaults to descending record order\",\n\ttier: \"should\",\n\tcitations: [\n\t\t{ source: \"reference\", ref: \"listRecords default order (descending)\" },\n\t\tL(\"com.atproto.space.listRecords\"),\n\t],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst space = await createProbeSpace(ctx);\n\t\ttry {\n\t\t\tfor (const rkey of [\"aaa\", \"bbb\", \"ccc\"])\n\t\t\t\tawait mustCreateRecord(ctx, space.uri, rkey);\n\t\t\tconst { res, records } = await listRecords(ctx, space.uri, {\n\t\t\t\tcollection: POST,\n\t\t\t});\n\t\t\tif (res.status !== 200) return fail(`listRecords ${describe(res)}`);\n\t\t\tconst rkeys = records.map((r) => r.rkey);\n\t\t\treturn rkeys.join(\",\") === \"ccc,bbb,aaa\"\n\t\t\t\t? pass(\"records returned descending by default\")\n\t\t\t\t: fail(`order was ${rkeys.join(\",\")}, reference is descending`);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nconst garbageCursor = defineCheck({\n\tid: \"request.garbage-cursor-rejected\",\n\ttitle: \"A cursor the host never issued answers InvalidCursor\",\n\ttier: \"should\",\n\tcitations: [\n\t\t{ source: \"reference\", ref: \"pds space readers validate cursor syntax\" },\n\t\tL(\"com.atproto.space.listRecords@error:InvalidCursor\"),\n\t],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst space = await createProbeSpace(ctx, memberspace());\n\t\ttry {\n\t\t\tawait mustCreateRecord(ctx, space.uri, \"a\");\n\t\t\tconst cursor = \"!!not-a-cursor!!\";\n\t\t\tconst base = { space: space.uri, repo: ctx.target.did, cursor };\n\t\t\tconst misses: string[] = [];\n\t\t\tfor (const [name, params] of [\n\t\t\t\t[\"com.atproto.space.listRecords\", base],\n\t\t\t\t[\"com.atproto.space.listRepoOps\", base],\n\t\t\t\t// Filtered to the probe type, so a session scoped to it may list.\n\t\t\t\t[\n\t\t\t\t\t\"com.atproto.space.listSpaces\",\n\t\t\t\t\t{ cursor, spaceType: PROBE_TYPE, spaceDid: ctx.target.did },\n\t\t\t\t],\n\t\t\t\t[\"com.atproto.memberspace.listMembers\", { space: space.uri, cursor }],\n\t\t\t] as const) {\n\t\t\t\tconst res = await xrpcGet(op(ctx), name, params);\n\t\t\t\tif (res.error !== \"InvalidCursor\")\n\t\t\t\t\tmisses.push(`${name.split(\".\").at(-1)} → ${describe(res)}`);\n\t\t\t}\n\t\t\treturn misses.length\n\t\t\t\t? fail(misses.join(\"; \"))\n\t\t\t\t: pass(\"all four answered InvalidCursor\");\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\n// --- blobs -------------------------------------------------------------\n\nasync function uploadBlob(ctx: CheckContext, bytes: Uint8Array) {\n\tconst upload = await operatorFetch(ctx)(\n\t\t`${ctx.target.origin}/xrpc/com.atproto.repo.uploadBlob`,\n\t\t{\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { \"Content-Type\": \"application/octet-stream\" },\n\t\t\tbody: bytes as BodyInit,\n\t\t},\n\t);\n\tif (upload.status !== 200) throw new Error(`uploadBlob ${upload.status}`);\n\treturn ((await upload.json()) as { blob: { ref: { $link: string } } }).blob;\n}\n\n/** Blob isolation: a space blob is never public. */\nconst blobsSpaceNotPublic = defineCheck({\n\tid: \"blobs.space-blob-not-public\",\n\ttitle: \"A blob is not publicly served unless a public record references it\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.space.getBlob\"),\n\t\t{ source: \"proposal\", ref: \"0016#blob-sync\" },\n\t],\n\t// uploadBlob and sync.getBlob are host-PDS endpoints, not space methods.\n\tneeds: [\"operator\", \"pds-blobs\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\t// A blob must never be publicly addressable until a *public* record\n\t\t// references it. Control first: one a public record references IS\n\t\t// served, so the refusals below are not just a getBlob that serves\n\t\t// nothing. Then both slices: freshly uploaded (unreferenced), then\n\t\t// referenced only from a space.\n\t\tconst blobUrl = (cid: string) =>\n\t\t\t`${ctx.target.origin}/xrpc/com.atproto.sync.getBlob?did=${encodeURIComponent(ctx.target.did)}&cid=${cid}`;\n\t\tconst publicBytes = crypto.getRandomValues(new Uint8Array(16));\n\t\tconst publicBlob = await uploadBlob(ctx, publicBytes);\n\t\tconst publicRkey = probeSkey();\n\t\tconst publicWrite = await xrpcPost(\n\t\t\top(ctx),\n\t\t\t\"com.atproto.repo.createRecord\",\n\t\t\t{\n\t\t\t\trepo: ctx.target.did,\n\t\t\t\tcollection: \"earth.cirrus.check.withblob\",\n\t\t\t\trkey: publicRkey,\n\t\t\t\trecord: { $type: \"earth.cirrus.check.withblob\", file: publicBlob },\n\t\t\t},\n\t\t);\n\t\tconst space = await createProbeSpace(ctx);\n\t\ttry {\n\t\t\tif (publicWrite.status !== 200)\n\t\t\t\treturn fail(\n\t\t\t\t\t`public referencing write (repo.createRecord) ${describe(publicWrite)}`,\n\t\t\t\t\tpublicWrite.json,\n\t\t\t\t);\n\t\t\tconst served = await ctx.fetch(blobUrl(publicBlob.ref.$link));\n\t\t\tif (served.status !== 200)\n\t\t\t\treturn fail(\n\t\t\t\t\t`positive control failed: a blob a public record references was not served by sync.getBlob (${served.status})`,\n\t\t\t\t);\n\t\t\tif (!bytesEqual(new Uint8Array(await served.arrayBuffer()), publicBytes))\n\t\t\t\treturn fail(\n\t\t\t\t\t\"sync.getBlob served a publicly referenced blob's bytes wrong\",\n\t\t\t\t);\n\t\t\tconst blob = await uploadBlob(\n\t\t\t\tctx,\n\t\t\t\tcrypto.getRandomValues(new Uint8Array(16)),\n\t\t\t);\n\t\t\tconst publicUrl = blobUrl(blob.ref.$link);\n\t\t\tconst stagedGet = await ctx.fetch(publicUrl);\n\t\t\tif (stagedGet.status === 200) {\n\t\t\t\treturn fail(\n\t\t\t\t\t\"an uploaded, unreferenced blob was served by the public sync.getBlob\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst write = await operatorCreateRecord(\n\t\t\t\tctx,\n\t\t\t\tspace.uri,\n\t\t\t\t\"earth.cirrus.check.withblob\",\n\t\t\t\t\"self\",\n\t\t\t\t{\n\t\t\t\t\t$type: \"earth.cirrus.check.withblob\",\n\t\t\t\t\tfile: blob,\n\t\t\t\t},\n\t\t\t);\n\t\t\tif (write.status !== 200)\n\t\t\t\treturn fail(`referencing write ${describe(write)}`, write.json);\n\t\t\tconst publicGet = await ctx.fetch(publicUrl);\n\t\t\treturn publicGet.status === 200\n\t\t\t\t? fail(\"a space blob was served by the public sync.getBlob\")\n\t\t\t\t: pass(\n\t\t\t\t\t\t`public sync.getBlob served a publicly referenced blob, and refused one unreferenced (${stagedGet.status}) and one space-referenced (${publicGet.status})`,\n\t\t\t\t\t);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t\tif (publicWrite.status === 200)\n\t\t\t\tawait xrpcPost(op(ctx), \"com.atproto.repo.deleteRecord\", {\n\t\t\t\t\trepo: ctx.target.did,\n\t\t\t\t\tcollection: \"earth.cirrus.check.withblob\",\n\t\t\t\t\trkey: publicRkey,\n\t\t\t\t}).catch(() => {});\n\t\t}\n\t},\n});\n\nconst blobsListAndGet = defineCheck({\n\tid: \"blobs.listblobs-and-getblob\",\n\ttitle: \"listBlobs lists a space record's blob and space.getBlob serves it\",\n\ttier: \"must\",\n\tcitations: [L(\"com.atproto.space.listBlobs\"), L(\"com.atproto.space.getBlob\")],\n\tneeds: [\"operator\", \"pds-blobs\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst space = await createProbeSpace(ctx);\n\t\ttry {\n\t\t\tconst bytes = crypto.getRandomValues(new Uint8Array(24));\n\t\t\tconst blob = await uploadBlob(ctx, bytes);\n\t\t\tconst write = await operatorCreateRecord(\n\t\t\t\tctx,\n\t\t\t\tspace.uri,\n\t\t\t\t\"earth.cirrus.check.withblob\",\n\t\t\t\t\"self\",\n\t\t\t\t{\n\t\t\t\t\t$type: \"earth.cirrus.check.withblob\",\n\t\t\t\t\tfile: blob,\n\t\t\t\t},\n\t\t\t);\n\t\t\tif (write.status !== 200)\n\t\t\t\treturn fail(`referencing write ${describe(write)}`, write.json);\n\t\t\tconst list = await xrpcGet(op(ctx), \"com.atproto.space.listBlobs\", {\n\t\t\t\tspace: space.uri,\n\t\t\t\trepo: ctx.target.did,\n\t\t\t});\n\t\t\tconst cids = (list.json as { cids?: string[] } | undefined)?.cids ?? [];\n\t\t\tif (!cids.includes(blob.ref.$link))\n\t\t\t\treturn fail(\n\t\t\t\t\t`listBlobs ${describe(list)} did not list the blob`,\n\t\t\t\t\tlist.json,\n\t\t\t\t);\n\t\t\tconst res = await operatorFetch(ctx)(\n\t\t\t\t`${ctx.target.origin}/xrpc/com.atproto.space.getBlob?space=${encodeURIComponent(space.uri)}&repo=${encodeURIComponent(ctx.target.did)}&cid=${blob.ref.$link}`,\n\t\t\t);\n\t\t\tif (res.status !== 200) return fail(`space.getBlob ${res.status}`);\n\t\t\tconst served = new Uint8Array(await res.arrayBuffer());\n\t\t\treturn bytesEqual(served, bytes)\n\t\t\t\t? pass(\"listed and served the exact bytes\")\n\t\t\t\t: fail(\"space.getBlob served different bytes\");\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nconst blobsNotFound = defineCheck({\n\tid: \"blobs.getblob-not-found\",\n\ttitle:\n\t\t\"space.getBlob of a blob the space does not reference answers BlobNotFound\",\n\ttier: \"must\",\n\tcitations: [L(\"com.atproto.space.getBlob@error:BlobNotFound\")],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\tconst space = await createProbeSpace(ctx);\n\t\ttry {\n\t\t\tawait mustCreateRecord(ctx, space.uri, \"present\");\n\t\t\tconst res = await xrpcGet(op(ctx), \"com.atproto.space.getBlob\", {\n\t\t\t\tspace: space.uri,\n\t\t\t\trepo: ctx.target.did,\n\t\t\t\tcid: await rawCid(crypto.getRandomValues(new Uint8Array(16))),\n\t\t\t});\n\t\t\treturn res.error === \"BlobNotFound\"\n\t\t\t\t? pass(\"answered BlobNotFound\")\n\t\t\t\t: fail(`answered ${describe(res)}, expected BlobNotFound`, res.json);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nconst requestInvalidSpaceUri = defineCheck({\n\tid: \"request.invalid-space-uri-rejected\",\n\ttitle:\n\t\t\"A malformed space reference is rejected as a bad request, not misread\",\n\ttier: \"must\",\n\tcitations: [L(\"com.atproto.space.getLatestCommit\")],\n\tneeds: [\"operator\"],\n\tasync run(ctx) {\n\t\t// Authenticated as the repo's own account, so an auth refusal can't\n\t\t// stand in for the parameter check: `space` fails its space-ref\n\t\t// format. The method declares no error for it, so it is XRPC's\n\t\t// generic InvalidRequest, as for the retired form and a handle\n\t\t// authority (request.legacy-space-uri-rejected and\n\t\t// request.handle-space-authority-rejected).\n\t\tconst res = await xrpcGet(op(ctx), \"com.atproto.space.getLatestCommit\", {\n\t\t\tspace: \"not-a-space-uri\",\n\t\t\trepo: ctx.target.did,\n\t\t});\n\t\treturn res.status === 400 && res.error === \"InvalidRequest\"\n\t\t\t? pass(`rejected the authenticated request with ${describe(res)}`)\n\t\t\t: fail(\n\t\t\t\t\t`answered ${describe(res)} to an authenticated request with a malformed space uri, expected 400 InvalidRequest`,\n\t\t\t\t\tres.json,\n\t\t\t\t);\n\t},\n});\n\nconst getSpace = (ctx: CheckContext, space: string) =>\n\txrpcGet(op(ctx), \"com.atproto.space.getSpace\", { space });\n\nconst requestLegacySpaceUri = defineCheck({\n\tid: \"request.legacy-space-uri-rejected\",\n\ttitle:\n\t\t\"A space param in the retired at://{did}/space/… form is rejected; the at:space/ ref of the same space is served\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.space.getRecord\"),\n\t\tL(\"com.atproto.space.createRecord\"),\n\t\tL(\"com.atproto.space.getSpace\"),\n\t\tP(\"0016#addressing\"),\n\t\tC(\"pds-space-uri-migration\"),\n\t\tC(\"alpha-space-uris\"),\n\t],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\t// Since the 2026-11-24 alpha the space-ref format admits only\n\t\t// at:space/{spaceDid}/{spaceType}/{skey}: \"Space params must use the new\n\t\t// form\", and strict validation — what params get — \"accept[s] only the\n\t\t// current form\". The old form survives only leniently, inside record\n\t\t// values. Authenticated as the authority, against a space that exists,\n\t\t// so neither an auth refusal nor SpaceNotFound can stand in: the same\n\t\t// space under its at:space/ ref is the positive control, and the old\n\t\t// form must fail param validation, which XRPC answers 400\n\t\t// InvalidRequest.\n\t\tconst space = await createProbeSpace(ctx, personalspace());\n\t\tconst ref = spaceUri(ctx.target.did, space.skey);\n\t\tconst legacy = legacySpaceUri(ctx.target.did, space.skey);\n\t\tconst invalid = (r: XrpcResult) =>\n\t\t\tr.status === 400 && errorIs(\"InvalidRequest\")(r);\n\t\tconst ok = (r: XrpcResult) => r.status === 200;\n\t\ttry {\n\t\t\tawait mustCreateRecord(ctx, ref, \"a\");\n\t\t\tconst {\n\t\t\t\tok: passed,\n\t\t\t\tdetail,\n\t\t\t\tevidence,\n\t\t\t} = await expectEach([\n\t\t\t\t[\"getRecord at:space/\", () => operatorGetRecord(ctx, ref, \"a\"), ok],\n\t\t\t\t[\"getSpace at:space/\", () => getSpace(ctx, ref), ok],\n\t\t\t\t[\n\t\t\t\t\t\"createRecord at:space/\",\n\t\t\t\t\t() => operatorCreateRecord(ctx, ref, POST, \"b\", note(\"b\")),\n\t\t\t\t\tok,\n\t\t\t\t],\n\t\t\t\t[\"getRecord at://\", () => operatorGetRecord(ctx, legacy, \"a\"), invalid],\n\t\t\t\t[\"getSpace at://\", () => getSpace(ctx, legacy), invalid],\n\t\t\t\t[\n\t\t\t\t\t\"createRecord at://\",\n\t\t\t\t\t() => operatorCreateRecord(ctx, legacy, POST, \"c\", note(\"c\")),\n\t\t\t\t\tinvalid,\n\t\t\t\t],\n\t\t\t]);\n\t\t\treturn passed\n\t\t\t\t? pass(\n\t\t\t\t\t\t\"the at:space/ ref was served; the at:// form was rejected 400 InvalidRequest by getRecord, getSpace and createRecord\",\n\t\t\t\t\t\tevidence,\n\t\t\t\t\t)\n\t\t\t\t: fail(\n\t\t\t\t\t\t`expected 200 for at:space/, 400 InvalidRequest for at://: ${detail}`,\n\t\t\t\t\t\tevidence,\n\t\t\t\t\t);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nconst requestHandleAuthority = defineCheck({\n\tid: \"request.handle-space-authority-rejected\",\n\ttitle:\n\t\t\"A space ref naming its authority by handle is rejected; the DID ref of the same space is served\",\n\ttier: \"must\",\n\tcitations: [\n\t\tL(\"com.atproto.space.getSpace\"),\n\t\tL(\"com.atproto.space.getRecord\"),\n\t\tP(\"0016#addressing\"),\n\t\tC(\"spaces-syntax\"),\n\t],\n\tneeds: [\"operator\"],\n\tdestructive: true,\n\tasync run(ctx) {\n\t\t// \"spaceDid and authorDid must be DIDs. Neither may be a handle\" — a\n\t\t// space URI \"must be valid in full\". The handle is the operator's own\n\t\t// (from its DID document) where it has one, so a host that resolved\n\t\t// handles would find the space: only refusing the syntax passes.\n\t\tconst handle = await resolveDidDocument(ctx, ctx.target.did)\n\t\t\t.then((doc) =>\n\t\t\t\tdoc.alsoKnownAs\n\t\t\t\t\t?.find((aka) => aka.startsWith(\"at://\"))\n\t\t\t\t\t?.slice(\"at://\".length),\n\t\t\t)\n\t\t\t.catch(() => undefined);\n\t\tconst authority = handle || \"space-conformance.invalid\";\n\t\tconst space = await createProbeSpace(ctx, personalspace());\n\t\tconst ref = spaceUri(ctx.target.did, space.skey);\n\t\tconst byHandle = spaceUri(authority, space.skey);\n\t\tconst invalid = (r: XrpcResult) =>\n\t\t\tr.status === 400 && errorIs(\"InvalidRequest\")(r);\n\t\tconst ok = (r: XrpcResult) => r.status === 200;\n\t\ttry {\n\t\t\tawait mustCreateRecord(ctx, ref, \"a\");\n\t\t\tconst {\n\t\t\t\tok: passed,\n\t\t\t\tdetail,\n\t\t\t\tevidence,\n\t\t\t} = await expectEach([\n\t\t\t\t[\"getSpace by DID\", () => getSpace(ctx, ref), ok],\n\t\t\t\t[\"getRecord by DID\", () => operatorGetRecord(ctx, ref, \"a\"), ok],\n\t\t\t\t[\"getSpace by handle\", () => getSpace(ctx, byHandle), invalid],\n\t\t\t\t[\n\t\t\t\t\t\"getRecord by handle\",\n\t\t\t\t\t() => operatorGetRecord(ctx, byHandle, \"a\"),\n\t\t\t\t\tinvalid,\n\t\t\t\t],\n\t\t\t]);\n\t\t\treturn passed\n\t\t\t\t? pass(\n\t\t\t\t\t\t`the DID ref was served; ${byHandle} was rejected 400 InvalidRequest`,\n\t\t\t\t\t\tevidence,\n\t\t\t\t\t)\n\t\t\t\t: fail(\n\t\t\t\t\t\t`expected 200 by DID, 400 InvalidRequest by handle (${authority}): ${detail}`,\n\t\t\t\t\t\tevidence,\n\t\t\t\t\t);\n\t\t} finally {\n\t\t\tawait deleteProbeSpace(ctx, space.uri);\n\t\t}\n\t},\n});\n\nexport const recordChecks: Check[] = [\n\twritesCreateRead,\n\twritesUnauthReadRefused,\n\twritesDuplicate,\n\twritesPutRecord,\n\twritesGetRecordMissing,\n\twritesDeleteIdempotent,\n\twritesApplyWritesAtomic,\n\twritesApplyWritesMissing,\n\twritesSpaceNotFound,\n\twritesDeleteSpaceNotFound,\n\twritesPublishedRefused,\n\twritesClearRecords,\n\twritesClearKeepsPublished,\n\tsyncListRecords,\n\tsyncListRecordsDescending,\n\tgarbageCursor,\n\trequestInvalidSpaceUri,\n\trequestLegacySpaceUri,\n\trequestHandleAuthority,\n\tblobsSpaceNotPublic,\n\tblobsListAndGet,\n\tblobsNotFound,\n];\n","/**\n * Operator checks: everything an authenticated session can prove with the\n * platform's own `fetch` and WebCrypto — no alpha crypto libs, no foreign\n * identities. They run wherever the base checks run, browsers included, as\n * long as the harness supplies an `operator` capability (and, for some,\n * `pds-blobs`, `pds-delegation` or a `syncer-inbox`).\n *\n * The split matters: checks live here or in `../full/checks.js` by what\n * they *actually import*, not by topic. Presenting a space credential —\n * a P-256 HTTP signature and a KEM key share — needs nothing a browser\n * lacks, so every check that only presents one belongs here; verifying the\n * MACs that come back needs the reference library, and lives there.\n */\n\nimport type { Check } from \"../model.js\";\nimport { credentialChecks } from \"./credential.js\";\nimport { hostChecks } from \"./host.js\";\nimport { recordChecks } from \"./records.js\";\nimport { spaceChecks } from \"./space.js\";\n\nexport {\n\tcreateProbeSpace,\n\tcredentialCall,\n\tcredentialGet,\n\tdeleteProbeSpace,\n\tmanagedspace,\n\tmemberspace,\n\tobtainCredentialViaDelegation,\n\tobtainPublicCredential,\n\toperatorCreateRecord,\n\tpersonalspace,\n\tpublicRead,\n\trequestCredential,\n} from \"./probe.js\";\nexport type {\n\tCredential,\n\tCredentialCallOptions,\n\tCredentialResult,\n\tPolicy,\n\tProbeSpace,\n} from \"./probe.js\";\n\n/**\n * The operator catalog: runnable anywhere the harness has an operator\n * session — browser included.\n */\nexport const operatorChecks: Check[] = [\n\t...recordChecks,\n\t...spaceChecks,\n\t...credentialChecks,\n\t...hostChecks,\n];\n","/**\n * A ready-made syncer inbox: the `notify` endpoint and managing app the\n * notification checks need, as a fetch-style handler. A harness serves\n * `handle` at `endpoint` however suits it — a node HTTP server, a route in\n * an in-process fixture — and passes `inbox` as `ctx.syncerInbox`.\n *\n * It also plays an OAuth client: `GET {endpoint}/client-metadata.json` is\n * a client-metadata document (client_id = that URL) publishing one ES256\n * key, and `inbox.attest()` mints client attestations signed by it — so\n * the attestation checks can send one a space host can actually verify.\n *\n * Browser-safe (Request/Response only), though no browser can be reached\n * by a remote host, so the web checker never offers it.\n */\n\nimport type { InboxDelivery, SyncerInbox } from \"./model.js\";\nimport { toBase64Url } from \"./encoding.js\";\nimport { signClientAttestation } from \"./space-auth.js\";\n\nexport interface SyncerInboxHandle {\n\tinbox: SyncerInbox;\n\t/** Serve a request addressed to the inbox's endpoint. */\n\thandle(request: Request): Promise<Response>;\n\t/** Every delivery so far, oldest first. */\n\tdeliveries(): readonly InboxDelivery[];\n}\n\nconst json = (status: number, body: unknown) =>\n\tnew Response(JSON.stringify(body), {\n\t\tstatus,\n\t\theaders: { \"Content-Type\": \"application/json\" },\n\t});\n\nexport function createSyncerInbox(opts: {\n\t/** Base URL the target will call (`{endpoint}/xrpc/<nsid>`). */\n\tendpoint: string;\n\t/** A `did#serviceId` reference resolving to `endpoint` (managing app). */\n\tservice: string;\n}): SyncerInboxHandle {\n\tconst deliveries: InboxDelivery[] = [];\n\tconst waiters = new Set<() => void>();\n\tconst responders = new Map<string, (d: InboxDelivery) => unknown>();\n\tconst tokens = new Map<string, string>(); // token → space\n\n\t// The OAuth client the inbox publishes, for client attestations.\n\tconst base = new URL(opts.endpoint);\n\tconst metadataPath = `${base.pathname.replace(/\\/$/, \"\")}/client-metadata.json`;\n\tconst clientId = `${base.origin}${metadataPath}`;\n\tconst kid = \"space-conformance-1\";\n\tconst keyPair = crypto.subtle.generateKey(\n\t\t{ name: \"ECDSA\", namedCurve: \"P-256\" },\n\t\ttrue,\n\t\t[\"sign\", \"verify\"],\n\t) as Promise<CryptoKeyPair>;\n\tasync function clientMetadata() {\n\t\tconst { kty, crv, x, y } = await crypto.subtle.exportKey(\n\t\t\t\"jwk\",\n\t\t\t(await keyPair).publicKey,\n\t\t);\n\t\treturn {\n\t\t\tclient_id: clientId,\n\t\t\tclient_name: \"space-conformance\",\n\t\t\tapplication_type: \"web\",\n\t\t\tgrant_types: [\"authorization_code\"],\n\t\t\tresponse_types: [\"code\"],\n\t\t\t// Never used: the client exists only to be attested.\n\t\t\tredirect_uris: [\"http://127.0.0.1/callback\"],\n\t\t\tscope: \"atproto\",\n\t\t\tdpop_bound_access_tokens: true,\n\t\t\ttoken_endpoint_auth_method: \"private_key_jwt\",\n\t\t\ttoken_endpoint_auth_signing_alg: \"ES256\",\n\t\t\tjwks: { keys: [{ kty, crv, x, y, kid, alg: \"ES256\", use: \"sig\" }] },\n\t\t};\n\t}\n\n\tconst known = (body: unknown) => {\n\t\tconst b = body as { space?: unknown; token?: unknown } | undefined;\n\t\treturn (\n\t\t\ttypeof b?.token === \"string\" &&\n\t\t\ttypeof b.space === \"string\" &&\n\t\t\ttokens.get(b.token) === b.space\n\t\t);\n\t};\n\n\tasync function handle(request: Request): Promise<Response> {\n\t\tconst url = new URL(request.url);\n\t\tif (request.method === \"GET\" && url.pathname === metadataPath) {\n\t\t\treturn json(200, await clientMetadata());\n\t\t}\n\t\tconst lxm = url.pathname.replace(/^\\/xrpc\\//, \"\");\n\t\tconst raw = request.method === \"POST\" ? await request.text() : \"\";\n\t\tlet body: unknown;\n\t\ttry {\n\t\t\tbody = raw ? JSON.parse(raw) : undefined;\n\t\t} catch {\n\t\t\tbody = raw;\n\t\t}\n\t\tlet response: Response;\n\t\tif (lxm === \"com.atproto.space.confirmRegistration\") {\n\t\t\t// Echo the challenge only for a token issued for this space.\n\t\t\tresponse = known(body)\n\t\t\t\t? json(200, { challenge: (body as { challenge: unknown }).challenge })\n\t\t\t\t: json(400, { error: \"InvalidToken\", message: \"unknown token\" });\n\t\t} else if (lxm === \"com.atproto.space.notifySpaceUpdate\") {\n\t\t\tresponse = known(body)\n\t\t\t\t? json(200, {})\n\t\t\t\t: json(400, { error: \"InvalidToken\", message: \"unknown token\" });\n\t\t} else {\n\t\t\tconst responder = responders.get(lxm);\n\t\t\tresponse = responder\n\t\t\t\t? json(\n\t\t\t\t\t\t200,\n\t\t\t\t\t\tresponder({\n\t\t\t\t\t\t\tlxm,\n\t\t\t\t\t\t\tbody,\n\t\t\t\t\t\t\tparams: Object.fromEntries(url.searchParams),\n\t\t\t\t\t\t\tstatus: 200,\n\t\t\t\t\t\t\treceivedAt: Date.now(),\n\t\t\t\t\t\t}),\n\t\t\t\t\t)\n\t\t\t\t: json(501, { error: \"MethodNotImplemented\" });\n\t\t}\n\t\tconst authorization = request.headers.get(\"authorization\");\n\t\tdeliveries.push({\n\t\t\tlxm,\n\t\t\tbody,\n\t\t\tparams: Object.fromEntries(url.searchParams),\n\t\t\t...(authorization ? { authorization } : {}),\n\t\t\tstatus: response.status,\n\t\t\treceivedAt: Date.now(),\n\t\t});\n\t\tfor (const wake of waiters) wake();\n\t\treturn response;\n\t}\n\n\tconst inbox: SyncerInbox = {\n\t\tendpoint: opts.endpoint,\n\t\tservice: opts.service,\n\t\tissueToken(space) {\n\t\t\tconst token = toBase64Url(crypto.getRandomValues(new Uint8Array(32)));\n\t\t\ttokens.set(token, space);\n\t\t\treturn token;\n\t\t},\n\t\tasync waitFor(predicate, timeoutMs) {\n\t\t\tconst deadline = Date.now() + timeoutMs;\n\t\t\tfor (;;) {\n\t\t\t\tconst found = deliveries.find(predicate);\n\t\t\t\tif (found) return found;\n\t\t\t\tconst remaining = deadline - Date.now();\n\t\t\t\tif (remaining <= 0) return null;\n\t\t\t\tawait new Promise<void>((resolve) => {\n\t\t\t\t\tconst done = () => {\n\t\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\t\twaiters.delete(done);\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t};\n\t\t\t\t\tconst timer = setTimeout(done, remaining);\n\t\t\t\t\twaiters.add(done);\n\t\t\t\t});\n\t\t\t}\n\t\t},\n\t\trespond(lxm, handler) {\n\t\t\tif (handler) responders.set(lxm, handler);\n\t\t\telse responders.delete(lxm);\n\t\t},\n\t\tclientId,\n\t\tasync attest(aud) {\n\t\t\tconst { privateKey } = await keyPair;\n\t\t\treturn signClientAttestation({\n\t\t\t\tclientId,\n\t\t\t\taud,\n\t\t\t\tkid,\n\t\t\t\tsign: async (bytes) =>\n\t\t\t\t\tnew Uint8Array(\n\t\t\t\t\t\tawait crypto.subtle.sign(\n\t\t\t\t\t\t\t{ name: \"ECDSA\", hash: \"SHA-256\" },\n\t\t\t\t\t\t\tprivateKey,\n\t\t\t\t\t\t\tbytes as BufferSource,\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t});\n\t\t},\n\t};\n\n\treturn { inbox, handle, deliveries: () => deliveries };\n}\n","/**\n * Dependency-free descriptors of the crypto-bound checks.\n *\n * The browser adapter can't import the real crypto catalog (it pulls the\n * alpha libs and node streams), but it must still *list* those checks so a\n * viewer sees them reported as \"not testable here\" rather than silently\n * omitted — an omitted check reads as conformant, the exact failure this\n * suite exists to prevent.\n *\n * These are the single source of the crypto checks' metadata: each real\n * check in `./full/checks.ts` is defined by spreading its descriptor, so\n * the two cannot drift. A test still pins that every descriptor has a\n * check and vice versa.\n */\n\nimport type { Capability, Check, Citation, Tier } from \"./model.js\";\nimport { pass } from \"./model.js\";\n\nexport interface CheckDescriptor {\n\tid: string;\n\ttitle: string;\n\ttier: Tier;\n\tneeds: Capability[];\n\tcitations: Citation[];\n\tdestructive?: boolean;\n\tslow?: boolean;\n\ttimeoutMs?: number;\n}\n\nconst L = (ref: string): Citation => ({ source: \"lexicon\", ref });\nconst C = (ref: string): Citation => ({ source: \"changeset\", ref });\n\nconst P = (ref: string): Citation => ({ source: \"proposal\", ref });\n\n/** Refusals a policy may give an account it does not authorise. */\nconst ACCOUNT_REFUSALS = [\n\tL(\"com.atproto.space.authorizeSpaceSync@error:SpaceNotFound\"),\n\tL(\"com.atproto.space.authorizeSpaceSync@error:AccountNotAuthorized\"),\n\tL(\"com.atproto.space.authorizeSpaceSync@error:NotAuthorized\"),\n];\n\n/** Every crypto-bound check, by metadata, in catalog order. */\nexport const cryptoCheckDescriptors: CheckDescriptor[] = [\n\t// --- MAC verification ------------------------------------------------\n\t{\n\t\tid: \"mac.commit-verifies\",\n\t\ttitle:\n\t\t\t\"getLatestCommit's commit MAC verifies, under the requested label, with Vary: Accept-Signature, naming the at:space/ ref\",\n\t\ttier: \"must\",\n\t\tneeds: [\"operator\"],\n\t\tcitations: [\n\t\t\tL(\"com.atproto.space.getLatestCommit\"),\n\t\t\tL(\"com.atproto.space.defs#commit\"),\n\t\t\tP(\"0016#requesting-a-mac\"),\n\t\t\tP(\"0016#commit-mac\"),\n\t\t\tC(\"pds-space-uri-migration\"),\n\t\t],\n\t\tdestructive: true,\n\t},\n\t{\n\t\tid: \"mac.record-verifies\",\n\t\ttitle:\n\t\t\t\"getRecord's record MAC verifies over its at:space/ uri, and its value encodes to its cid\",\n\t\ttier: \"must\",\n\t\tneeds: [\"operator\"],\n\t\tcitations: [\n\t\t\tL(\"com.atproto.space.getRecord\"),\n\t\t\tP(\"0016#record-mac\"),\n\t\t\tC(\"spaces-syntax\"),\n\t\t],\n\t\tdestructive: true,\n\t},\n\t{\n\t\tid: \"sync.oplog-folds-to-commit\",\n\t\ttitle:\n\t\t\t\"Every listRepoOps page carries a MAC-verified commit, and the ops fold to its data\",\n\t\ttier: \"must\",\n\t\tneeds: [\"operator\"],\n\t\tcitations: [\n\t\t\tL(\"com.atproto.space.listRepoOps\"),\n\t\t\tL(\"com.atproto.space.defs#commit\"),\n\t\t\tP(\"0016#incremental-sync\"),\n\t\t],\n\t\tdestructive: true,\n\t},\n\t{\n\t\tid: \"sync.getrepo-star\",\n\t\ttitle:\n\t\t\t\"getRepo serves a STAR archive (application/vnd.dasl.star) that verifies against its MAC\",\n\t\ttier: \"must\",\n\t\tneeds: [\"operator\"],\n\t\tcitations: [L(\"com.atproto.space.getRepo\"), P(\"0016#repo-serialization\")],\n\t\tdestructive: true,\n\t},\n\t// --- token signatures ------------------------------------------------\n\t{\n\t\tid: \"credential.signed-by-authority\",\n\t\ttitle: \"A credential verifies against the authority's #atproto key\",\n\t\ttier: \"must\",\n\t\tneeds: [\"operator\"],\n\t\tcitations: [\n\t\t\tL(\"com.atproto.space.authorizeSpaceSync\"),\n\t\t\tP(\"0016#space-credential\"),\n\t\t],\n\t\tdestructive: true,\n\t},\n\t{\n\t\tid: \"delegation.signed-by-user\",\n\t\ttitle: \"A delegation token verifies against the user's #atproto key\",\n\t\ttier: \"must\",\n\t\tneeds: [\"operator\", \"pds-delegation\"],\n\t\tcitations: [\n\t\t\tL(\"com.atproto.space.getDelegationToken\"),\n\t\t\tP(\"0016#delegation-token\"),\n\t\t],\n\t\tdestructive: true,\n\t},\n\t// --- migration -------------------------------------------------------\n\t{\n\t\tid: \"migration.export-space-meta\",\n\t\ttitle:\n\t\t\t\"exportSpaceMeta serves the policy, members and live writers (with repoRev) as a STAR file\",\n\t\ttier: \"must\",\n\t\tneeds: [\"operator\"],\n\t\tcitations: [\n\t\t\tL(\"com.atproto.space.exportSpaceMeta\"),\n\t\t\tP(\"0016#space-meta-archive\"),\n\t\t\tC(\"removed-writers-notify\"),\n\t\t],\n\t\tdestructive: true,\n\t},\n\t{\n\t\tid: \"migration.import-space-meta\",\n\t\ttitle: \"importSpaceMeta replaces the space's policy and member list\",\n\t\ttier: \"must\",\n\t\tneeds: [\"operator\"],\n\t\tcitations: [\n\t\t\tL(\"com.atproto.space.importSpaceMeta\"),\n\t\t\tP(\"0016#space-meta-archive\"),\n\t\t],\n\t\tdestructive: true,\n\t},\n\t{\n\t\tid: \"migration.import-space-meta-not-authority\",\n\t\ttitle: \"importSpaceMeta of another DID's space answers NotAuthorized\",\n\t\ttier: \"must\",\n\t\tneeds: [\"operator\"],\n\t\tcitations: [L(\"com.atproto.space.importSpaceMeta@error:NotAuthorized\")],\n\t},\n\t{\n\t\tid: \"migration.import-space-meta-unsupported-policy\",\n\t\ttitle:\n\t\t\t\"importSpaceMeta of an unimplemented policy answers UnsupportedPolicy\",\n\t\ttier: \"must\",\n\t\tneeds: [\"operator\"],\n\t\tcitations: [\n\t\t\tL(\"com.atproto.space.importSpaceMeta@error:UnsupportedPolicy\"),\n\t\t\tP(\"0016#space-meta-archive\"),\n\t\t],\n\t\tdestructive: true,\n\t},\n\t{\n\t\tid: \"migration.import-space-meta-invalid\",\n\t\ttitle: \"importSpaceMeta of a malformed archive answers InvalidSpaceMeta\",\n\t\ttier: \"must\",\n\t\tneeds: [\"operator\"],\n\t\tcitations: [\n\t\t\tL(\"com.atproto.space.importSpaceMeta@error:InvalidSpaceMeta\"),\n\t\t\tP(\"0016#space-meta-archive\"),\n\t\t],\n\t},\n\t{\n\t\tid: \"migration.import-repo\",\n\t\ttitle:\n\t\t\t\"importRepo of a getRepo archive keeps the records and data at a new rev\",\n\t\ttier: \"must\",\n\t\tneeds: [\"operator\"],\n\t\tcitations: [\n\t\t\tL(\"com.atproto.space.importRepo\"),\n\t\t\tL(\"com.atproto.space.getRepo\"),\n\t\t\tP(\"0016#account-migration\"),\n\t\t],\n\t\tdestructive: true,\n\t},\n\t{\n\t\tid: \"migration.import-repo-space-not-found\",\n\t\ttitle:\n\t\t\t\"importRepo into an own space that was never imported answers SpaceNotFound\",\n\t\ttier: \"must\",\n\t\tneeds: [\"operator\"],\n\t\tcitations: [L(\"com.atproto.space.importRepo@error:SpaceNotFound\")],\n\t},\n\t{\n\t\tid: \"migration.import-repo-invalid\",\n\t\ttitle: \"importRepo of a malformed archive answers InvalidRepoFile\",\n\t\ttier: \"must\",\n\t\tneeds: [\"operator\"],\n\t\tcitations: [L(\"com.atproto.space.importRepo@error:InvalidRepoFile\")],\n\t},\n\t{\n\t\tid: \"migration.import-repo-mismatch\",\n\t\ttitle: \"importRepo of another account's repo answers RepoMismatch\",\n\t\ttier: \"must\",\n\t\tneeds: [\"operator\"],\n\t\tcitations: [L(\"com.atproto.space.importRepo@error:RepoMismatch\")],\n\t\tdestructive: true,\n\t},\n\t// --- foreign identities ----------------------------------------------\n\t{\n\t\tid: \"credential.member-gate\",\n\t\ttitle:\n\t\t\t\"A memberspace refuses a non-member and a read:false member, and admits a reader\",\n\t\ttier: \"must\",\n\t\tneeds: [\"operator\", \"identities\"],\n\t\tcitations: [\n\t\t\t...ACCOUNT_REFUSALS,\n\t\t\tL(\"com.atproto.memberspace.putMembers\"),\n\t\t\tL(\"com.atproto.memberspace.policy\"),\n\t\t\tP(\"0016#memberspace\"),\n\t\t],\n\t\tdestructive: true,\n\t},\n\t{\n\t\tid: \"policy.personalspace-owner-only\",\n\t\ttitle: \"A personalspace refuses every account but its authority\",\n\t\ttier: \"must\",\n\t\tneeds: [\"operator\", \"identities\"],\n\t\tcitations: [\n\t\t\t...ACCOUNT_REFUSALS,\n\t\t\tL(\"com.atproto.personalspace.policy\"),\n\t\t\tP(\"0016#personalspace\"),\n\t\t],\n\t\tdestructive: true,\n\t},\n\t{\n\t\tid: \"delegation.wrong-audience-refused\",\n\t\ttitle: \"A delegation token addressed to another host is refused\",\n\t\ttier: \"must\",\n\t\tneeds: [\"operator\", \"identities\"],\n\t\tcitations: [\n\t\t\tL(\"com.atproto.space.authorizeSpaceSync@error:InvalidDelegationToken\"),\n\t\t\tP(\"0016#delegation-token\"),\n\t\t],\n\t\tdestructive: true,\n\t},\n\t{\n\t\tid: \"host.notifyrepoupdate-accepted\",\n\t\ttitle: \"An authorised writer's notifyRepoUpdate enters the writer set\",\n\t\ttier: \"must\",\n\t\tneeds: [\"operator\", \"identities\"],\n\t\tcitations: [\n\t\t\tL(\"com.atproto.space.notifyRepoUpdate\"),\n\t\t\tL(\"com.atproto.space.listWriters\"),\n\t\t\tP(\"0016#write-notifications\"),\n\t\t],\n\t\tdestructive: true,\n\t},\n\t{\n\t\tid: \"host.notifyrepoupdate-future-rev\",\n\t\ttitle:\n\t\t\t\"notifyRepoUpdate with a repoRev beyond clock skew answers FutureRev\",\n\t\ttier: \"must\",\n\t\tneeds: [\"operator\", \"identities\"],\n\t\tcitations: [\n\t\t\tL(\"com.atproto.space.notifyRepoUpdate@error:FutureRev\"),\n\t\t\tP(\"0016#write-notifications\"),\n\t\t],\n\t\tdestructive: true,\n\t},\n\t{\n\t\tid: \"host.notifyrepoupdate-unknown-space\",\n\t\ttitle:\n\t\t\t\"notifyRepoUpdate for a space the authority does not have answers SpaceNotFound\",\n\t\ttier: \"must\",\n\t\tneeds: [\"operator\", \"identities\"],\n\t\tcitations: [L(\"com.atproto.space.notifyRepoUpdate@error:SpaceNotFound\")],\n\t},\n\t{\n\t\tid: \"memberspace.write-revocation-removes-writer\",\n\t\ttitle:\n\t\t\t\"Revoking a member's write access removes it from the writer set, and its writes stop being tracked\",\n\t\ttier: \"should\",\n\t\tneeds: [\"operator\", \"identities\"],\n\t\tcitations: [P(\"0016#memberspace\"), P(\"0016#write-notifications\")],\n\t\tdestructive: true,\n\t},\n\t{\n\t\tid: \"revocation.revoked-credential-refused\",\n\t\ttitle:\n\t\t\t\"A repo host accepts a foreign authority's credential until it is revoked\",\n\t\ttier: \"must\",\n\t\tneeds: [\"operator\", \"identities\"],\n\t\tcitations: [\n\t\t\tL(\"com.atproto.space.notifyCredentialsRevoked\"),\n\t\t\tL(\"com.atproto.space.getRecord\"),\n\t\t\tP(\"0016#credential-expiration-and-revocation\"),\n\t\t],\n\t\tdestructive: true,\n\t},\n\t{\n\t\tid: \"revocation.error-name\",\n\t\ttitle: \"A revoked credential is refused with CredentialRevoked\",\n\t\ttier: \"should\",\n\t\tneeds: [\"operator\", \"identities\"],\n\t\tcitations: [\n\t\t\t{ source: \"reference\", ref: \"pds auth-verifier spaceCredentialAuth\" },\n\t\t],\n\t\tdestructive: true,\n\t},\n\t{\n\t\tid: \"revocation.non-authority-refused\",\n\t\ttitle:\n\t\t\t\"notifyCredentialsRevoked from anyone but the space authority is refused\",\n\t\ttier: \"must\",\n\t\tneeds: [\"operator\", \"identities\"],\n\t\tcitations: [\n\t\t\tL(\"com.atproto.space.notifyCredentialsRevoked\"),\n\t\t\tP(\"0016#credential-expiration-and-revocation\"),\n\t\t],\n\t\tdestructive: true,\n\t},\n\t{\n\t\tid: \"managedspace.check-access-account\",\n\t\ttitle: \"A managedspace asks its managing app about the delegated account\",\n\t\ttier: \"must\",\n\t\tneeds: [\"operator\", \"identities\", \"syncer-inbox\"],\n\t\tcitations: [\n\t\t\tL(\"com.atproto.managedspace.checkAccess\"),\n\t\t\tL(\"com.atproto.managedspace.policy\"),\n\t\t\tP(\"0016#managedspace\"),\n\t\t],\n\t\tdestructive: true,\n\t},\n];\n\nexport function descriptor(id: string): CheckDescriptor {\n\tconst found = cryptoCheckDescriptors.find((d) => d.id === id);\n\tif (!found) throw new Error(`no crypto check descriptor ${id}`);\n\treturn found;\n}\n\n/**\n * Turn a descriptor into a listable Check. Its run() is never invoked —\n * beyond the descriptor's own needs, the stub declares `alpha-libs` (the\n * ability to execute the alpha crypto code), which no browser harness\n * provides, so the runner always filters it into `skipped` — but it\n * throws if reached, so a mistaken run surfaces loudly rather than\n * passing.\n */\nexport function descriptorToStub(d: CheckDescriptor): Check {\n\treturn {\n\t\tid: d.id,\n\t\ttitle: d.title,\n\t\ttier: d.tier,\n\t\tneeds: [...d.needs, \"alpha-libs\"],\n\t\tcitations: d.citations,\n\t\t...(d.destructive ? { destructive: true } : {}),\n\t\t...(d.slow ? { slow: true } : {}),\n\t\trun: async () => {\n\t\t\tthrow new Error(\n\t\t\t\t`${d.id} is a metadata stub and cannot run in this transport`,\n\t\t\t);\n\t\t\t// unreachable; satisfies the return type\n\t\t\treturn pass(\"\");\n\t\t},\n\t};\n}\n"],"mappings":";AAgRA,MAAa,QAAQ,QAAgB,cAAsC;CAC1E,QAAQ;CACR;CACA,GAAI,aAAa,SAAY,EAAE,UAAU,GAAG,EAAE;CAC9C;AAED,MAAa,QAAQ,QAAgB,cAAsC;CAC1E,QAAQ;CACR;CACA,GAAI,aAAa,SAAY,EAAE,UAAU,GAAG,EAAE;CAC9C;;;;;;;;;;;;AC5QD,SAAgB,YAAY,OAAqB;AAChD,KAAI,CAAC,2BAA2B,KAAK,MAAM,GAAG,CAC7C,OAAM,IAAI,MAAM,8CAA8C,MAAM,KAAK;AAE1E,KAAI,MAAM,SAAS,UAAU,MAAM,UAAU,WAAW,EACvD,OAAM,IAAI,MACT,SAAS,MAAM,GAAG,8FAClB;AAEF,QAAO;;AAsBR,SAAgB,aAAa,QAA0B;CACtD,MAAM,uBAAO,IAAI,KAAa;AAC9B,MAAK,MAAM,SAAS,QAAQ;AAC3B,MAAI,KAAK,IAAI,MAAM,GAAG,CACrB,OAAM,IAAI,MAAM,uBAAuB,MAAM,KAAK;AAEnD,OAAK,IAAI,MAAM,GAAG;;AAEnB,QAAO;;;;;;;AAQR,SAA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