@getcirrus/spaces 0.1.0 → 0.3.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/index.d.ts +476 -155
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2077 -891
- package/dist/index.js.map +1 -1
- package/package.json +13 -11
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["CODE_SET: ReadonlySet<string>","ERROR_STATUS: Partial<Record<SpaceErrorCode, number>>","code: SpaceErrorCode","tidNow","payload: Record<string, unknown>","results: ApplyWritesResult[\"results\"]","args: unknown[]","ops: OplogEntry[]","now","now","args: unknown[]","clientUrl: URL","metadata: { jwks?: unknown; jwks_uri?: string }","jwksUrl: URL","blobCids: string[]","doFetch: typeof fetch","items: NotifyItem[]","prepared: PreparedSpaceWrite[]","statuses: Array<string | undefined>","tidNow","state: Awaited<ReturnType<typeof stub.rpcGetRepoState>>","records: SerializedRecord[] | null","collected: SerializedRecord[]","after: { collection: string; rkey: string } | undefined","clientId: string | undefined","config: SpaceConfig","cursor: string | undefined"],"sources":["../src/errors.ts","../src/schema.ts","../src/tid.ts","../src/service-jwt.ts","../src/space-do.ts","../src/index-do.ts","../src/space-uri.ts","../src/blob-keys.ts","../src/auth.ts","../src/attestation.ts","../src/commit.ts","../src/records.ts","../src/routes.ts"],"sourcesContent":["/**\n * Typed errors for the spaces engine.\n *\n * Durable Object RPC flattens thrown errors into a wrapper `Error` whose\n * message is `\"${name}: ${message}\"`, so every error here encodes its\n * protocol error name as a message prefix. Worker-side handlers recover the\n * name with {@link parseSpaceErrorCode} and map it onto the lexicon error\n * shape.\n */\n\n/** Protocol error names used across space and simplespace endpoints. */\nexport const SPACE_ERROR_CODES = [\n\t\"SpaceNotFound\",\n\t\"SpaceDeleted\",\n\t\"SpaceAlreadyExists\",\n\t\"RepoNotFound\",\n\t\"RecordNotFound\",\n\t\"RecordAlreadyExists\",\n\t\"BlobNotFound\",\n\t\"UserNotAuthorized\",\n\t\"AppNotAuthorized\",\n\t\"NotAuthorized\",\n\t\"InvalidDelegationToken\",\n\t\"InvalidClientAttestation\",\n\t\"InvalidCredential\",\n\t\"NotSpaceOwner\",\n\t\"UnsupportedPolicy\",\n\t\"UnsupportedAppAccess\",\n\t\"ServiceNotResolvable\",\n\t\"MalformedCursor\",\n\t\"InvalidSpaceUri\",\n\t\"InvalidRequest\",\n\t\"SpacesSchemaOutdated\",\n] as const;\n\nexport type SpaceErrorCode = (typeof SPACE_ERROR_CODES)[number];\n\nconst CODE_SET: ReadonlySet<string> = new Set(SPACE_ERROR_CODES);\n\n/** HTTP status for each error name when it isn't the default 400. */\nconst ERROR_STATUS: Partial<Record<SpaceErrorCode, number>> = {\n\tSpaceNotFound: 404,\n\tRepoNotFound: 404,\n\tBlobNotFound: 404,\n\tRecordAlreadyExists: 409,\n\tSpaceAlreadyExists: 409,\n\tUserNotAuthorized: 403,\n\tAppNotAuthorized: 403,\n\tNotAuthorized: 403,\n\tNotSpaceOwner: 403,\n\tInvalidDelegationToken: 401,\n\tInvalidClientAttestation: 401,\n\tInvalidCredential: 401,\n\tSpacesSchemaOutdated: 503,\n};\n\nexport class SpaceError extends Error {\n\toverride name = \"SpaceError\";\n\tconstructor(\n\t\treadonly code: SpaceErrorCode,\n\t\tmessage: string,\n\t) {\n\t\t// The `${code}: ` prefix survives the DO RPC boundary.\n\t\tsuper(`${code}: ${message}`);\n\t}\n\n\tget status(): number {\n\t\treturn ERROR_STATUS[this.code] ?? 400;\n\t}\n\n\t/** The human message without the code prefix. */\n\tget detail(): string {\n\t\treturn this.message.slice(this.code.length + 2);\n\t}\n}\n\n/**\n * Recover the space error name from an error that may have crossed a DO RPC\n * boundary. Returns null for errors that aren't space errors.\n */\nexport function parseSpaceErrorCode(\n\terr: unknown,\n): { code: SpaceErrorCode; message: string } | null {\n\tif (err instanceof SpaceError) {\n\t\treturn { code: err.code, message: err.detail };\n\t}\n\tif (err instanceof Error) {\n\t\t// Durable Object RPC re-throws errors with the class name folded into\n\t\t// the message (\"SpaceError: RecordNotFound: ...\"), so scan the first\n\t\t// few prefix segments for a known code.\n\t\tlet message = err.message;\n\t\tfor (let hop = 0; hop < 3; hop++) {\n\t\t\tconst colon = message.indexOf(\": \");\n\t\t\tif (colon <= 0) break;\n\t\t\tconst code = message.slice(0, colon);\n\t\t\tif (CODE_SET.has(code)) {\n\t\t\t\treturn {\n\t\t\t\t\tcode: code as SpaceErrorCode,\n\t\t\t\t\tmessage: message.slice(colon + 2),\n\t\t\t\t};\n\t\t\t}\n\t\t\tmessage = message.slice(colon + 2);\n\t\t}\n\t}\n\treturn null;\n}\n\n/** HTTP status for a recovered space error name. */\nexport function spaceErrorStatus(code: SpaceErrorCode): number {\n\treturn ERROR_STATUS[code] ?? 400;\n}\n","/**\n * SQLite schema for SpaceDurableObject.\n *\n * Mirrors the reference PDS's `002-space` migration table for table, minus\n * the `space` column on every row — one DO per space makes it redundant.\n *\n * There is no migration path between alpha schema versions: bumping\n * {@link SPACE_SCHEMA_VERSION} puts existing DOs into a refusing state until\n * `pds spaces reset` wipes them. That is the alpha policy, applied honestly.\n */\n\n/** Bump on any breaking change to the tables below. */\nexport const SPACE_SCHEMA_VERSION = 1;\n\nexport const SPACE_DO_SCHEMA = `\n\t-- One row. schema_version is checked on every open.\n\tCREATE TABLE IF NOT EXISTS meta (\n\t\turi TEXT NOT NULL,\n\t\tauthority TEXT NOT NULL,\n\t\ttype TEXT NOT NULL,\n\t\tskey TEXT NOT NULL,\n\t\tis_authority INTEGER NOT NULL,\n\t\tcreated_at TEXT NOT NULL,\n\t\tdeleted_at TEXT,\n\t\tschema_version INTEGER NOT NULL\n\t);\n\n\t-- Operator's permissioned repo in this space.\n\tCREATE TABLE IF NOT EXISTS record (\n\t\tcollection TEXT NOT NULL,\n\t\trkey TEXT NOT NULL,\n\t\tcid TEXT NOT NULL,\n\t\tbytes BLOB NOT NULL,\n\t\trev TEXT NOT NULL,\n\t\tindexed_at TEXT NOT NULL,\n\t\tPRIMARY KEY (collection, rkey)\n\t);\n\tCREATE INDEX IF NOT EXISTS idx_record_rev ON record(rev);\n\n\tCREATE TABLE IF NOT EXISTS record_blob (\n\t\tblob_cid TEXT NOT NULL,\n\t\tcollection TEXT NOT NULL,\n\t\trkey TEXT NOT NULL,\n\t\tPRIMARY KEY (blob_cid, collection, rkey)\n\t);\n\tCREATE INDEX IF NOT EXISTS idx_record_blob_record ON record_blob(collection, rkey);\n\n\tCREATE TABLE IF NOT EXISTS repo_state (\n\t\tid INTEGER PRIMARY KEY CHECK (id = 1),\n\t\tset_hash BLOB NOT NULL,\n\t\trev TEXT NOT NULL\n\t);\n\n\tCREATE TABLE IF NOT EXISTS oplog (\n\t\trev TEXT NOT NULL,\n\t\tidx INTEGER NOT NULL,\n\t\tcollection TEXT NOT NULL,\n\t\trkey TEXT NOT NULL,\n\t\tcid TEXT,\n\t\tprev TEXT,\n\t\tPRIMARY KEY (rev, idx)\n\t);\n\n\t-- Authority role only.\n\tCREATE TABLE IF NOT EXISTS config (\n\t\tid INTEGER PRIMARY KEY CHECK (id = 1),\n\t\tpolicy TEXT NOT NULL,\n\t\tmanaging_app TEXT,\n\t\tapp_access TEXT NOT NULL,\n\t\tapp_allowed TEXT NOT NULL\n\t);\n\n\tCREATE TABLE IF NOT EXISTS member (did TEXT PRIMARY KEY);\n\n\tCREATE TABLE IF NOT EXISTS writer (\n\t\tdid TEXT PRIMARY KEY,\n\t\trev TEXT NOT NULL,\n\t\thash BLOB NOT NULL\n\t);\n\n\tCREATE TABLE IF NOT EXISTS notify_registration (\n\t\tservice TEXT PRIMARY KEY,\n\t\tendpoint TEXT NOT NULL,\n\t\texpires_at TEXT NOT NULL\n\t);\n\n\tCREATE TABLE IF NOT EXISTS notify_queue (\n\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\tservice TEXT NOT NULL,\n\t\tbody TEXT NOT NULL,\n\t\tattempts INTEGER NOT NULL DEFAULT 0,\n\t\tnext_at INTEGER NOT NULL\n\t);\n\tCREATE INDEX IF NOT EXISTS idx_notify_queue_next ON notify_queue(next_at);\n\n\t-- Replay protection, both roles.\n\tCREATE TABLE IF NOT EXISTS replay (\n\t\tkind TEXT NOT NULL,\n\t\tkey TEXT NOT NULL,\n\t\texpires_at INTEGER NOT NULL,\n\t\tPRIMARY KEY (kind, key)\n\t);\n`;\n\n/** Retain oplog entries for at most this many days. */\nexport const OPLOG_RETENTION_DAYS = 30;\n/** Retain at most this many oplog entries. */\nexport const OPLOG_RETENTION_OPS = 10_000;\n/** Notify registrations expire after this many days. */\nexport const NOTIFY_REGISTRATION_DAYS = 7;\n/** Give up delivering a notification after this many attempts. */\nexport const NOTIFY_MAX_ATTEMPTS = 5;\n/** Base delay for notification retry backoff, in milliseconds. */\nexport const NOTIFY_BACKOFF_BASE_MS = 30_000;\n\nexport const INDEX_DO_SCHEMA = `\n\tCREATE TABLE IF NOT EXISTS space (\n\t\turi TEXT PRIMARY KEY,\n\t\tauthority TEXT NOT NULL,\n\t\ttype TEXT NOT NULL,\n\t\tskey TEXT NOT NULL,\n\t\tis_authority INTEGER NOT NULL,\n\t\tstate TEXT NOT NULL, -- 'pending' | 'active' | 'deleted'\n\t\tcreated_at TEXT NOT NULL,\n\t\tupdated_at TEXT NOT NULL,\n\t\tschema_version INTEGER NOT NULL\n\t);\n\tCREATE INDEX IF NOT EXISTS idx_space_state ON space(state);\n`;\n\n/** Remove `pending` index entries that never activated after this long. */\nexport const PENDING_ENTRY_TTL_MS = 24 * 60 * 60 * 1000;\n","/**\n * Revision (TID) helpers for the space repo.\n */\n\nimport { now as tidNow } from \"@atcute/tid\";\n\nconst S32_CHAR = \"234567abcdefghijklmnopqrstuvwxyz\";\n\n/**\n * Next revision: a fresh TID guaranteed strictly greater than `prev`.\n * `@atcute/tid`'s clock is monotonic within an isolate, but the previous\n * rev may come from a different isolate's clock (e.g. after a DO restart),\n * so bump lexicographically when needed.\n */\nexport function nextRev(prev: string | null | undefined): string {\n\tconst candidate = tidNow();\n\tif (!prev || candidate > prev) return candidate;\n\t// Increment the previous TID by one in s32 space.\n\tconst chars = prev.split(\"\");\n\tfor (let i = chars.length - 1; i >= 0; i--) {\n\t\tconst idx = S32_CHAR.indexOf(chars[i]!);\n\t\tif (idx < S32_CHAR.length - 1) {\n\t\t\tchars[i] = S32_CHAR[idx + 1]!;\n\t\t\treturn chars.join(\"\");\n\t\t}\n\t\tchars[i] = S32_CHAR[0]!;\n\t}\n\t// prev was the maximal TID; not reachable with real clocks.\n\treturn candidate;\n}\n\n/**\n * The smallest TID whose timestamp is `ms` milliseconds in the past, with a\n * zero clockid. Used as a deletion cutoff for oplog compaction.\n */\nexport function tidCutoff(msAgo: number): string {\n\tconst micros = BigInt(Math.max(0, Date.now() - msAgo)) * 1000n;\n\t// TID layout: 53 bits of microseconds followed by 10 bits of clockid,\n\t// encoded as 13 sortable-base32 characters.\n\tlet value = (micros << 10n) & ((1n << 63n) - 1n);\n\tlet out = \"\";\n\tfor (let i = 12; i >= 0; i--) {\n\t\tout = S32_CHAR[Number(value & 31n)] + out;\n\t\tvalue >>= 5n;\n\t}\n\treturn out;\n}\n","/**\n * Minimal atproto service-auth JWT creation, used for outbound\n * `com.atproto.space.notifyWrite` / `notifySpaceDeleted` calls. Matches the\n * shape `verifyServiceJwt` implementations expect: `{iss, aud, lxm?, jti,\n * iat, exp}` signed with the account signing key (alg from the keypair).\n */\n\nimport type { Keypair } from \"@atproto/crypto\";\n\nconst encoder = new TextEncoder();\n\nfunction base64url(bytes: Uint8Array): string {\n\tlet bin = \"\";\n\tfor (const b of bytes) bin += String.fromCharCode(b);\n\treturn btoa(bin).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nexport interface ServiceJwtParams {\n\tiss: string;\n\taud: string;\n\tlxm?: string;\n\t/** Lifetime in seconds (default 60). */\n\texpiresInSec?: number;\n}\n\nexport async function createServiceJwt(\n\tparams: ServiceJwtParams,\n\tkeypair: Keypair,\n): Promise<string> {\n\tconst iat = Math.floor(Date.now() / 1000);\n\tconst header = { typ: \"JWT\", alg: keypair.jwtAlg };\n\tconst payload: Record<string, unknown> = {\n\t\tiat,\n\t\tiss: params.iss,\n\t\taud: params.aud,\n\t\texp: iat + (params.expiresInSec ?? 60),\n\t\tjti: crypto.randomUUID(),\n\t};\n\tif (params.lxm) payload.lxm = params.lxm;\n\n\tconst signingInput = `${base64url(encoder.encode(JSON.stringify(header)))}.${base64url(\n\t\tencoder.encode(JSON.stringify(payload)),\n\t)}`;\n\tconst sig = await keypair.sign(encoder.encode(signingInput));\n\treturn `${signingInput}.${base64url(sig)}`;\n}\n","/**\n * SpaceDurableObject – one instance per space, addressed by\n * `idFromName(spaceUri)`.\n *\n * Holds everything Cirrus knows about that space: the operator's\n * permissioned repo (records, oplog, LtHash state, blob references) and,\n * when the operator is the authority, the simplespace config, member list,\n * writer set, notification registrations and the outbound notification\n * queue. Also the replay tables for DPoP proofs and delegation tokens\n * presented against the space.\n *\n * Constraints inherited from the Cirrus architecture:\n * - No R2 I/O in here, ever. Blobs are the Worker's job.\n * - Commits are never signed here; the signing key never enters this class\n * except through {@link SpaceHostConfig.getKeypair}, which is used only\n * for outbound notification service JWTs from the alarm.\n * - The host supplies its identity via {@link getHostConfig}; this class\n * must not read `env.DID`. If it ever contains a branch on which host is\n * running it, the boundary has failed.\n */\n\nimport { DurableObject } from \"cloudflare:workers\";\nimport { RepoCommit } from \"@atproto/space\";\nimport { SpaceError } from \"./errors.js\";\nimport {\n\tNOTIFY_BACKOFF_BASE_MS,\n\tNOTIFY_MAX_ATTEMPTS,\n\tNOTIFY_REGISTRATION_DAYS,\n\tOPLOG_RETENTION_DAYS,\n\tOPLOG_RETENTION_OPS,\n\tSPACE_DO_SCHEMA,\n\tSPACE_SCHEMA_VERSION,\n} from \"./schema.js\";\nimport { nextRev, tidCutoff } from \"./tid.js\";\nimport { createServiceJwt } from \"./service-jwt.js\";\nimport type {\n\tApplyWritesResult,\n\tNotifyItem,\n\tOplogEntry,\n\tPreparedSpaceWrite,\n\tRepoState,\n\tSpaceAppAccess,\n\tSpaceConfig,\n\tSpaceHostConfig,\n\tSpaceMeta,\n\tSpacePolicy,\n\tSpaceRecordRow,\n} from \"./types.js\";\n\nconst DAY_MS = 24 * 60 * 60 * 1000;\n/** Interval between maintenance passes (compaction, replay cleanup). */\nconst MAINTENANCE_INTERVAL_MS = DAY_MS;\n/** How many queued notifications to attempt per alarm invocation. */\nconst NOTIFY_BATCH = 20;\n\ninterface QueueRow {\n\tid: number;\n\tservice: string;\n\tbody: string;\n\tattempts: number;\n\tnext_at: number;\n}\n\nexport abstract class SpaceDurableObject<Env = unknown> extends DurableObject<Env> {\n\tprivate sql: SqlStorage;\n\tprivate initialized = false;\n\tprivate outdated = false;\n\n\tconstructor(ctx: DurableObjectState, env: Env) {\n\t\tsuper(ctx, env);\n\t\tthis.sql = ctx.storage.sql;\n\t}\n\n\t/**\n\t * Host identity and signing configuration. Implemented by the host\n\t * Worker's subclass; see {@link SpaceHostConfig}.\n\t */\n\tprotected abstract getHostConfig(): SpaceHostConfig | Promise<SpaceHostConfig>;\n\n\t// ------------------------------------------------------------------\n\t// Initialisation and schema versioning\n\t// ------------------------------------------------------------------\n\n\tprivate async ensureInitialized(): Promise<void> {\n\t\tif (this.initialized) return;\n\t\tawait this.ctx.blockConcurrencyWhile(async () => {\n\t\t\tif (this.initialized) return;\n\t\t\tconst hasMeta =\n\t\t\t\tthis.sql\n\t\t\t\t\t.exec(\n\t\t\t\t\t\t\"SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'meta'\",\n\t\t\t\t\t)\n\t\t\t\t\t.toArray().length > 0;\n\t\t\tif (hasMeta) {\n\t\t\t\tconst row = this.sql\n\t\t\t\t\t.exec(\"SELECT schema_version FROM meta LIMIT 1\")\n\t\t\t\t\t.toArray()[0];\n\t\t\t\tif (\n\t\t\t\t\trow &&\n\t\t\t\t\t(row.schema_version as number) !== SPACE_SCHEMA_VERSION\n\t\t\t\t) {\n\t\t\t\t\t// Alpha policy: no migrations between schema versions. The DO\n\t\t\t\t\t// refuses every RPC until `pds spaces reset` wipes it.\n\t\t\t\t\tthis.outdated = true;\n\t\t\t\t\tthis.initialized = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.sql.exec(SPACE_DO_SCHEMA);\n\t\t\tthis.initialized = true;\n\t\t});\n\t}\n\n\t/**\n\t * Gate every RPC: initialise storage and refuse when the stored schema\n\t * belongs to a different alpha build.\n\t */\n\tprivate async ensureOpen(): Promise<void> {\n\t\tawait this.ensureInitialized();\n\t\tif (this.outdated) {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"SpacesSchemaOutdated\",\n\t\t\t\t\"Space data was written by an incompatible alpha build. Run `pds spaces reset` to wipe space data (the public repo is unaffected).\",\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate readMeta(): SpaceMeta | null {\n\t\tconst row = this.sql.exec(\"SELECT * FROM meta LIMIT 1\").toArray()[0];\n\t\tif (!row) return null;\n\t\treturn {\n\t\t\turi: row.uri as string,\n\t\t\tauthority: row.authority as string,\n\t\t\ttype: row.type as string,\n\t\t\tskey: row.skey as string,\n\t\t\tisAuthority: (row.is_authority as number) === 1,\n\t\t\tcreatedAt: row.created_at as string,\n\t\t\tdeletedAt: (row.deleted_at as string | null) ?? null,\n\t\t};\n\t}\n\n\t/** Meta for an existing, non-deleted space, or throw. */\n\tprivate requireLiveMeta(): SpaceMeta {\n\t\tconst meta = this.readMeta();\n\t\tif (!meta) {\n\t\t\tthrow new SpaceError(\"SpaceNotFound\", \"Space is not initialised\");\n\t\t}\n\t\tif (meta.deletedAt) {\n\t\t\tthrow new SpaceError(\"SpaceNotFound\", \"Space has been deleted\");\n\t\t}\n\t\treturn meta;\n\t}\n\n\tasync rpcGetMeta(): Promise<SpaceMeta | null> {\n\t\tawait this.ensureOpen();\n\t\treturn this.readMeta();\n\t}\n\n\t/**\n\t * Initialise this DO as the operator's repo in a space (either role).\n\t * Idempotent for an existing live space with matching identity.\n\t */\n\tasync rpcInit(params: {\n\t\turi: string;\n\t\tauthority: string;\n\t\ttype: string;\n\t\tskey: string;\n\t\tisAuthority: boolean;\n\t\tconfig?: SpaceConfig;\n\t}): Promise<void> {\n\t\tawait this.ensureOpen();\n\t\tconst existing = this.readMeta();\n\t\tif (existing) {\n\t\t\tif (existing.uri !== params.uri) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"InvalidSpaceUri\",\n\t\t\t\t\t`Space DO already holds ${existing.uri}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!existing.deletedAt) {\n\t\t\t\tif (params.isAuthority && params.config) {\n\t\t\t\t\tconst hasConfig =\n\t\t\t\t\t\tthis.sql.exec(\"SELECT id FROM config\").toArray().length > 0;\n\t\t\t\t\tif (hasConfig) {\n\t\t\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\t\t\"SpaceAlreadyExists\",\n\t\t\t\t\t\t\t`Space already exists: ${params.uri}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tthis.writeConfig(params.config);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// A previously deleted space may be created again: tables were\n\t\t\t// wiped at deletion, so reviving is a fresh start.\n\t\t\tthis.sql.exec(\n\t\t\t\t\"UPDATE meta SET deleted_at = NULL, created_at = ?, is_authority = ?\",\n\t\t\t\tnew Date().toISOString(),\n\t\t\t\tparams.isAuthority ? 1 : 0,\n\t\t\t);\n\t\t\tif (params.config) this.writeConfig(params.config);\n\t\t\treturn;\n\t\t}\n\t\tthis.sql.exec(\n\t\t\t`INSERT INTO meta (uri, authority, type, skey, is_authority, created_at, deleted_at, schema_version)\n\t\t\t VALUES (?, ?, ?, ?, ?, ?, NULL, ?)`,\n\t\t\tparams.uri,\n\t\t\tparams.authority,\n\t\t\tparams.type,\n\t\t\tparams.skey,\n\t\t\tparams.isAuthority ? 1 : 0,\n\t\t\tnew Date().toISOString(),\n\t\t\tSPACE_SCHEMA_VERSION,\n\t\t);\n\t\tif (params.config) this.writeConfig(params.config);\n\t}\n\n\t// ------------------------------------------------------------------\n\t// Permissioned repo: writes\n\t// ------------------------------------------------------------------\n\n\tasync rpcApplyWrites(\n\t\twrites: PreparedSpaceWrite[],\n\t): Promise<ApplyWritesResult> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\n\t\treturn this.ctx.storage.transactionSync(() => {\n\t\t\tconst stateRow = this.sql\n\t\t\t\t.exec(\"SELECT set_hash, rev FROM repo_state WHERE id = 1\")\n\t\t\t\t.toArray()[0];\n\t\t\tconst prevRev = stateRow ? (stateRow.rev as string) : null;\n\t\t\tconst commit = RepoCommit.fromState(\n\t\t\t\tstateRow ? new Uint8Array(stateRow.set_hash as ArrayBuffer) : null,\n\t\t\t);\n\t\t\tconst rev = nextRev(prevRev);\n\t\t\tconst indexedAt = new Date().toISOString();\n\t\t\tconst results: ApplyWritesResult[\"results\"] = [];\n\t\t\tlet idx = 0;\n\n\t\t\tfor (const write of writes) {\n\t\t\t\tconst prevRow = this.sql\n\t\t\t\t\t.exec(\n\t\t\t\t\t\t\"SELECT cid FROM record WHERE collection = ? AND rkey = ?\",\n\t\t\t\t\t\twrite.collection,\n\t\t\t\t\t\twrite.rkey,\n\t\t\t\t\t)\n\t\t\t\t\t.toArray()[0];\n\t\t\t\tconst prev = prevRow ? (prevRow.cid as string) : null;\n\n\t\t\t\tif (write.action === \"create\" && prev) {\n\t\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\t\"RecordAlreadyExists\",\n\t\t\t\t\t\t`Record already exists: ${write.collection}/${write.rkey}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (write.action !== \"create\" && !prev) {\n\t\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\t\"RecordNotFound\",\n\t\t\t\t\t\t`Record not found: ${write.collection}/${write.rkey}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tif (write.action === \"delete\") {\n\t\t\t\t\tthis.sql.exec(\n\t\t\t\t\t\t\"DELETE FROM record WHERE collection = ? AND rkey = ?\",\n\t\t\t\t\t\twrite.collection,\n\t\t\t\t\t\twrite.rkey,\n\t\t\t\t\t);\n\t\t\t\t\tthis.sql.exec(\n\t\t\t\t\t\t\"DELETE FROM record_blob WHERE collection = ? AND rkey = ?\",\n\t\t\t\t\t\twrite.collection,\n\t\t\t\t\t\twrite.rkey,\n\t\t\t\t\t);\n\t\t\t\t\tcommit.setHash.remove(\n\t\t\t\t\t\t`${write.collection}/${write.rkey}/${prev}`,\n\t\t\t\t\t);\n\t\t\t\t\tthis.appendOplog(rev, idx++, write.collection, write.rkey, null, prev);\n\t\t\t\t\tresults.push({\n\t\t\t\t\t\taction: \"delete\",\n\t\t\t\t\t\tcollection: write.collection,\n\t\t\t\t\t\trkey: write.rkey,\n\t\t\t\t\t\tcid: null,\n\t\t\t\t\t});\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tthis.sql.exec(\n\t\t\t\t\t`INSERT OR REPLACE INTO record (collection, rkey, cid, bytes, rev, indexed_at)\n\t\t\t\t\t VALUES (?, ?, ?, ?, ?, ?)`,\n\t\t\t\t\twrite.collection,\n\t\t\t\t\twrite.rkey,\n\t\t\t\t\twrite.cid,\n\t\t\t\t\twrite.bytes,\n\t\t\t\t\trev,\n\t\t\t\t\tindexedAt,\n\t\t\t\t);\n\t\t\t\tthis.sql.exec(\n\t\t\t\t\t\"DELETE FROM record_blob WHERE collection = ? AND rkey = ?\",\n\t\t\t\t\twrite.collection,\n\t\t\t\t\twrite.rkey,\n\t\t\t\t);\n\t\t\t\tfor (const blobCid of write.blobCids) {\n\t\t\t\t\tthis.sql.exec(\n\t\t\t\t\t\t\"INSERT OR IGNORE INTO record_blob (blob_cid, collection, rkey) VALUES (?, ?, ?)\",\n\t\t\t\t\t\tblobCid,\n\t\t\t\t\t\twrite.collection,\n\t\t\t\t\t\twrite.rkey,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (prev) {\n\t\t\t\t\tcommit.setHash.remove(\n\t\t\t\t\t\t`${write.collection}/${write.rkey}/${prev}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tcommit.setHash.add(\n\t\t\t\t\t`${write.collection}/${write.rkey}/${write.cid}`,\n\t\t\t\t);\n\t\t\t\tthis.appendOplog(\n\t\t\t\t\trev,\n\t\t\t\t\tidx++,\n\t\t\t\t\twrite.collection,\n\t\t\t\t\twrite.rkey,\n\t\t\t\t\twrite.cid,\n\t\t\t\t\tprev,\n\t\t\t\t);\n\t\t\t\tresults.push({\n\t\t\t\t\taction: write.action,\n\t\t\t\t\tcollection: write.collection,\n\t\t\t\t\trkey: write.rkey,\n\t\t\t\t\tcid: write.cid,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tthis.sql.exec(\n\t\t\t\t`INSERT INTO repo_state (id, set_hash, rev) VALUES (1, ?, ?)\n\t\t\t\t ON CONFLICT (id) DO UPDATE SET set_hash = excluded.set_hash, rev = excluded.rev`,\n\t\t\t\tcommit.setHash.state(),\n\t\t\t\trev,\n\t\t\t);\n\n\t\t\treturn { rev, hash: commit.setHash.digest(), results };\n\t\t});\n\t}\n\n\tprivate appendOplog(\n\t\trev: string,\n\t\tidx: number,\n\t\tcollection: string,\n\t\trkey: string,\n\t\tcid: string | null,\n\t\tprev: string | null,\n\t): void {\n\t\tthis.sql.exec(\n\t\t\t\"INSERT INTO oplog (rev, idx, collection, rkey, cid, prev) VALUES (?, ?, ?, ?, ?, ?)\",\n\t\t\trev,\n\t\t\tidx,\n\t\t\tcollection,\n\t\t\trkey,\n\t\t\tcid,\n\t\t\tprev,\n\t\t);\n\t}\n\n\t// ------------------------------------------------------------------\n\t// Permissioned repo: reads\n\t// ------------------------------------------------------------------\n\n\tasync rpcGetRecord(\n\t\tcollection: string,\n\t\trkey: string,\n\t): Promise<{ cid: string; bytes: Uint8Array } | null> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\tconst row = this.sql\n\t\t\t.exec(\n\t\t\t\t\"SELECT cid, bytes FROM record WHERE collection = ? AND rkey = ?\",\n\t\t\t\tcollection,\n\t\t\t\trkey,\n\t\t\t)\n\t\t\t.toArray()[0];\n\t\tif (!row) return null;\n\t\treturn {\n\t\t\tcid: row.cid as string,\n\t\t\tbytes: new Uint8Array(row.bytes as ArrayBuffer),\n\t\t};\n\t}\n\n\t/**\n\t * List records ordered by (collection, rkey) — equivalent to record-URI\n\t * order since every record shares the space and repo prefix. Descending\n\t * by default, matching the reference; `reverse` flips to ascending.\n\t *\n\t * `rev` is the repo revision the page was read at — the page and the\n\t * revision are one snapshot (synchronous reads, single-threaded DO), so\n\t * a paged reader can fence against concurrent writes.\n\t */\n\tasync rpcListRecords(params: {\n\t\tcollection?: string;\n\t\tlimit: number;\n\t\tafter?: { collection: string; rkey: string };\n\t\treverse?: boolean;\n\t\texcludeValues?: boolean;\n\t}): Promise<{\n\t\trecords: SpaceRecordRow[];\n\t\thasMore: boolean;\n\t\trev: string | null;\n\t}> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\tconst stateRow = this.sql\n\t\t\t.exec(\"SELECT rev FROM repo_state WHERE id = 1\")\n\t\t\t.toArray()[0];\n\t\tconst rev = stateRow ? (stateRow.rev as string) : null;\n\t\tconst asc = params.reverse === true;\n\t\tconst op = asc ? \">\" : \"<\";\n\t\tconst order = asc ? \"ASC\" : \"DESC\";\n\t\tconst args: unknown[] = [];\n\t\tlet where = \"1=1\";\n\t\tif (params.collection) {\n\t\t\twhere += \" AND collection = ?\";\n\t\t\targs.push(params.collection);\n\t\t}\n\t\tif (params.after) {\n\t\t\twhere += ` AND (collection ${op} ? OR (collection = ? AND rkey ${op} ?))`;\n\t\t\targs.push(params.after.collection, params.after.collection, params.after.rkey);\n\t\t}\n\t\tconst rows = this.sql\n\t\t\t.exec(\n\t\t\t\t`SELECT collection, rkey, cid${params.excludeValues ? \"\" : \", bytes\"} FROM record\n\t\t\t\t WHERE ${where}\n\t\t\t\t ORDER BY collection ${order}, rkey ${order}\n\t\t\t\t LIMIT ?`,\n\t\t\t\t...args,\n\t\t\t\tparams.limit + 1,\n\t\t\t)\n\t\t\t.toArray();\n\t\tconst hasMore = rows.length > params.limit;\n\t\tconst page = hasMore ? rows.slice(0, params.limit) : rows;\n\t\treturn {\n\t\t\trecords: page.map((row) => ({\n\t\t\t\tcollection: row.collection as string,\n\t\t\t\trkey: row.rkey as string,\n\t\t\t\tcid: row.cid as string,\n\t\t\t\t...(params.excludeValues\n\t\t\t\t\t? {}\n\t\t\t\t\t: { bytes: new Uint8Array(row.bytes as ArrayBuffer) }),\n\t\t\t})),\n\t\t\thasMore,\n\t\t\trev,\n\t\t};\n\t}\n\n\tasync rpcGetRepoState(): Promise<RepoState | null> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\tconst row = this.sql\n\t\t\t.exec(\"SELECT set_hash, rev FROM repo_state WHERE id = 1\")\n\t\t\t.toArray()[0];\n\t\tif (!row) return null;\n\t\treturn {\n\t\t\tsetHash: new Uint8Array(row.set_hash as ArrayBuffer),\n\t\t\trev: row.rev as string,\n\t\t};\n\t}\n\n\t/**\n\t * List oplog entries after `since` (a rev) or `after` (an exact cursor\n\t * position). Creates and updates carry the record's current bytes when\n\t * the oplog cid still matches the live record; superseded values are\n\t * omitted. When the page reaches the head, `head` carries the repo\n\t * state read in the same transaction so the Worker can attach a freshly\n\t * signed commit without a state race.\n\t */\n\tasync rpcListRepoOps(params: {\n\t\tsince?: string;\n\t\tafter?: { rev: string; idx: number };\n\t\tlimit: number;\n\t\texcludeValues?: boolean;\n\t}): Promise<{ ops: OplogEntry[]; head?: RepoState }> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\treturn this.ctx.storage.transactionSync(() => {\n\t\t\tconst args: unknown[] = [];\n\t\t\tlet where = \"1=1\";\n\t\t\tif (params.after) {\n\t\t\t\twhere += \" AND (o.rev > ? OR (o.rev = ? AND o.idx > ?))\";\n\t\t\t\targs.push(params.after.rev, params.after.rev, params.after.idx);\n\t\t\t} else if (params.since) {\n\t\t\t\twhere += \" AND o.rev > ?\";\n\t\t\t\targs.push(params.since);\n\t\t\t}\n\t\t\tconst values = params.excludeValues\n\t\t\t\t? \"\"\n\t\t\t\t: \", r.bytes AS live_bytes\";\n\t\t\tconst rows = this.sql\n\t\t\t\t.exec(\n\t\t\t\t\t`SELECT o.rev, o.idx, o.collection, o.rkey, o.cid, o.prev${values}\n\t\t\t\t\t FROM oplog o\n\t\t\t\t\t ${params.excludeValues ? \"\" : \"LEFT JOIN record r ON r.collection = o.collection AND r.rkey = o.rkey AND r.cid = o.cid\"}\n\t\t\t\t\t WHERE ${where}\n\t\t\t\t\t ORDER BY o.rev ASC, o.idx ASC\n\t\t\t\t\t LIMIT ?`,\n\t\t\t\t\t...args,\n\t\t\t\t\tparams.limit + 1,\n\t\t\t\t)\n\t\t\t\t.toArray();\n\t\t\tconst hasMore = rows.length > params.limit;\n\t\t\tconst page = hasMore ? rows.slice(0, params.limit) : rows;\n\t\t\tconst ops: OplogEntry[] = page.map((row) => ({\n\t\t\t\trev: row.rev as string,\n\t\t\t\tidx: row.idx as number,\n\t\t\t\tcollection: row.collection as string,\n\t\t\t\trkey: row.rkey as string,\n\t\t\t\tcid: (row.cid as string | null) ?? null,\n\t\t\t\tprev: (row.prev as string | null) ?? null,\n\t\t\t\t...(row.live_bytes\n\t\t\t\t\t? { bytes: new Uint8Array(row.live_bytes as ArrayBuffer) }\n\t\t\t\t\t: {}),\n\t\t\t}));\n\t\t\tif (hasMore) return { ops };\n\t\t\tconst stateRow = this.sql\n\t\t\t\t.exec(\"SELECT set_hash, rev FROM repo_state WHERE id = 1\")\n\t\t\t\t.toArray()[0];\n\t\t\treturn {\n\t\t\t\tops,\n\t\t\t\t...(stateRow\n\t\t\t\t\t? {\n\t\t\t\t\t\t\thead: {\n\t\t\t\t\t\t\t\tsetHash: new Uint8Array(\n\t\t\t\t\t\t\t\t\tstateRow.set_hash as ArrayBuffer,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\trev: stateRow.rev as string,\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};\n\t\t});\n\t}\n\n\t/** Distinct blob CIDs referenced by records, ascending, paged. */\n\tasync rpcListBlobs(params: {\n\t\tsince?: string;\n\t\tlimit: number;\n\t\tafterCid?: string;\n\t}): Promise<{ cids: string[]; hasMore: boolean }> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\tconst args: unknown[] = [];\n\t\tlet where = \"1=1\";\n\t\tif (params.since) {\n\t\t\twhere += \" AND r.rev > ?\";\n\t\t\targs.push(params.since);\n\t\t}\n\t\tif (params.afterCid) {\n\t\t\twhere += \" AND b.blob_cid > ?\";\n\t\t\targs.push(params.afterCid);\n\t\t}\n\t\tconst rows = this.sql\n\t\t\t.exec(\n\t\t\t\t`SELECT DISTINCT b.blob_cid FROM record_blob b\n\t\t\t\t JOIN record r ON r.collection = b.collection AND r.rkey = b.rkey\n\t\t\t\t WHERE ${where}\n\t\t\t\t ORDER BY b.blob_cid ASC\n\t\t\t\t LIMIT ?`,\n\t\t\t\t...args,\n\t\t\t\tparams.limit + 1,\n\t\t\t)\n\t\t\t.toArray();\n\t\tconst hasMore = rows.length > params.limit;\n\t\tconst page = hasMore ? rows.slice(0, params.limit) : rows;\n\t\treturn { cids: page.map((r) => r.blob_cid as string), hasMore };\n\t}\n\n\t/** Whether a blob CID is referenced by any record in this space. */\n\tasync rpcHasSpaceBlob(cid: string): Promise<boolean> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\treturn (\n\t\t\tthis.sql\n\t\t\t\t.exec(\"SELECT 1 FROM record_blob WHERE blob_cid = ? LIMIT 1\", cid)\n\t\t\t\t.toArray().length > 0\n\t\t);\n\t}\n\n\t// ------------------------------------------------------------------\n\t// Replay protection\n\t// ------------------------------------------------------------------\n\n\t/**\n\t * Record a single-use key. Returns true when the key was fresh (now\n\t * recorded), false when it was already seen and must be refused.\n\t */\n\tasync rpcCheckReplay(\n\t\tkind: string,\n\t\tkey: string,\n\t\texpiresAtSec: number,\n\t): Promise<boolean> {\n\t\tawait this.ensureOpen();\n\t\tconst result = this.sql.exec(\n\t\t\t\"INSERT OR IGNORE INTO replay (kind, key, expires_at) VALUES (?, ?, ?)\",\n\t\t\tkind,\n\t\t\tkey,\n\t\t\texpiresAtSec,\n\t\t);\n\t\treturn result.rowsWritten > 0;\n\t}\n\n\t// ------------------------------------------------------------------\n\t// Authority role: config, members, writers, notifications\n\t// ------------------------------------------------------------------\n\n\tprivate writeConfig(config: SpaceConfig): void {\n\t\tthis.sql.exec(\n\t\t\t`INSERT INTO config (id, policy, managing_app, app_access, app_allowed)\n\t\t\t VALUES (1, ?, ?, ?, ?)\n\t\t\t ON CONFLICT (id) DO UPDATE SET\n\t\t\t\tpolicy = excluded.policy,\n\t\t\t\tmanaging_app = excluded.managing_app,\n\t\t\t\tapp_access = excluded.app_access,\n\t\t\t\tapp_allowed = excluded.app_allowed`,\n\t\t\tconfig.policy.kind,\n\t\t\tconfig.policy.kind === \"managing-app\" ? config.policy.managingApp : null,\n\t\t\tconfig.appAccess.kind,\n\t\t\tJSON.stringify(\n\t\t\t\tconfig.appAccess.kind === \"allowList\" ? config.appAccess.allowed : [],\n\t\t\t),\n\t\t);\n\t}\n\n\tprivate readConfig(): SpaceConfig | null {\n\t\tconst row = this.sql.exec(\"SELECT * FROM config WHERE id = 1\").toArray()[0];\n\t\tif (!row) return null;\n\t\tconst policyKind = row.policy as string;\n\t\tconst policy: SpacePolicy =\n\t\t\tpolicyKind === \"managing-app\"\n\t\t\t\t? {\n\t\t\t\t\t\tkind: \"managing-app\",\n\t\t\t\t\t\tmanagingApp: row.managing_app as string,\n\t\t\t\t\t}\n\t\t\t\t: policyKind === \"member-list\"\n\t\t\t\t\t? { kind: \"member-list\" }\n\t\t\t\t\t: { kind: \"public\" };\n\t\tconst appAccess: SpaceAppAccess =\n\t\t\t(row.app_access as string) === \"allowList\"\n\t\t\t\t? {\n\t\t\t\t\t\tkind: \"allowList\",\n\t\t\t\t\t\tallowed: JSON.parse(row.app_allowed as string) as string[],\n\t\t\t\t\t}\n\t\t\t\t: { kind: \"open\" };\n\t\treturn { policy, appAccess };\n\t}\n\n\t/**\n\t * State needed to answer getSpaceCredential: meta (including the\n\t * deletion tombstone) and the simplespace config. Never throws on a\n\t * deleted space — a late credential request must get SpaceDeleted, not\n\t * SpaceNotFound, and that mapping is the caller's.\n\t */\n\tasync rpcGetAuthorityState(): Promise<{\n\t\tmeta: SpaceMeta | null;\n\t\tconfig: SpaceConfig | null;\n\t}> {\n\t\tawait this.ensureOpen();\n\t\treturn { meta: this.readMeta(), config: this.readConfig() };\n\t}\n\n\tasync rpcUpdateConfig(update: {\n\t\tpolicy?: SpacePolicy;\n\t\tappAccess?: SpaceAppAccess;\n\t}): Promise<void> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\tconst current = this.readConfig();\n\t\tif (!current) {\n\t\t\tthrow new SpaceError(\"SpaceNotFound\", \"Space has no configuration\");\n\t\t}\n\t\tthis.writeConfig({\n\t\t\tpolicy: update.policy ?? current.policy,\n\t\t\tappAccess: update.appAccess ?? current.appAccess,\n\t\t});\n\t}\n\n\tasync rpcAddMember(did: string): Promise<void> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\tthis.sql.exec(\"INSERT OR IGNORE INTO member (did) VALUES (?)\", did);\n\t}\n\n\tasync rpcRemoveMember(did: string): Promise<void> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\tthis.sql.exec(\"DELETE FROM member WHERE did = ?\", did);\n\t}\n\n\tasync rpcIsMember(did: string): Promise<boolean> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\treturn (\n\t\t\tthis.sql.exec(\"SELECT 1 FROM member WHERE did = ?\", did).toArray()\n\t\t\t\t.length > 0\n\t\t);\n\t}\n\n\tasync rpcListMembers(params: {\n\t\tlimit: number;\n\t\tafterDid?: string;\n\t}): Promise<{ dids: string[]; hasMore: boolean }> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\tconst args: unknown[] = [];\n\t\tlet where = \"1=1\";\n\t\tif (params.afterDid) {\n\t\t\twhere += \" AND did > ?\";\n\t\t\targs.push(params.afterDid);\n\t\t}\n\t\tconst rows = this.sql\n\t\t\t.exec(\n\t\t\t\t`SELECT did FROM member WHERE ${where} ORDER BY did ASC LIMIT ?`,\n\t\t\t\t...args,\n\t\t\t\tparams.limit + 1,\n\t\t\t)\n\t\t\t.toArray();\n\t\tconst hasMore = rows.length > params.limit;\n\t\tconst page = hasMore ? rows.slice(0, params.limit) : rows;\n\t\treturn { dids: page.map((r) => r.did as string), hasMore };\n\t}\n\n\t/**\n\t * Record a writer's latest (rev, hash), from notifyWrite or own writes.\n\t * Monotonic per writer: a delayed or replayed notification with an older\n\t * rev never rolls the writer set backwards. Returns whether the write\n\t * advanced state, so callers can skip fan-out for stale notifications.\n\t */\n\tasync rpcRecordWriter(\n\t\tdid: string,\n\t\trev: string,\n\t\thash: Uint8Array,\n\t): Promise<{ advanced: boolean }> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\tconst result = this.sql.exec(\n\t\t\t`INSERT INTO writer (did, rev, hash) VALUES (?, ?, ?)\n\t\t\t ON CONFLICT (did) DO UPDATE SET rev = excluded.rev, hash = excluded.hash\n\t\t\t WHERE excluded.rev > writer.rev`,\n\t\t\tdid,\n\t\t\trev,\n\t\t\thash,\n\t\t);\n\t\treturn { advanced: result.rowsWritten > 0 };\n\t}\n\n\tasync rpcListWriters(params: {\n\t\tlimit: number;\n\t\tafterDid?: string;\n\t}): Promise<{\n\t\trepos: Array<{ did: string; rev: string; hash: Uint8Array }>;\n\t\thasMore: boolean;\n\t}> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\tconst args: unknown[] = [];\n\t\tlet where = \"1=1\";\n\t\tif (params.afterDid) {\n\t\t\twhere += \" AND did > ?\";\n\t\t\targs.push(params.afterDid);\n\t\t}\n\t\tconst rows = this.sql\n\t\t\t.exec(\n\t\t\t\t`SELECT did, rev, hash FROM writer WHERE ${where} ORDER BY did ASC LIMIT ?`,\n\t\t\t\t...args,\n\t\t\t\tparams.limit + 1,\n\t\t\t)\n\t\t\t.toArray();\n\t\tconst hasMore = rows.length > params.limit;\n\t\tconst page = hasMore ? rows.slice(0, params.limit) : rows;\n\t\treturn {\n\t\t\trepos: page.map((r) => ({\n\t\t\t\tdid: r.did as string,\n\t\t\t\trev: r.rev as string,\n\t\t\t\thash: new Uint8Array(r.hash as ArrayBuffer),\n\t\t\t})),\n\t\t\thasMore,\n\t\t};\n\t}\n\n\t/**\n\t * Register a syncing service for write notifications. The endpoint was\n\t * resolved by the Worker at registration time so fan-out never resolves\n\t * DIDs. Re-registration replaces the endpoint and extends the expiry.\n\t */\n\tasync rpcRegisterNotify(\n\t\tservice: string,\n\t\tendpoint: string,\n\t): Promise<{ expiresAt: string }> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\tconst expiresAt = new Date(\n\t\t\tDate.now() + NOTIFY_REGISTRATION_DAYS * DAY_MS,\n\t\t).toISOString();\n\t\tthis.sql.exec(\n\t\t\t`INSERT INTO notify_registration (service, endpoint, expires_at) VALUES (?, ?, ?)\n\t\t\t ON CONFLICT (service) DO UPDATE SET endpoint = excluded.endpoint, expires_at = excluded.expires_at`,\n\t\t\tservice,\n\t\t\tendpoint,\n\t\t\texpiresAt,\n\t\t);\n\t\treturn { expiresAt };\n\t}\n\n\t/** Idempotent: succeeds whether or not a registration existed. */\n\tasync rpcUnregisterNotify(service: string): Promise<void> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\tthis.sql.exec(\"DELETE FROM notify_registration WHERE service = ?\", service);\n\t}\n\n\tasync rpcGetActiveRegistrations(): Promise<\n\t\tArray<{ service: string; endpoint: string }>\n\t> {\n\t\tawait this.ensureOpen();\n\t\treturn this.sql\n\t\t\t.exec(\n\t\t\t\t\"SELECT service, endpoint FROM notify_registration WHERE expires_at > ?\",\n\t\t\t\tnew Date().toISOString(),\n\t\t\t)\n\t\t\t.toArray()\n\t\t\t.map((r) => ({\n\t\t\t\tservice: r.service as string,\n\t\t\t\tendpoint: r.endpoint as string,\n\t\t\t}));\n\t}\n\n\t/**\n\t * Queue outbound notifications for the alarm to deliver with bounded\n\t * retries. The Worker only enqueues; delivery happens here because this\n\t * DO holds no WebSocket and does no storage-bound work that a slow\n\t * outbound fetch could pin.\n\t */\n\tasync rpcEnqueueNotify(items: NotifyItem[]): Promise<void> {\n\t\tawait this.ensureOpen();\n\t\tif (items.length === 0) return;\n\t\tconst now = Date.now();\n\t\tfor (const item of items) {\n\t\t\tthis.sql.exec(\n\t\t\t\t\"INSERT INTO notify_queue (service, body, attempts, next_at) VALUES (?, ?, 0, ?)\",\n\t\t\t\titem.service,\n\t\t\t\tJSON.stringify({\n\t\t\t\t\tendpoint: item.endpoint,\n\t\t\t\t\tlxm: item.lxm,\n\t\t\t\t\tbody: item.body,\n\t\t\t\t}),\n\t\t\t\tnow,\n\t\t\t);\n\t\t}\n\t\tawait this.scheduleNextAlarm();\n\t}\n\n\t// ------------------------------------------------------------------\n\t// Deletion and status\n\t// ------------------------------------------------------------------\n\n\t/**\n\t * Tombstone the space (authority role). Enqueues nothing itself — the\n\t * caller reads the registrations from the result and enqueues\n\t * `notifySpaceDeleted` before the queue rows would be unreachable. The\n\t * meta row is retained so a late getSpaceCredential can answer\n\t * SpaceDeleted rather than SpaceNotFound. Idempotent.\n\t */\n\tasync rpcDeleteSpace(): Promise<{\n\t\tregistrations: Array<{ service: string; endpoint: string }>;\n\t}> {\n\t\tawait this.ensureOpen();\n\t\tconst meta = this.readMeta();\n\t\tif (!meta) {\n\t\t\tthrow new SpaceError(\"SpaceNotFound\", \"Space is not initialised\");\n\t\t}\n\t\tif (meta.deletedAt) return { registrations: [] };\n\t\tconst registrations = await this.rpcGetActiveRegistrations();\n\t\tthis.ctx.storage.transactionSync(() => {\n\t\t\tthis.sql.exec(\n\t\t\t\t\"UPDATE meta SET deleted_at = ?\",\n\t\t\t\tnew Date().toISOString(),\n\t\t\t);\n\t\t\tfor (const table of [\n\t\t\t\t\"record\",\n\t\t\t\t\"record_blob\",\n\t\t\t\t\"repo_state\",\n\t\t\t\t\"oplog\",\n\t\t\t\t\"config\",\n\t\t\t\t\"member\",\n\t\t\t\t\"writer\",\n\t\t\t\t\"notify_registration\",\n\t\t\t\t\"replay\",\n\t\t\t]) {\n\t\t\t\tthis.sql.exec(`DELETE FROM ${table}`);\n\t\t\t}\n\t\t});\n\t\treturn { registrations };\n\t}\n\n\t/** Wipe everything, including queued notifications and alarms. */\n\tasync rpcDestroy(): Promise<void> {\n\t\tawait this.ctx.storage.deleteAlarm();\n\t\tawait this.ctx.storage.deleteAll();\n\t\tthis.initialized = false;\n\t\tthis.outdated = false;\n\t}\n\n\tasync rpcStatus(): Promise<{\n\t\tmeta: SpaceMeta | null;\n\t\toutdated: boolean;\n\t\trecordCount: number;\n\t\tmemberCount: number;\n\t\twriterCount: number;\n\t\tqueuedNotifications: number;\n\t}> {\n\t\tawait this.ensureInitialized();\n\t\tif (this.outdated) {\n\t\t\treturn {\n\t\t\t\tmeta: null,\n\t\t\t\toutdated: true,\n\t\t\t\trecordCount: 0,\n\t\t\t\tmemberCount: 0,\n\t\t\t\twriterCount: 0,\n\t\t\t\tqueuedNotifications: 0,\n\t\t\t};\n\t\t}\n\t\tconst count = (table: string): number =>\n\t\t\t(this.sql.exec(`SELECT COUNT(*) AS n FROM ${table}`).toArray()[0]\n\t\t\t\t?.n as number) ?? 0;\n\t\treturn {\n\t\t\tmeta: this.readMeta(),\n\t\t\toutdated: false,\n\t\t\trecordCount: count(\"record\"),\n\t\t\tmemberCount: count(\"member\"),\n\t\t\twriterCount: count(\"writer\"),\n\t\t\tqueuedNotifications: count(\"notify_queue\"),\n\t\t};\n\t}\n\n\t// ------------------------------------------------------------------\n\t// Alarm: notification fan-out, oplog compaction, replay cleanup\n\t// ------------------------------------------------------------------\n\n\toverride async alarm(): Promise<void> {\n\t\tawait this.ensureInitialized();\n\t\tif (this.outdated) return;\n\n\t\tawait this.deliverQueuedNotifications();\n\t\tthis.runMaintenanceIfDue();\n\t\tawait this.scheduleNextAlarm();\n\t}\n\n\tprivate async deliverQueuedNotifications(): Promise<void> {\n\t\tconst due = this.sql\n\t\t\t.exec(\n\t\t\t\t\"SELECT id, service, body, attempts, next_at FROM notify_queue WHERE next_at <= ? ORDER BY next_at ASC LIMIT ?\",\n\t\t\t\tDate.now(),\n\t\t\t\tNOTIFY_BATCH,\n\t\t\t)\n\t\t\t.toArray() as unknown as QueueRow[];\n\t\tif (due.length === 0) return;\n\n\t\tconst meta = this.readMeta();\n\t\tif (!meta) {\n\t\t\tthis.sql.exec(\"DELETE FROM notify_queue\");\n\t\t\treturn;\n\t\t}\n\t\tconst host = await this.getHostConfig();\n\t\tconst keypair = await host.getKeypair();\n\n\t\tfor (const row of due) {\n\t\t\tlet delivered = false;\n\t\t\ttry {\n\t\t\t\tconst parsed = JSON.parse(row.body) as {\n\t\t\t\t\tendpoint: string;\n\t\t\t\t\tlxm: string;\n\t\t\t\t\tbody: Record<string, unknown>;\n\t\t\t\t};\n\t\t\t\tconst token = await createServiceJwt(\n\t\t\t\t\t{ iss: meta.authority, aud: row.service, lxm: parsed.lxm },\n\t\t\t\t\tkeypair,\n\t\t\t\t);\n\t\t\t\tconst res = await fetch(`${parsed.endpoint}/xrpc/${parsed.lxm}`, {\n\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t\tAuthorization: `Bearer ${token}`,\n\t\t\t\t\t},\n\t\t\t\t\tbody: JSON.stringify(parsed.body),\n\t\t\t\t});\n\t\t\t\tdelivered = res.ok;\n\t\t\t\tif (!res.ok) {\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`notify ${parsed.lxm} to ${row.service} failed: ${res.status}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tconsole.warn(`notify to ${row.service} errored:`, err);\n\t\t\t}\n\n\t\t\tif (delivered || row.attempts + 1 >= NOTIFY_MAX_ATTEMPTS) {\n\t\t\t\tthis.sql.exec(\"DELETE FROM notify_queue WHERE id = ?\", row.id);\n\t\t\t} else {\n\t\t\t\tthis.sql.exec(\n\t\t\t\t\t\"UPDATE notify_queue SET attempts = ?, next_at = ? WHERE id = ?\",\n\t\t\t\t\trow.attempts + 1,\n\t\t\t\t\tDate.now() + NOTIFY_BACKOFF_BASE_MS * 2 ** row.attempts,\n\t\t\t\t\trow.id,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate runMaintenanceIfDue(): void {\n\t\tconst now = Date.now();\n\t\tconst last =\n\t\t\t(this.sql\n\t\t\t\t.exec(\n\t\t\t\t\t\"SELECT expires_at FROM replay WHERE kind = '__maintenance' AND key = 'last' LIMIT 1\",\n\t\t\t\t)\n\t\t\t\t.toArray()[0]?.expires_at as number | undefined) ?? 0;\n\t\tif (now - last < MAINTENANCE_INTERVAL_MS) return;\n\n\t\t// Oplog compaction: 30 days or 10,000 ops, whichever is smaller.\n\t\t// DO SQLite is billed and capped; the reference has no compaction\n\t\t// yet, ours must.\n\t\tthis.sql.exec(\n\t\t\t\"DELETE FROM oplog WHERE rev < ?\",\n\t\t\ttidCutoff(OPLOG_RETENTION_DAYS * DAY_MS),\n\t\t);\n\t\tconst excess = this.sql\n\t\t\t.exec(\n\t\t\t\t\"SELECT rev, idx FROM oplog ORDER BY rev DESC, idx DESC LIMIT 1 OFFSET ?\",\n\t\t\t\tOPLOG_RETENTION_OPS,\n\t\t\t)\n\t\t\t.toArray()[0];\n\t\tif (excess) {\n\t\t\tthis.sql.exec(\n\t\t\t\t\"DELETE FROM oplog WHERE rev < ? OR (rev = ? AND idx <= ?)\",\n\t\t\t\texcess.rev,\n\t\t\t\texcess.rev,\n\t\t\t\texcess.idx,\n\t\t\t);\n\t\t}\n\n\t\t// Replay entries expire on their own clock.\n\t\tthis.sql.exec(\n\t\t\t\"DELETE FROM replay WHERE kind != '__maintenance' AND expires_at < ?\",\n\t\t\tMath.floor(now / 1000),\n\t\t);\n\t\t// Expired notify registrations.\n\t\tthis.sql.exec(\n\t\t\t\"DELETE FROM notify_registration WHERE expires_at <= ?\",\n\t\t\tnew Date(now).toISOString(),\n\t\t);\n\n\t\tthis.sql.exec(\n\t\t\t`INSERT INTO replay (kind, key, expires_at) VALUES ('__maintenance', 'last', ?)\n\t\t\t ON CONFLICT (kind, key) DO UPDATE SET expires_at = excluded.expires_at`,\n\t\t\tnow,\n\t\t);\n\t}\n\n\tprivate async scheduleNextAlarm(): Promise<void> {\n\t\tconst nextQueue = this.sql\n\t\t\t.exec(\"SELECT MIN(next_at) AS next FROM notify_queue\")\n\t\t\t.toArray()[0]?.next as number | null;\n\t\tconst nextMaintenance = Date.now() + MAINTENANCE_INTERVAL_MS;\n\t\tconst next = nextQueue\n\t\t\t? Math.min(Math.max(nextQueue, Date.now() + 1000), nextMaintenance)\n\t\t\t: nextMaintenance;\n\t\tconst current = await this.ctx.storage.getAlarm();\n\t\tif (current === null || next < current) {\n\t\t\tawait this.ctx.storage.setAlarm(next);\n\t\t}\n\t}\n}\n","/**\n * SpaceIndexDurableObject – singleton registry of space URIs with role\n * flags, timestamps and lifecycle state, addressed by `idFromName(\"spaces\")`.\n *\n * Serves listSpaces, the dashboard, export and reset. Nothing reads it on\n * the hot path: the space DO id is derived from the URI, so reads never\n * depend on the index. Creation is a two-step write — the index entry is\n * written `pending`, the space DO is initialised, then the entry is marked\n * `active`. A `pending` entry that never activates is cleaned up by this\n * DO's alarm.\n */\n\nimport { DurableObject } from \"cloudflare:workers\";\nimport { INDEX_DO_SCHEMA, PENDING_ENTRY_TTL_MS, SPACE_SCHEMA_VERSION } from \"./schema.js\";\n\nexport type SpaceIndexState = \"pending\" | \"active\" | \"deleted\";\n\nexport interface SpaceIndexEntry {\n\turi: string;\n\tauthority: string;\n\ttype: string;\n\tskey: string;\n\tisAuthority: boolean;\n\tstate: SpaceIndexState;\n\tcreatedAt: string;\n\tupdatedAt: string;\n}\n\nconst ALARM_INTERVAL_MS = 6 * 60 * 60 * 1000;\n\nexport class SpaceIndexDurableObject<Env = unknown> extends DurableObject<Env> {\n\tprivate sql: SqlStorage;\n\tprivate initialized = false;\n\n\tconstructor(ctx: DurableObjectState, env: Env) {\n\t\tsuper(ctx, env);\n\t\tthis.sql = ctx.storage.sql;\n\t}\n\n\tprivate async ensureInitialized(): Promise<void> {\n\t\tif (this.initialized) return;\n\t\tawait this.ctx.blockConcurrencyWhile(async () => {\n\t\t\tif (this.initialized) return;\n\t\t\tthis.sql.exec(INDEX_DO_SCHEMA);\n\t\t\tthis.initialized = true;\n\t\t\tconst alarm = await this.ctx.storage.getAlarm();\n\t\t\tif (alarm === null) {\n\t\t\t\tawait this.ctx.storage.setAlarm(Date.now() + ALARM_INTERVAL_MS);\n\t\t\t}\n\t\t});\n\t}\n\n\t/** Register (or revive) an entry in `pending` state. */\n\tasync rpcRegister(entry: {\n\t\turi: string;\n\t\tauthority: string;\n\t\ttype: string;\n\t\tskey: string;\n\t\tisAuthority: boolean;\n\t}): Promise<void> {\n\t\tawait this.ensureInitialized();\n\t\tconst now = new Date().toISOString();\n\t\tthis.sql.exec(\n\t\t\t`INSERT INTO space (uri, authority, type, skey, is_authority, state, created_at, updated_at, schema_version)\n\t\t\t VALUES (?, ?, ?, ?, ?, 'pending', ?, ?, ?)\n\t\t\t ON CONFLICT (uri) DO UPDATE SET\n\t\t\t\tstate = CASE WHEN space.state = 'active' THEN 'active' ELSE 'pending' END,\n\t\t\t\tis_authority = excluded.is_authority,\n\t\t\t\tupdated_at = excluded.updated_at`,\n\t\t\tentry.uri,\n\t\t\tentry.authority,\n\t\t\tentry.type,\n\t\t\tentry.skey,\n\t\t\tentry.isAuthority ? 1 : 0,\n\t\t\tnow,\n\t\t\tnow,\n\t\t\tSPACE_SCHEMA_VERSION,\n\t\t);\n\t}\n\n\tasync rpcActivate(uri: string): Promise<void> {\n\t\tawait this.ensureInitialized();\n\t\tthis.sql.exec(\n\t\t\t\"UPDATE space SET state = 'active', updated_at = ? WHERE uri = ?\",\n\t\t\tnew Date().toISOString(),\n\t\t\turi,\n\t\t);\n\t}\n\n\tasync rpcMarkDeleted(uri: string): Promise<void> {\n\t\tawait this.ensureInitialized();\n\t\tthis.sql.exec(\n\t\t\t\"UPDATE space SET state = 'deleted', updated_at = ? WHERE uri = ?\",\n\t\t\tnew Date().toISOString(),\n\t\t\turi,\n\t\t);\n\t}\n\n\tasync rpcGet(uri: string): Promise<SpaceIndexEntry | null> {\n\t\tawait this.ensureInitialized();\n\t\tconst row = this.sql\n\t\t\t.exec(\"SELECT * FROM space WHERE uri = ?\", uri)\n\t\t\t.toArray()[0];\n\t\treturn row ? toEntry(row) : null;\n\t}\n\n\tasync rpcList(params: {\n\t\ttype?: string;\n\t\tauthority?: string;\n\t\tstate?: SpaceIndexState;\n\t\tlimit: number;\n\t\tafterUri?: string;\n\t}): Promise<{ spaces: SpaceIndexEntry[]; hasMore: boolean }> {\n\t\tawait this.ensureInitialized();\n\t\tconst args: unknown[] = [];\n\t\tlet where = \"1=1\";\n\t\tif (params.type) {\n\t\t\twhere += \" AND type = ?\";\n\t\t\targs.push(params.type);\n\t\t}\n\t\tif (params.authority) {\n\t\t\twhere += \" AND authority = ?\";\n\t\t\targs.push(params.authority);\n\t\t}\n\t\tif (params.state) {\n\t\t\twhere += \" AND state = ?\";\n\t\t\targs.push(params.state);\n\t\t}\n\t\tif (params.afterUri) {\n\t\t\twhere += \" AND uri > ?\";\n\t\t\targs.push(params.afterUri);\n\t\t}\n\t\tconst rows = this.sql\n\t\t\t.exec(\n\t\t\t\t`SELECT * FROM space WHERE ${where} ORDER BY uri ASC LIMIT ?`,\n\t\t\t\t...args,\n\t\t\t\tparams.limit + 1,\n\t\t\t)\n\t\t\t.toArray();\n\t\tconst hasMore = rows.length > params.limit;\n\t\tconst page = hasMore ? rows.slice(0, params.limit) : rows;\n\t\treturn { spaces: page.map(toEntry), hasMore };\n\t}\n\n\tasync rpcStats(): Promise<{\n\t\ttotal: number;\n\t\tactive: number;\n\t\tpending: number;\n\t\tdeleted: number;\n\t\thosted: number;\n\t}> {\n\t\tawait this.ensureInitialized();\n\t\tconst count = (where: string): number =>\n\t\t\t(this.sql\n\t\t\t\t.exec(`SELECT COUNT(*) AS n FROM space WHERE ${where}`)\n\t\t\t\t.toArray()[0]?.n as number) ?? 0;\n\t\treturn {\n\t\t\ttotal: count(\"1=1\"),\n\t\t\tactive: count(\"state = 'active'\"),\n\t\t\tpending: count(\"state = 'pending'\"),\n\t\t\tdeleted: count(\"state = 'deleted'\"),\n\t\t\thosted: count(\"is_authority = 1 AND state = 'active'\"),\n\t\t};\n\t}\n\n\t/** Wipe the registry (spaces reset). */\n\tasync rpcDestroy(): Promise<void> {\n\t\tawait this.ctx.storage.deleteAlarm();\n\t\tawait this.ctx.storage.deleteAll();\n\t\tthis.initialized = false;\n\t}\n\n\t/**\n\t * Tombstone `pending` entries that never activated. They become\n\t * `deleted` rather than being removed: a crash between the space DO's\n\t * initialisation and the index activation leaves real DO storage\n\t * behind, and the index row is the only durable manifest `spaces reset`\n\t * has for finding and destroying it.\n\t */\n\toverride async alarm(): Promise<void> {\n\t\tawait this.ensureInitialized();\n\t\tconst cutoff = new Date(Date.now() - PENDING_ENTRY_TTL_MS).toISOString();\n\t\tthis.sql.exec(\n\t\t\t\"UPDATE space SET state = 'deleted', updated_at = ? WHERE state = 'pending' AND updated_at < ?\",\n\t\t\tnew Date().toISOString(),\n\t\t\tcutoff,\n\t\t);\n\t\tawait this.ctx.storage.setAlarm(Date.now() + ALARM_INTERVAL_MS);\n\t}\n}\n\nfunction toEntry(row: Record<string, unknown>): SpaceIndexEntry {\n\treturn {\n\t\turi: row.uri as string,\n\t\tauthority: row.authority as string,\n\t\ttype: row.type as string,\n\t\tskey: row.skey as string,\n\t\tisAuthority: (row.is_authority as number) === 1,\n\t\tstate: row.state as SpaceIndexState,\n\t\tcreatedAt: row.created_at as string,\n\t\tupdatedAt: row.updated_at as string,\n\t};\n}\n","/**\n * Space URI handling.\n *\n * A space is addressed as `at://{authorityDid}/space/{typeNsid}/{skey}` —\n * the literal `space` marker keeps it unambiguous with public record URIs\n * because a collection NSID always contains at least two dots. A record in\n * a space appends `/{authorDid}/{collection}/{rkey}`.\n */\n\nimport { isDid, isNsid, isRecordKey } from \"@atcute/lexicons/syntax\";\nimport { SpaceError } from \"./errors.js\";\n\nexport interface SpaceRef {\n\t/** The full space URI. */\n\turi: string;\n\t/** The space authority DID. */\n\tauthority: string;\n\t/** The space type NSID. */\n\ttype: string;\n\t/** The space key (record-key syntax). */\n\tskey: string;\n}\n\n/**\n * Parse a space URI. Returns null when the string is not a valid space\n * reference.\n */\nexport function parseSpaceUri(uri: string): SpaceRef | null {\n\tif (!uri.startsWith(\"at://\")) return null;\n\tconst parts = uri.slice(\"at://\".length).split(\"/\");\n\tif (parts.length !== 4) return null;\n\tconst [authority, marker, type, skey] = parts as [\n\t\tstring,\n\t\tstring,\n\t\tstring,\n\t\tstring,\n\t];\n\tif (marker !== \"space\") return null;\n\tif (!isDid(authority) || !isNsid(type) || !isRecordKey(skey)) return null;\n\tconst ref = { uri: formatSpaceUri(authority, type, skey), authority, type, skey };\n\t// Round-trip requirement mirrors the reference's SpaceRef.parse.\n\tif (ref.uri !== uri) return null;\n\treturn ref;\n}\n\n/** Parse a space URI or throw an InvalidSpaceUri error. */\nexport function requireSpaceUri(uri: string | undefined): SpaceRef {\n\tconst ref = uri ? parseSpaceUri(uri) : null;\n\tif (!ref) {\n\t\tthrow new SpaceError(\"InvalidSpaceUri\", `Invalid space URI: ${uri}`);\n\t}\n\treturn ref;\n}\n\nexport function formatSpaceUri(\n\tauthority: string,\n\ttype: string,\n\tskey: string,\n): string {\n\treturn `at://${authority}/space/${type}/${skey}`;\n}\n\n/** URI of a record within a space: `{spaceUri}/{repoDid}/{collection}/{rkey}`. */\nexport function spaceRecordUri(\n\tspaceUri: string,\n\trepo: string,\n\tcollection: string,\n\trkey: string,\n): string {\n\treturn `${spaceUri}/${repo}/${collection}/${rkey}`;\n}\n\nconst BASE32_ALPHABET = \"abcdefghijklmnopqrstuvwxyz234567\";\n\n/**\n * Stable identifier for a space used in R2 key prefixes: the lowercase,\n * unpadded base32 encoding of the SHA-256 of the space URI. Deterministic,\n * filesystem-safe and free of the URI's slashes and colons.\n */\nexport async function spaceId(spaceUri: string): Promise<string> {\n\tconst digest = new Uint8Array(\n\t\tawait crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(spaceUri)),\n\t);\n\tlet out = \"\";\n\tlet bits = 0;\n\tlet value = 0;\n\tfor (const byte of digest) {\n\t\tvalue = (value << 8) | byte;\n\t\tbits += 8;\n\t\twhile (bits >= 5) {\n\t\t\tout += BASE32_ALPHABET[(value >>> (bits - 5)) & 31];\n\t\t\tbits -= 5;\n\t\t}\n\t}\n\tif (bits > 0) {\n\t\tout += BASE32_ALPHABET[(value << (5 - bits)) & 31];\n\t}\n\treturn out;\n}\n","/**\n * R2 key layout for space blobs.\n *\n * A blob referenced by a record in a space lives at\n * `${did}/space/${spaceId}/${cid}` and is served only by the\n * credential-gated `com.atproto.space.getBlob`. The same blob referenced\n * from two spaces is stored twice: per-space prefixes make space deletion\n * and full reset a prefix delete with no cross-space reference counting.\n */\n\nimport { spaceId } from \"./space-uri.js\";\n\n/**\n * Key for a staged (uploaded, not yet referenced) blob. Must match the\n * host's public blob layout: uploads land here and are promoted to their\n * serving key when a record write references them.\n */\nexport function stagedBlobKey(did: string, cid: string): string {\n\treturn `${did}/staged/${cid}`;\n}\n\n/** Prefix holding every space blob for the account. */\nexport function spaceBlobRootPrefix(did: string): string {\n\treturn `${did}/space/`;\n}\n\n/** Prefix holding one space's blobs. `id` comes from {@link spaceId}. */\nexport function spaceBlobPrefix(did: string, id: string): string {\n\treturn `${did}/space/${id}/`;\n}\n\n/** Key for one blob in one space. */\nexport function spaceBlobKey(did: string, id: string, cid: string): string {\n\treturn `${did}/space/${id}/${cid}`;\n}\n\n/** Convenience: key for a blob given the space URI rather than its id. */\nexport async function spaceBlobKeyForUri(\n\tdid: string,\n\tspaceUri: string,\n\tcid: string,\n): Promise<string> {\n\treturn spaceBlobKey(did, await spaceId(spaceUri), cid);\n}\n","/**\n * Worker-side verification of space credentials and delegation tokens.\n *\n * Everything here is stateless except the replay checks, which are one RPC\n * to the space DO's `replay` table. Key resolution goes through the host's\n * DID resolver with a forced refresh on signature failure (handled inside\n * `verifySpaceToken`) so key rotation doesn't strand callers.\n */\n\nimport {\n\tDpopProofError,\n\tSPACE_TOKEN_TYPES,\n\tSpaceTokenError,\n\tspaceHostAud,\n\tverifyDpopProof,\n\tverifySpaceToken,\n} from \"@atproto/space\";\nimport { SpaceError } from \"./errors.js\";\nimport type { SpaceRef } from \"./space-uri.js\";\n\n/** Resolve an issuer DID (+ key id) to a did:key string. */\nexport type GetSigningKey = (\n\tiss: string,\n\tkid: string | undefined,\n\tforceRefresh: boolean,\n) => Promise<string>;\n\n/** Record a single-use key; false when it was already seen. */\nexport type CheckReplay = (\n\tkind: string,\n\tkey: string,\n\texpiresAtSec: number,\n) => Promise<boolean>;\n\n/**\n * Peek at an unverified JWT's `typ` header. Used only for routing between\n * authentication schemes — safe because neither token type verifies as the\n * other.\n */\nexport function unverifiedJwtTyp(token: string): string | null {\n\tconst dot = token.indexOf(\".\");\n\tif (dot <= 0) return null;\n\ttry {\n\t\tconst header = JSON.parse(\n\t\t\tatob(token.slice(0, dot).replace(/-/g, \"+\").replace(/_/g, \"/\")),\n\t\t) as { typ?: unknown };\n\t\treturn typeof header.typ === \"string\" ? header.typ : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/** Whether an Authorization header carries a space credential. */\nexport function isSpaceCredentialAuth(authorization: string | undefined): boolean {\n\tif (!authorization?.startsWith(\"DPoP \")) return false;\n\treturn (\n\t\tunverifiedJwtTyp(authorization.slice(5)) ===\n\t\tSPACE_TOKEN_TYPES.credential.typ\n\t);\n}\n\nexport interface VerifyRequestOpts {\n\t/** HTTP method of the request. */\n\thtm: string;\n\t/** Request URL; its path is combined with `publicOrigin` for htu. */\n\turl: string;\n\t/**\n\t * The origin clients see (`https://host`). The Worker may be behind a\n\t * proxy, so htu is reconstructed from this rather than trusted from the\n\t * incoming URL.\n\t */\n\tpublicOrigin: string;\n\tdpopProof: string | undefined;\n\tgetSigningKey: GetSigningKey;\n\tcheckReplay: CheckReplay;\n}\n\nfunction htuFor(opts: VerifyRequestOpts): string {\n\treturn `${opts.publicOrigin}${new URL(opts.url).pathname}`;\n}\n\nconst nowSec = () => Math.floor(Date.now() / 1000);\n\nexport interface SpaceCredentialResult {\n\tkind: \"credential\";\n\t/** The credential issuer — the space's authority DID. */\n\tiss: string;\n}\n\n/**\n * Verify a space credential (`Authorization: DPoP <jwt>` + `DPoP` proof)\n * presented against `space`. Checks, per the proposal: signature against\n * the issuer's `#atproto_space` / `#atproto` key, `sub` equal to the\n * requested space, `iss` equal to the space's authority, `cnf.jkt` equal\n * to the proof key's thumbprint, proof `htm`/`htu`/`ath`/`iat` valid and\n * proof `jti` unseen.\n */\nexport async function verifySpaceCredentialAuth(\n\tcredential: string,\n\tspace: SpaceRef,\n\topts: VerifyRequestOpts,\n): Promise<SpaceCredentialResult> {\n\tlet payload;\n\ttry {\n\t\t({ payload } = await verifySpaceToken(\"credential\", credential, {\n\t\t\tgetSigningKey: opts.getSigningKey,\n\t\t\tsub: space.uri,\n\t\t}));\n\t} catch (err) {\n\t\tthrow invalidCredential(err);\n\t}\n\tif (payload.iss !== space.authority) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidCredential\",\n\t\t\t\"Space credential issuer is not the space authority\",\n\t\t);\n\t}\n\tconst jkt = payload.cnf?.jkt;\n\tif (!jkt) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidCredential\",\n\t\t\t\"Space credential is missing its cnf.jkt binding\",\n\t\t);\n\t}\n\tif (!opts.dpopProof) {\n\t\tthrow new SpaceError(\"InvalidCredential\", \"Missing DPoP proof\");\n\t}\n\tlet proof;\n\ttry {\n\t\tproof = await verifyDpopProof(opts.dpopProof, {\n\t\t\thtm: opts.htm,\n\t\t\thtu: htuFor(opts),\n\t\t\tcredential,\n\t\t\tjkt,\n\t\t});\n\t} catch (err) {\n\t\tthrow invalidCredential(err);\n\t}\n\tconst fresh = await opts.checkReplay(\n\t\t\"dpop\",\n\t\tproof.jti,\n\t\tnowSec() + 300,\n\t);\n\tif (!fresh) {\n\t\tthrow new SpaceError(\"InvalidCredential\", \"DPoP proof replayed\");\n\t}\n\treturn { kind: \"credential\", iss: payload.iss };\n}\n\nexport interface DelegationResult {\n\t/** The user the delegation token vouches for. */\n\tuserDid: string;\n\t/** Thumbprint of the DPoP key the credential must be bound to. */\n\tdpopJkt: string;\n}\n\n/**\n * Verify a delegation token (`Authorization: Bearer <jwt>` on\n * getSpaceCredential) plus its DPoP proof (no `ath` when obtaining a\n * credential). Single use by `(iss, jti)`.\n */\nexport async function verifyDelegationAuth(\n\ttoken: string,\n\tspace: SpaceRef,\n\topts: VerifyRequestOpts,\n): Promise<DelegationResult> {\n\tlet payload;\n\ttry {\n\t\t({ payload } = await verifySpaceToken(\"delegation\", token, {\n\t\t\tgetSigningKey: opts.getSigningKey,\n\t\t\taud: spaceHostAud(space.authority),\n\t\t\tsub: space.uri,\n\t\t}));\n\t} catch (err) {\n\t\tthrow invalidDelegation(err);\n\t}\n\tif (!payload.iss.startsWith(\"did:\")) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidDelegationToken\",\n\t\t\t\"Delegation token issuer is not a DID\",\n\t\t);\n\t}\n\tif (!opts.dpopProof) {\n\t\tthrow new SpaceError(\"InvalidDelegationToken\", \"Missing DPoP proof\");\n\t}\n\tlet proof;\n\ttry {\n\t\tproof = await verifyDpopProof(opts.dpopProof, {\n\t\t\thtm: opts.htm,\n\t\t\thtu: htuFor(opts),\n\t\t});\n\t} catch (err) {\n\t\tthrow invalidDelegation(err);\n\t}\n\tconst fresh = await opts.checkReplay(\n\t\t\"delegation\",\n\t\t`${payload.iss}:${payload.jti}`,\n\t\tpayload.exp,\n\t);\n\tif (!fresh) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidDelegationToken\",\n\t\t\t\"Delegation token has already been used\",\n\t\t);\n\t}\n\treturn { userDid: payload.iss, dpopJkt: proof.jkt };\n}\n\nfunction invalidCredential(err: unknown): SpaceError {\n\t// Server-side detail for operators; clients get the generic message.\n\tconsole.warn(\"space credential verification failed:\", err);\n\treturn new SpaceError(\"InvalidCredential\", authErrorMessage(err));\n}\n\nfunction invalidDelegation(err: unknown): SpaceError {\n\tconsole.warn(\"delegation token verification failed:\", err);\n\treturn new SpaceError(\"InvalidDelegationToken\", authErrorMessage(err));\n}\n\nfunction authErrorMessage(err: unknown): string {\n\tif (err instanceof SpaceTokenError || err instanceof DpopProofError) {\n\t\treturn err.message;\n\t}\n\t// DID resolution failures and other infrastructure errors must surface\n\t// as 401s, never 500s — but without leaking internals.\n\treturn \"Token verification failed\";\n}\n","/**\n * Client attestation verification (app-identity gating, `allowList` app\n * access). The attestation is a short-lived JWT signed by the OAuth\n * client's published JWKS key, with `iss` = `sub` = client_id and `aud`\n * the space host. Verified against the client's `client-metadata.json`.\n *\n * The client_id in the payload is attacker-controlled until the signature\n * verifies, so nothing is fetched before it has been validated as an\n * https client-metadata URL and checked against the caller's allow-list —\n * a space gated on an allow-list never performs network I/O for a client\n * that could not be authorized anyway. All fetches are bounded by a\n * timeout.\n */\n\nimport { createLocalJWKSet, jwtVerify } from \"jose\";\nimport { SPACE_TOKEN_TYPES, parseSpaceToken } from \"@atproto/space\";\nimport { SpaceError } from \"./errors.js\";\nimport type { CheckReplay } from \"./auth.js\";\n\n/** Upper bound for each outbound metadata/JWKS fetch. */\nconst FETCH_TIMEOUT_MS = 5000;\n\nexport interface VerifyAttestationOpts {\n\t/** Expected audience: `spaceHostAud(authorityDid)`. */\n\texpectedAud: string;\n\t/**\n\t * When set, an (unverified) client_id outside this list is rejected\n\t * before any network I/O. The membership check runs regardless of\n\t * signature state because the caller re-derives authorization from the\n\t * returned client_id after full verification.\n\t */\n\tallowedClientIds?: readonly string[];\n\tcheckReplay: CheckReplay;\n\t/** Fetch override for tests. */\n\tfetch?: typeof fetch;\n}\n\n/**\n * Verify a client attestation and return the attested client_id.\n * Single-use by `(clientId, jti)`.\n */\nexport async function verifyClientAttestation(\n\tattestation: string,\n\topts: VerifyAttestationOpts,\n): Promise<string> {\n\tlet parsed;\n\ttry {\n\t\tparsed = parseSpaceToken(\"clientAttestation\", attestation);\n\t} catch (err) {\n\t\tthrow invalid(err);\n\t}\n\tconst clientId = parsed.payload.iss;\n\tif (parsed.payload.aud !== opts.expectedAud) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidClientAttestation\",\n\t\t\t\"Attestation audience does not match this space host\",\n\t\t);\n\t}\n\n\t// Everything below this point costs network I/O, so gate on what can be\n\t// decided statically first: the client_id must be a plausible https\n\t// client-metadata URL, and must be one the space could authorize at all.\n\tlet clientUrl: URL;\n\ttry {\n\t\tclientUrl = new URL(clientId);\n\t} catch {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidClientAttestation\",\n\t\t\t\"Attestation client_id is not a URL\",\n\t\t);\n\t}\n\tif (clientUrl.protocol !== \"https:\" || clientUrl.username || clientUrl.password) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidClientAttestation\",\n\t\t\t\"Attestation client_id must be a plain https URL\",\n\t\t);\n\t}\n\tif (opts.allowedClientIds && !opts.allowedClientIds.includes(clientId)) {\n\t\tthrow new SpaceError(\n\t\t\t\"AppNotAuthorized\",\n\t\t\t\"App is not authorized for this space\",\n\t\t);\n\t}\n\n\tconst doFetch = opts.fetch ?? fetch;\n\tconst boundedJson = async (url: string): Promise<unknown> => {\n\t\tconst res = await doFetch(url, {\n\t\t\theaders: { Accept: \"application/json\" },\n\t\t\tsignal: AbortSignal.timeout(FETCH_TIMEOUT_MS),\n\t\t\tredirect: \"error\",\n\t\t});\n\t\tif (!res.ok) {\n\t\t\tthrow new Error(`fetch of ${url} returned ${res.status}`);\n\t\t}\n\t\treturn res.json();\n\t};\n\n\tlet metadata: { jwks?: unknown; jwks_uri?: string };\n\ttry {\n\t\tmetadata = (await boundedJson(clientId)) as typeof metadata;\n\t} catch {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidClientAttestation\",\n\t\t\t\"Could not resolve client metadata\",\n\t\t);\n\t}\n\n\tlet jwks = metadata.jwks;\n\tif (!jwks && typeof metadata.jwks_uri === \"string\") {\n\t\tlet jwksUrl: URL;\n\t\ttry {\n\t\t\tjwksUrl = new URL(metadata.jwks_uri);\n\t\t} catch {\n\t\t\tjwksUrl = null as never;\n\t\t}\n\t\tif (!jwksUrl || jwksUrl.protocol !== \"https:\") {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"InvalidClientAttestation\",\n\t\t\t\t\"Client metadata jwks_uri must be an https URL\",\n\t\t\t);\n\t\t}\n\t\ttry {\n\t\t\tjwks = await boundedJson(metadata.jwks_uri);\n\t\t} catch {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"InvalidClientAttestation\",\n\t\t\t\t\"Could not resolve client JWKS\",\n\t\t\t);\n\t\t}\n\t}\n\tif (!jwks) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidClientAttestation\",\n\t\t\t\"Client metadata declares no JWKS\",\n\t\t);\n\t}\n\n\ttry {\n\t\tconst keySet = createLocalJWKSet(\n\t\t\tjwks as Parameters<typeof createLocalJWKSet>[0],\n\t\t);\n\t\tawait jwtVerify(attestation, keySet, {\n\t\t\tissuer: clientId,\n\t\t\tsubject: clientId,\n\t\t\taudience: opts.expectedAud,\n\t\t\ttyp: SPACE_TOKEN_TYPES.clientAttestation.typ,\n\t\t\trequiredClaims: [\"jti\", \"exp\"],\n\t\t\tclockTolerance: 5,\n\t\t});\n\t} catch (err) {\n\t\tthrow invalid(err);\n\t}\n\n\tconst fresh = await opts.checkReplay(\n\t\t\"attestation\",\n\t\t`${clientId}:${parsed.payload.jti}`,\n\t\tparsed.payload.exp,\n\t);\n\tif (!fresh) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidClientAttestation\",\n\t\t\t\"Client attestation has already been used\",\n\t\t);\n\t}\n\treturn clientId;\n}\n\nfunction invalid(err: unknown): SpaceError {\n\treturn new SpaceError(\n\t\t\"InvalidClientAttestation\",\n\t\terr instanceof Error ? err.message : \"Invalid client attestation\",\n\t);\n}\n","/**\n * Commit signing.\n *\n * Signing happens in the Worker, never in the Durable Object. The proposal\n * requires a fresh `ikm` per reader, so a signature is never stored — each\n * response that carries a commit signs the persisted LtHash state anew with\n * the account keypair the Worker already holds.\n */\n\nimport { RepoCommit } from \"@atproto/space\";\nimport type { SignedCommit } from \"@atproto/space\";\nimport type { Keypair } from \"@atproto/crypto\";\nimport { toBase64 } from \"@atproto/lex-data\";\nimport type { RepoState } from \"./types.js\";\n\nexport interface SignCommitParams {\n\tspaceUri: string;\n\t/** The repo author (the operator DID for every repo Cirrus serves). */\n\tauthor: string;\n\tstate: RepoState;\n}\n\nexport async function signCommit(\n\tparams: SignCommitParams,\n\tkeypair: Keypair,\n): Promise<SignedCommit> {\n\treturn RepoCommit.fromState(params.state.setHash).sign(\n\t\t{\n\t\t\tspace: params.spaceUri,\n\t\t\tauthor: params.author,\n\t\t\trev: params.state.rev,\n\t\t},\n\t\tkeypair,\n\t);\n}\n\n/**\n * Lexicon JSON form of a signed commit (`com.atproto.space.defs#signedCommit`):\n * bytes fields encode as `{\"$bytes\": \"<base64>\"}`.\n */\nexport function commitToJson(commit: SignedCommit): Record<string, unknown> {\n\treturn {\n\t\tver: commit.ver,\n\t\thash: { $bytes: toBase64(commit.hash) },\n\t\tikm: { $bytes: toBase64(commit.ikm) },\n\t\tsig: { $bytes: toBase64(commit.sig) },\n\t\tmac: { $bytes: toBase64(commit.mac) },\n\t\trev: commit.rev,\n\t};\n}\n\n/** Lexicon JSON form of a bare bytes value. */\nexport function bytesToJson(bytes: Uint8Array): { $bytes: string } {\n\treturn { $bytes: toBase64(bytes) };\n}\n","/**\n * Record preparation and serialization for the Worker side of the write\n * and read paths. Records are stored as dag-cbor bytes with their CID,\n * computed here — the same encoding path the reference uses.\n */\n\nimport { encode, decode, cidForLex } from \"@atproto/lex-cbor\";\nimport { enumBlobRefs, getBlobCidString } from \"@atproto/lex-data\";\nimport type { LexValue } from \"@atproto/lex-data\";\nimport { jsonToLex, lexToJson } from \"@atproto/lex-json\";\nimport type { JsonValue } from \"@atproto/lex-json\";\n\nexport interface PreparedRecord {\n\tcid: string;\n\tbytes: Uint8Array;\n\tblobCids: string[];\n\t/** The lex-normalised record, for echoing back in responses. */\n\tjson: unknown;\n}\n\n/**\n * Convert a client-supplied JSON record into its stored form: lex value →\n * dag-cbor bytes → CID, with blob references enumerated for the space's\n * blob tracking.\n */\nexport async function prepareRecord(record: unknown): Promise<PreparedRecord> {\n\tconst lex = jsonToLex(record as JsonValue) as LexValue;\n\tconst bytes = encode(lex);\n\tconst cid = await cidForLex(lex);\n\tconst blobCids: string[] = [];\n\tfor (const ref of enumBlobRefs(lex)) {\n\t\tblobCids.push(getBlobCidString(ref));\n\t}\n\treturn { cid: cid.toString(), bytes, blobCids, json: lexToJson(lex) };\n}\n\n/** Decode stored record bytes back into response JSON. */\nexport function recordBytesToJson(bytes: Uint8Array): unknown {\n\treturn lexToJson(decode(bytes));\n}\n","/**\n * Hono route factory for `com.atproto.space.*` and\n * `com.atproto.simplespace.*`.\n *\n * The factory is host-agnostic: everything account-specific — session\n * authentication, DID resolution, record validation, the operator identity\n * — arrives through {@link SpaceRoutesHost}. The host mounts the returned\n * app behind its feature flag.\n */\n\nimport { Hono } from \"hono\";\nimport type { Context } from \"hono\";\nimport { createSpaceToken, serializeRepo, spaceHostAud } from \"@atproto/space\";\nimport type { SerializedRecord } from \"@atproto/space\";\nimport type { Keypair } from \"@atproto/crypto\";\nimport { fromBase64, parseCid } from \"@atproto/lex-data\";\nimport { now as tidNow } from \"@atcute/tid\";\nimport {\n\tisSpaceCredentialAuth,\n\tverifyDelegationAuth,\n\tverifySpaceCredentialAuth,\n\ttype CheckReplay,\n\ttype GetSigningKey,\n} from \"./auth.js\";\nimport { verifyClientAttestation } from \"./attestation.js\";\nimport { bytesToJson, commitToJson, signCommit } from \"./commit.js\";\nimport { SpaceError, parseSpaceErrorCode, spaceErrorStatus } from \"./errors.js\";\nimport { prepareRecord, recordBytesToJson } from \"./records.js\";\nimport { createServiceJwt } from \"./service-jwt.js\";\nimport { spaceBlobPrefix, spaceBlobKey, stagedBlobKey } from \"./blob-keys.js\";\nimport { requireSpaceUri, spaceId, spaceRecordUri } from \"./space-uri.js\";\nimport type { SpaceRef } from \"./space-uri.js\";\nimport type { SpaceDurableObject } from \"./space-do.js\";\nimport type { SpaceIndexDurableObject } from \"./index-do.js\";\nimport type {\n\tNotifyItem,\n\tPreparedSpaceWrite,\n\tSpaceAppAccess,\n\tSpaceConfig,\n\tSpacePolicy,\n} from \"./types.js\";\n\nconst NOTIFY_WRITE_LXM = \"com.atproto.space.notifyWrite\";\nconst SPACE_DELETED_LXM = \"com.atproto.space.notifySpaceDeleted\";\nconst CHECK_USER_ACCESS_LXM = \"com.atproto.simplespace.checkUserAccess\";\n/** A managing app that doesn't answer within this window denies access. */\nconst CHECK_USER_ACCESS_TIMEOUT_MS = 5000;\n\nexport type SpaceStub = DurableObjectStub<SpaceDurableObject>;\nexport type SpaceIndexStub = DurableObjectStub<SpaceIndexDurableObject>;\n\n/** The operation shapes checked against a session's `space:` grants. */\nexport type SpaceScopeMatch = { type: string; authority: string; skey: string } & (\n\t| { action: \"read\" | \"read_self\" }\n\t| { action: \"create\" | \"update\" | \"delete\"; collection: string }\n\t| { manage: \"create\" | \"update\" | \"delete\" }\n);\n\n/**\n * A host session (OAuth token with `space:` grants, or a fully-trusted\n * operator session). App passwords are excluded in the alpha — the host's\n * authenticate() must not produce one of these for them.\n */\nexport interface SpaceSessionAuth {\n\tdid: string;\n\t/** Fully-trusted operator session: skips scope checks. */\n\tfullTrust: boolean;\n\tallowsSpace(match: SpaceScopeMatch): boolean;\n}\n\nexport interface SpaceRoutesHost {\n\toperatorDid: string;\n\t/** Public origin clients address, e.g. `https://pds.example.com`. */\n\tpublicOrigin: string;\n\t/** R2 bucket for blobs; space blob endpoints 503 without it. */\n\tblobs?: R2Bucket;\n\tgetKeypair(): Promise<Keypair>;\n\t/** DID-doc signing key resolution for foreign issuers. */\n\tgetSigningKey: GetSigningKey;\n\t/**\n\t * Resolve a service identifier (`did` or `did#fragment`) to an HTTPS\n\t * endpoint, or null when unresolvable.\n\t */\n\tresolveServiceEndpoint(service: string): Promise<string | null>;\n\t/**\n\t * Resolve a space authority's host endpoint: try\n\t * `#atproto_space_host`, fall back to `#atproto_pds`.\n\t */\n\tresolveAuthorityEndpoint(did: string): Promise<string | null>;\n\t/** Verify an inbound service-auth JWT bound to `lxm`. */\n\tverifyServiceJwt(\n\t\ttoken: string,\n\t\tlxm: string,\n\t): Promise<{ iss: string; aud: string }>;\n\t/**\n\t * Host session authentication (OAuth / operator sessions). Returns a\n\t * Response for authentication failures.\n\t */\n\tauthenticate(c: Context): Promise<SpaceSessionAuth | Response>;\n\t/**\n\t * Lexicon validation with the host's validator. Throws on invalid\n\t * records; the thrown message is surfaced as an InvalidRecord error.\n\t */\n\tvalidateRecord(input: {\n\t\tcollection: string;\n\t\trecord: unknown;\n\t\trkey: string;\n\t\tvalidate?: boolean;\n\t}): { record: unknown; status?: \"valid\" | \"unknown\" };\n\tgetSpaceDO(uri: string): SpaceStub;\n\tgetIndexDO(): SpaceIndexStub;\n\t/** Fetch override for outbound calls (tests). */\n\toutboundFetch?: typeof fetch;\n}\n\n// ---------------------------------------------------------------------\n// Shared helpers\n// ---------------------------------------------------------------------\n\nfunction errorResponse(c: Context, err: unknown): Response {\n\tconst parsed = parseSpaceErrorCode(err);\n\tif (parsed) {\n\t\treturn c.json(\n\t\t\t{ error: parsed.code, message: parsed.message },\n\t\t\tspaceErrorStatus(parsed.code) as 400,\n\t\t);\n\t}\n\tthrow err;\n}\n\nfunction waitUntil(c: Context, promise: Promise<unknown>): void {\n\ttry {\n\t\tc.executionCtx.waitUntil(promise);\n\t} catch {\n\t\t// No execution context (tests): let it float.\n\t\tvoid promise.catch((err) => console.warn(\"background task failed\", err));\n\t}\n}\n\nfunction replayChecker(stub: SpaceStub): CheckReplay {\n\treturn (kind, key, expiresAtSec) => stub.rpcCheckReplay(kind, key, expiresAtSec);\n}\n\ninterface AuthedRead {\n\tkind: \"credential\" | \"session\";\n}\n\nexport function createSpaceRoutes(host: SpaceRoutesHost): Hono {\n\tconst app = new Hono();\n\tconst doFetch: typeof fetch = host.outboundFetch ?? fetch;\n\n\t/** The `repo` param on every repo-host method must be the operator DID. */\n\tfunction requireRepoParam(repo: unknown): void {\n\t\tif (repo !== host.operatorDid) {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"RepoNotFound\",\n\t\t\t\t`Repository not found: ${String(repo)}`,\n\t\t\t);\n\t\t}\n\t}\n\n\tconst verifyOpts = (c: Context, stub: SpaceStub) => ({\n\t\thtm: c.req.method,\n\t\turl: c.req.url,\n\t\tpublicOrigin: host.publicOrigin,\n\t\tdpopProof: c.req.header(\"DPoP\"),\n\t\tgetSigningKey: host.getSigningKey,\n\t\tcheckReplay: replayChecker(stub),\n\t});\n\n\t/**\n\t * Authenticate a read: a space credential for the requested space, or a\n\t * host session covering `read_self` on it. The `repo` param on every\n\t * repo-host method must be the operator DID — anything else is\n\t * RepoNotFound, deliberately indistinguishable from an absent repo.\n\t */\n\tasync function readAuth(\n\t\tc: Context,\n\t\tref: SpaceRef,\n\t\trepo: string | undefined,\n\t): Promise<AuthedRead | Response> {\n\t\tif (repo !== host.operatorDid) {\n\t\t\tthrow new SpaceError(\"RepoNotFound\", `Repository not found: ${repo}`);\n\t\t}\n\t\tconst authHeader = c.req.header(\"Authorization\");\n\t\tif (isSpaceCredentialAuth(authHeader)) {\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tawait verifySpaceCredentialAuth(\n\t\t\t\tauthHeader!.slice(5),\n\t\t\t\tref,\n\t\t\t\tverifyOpts(c, stub),\n\t\t\t);\n\t\t\treturn { kind: \"credential\" };\n\t\t}\n\t\tconst session = await host.authenticate(c);\n\t\tif (session instanceof Response) return session;\n\t\tif (!session.fullTrust) {\n\t\t\tconst allowed = session.allowsSpace({\n\t\t\t\ttype: ref.type,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\tskey: ref.skey,\n\t\t\t\taction: \"read_self\",\n\t\t\t});\n\t\t\tif (!allowed) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror: \"InsufficientScope\",\n\t\t\t\t\t\tmessage: \"Token does not cover reading this space\",\n\t\t\t\t\t},\n\t\t\t\t\t403,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\treturn { kind: \"session\" };\n\t}\n\n\t/** Session-only auth for writes and management. */\n\tasync function sessionAuth(\n\t\tc: Context,\n\t): Promise<SpaceSessionAuth | Response> {\n\t\treturn host.authenticate(c);\n\t}\n\n\tfunction assertScope(\n\t\tc: Context,\n\t\tsession: SpaceSessionAuth,\n\t\tmatch: SpaceScopeMatch,\n\t): Response | null {\n\t\tif (session.fullTrust) return null;\n\t\tif (session.allowsSpace(match)) return null;\n\t\treturn c.json(\n\t\t\t{\n\t\t\t\terror: \"InsufficientScope\",\n\t\t\t\tmessage: \"Token does not cover this space operation\",\n\t\t\t},\n\t\t\t403,\n\t\t);\n\t}\n\n\t/** The operator hosts this space, or SpaceNotFound. */\n\tfunction assertSpaceHost(ref: SpaceRef): void {\n\t\tif (ref.authority !== host.operatorDid) {\n\t\t\tthrow new SpaceError(\"SpaceNotFound\", `Space not found: ${ref.uri}`);\n\t\t}\n\t}\n\n\t/**\n\t * The simplespace user-access policy, applied at credential mint and to\n\t * inbound notifyWrite writers. The authority itself always passes; a\n\t * managing app that errors or times out denies.\n\t */\n\tasync function authorizeUser(\n\t\tconfig: SpaceConfig,\n\t\tref: SpaceRef,\n\t\tuserDid: string,\n\t\tclientId: string | undefined,\n\t\tstub: SpaceStub,\n\t): Promise<boolean> {\n\t\tif (userDid === ref.authority) return true;\n\t\tswitch (config.policy.kind) {\n\t\t\tcase \"public\":\n\t\t\t\treturn true;\n\t\t\tcase \"member-list\":\n\t\t\t\treturn stub.rpcIsMember(userDid);\n\t\t\tcase \"managing-app\": {\n\t\t\t\tconst managingApp = config.policy.managingApp;\n\t\t\t\ttry {\n\t\t\t\t\tconst endpoint = await host.resolveServiceEndpoint(managingApp);\n\t\t\t\t\tif (!endpoint) return false;\n\t\t\t\t\tconst keypair = await host.getKeypair();\n\t\t\t\t\tconst token = await createServiceJwt(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tiss: host.operatorDid,\n\t\t\t\t\t\t\taud: managingApp,\n\t\t\t\t\t\t\tlxm: CHECK_USER_ACCESS_LXM,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tkeypair,\n\t\t\t\t\t);\n\t\t\t\t\tconst url = new URL(`${endpoint}/xrpc/${CHECK_USER_ACCESS_LXM}`);\n\t\t\t\t\turl.searchParams.set(\"space\", ref.uri);\n\t\t\t\t\turl.searchParams.set(\"user\", userDid);\n\t\t\t\t\tif (clientId) url.searchParams.set(\"clientId\", clientId);\n\t\t\t\t\tconst res = await doFetch(url.toString(), {\n\t\t\t\t\t\theaders: { Authorization: `Bearer ${token}` },\n\t\t\t\t\t\tsignal: AbortSignal.timeout(CHECK_USER_ACCESS_TIMEOUT_MS),\n\t\t\t\t\t});\n\t\t\t\t\tif (!res.ok) return false;\n\t\t\t\t\tconst body = (await res.json()) as { authorized?: unknown };\n\t\t\t\t\treturn body.authorized === true;\n\t\t\t\t} catch {\n\t\t\t\t\t// No decision caching in the alpha; unreachable app denies.\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Ensure the space DO exists for a write. First write into a foreign\n\t * space registers it `pending` in the index, initialises the DO as\n\t * repo-host, then activates the entry. Spaces under the operator's own\n\t * authority must have been created via simplespace first.\n\t */\n\tasync function ensureSpaceForWrite(ref: SpaceRef, stub: SpaceStub): Promise<void> {\n\t\tconst meta = await stub.rpcGetMeta();\n\t\tif (meta && !meta.deletedAt) return;\n\t\tif (ref.authority === host.operatorDid) {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"SpaceNotFound\",\n\t\t\t\t`Space not found: ${ref.uri}. Create it with com.atproto.simplespace.createSpace.`,\n\t\t\t);\n\t\t}\n\t\tconst index = host.getIndexDO();\n\t\tawait index.rpcRegister({\n\t\t\turi: ref.uri,\n\t\t\tauthority: ref.authority,\n\t\t\ttype: ref.type,\n\t\t\tskey: ref.skey,\n\t\t\tisAuthority: false,\n\t\t});\n\t\tawait stub.rpcInit({\n\t\t\turi: ref.uri,\n\t\t\tauthority: ref.authority,\n\t\t\ttype: ref.type,\n\t\t\tskey: ref.skey,\n\t\t\tisAuthority: false,\n\t\t});\n\t\tawait index.rpcActivate(ref.uri);\n\t}\n\n\t/**\n\t * Promote staged blobs to the space's R2 prefix. Runs before the DO\n\t * commit so nothing reacting to the commit sees a 404. Idempotent per\n\t * CID; CIDs that are neither staged nor at the destination are skipped.\n\t */\n\tasync function promoteSpaceBlobs(\n\t\tref: SpaceRef,\n\t\tblobCids: string[],\n\t): Promise<void> {\n\t\tif (!host.blobs || blobCids.length === 0) return;\n\t\tconst id = await spaceId(ref.uri);\n\t\tawait Promise.all(\n\t\t\tblobCids.map(async (cid) => {\n\t\t\t\tconst destKey = spaceBlobKey(host.operatorDid, id, cid);\n\t\t\t\tif (await host.blobs!.head(destKey)) return;\n\t\t\t\tconst staged = await host.blobs!.get(\n\t\t\t\t\tstagedBlobKey(host.operatorDid, cid),\n\t\t\t\t);\n\t\t\t\tif (!staged) return;\n\t\t\t\tawait host.blobs!.put(destKey, staged.body, {\n\t\t\t\t\thttpMetadata: staged.httpMetadata,\n\t\t\t\t});\n\t\t\t}),\n\t\t);\n\t}\n\n\t/**\n\t * Step 8 of the write path: after the commit is applied, record the\n\t * writer and fan out (own authority) or send one best-effort\n\t * notifyWrite to the space's authority (foreign space).\n\t */\n\tasync function postWrite(\n\t\tref: SpaceRef,\n\t\tstub: SpaceStub,\n\t\trev: string,\n\t\thash: Uint8Array,\n\t): Promise<void> {\n\t\tif (ref.authority === host.operatorDid) {\n\t\t\tconst { advanced } = await stub.rpcRecordWriter(\n\t\t\t\thost.operatorDid,\n\t\t\t\trev,\n\t\t\t\thash,\n\t\t\t);\n\t\t\t// Own writes always advance in practice; guard anyway so a\n\t\t\t// re-ordered background task never fans out stale state.\n\t\t\tif (!advanced) return;\n\t\t\tconst registrations = await stub.rpcGetActiveRegistrations();\n\t\t\tif (registrations.length === 0) return;\n\t\t\tconst body = {\n\t\t\t\tspace: ref.uri,\n\t\t\t\trepo: host.operatorDid,\n\t\t\t\trev,\n\t\t\t\thash: bytesToJson(hash),\n\t\t\t};\n\t\t\tconst items: NotifyItem[] = registrations.map((registration) => ({\n\t\t\t\tservice: registration.service,\n\t\t\t\tendpoint: registration.endpoint,\n\t\t\t\tlxm: NOTIFY_WRITE_LXM,\n\t\t\t\tbody,\n\t\t\t}));\n\t\t\tawait stub.rpcEnqueueNotify(items);\n\t\t\treturn;\n\t\t}\n\t\t// One attempt, logged on failure: notifications are best-effort and\n\t\t// syncers self-heal, so a retry queue for the writer role is not\n\t\t// worth its complexity.\n\t\ttry {\n\t\t\tconst endpoint = await host.resolveAuthorityEndpoint(ref.authority);\n\t\t\tif (!endpoint) {\n\t\t\t\tconsole.warn(`notifyWrite: no endpoint for ${ref.authority}`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst keypair = await host.getKeypair();\n\t\t\tconst token = await createServiceJwt(\n\t\t\t\t{ iss: host.operatorDid, aud: ref.authority, lxm: NOTIFY_WRITE_LXM },\n\t\t\t\tkeypair,\n\t\t\t);\n\t\t\tconst res = await doFetch(`${endpoint}/xrpc/${NOTIFY_WRITE_LXM}`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\tAuthorization: `Bearer ${token}`,\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tspace: ref.uri,\n\t\t\t\t\trepo: host.operatorDid,\n\t\t\t\t\trev,\n\t\t\t\t\thash: bytesToJson(hash),\n\t\t\t\t}),\n\t\t\t});\n\t\t\tif (!res.ok) {\n\t\t\t\tconsole.warn(\n\t\t\t\t\t`notifyWrite to ${ref.authority} failed: ${res.status}`,\n\t\t\t\t);\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tconsole.warn(`notifyWrite to ${ref.authority} errored:`, err);\n\t\t}\n\t}\n\n\tinterface WriteInput {\n\t\taction: \"create\" | \"update\" | \"delete\";\n\t\tcollection: string;\n\t\trkey?: string;\n\t\tvalue?: unknown;\n\t}\n\n\t/**\n\t * Common write pipeline for createRecord/putRecord/deleteRecord and\n\t * applyWrites: validate, prepare bytes and CIDs, promote blobs, ensure\n\t * the space DO, apply the batch, notify in the background.\n\t */\n\tasync function runWrites(\n\t\tc: Context,\n\t\tref: SpaceRef,\n\t\tsession: SpaceSessionAuth,\n\t\twrites: WriteInput[],\n\t\tvalidate: boolean | undefined,\n\t): Promise<\n\t\t| Response\n\t\t| {\n\t\t\t\trev: string;\n\t\t\t\tresults: Array<{\n\t\t\t\t\taction: string;\n\t\t\t\t\tcollection: string;\n\t\t\t\t\trkey: string;\n\t\t\t\t\tcid: string | null;\n\t\t\t\t\tvalidationStatus?: string;\n\t\t\t\t}>;\n\t\t }\n\t> {\n\t\tconst prepared: PreparedSpaceWrite[] = [];\n\t\tconst statuses: Array<string | undefined> = [];\n\t\tconst blobCids = new Set<string>();\n\n\t\tfor (const write of writes) {\n\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\ttype: ref.type,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\tskey: ref.skey,\n\t\t\t\taction: write.action,\n\t\t\t\tcollection: write.collection,\n\t\t\t});\n\t\t\tif (scopeError) return scopeError;\n\n\t\t\tif (write.action === \"delete\") {\n\t\t\t\tprepared.push({\n\t\t\t\t\taction: \"delete\",\n\t\t\t\t\tcollection: write.collection,\n\t\t\t\t\trkey: write.rkey!,\n\t\t\t\t});\n\t\t\t\tstatuses.push(undefined);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst rkey = write.rkey ?? tidNow();\n\t\t\tlet validated;\n\t\t\ttry {\n\t\t\t\tvalidated = host.validateRecord({\n\t\t\t\t\tcollection: write.collection,\n\t\t\t\t\trecord: write.value,\n\t\t\t\t\trkey,\n\t\t\t\t\tvalidate,\n\t\t\t\t});\n\t\t\t} catch (err) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror: \"InvalidRecord\",\n\t\t\t\t\t\tmessage: err instanceof Error ? err.message : String(err),\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst preparedRecord = await prepareRecord(validated.record);\n\t\t\tfor (const cid of preparedRecord.blobCids) blobCids.add(cid);\n\t\t\tprepared.push({\n\t\t\t\taction: write.action,\n\t\t\t\tcollection: write.collection,\n\t\t\t\trkey,\n\t\t\t\tcid: preparedRecord.cid,\n\t\t\t\tbytes: preparedRecord.bytes,\n\t\t\t\tblobCids: preparedRecord.blobCids,\n\t\t\t});\n\t\t\tstatuses.push(validated.status);\n\t\t}\n\n\t\t// The copy completes before the DO commit is applied, so a relay or\n\t\t// syncer reacting to the commit never sees a 404.\n\t\tawait promoteSpaceBlobs(ref, Array.from(blobCids));\n\n\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\tawait ensureSpaceForWrite(ref, stub);\n\t\tconst result = await stub.rpcApplyWrites(prepared);\n\n\t\twaitUntil(c, postWrite(ref, stub, result.rev, result.hash));\n\n\t\treturn {\n\t\t\trev: result.rev,\n\t\t\tresults: result.results.map((r, i) => ({\n\t\t\t\t...r,\n\t\t\t\t...(statuses[i] !== undefined\n\t\t\t\t\t? { validationStatus: statuses[i] }\n\t\t\t\t\t: {}),\n\t\t\t})),\n\t\t};\n\t}\n\n\t// ---------------------------------------------------------------\n\t// Write endpoints (repo host, session auth)\n\t// ---------------------------------------------------------------\n\n\tapp.post(\"/xrpc/com.atproto.space.createRecord\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{\n\t\t\t\tspace?: string;\n\t\t\t\trepo?: string;\n\t\t\t\tcollection?: string;\n\t\t\t\trkey?: string;\n\t\t\t\tvalidate?: boolean;\n\t\t\t\trecord?: unknown;\n\t\t\t}>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\trequireRepoParam(body.repo);\n\t\t\trequireString(body.collection, \"collection\");\n\t\t\tconst session = await sessionAuth(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst result = await runWrites(\n\t\t\t\tc,\n\t\t\t\tref,\n\t\t\t\tsession,\n\t\t\t\t[\n\t\t\t\t\t{\n\t\t\t\t\t\taction: \"create\",\n\t\t\t\t\t\tcollection: body.collection!,\n\t\t\t\t\t\trkey: body.rkey,\n\t\t\t\t\t\tvalue: body.record,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tbody.validate,\n\t\t\t);\n\t\t\tif (result instanceof Response) return result;\n\t\t\tconst write = result.results[0]!;\n\t\t\treturn c.json({\n\t\t\t\turi: spaceRecordUri(\n\t\t\t\t\tref.uri,\n\t\t\t\t\thost.operatorDid,\n\t\t\t\t\twrite.collection,\n\t\t\t\t\twrite.rkey,\n\t\t\t\t),\n\t\t\t\tcid: write.cid,\n\t\t\t\t...(write.validationStatus\n\t\t\t\t\t? { validationStatus: write.validationStatus }\n\t\t\t\t\t: {}),\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.space.putRecord\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{\n\t\t\t\tspace?: string;\n\t\t\t\trepo?: string;\n\t\t\t\tcollection?: string;\n\t\t\t\trkey?: string;\n\t\t\t\tvalidate?: boolean;\n\t\t\t\trecord?: unknown;\n\t\t\t}>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\trequireRepoParam(body.repo);\n\t\t\trequireString(body.collection, \"collection\");\n\t\t\trequireString(body.rkey, \"rkey\");\n\t\t\tconst session = await sessionAuth(c);\n\t\t\tif (session instanceof Response) return session;\n\n\t\t\t// Upsert: the scope asserted is the operation actually performed.\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tconst meta = await stub.rpcGetMeta();\n\t\t\tconst exists =\n\t\t\t\tmeta && !meta.deletedAt\n\t\t\t\t\t? (await stub.rpcGetRecord(body.collection!, body.rkey!)) !== null\n\t\t\t\t\t: false;\n\n\t\t\tconst result = await runWrites(\n\t\t\t\tc,\n\t\t\t\tref,\n\t\t\t\tsession,\n\t\t\t\t[\n\t\t\t\t\t{\n\t\t\t\t\t\taction: exists ? \"update\" : \"create\",\n\t\t\t\t\t\tcollection: body.collection!,\n\t\t\t\t\t\trkey: body.rkey,\n\t\t\t\t\t\tvalue: body.record,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tbody.validate,\n\t\t\t);\n\t\t\tif (result instanceof Response) return result;\n\t\t\tconst write = result.results[0]!;\n\t\t\treturn c.json({\n\t\t\t\turi: spaceRecordUri(\n\t\t\t\t\tref.uri,\n\t\t\t\t\thost.operatorDid,\n\t\t\t\t\twrite.collection,\n\t\t\t\t\twrite.rkey,\n\t\t\t\t),\n\t\t\t\tcid: write.cid,\n\t\t\t\t...(write.validationStatus\n\t\t\t\t\t? { validationStatus: write.validationStatus }\n\t\t\t\t\t: {}),\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.space.deleteRecord\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{\n\t\t\t\tspace?: string;\n\t\t\t\trepo?: string;\n\t\t\t\tcollection?: string;\n\t\t\t\trkey?: string;\n\t\t\t}>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\trequireRepoParam(body.repo);\n\t\t\trequireString(body.collection, \"collection\");\n\t\t\trequireString(body.rkey, \"rkey\");\n\t\t\tconst session = await sessionAuth(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst result = await runWrites(\n\t\t\t\tc,\n\t\t\t\tref,\n\t\t\t\tsession,\n\t\t\t\t[\n\t\t\t\t\t{\n\t\t\t\t\t\taction: \"delete\",\n\t\t\t\t\t\tcollection: body.collection!,\n\t\t\t\t\t\trkey: body.rkey,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tundefined,\n\t\t\t);\n\t\t\tif (result instanceof Response) return result;\n\t\t\treturn c.json({});\n\t\t} catch (err) {\n\t\t\t// Deleting an absent record succeeds: nothing committed, nothing\n\t\t\t// notified.\n\t\t\tif (parseSpaceErrorCode(err)?.code === \"RecordNotFound\") {\n\t\t\t\treturn c.json({});\n\t\t\t}\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.space.applyWrites\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{\n\t\t\t\tspace?: string;\n\t\t\t\trepo?: string;\n\t\t\t\tvalidate?: boolean;\n\t\t\t\twrites?: Array<{\n\t\t\t\t\t$type?: string;\n\t\t\t\t\tcollection?: string;\n\t\t\t\t\trkey?: string;\n\t\t\t\t\tvalue?: unknown;\n\t\t\t\t}>;\n\t\t\t}>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\trequireRepoParam(body.repo);\n\t\t\tif (!Array.isArray(body.writes)) {\n\t\t\t\tthrow new SpaceError(\"InvalidRequest\", \"writes must be an array\");\n\t\t\t}\n\t\t\tif (body.writes.length > 200) {\n\t\t\t\tthrow new SpaceError(\"InvalidRequest\", \"Too many writes. Max: 200\");\n\t\t\t}\n\t\t\tconst session = await sessionAuth(c);\n\t\t\tif (session instanceof Response) return session;\n\n\t\t\tconst inputs: WriteInput[] = body.writes.map((write, i) => {\n\t\t\t\tconst action =\n\t\t\t\t\twrite.$type === \"com.atproto.space.applyWrites#create\"\n\t\t\t\t\t\t? (\"create\" as const)\n\t\t\t\t\t\t: write.$type === \"com.atproto.space.applyWrites#update\"\n\t\t\t\t\t\t\t? (\"update\" as const)\n\t\t\t\t\t\t\t: write.$type === \"com.atproto.space.applyWrites#delete\"\n\t\t\t\t\t\t\t\t? (\"delete\" as const)\n\t\t\t\t\t\t\t\t: null;\n\t\t\t\tif (!action || !write.collection) {\n\t\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\t\"InvalidRequest\",\n\t\t\t\t\t\t`Write ${i}: unknown $type or missing collection`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (action !== \"create\" && !write.rkey) {\n\t\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\t\"InvalidRequest\",\n\t\t\t\t\t\t`Write ${i}: ${action} requires rkey`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\taction,\n\t\t\t\t\tcollection: write.collection,\n\t\t\t\t\trkey: write.rkey,\n\t\t\t\t\tvalue: write.value,\n\t\t\t\t};\n\t\t\t});\n\n\t\t\tconst result = await runWrites(c, ref, session, inputs, body.validate);\n\t\t\tif (result instanceof Response) return result;\n\t\t\treturn c.json({\n\t\t\t\tresults: result.results.map((write) => {\n\t\t\t\t\tif (write.action === \"delete\") {\n\t\t\t\t\t\treturn { $type: \"com.atproto.space.applyWrites#deleteResult\" };\n\t\t\t\t\t}\n\t\t\t\t\treturn {\n\t\t\t\t\t\t$type: `com.atproto.space.applyWrites#${write.action}Result`,\n\t\t\t\t\t\turi: spaceRecordUri(\n\t\t\t\t\t\t\tref.uri,\n\t\t\t\t\t\t\thost.operatorDid,\n\t\t\t\t\t\t\twrite.collection,\n\t\t\t\t\t\t\twrite.rkey,\n\t\t\t\t\t\t),\n\t\t\t\t\t\tcid: write.cid,\n\t\t\t\t\t\t...(write.validationStatus\n\t\t\t\t\t\t\t? { validationStatus: write.validationStatus }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t};\n\t\t\t\t}),\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\t// ---------------------------------------------------------------\n\t// Read and sync endpoints (credential or session auth)\n\t// ---------------------------------------------------------------\n\n\tapp.get(\"/xrpc/com.atproto.space.getRecord\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tconst auth = await readAuth(c, ref, c.req.query(\"repo\"));\n\t\t\tif (auth instanceof Response) return auth;\n\t\t\tconst collection = c.req.query(\"collection\");\n\t\t\tconst rkey = c.req.query(\"rkey\");\n\t\t\trequireString(collection, \"collection\");\n\t\t\trequireString(rkey, \"rkey\");\n\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tawait requireRepoExists(stub, ref);\n\t\t\tconst record = await stub.rpcGetRecord(collection!, rkey!);\n\t\t\tconst uri = spaceRecordUri(ref.uri, host.operatorDid, collection!, rkey!);\n\t\t\tif (!record) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"RecordNotFound\",\n\t\t\t\t\t`Could not locate record: ${uri}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn c.json({\n\t\t\t\turi,\n\t\t\t\tcid: record.cid,\n\t\t\t\tvalue: recordBytesToJson(record.bytes),\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.get(\"/xrpc/com.atproto.space.listRecords\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tconst auth = await readAuth(c, ref, c.req.query(\"repo\"));\n\t\t\tif (auth instanceof Response) return auth;\n\t\t\tconst collection = c.req.query(\"collection\");\n\t\t\tconst limit = clampLimit(c.req.query(\"limit\"), 50, 1000);\n\t\t\tconst reverse = c.req.query(\"reverse\") === \"true\";\n\t\t\tconst excludeValues = c.req.query(\"excludeValues\") === \"true\";\n\t\t\tconst after = parseRecordCursor(c.req.query(\"cursor\"));\n\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tawait requireRepoExists(stub, ref);\n\t\t\tconst page = await stub.rpcListRecords({\n\t\t\t\tcollection,\n\t\t\t\tlimit,\n\t\t\t\tafter,\n\t\t\t\treverse,\n\t\t\t\texcludeValues,\n\t\t\t});\n\t\t\tconst records = page.records.map((record) => ({\n\t\t\t\tcollection: record.collection,\n\t\t\t\trkey: record.rkey,\n\t\t\t\tcid: record.cid,\n\t\t\t\t...(record.bytes\n\t\t\t\t\t? { value: recordBytesToJson(new Uint8Array(record.bytes)) }\n\t\t\t\t\t: {}),\n\t\t\t}));\n\t\t\tconst last = page.records[page.records.length - 1];\n\t\t\treturn c.json({\n\t\t\t\trecords,\n\t\t\t\t...(page.hasMore && last\n\t\t\t\t\t? { cursor: `${last.collection}/${last.rkey}` }\n\t\t\t\t\t: {}),\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.get(\"/xrpc/com.atproto.space.getLatestCommit\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tconst auth = await readAuth(c, ref, c.req.query(\"repo\"));\n\t\t\tif (auth instanceof Response) return auth;\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tawait requireRepoExists(stub, ref);\n\t\t\tconst state = await stub.rpcGetRepoState();\n\t\t\tif (!state) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"RepoNotFound\",\n\t\t\t\t\t`Could not find repo for space: ${ref.uri}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst keypair = await host.getKeypair();\n\t\t\tconst commit = await signCommit(\n\t\t\t\t{\n\t\t\t\t\tspaceUri: ref.uri,\n\t\t\t\t\tauthor: host.operatorDid,\n\t\t\t\t\tstate: {\n\t\t\t\t\t\tsetHash: new Uint8Array(state.setHash),\n\t\t\t\t\t\trev: state.rev,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tkeypair,\n\t\t\t);\n\t\t\treturn c.json({ commit: commitToJson(commit) });\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.get(\"/xrpc/com.atproto.space.listRepoOps\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tconst auth = await readAuth(c, ref, c.req.query(\"repo\"));\n\t\t\tif (auth instanceof Response) return auth;\n\t\t\tconst limit = clampLimit(c.req.query(\"limit\"), 100, 1000);\n\t\t\tconst since = c.req.query(\"since\");\n\t\t\tconst excludeValues = c.req.query(\"excludeValues\") === \"true\";\n\t\t\tconst after = parseOpsCursor(c.req.query(\"cursor\"));\n\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tawait requireRepoExists(stub, ref);\n\t\t\tconst page = await stub.rpcListRepoOps({\n\t\t\t\tsince,\n\t\t\t\tafter,\n\t\t\t\tlimit,\n\t\t\t\texcludeValues,\n\t\t\t});\n\t\t\tconst ops = page.ops.map((op) => ({\n\t\t\t\trev: op.rev,\n\t\t\t\tcollection: op.collection,\n\t\t\t\trkey: op.rkey,\n\t\t\t\tcid: op.cid,\n\t\t\t\tprev: op.prev,\n\t\t\t\t...(op.bytes\n\t\t\t\t\t? { value: recordBytesToJson(new Uint8Array(op.bytes)) }\n\t\t\t\t\t: {}),\n\t\t\t}));\n\t\t\tif (!page.head) {\n\t\t\t\tconst last = page.ops[page.ops.length - 1];\n\t\t\t\treturn c.json({\n\t\t\t\t\tops,\n\t\t\t\t\t...(last ? { cursor: `${last.rev}/${last.idx}` } : {}),\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst keypair = await host.getKeypair();\n\t\t\tconst commit = await signCommit(\n\t\t\t\t{\n\t\t\t\t\tspaceUri: ref.uri,\n\t\t\t\t\tauthor: host.operatorDid,\n\t\t\t\t\tstate: {\n\t\t\t\t\t\tsetHash: new Uint8Array(page.head.setHash),\n\t\t\t\t\t\trev: page.head.rev,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tkeypair,\n\t\t\t);\n\t\t\treturn c.json({ ops, commit: commitToJson(commit) });\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.get(\"/xrpc/com.atproto.space.getRepo\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tconst auth = await readAuth(c, ref, c.req.query(\"repo\"));\n\t\t\tif (auth instanceof Response) return auth;\n\t\t\tconst excludeValues = c.req.query(\"excludeValues\") === \"true\";\n\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tawait requireRepoExists(stub, ref);\n\n\t\t\t// The commit signs one revision, so every record page must belong\n\t\t\t// to it: each page reports the rev it was read at, and a page from\n\t\t\t// a different rev restarts the export. Records are collected\n\t\t\t// before signing (serializeRepo buffers anyway — see spec open\n\t\t\t// questions), so the CAR always matches its commit.\n\t\t\tlet state: Awaited<ReturnType<typeof stub.rpcGetRepoState>> = null;\n\t\t\tlet records: SerializedRecord[] | null = null;\n\t\t\tfor (let attempt = 0; attempt < 3 && !records; attempt++) {\n\t\t\t\tstate = await stub.rpcGetRepoState();\n\t\t\t\tif (!state) {\n\t\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\t\"RepoNotFound\",\n\t\t\t\t\t\t`Could not find repo for space: ${ref.uri}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst collected: SerializedRecord[] = [];\n\t\t\t\tlet after: { collection: string; rkey: string } | undefined;\n\t\t\t\tlet fenced = true;\n\t\t\t\tfor (;;) {\n\t\t\t\t\tconst page = await stub.rpcListRecords({\n\t\t\t\t\t\tlimit: 500,\n\t\t\t\t\t\tafter,\n\t\t\t\t\t\treverse: true, // ascending\n\t\t\t\t\t\texcludeValues: false,\n\t\t\t\t\t});\n\t\t\t\t\tif (page.rev !== state.rev) {\n\t\t\t\t\t\t// A write landed mid-export; retry from a fresh head.\n\t\t\t\t\t\tfenced = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tfor (const record of page.records) {\n\t\t\t\t\t\tcollected.push({\n\t\t\t\t\t\t\tcollection: record.collection,\n\t\t\t\t\t\t\trkey: record.rkey,\n\t\t\t\t\t\t\tcid: parseCid(record.cid),\n\t\t\t\t\t\t\tbytes: new Uint8Array(record.bytes!),\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tconst last = page.records[page.records.length - 1];\n\t\t\t\t\tif (!page.hasMore || !last) break;\n\t\t\t\t\tafter = { collection: last.collection, rkey: last.rkey };\n\t\t\t\t}\n\t\t\t\tif (fenced) records = collected;\n\t\t\t}\n\t\t\tif (!records || !state) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror: \"ConcurrentModification\",\n\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\t\"The repo changed repeatedly during export; retry getRepo\",\n\t\t\t\t\t},\n\t\t\t\t\t409,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst keypair = await host.getKeypair();\n\t\t\tconst commit = await signCommit(\n\t\t\t\t{\n\t\t\t\t\tspaceUri: ref.uri,\n\t\t\t\t\tauthor: host.operatorDid,\n\t\t\t\t\tstate: {\n\t\t\t\t\t\tsetHash: new Uint8Array(state.setHash),\n\t\t\t\t\t\trev: state.rev,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tkeypair,\n\t\t\t);\n\n\t\t\tconst car = serializeRepo(commit, records, { excludeValues });\n\t\t\tconst stream = new ReadableStream<Uint8Array>({\n\t\t\t\tasync start(controller) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tfor await (const chunk of car) {\n\t\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\tcontroller.error(err);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t});\n\t\t\treturn new Response(stream, {\n\t\t\t\tstatus: 200,\n\t\t\t\theaders: { \"Content-Type\": \"application/vnd.ipld.car\" },\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.get(\"/xrpc/com.atproto.space.listBlobs\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tconst auth = await readAuth(c, ref, c.req.query(\"repo\"));\n\t\t\tif (auth instanceof Response) return auth;\n\t\t\tconst limit = clampLimit(c.req.query(\"limit\"), 500, 1000);\n\t\t\tconst since = c.req.query(\"since\");\n\t\t\tconst afterCid = c.req.query(\"cursor\");\n\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tawait requireRepoExists(stub, ref);\n\t\t\tconst page = await stub.rpcListBlobs({ since, limit, afterCid });\n\t\t\tconst last = page.cids[page.cids.length - 1];\n\t\t\treturn c.json({\n\t\t\t\tcids: page.cids,\n\t\t\t\t...(page.hasMore && last ? { cursor: last } : {}),\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.get(\"/xrpc/com.atproto.space.getBlob\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tconst auth = await readAuth(c, ref, c.req.query(\"repo\"));\n\t\t\tif (auth instanceof Response) return auth;\n\t\t\tconst cid = c.req.query(\"cid\");\n\t\t\trequireString(cid, \"cid\");\n\t\t\tif (!host.blobs) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror: \"ServiceUnavailable\",\n\t\t\t\t\t\tmessage: \"Blob storage is not configured\",\n\t\t\t\t\t},\n\t\t\t\t\t503,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tawait requireRepoExists(stub, ref);\n\t\t\t// Refuse before touching the blobstore: do not reveal whether an\n\t\t\t// unreferenced blob exists.\n\t\t\tif (!(await stub.rpcHasSpaceBlob(cid!))) {\n\t\t\t\tthrow new SpaceError(\"BlobNotFound\", `Blob not found: ${cid}`);\n\t\t\t}\n\t\t\tconst key = spaceBlobKey(host.operatorDid, await spaceId(ref.uri), cid!);\n\t\t\tconst blob = await host.blobs.get(key);\n\t\t\tif (!blob) {\n\t\t\t\tthrow new SpaceError(\"BlobNotFound\", `Blob not found: ${cid}`);\n\t\t\t}\n\t\t\treturn new Response(blob.body, {\n\t\t\t\tstatus: 200,\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\":\n\t\t\t\t\t\tblob.httpMetadata?.contentType ?? \"application/octet-stream\",\n\t\t\t\t\t\"Content-Length\": blob.size.toString(),\n\t\t\t\t\t// A shared cache in front of the PDS must never store a\n\t\t\t\t\t// response whose authorisation was per-credential.\n\t\t\t\t\t\"Cache-Control\": \"private, no-store\",\n\t\t\t\t\tVary: \"Authorization, DPoP\",\n\t\t\t\t\t\"X-Content-Type-Options\": \"nosniff\",\n\t\t\t\t\t\"Content-Disposition\": `attachment; filename=\"${cid}\"`,\n\t\t\t\t\t\"Content-Security-Policy\": \"default-src 'none'; sandbox\",\n\t\t\t\t},\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\t// ---------------------------------------------------------------\n\t// Space host endpoints (authority role)\n\t// ---------------------------------------------------------------\n\n\tapp.post(\"/xrpc/com.atproto.space.getSpaceCredential\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{\n\t\t\t\tspace?: string;\n\t\t\t\tclientAttestation?: string;\n\t\t\t}>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\tassertSpaceHost(ref);\n\n\t\t\tconst authHeader = c.req.header(\"Authorization\");\n\t\t\tif (!authHeader?.startsWith(\"Bearer \")) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"InvalidDelegationToken\",\n\t\t\t\t\t\"Expected a Bearer delegation token\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tconst delegation = await verifyDelegationAuth(\n\t\t\t\tauthHeader.slice(7),\n\t\t\t\tref,\n\t\t\t\tverifyOpts(c, stub),\n\t\t\t);\n\n\t\t\tconst { meta, config } = await stub.rpcGetAuthorityState();\n\t\t\tif (meta?.deletedAt) {\n\t\t\t\t// The durable signal that a space is gone: a syncer that missed\n\t\t\t\t// notifySpaceDeleted learns to drop its copy here.\n\t\t\t\tthrow new SpaceError(\"SpaceDeleted\", `Space deleted: ${ref.uri}`);\n\t\t\t}\n\t\t\tif (!meta || !config) {\n\t\t\t\tthrow new SpaceError(\"SpaceNotFound\", `Space not found: ${ref.uri}`);\n\t\t\t}\n\n\t\t\t// App perimeter first, so a refused app is never disclosed to a\n\t\t\t// third-party managing app.\n\t\t\tlet clientId: string | undefined;\n\t\t\tif (config.appAccess.kind === \"allowList\") {\n\t\t\t\tif (!body.clientAttestation) {\n\t\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\t\"AppNotAuthorized\",\n\t\t\t\t\t\t\"This space requires a client attestation\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tclientId = await verifyClientAttestation(body.clientAttestation, {\n\t\t\t\t\texpectedAud: spaceHostAud(ref.authority),\n\t\t\t\t\t// Checked pre-verification inside so a non-allowlisted\n\t\t\t\t\t// client never triggers network I/O.\n\t\t\t\t\tallowedClientIds: config.appAccess.allowed,\n\t\t\t\t\tcheckReplay: replayChecker(stub),\n\t\t\t\t\tfetch: host.outboundFetch,\n\t\t\t\t});\n\t\t\t\tif (!config.appAccess.allowed.includes(clientId)) {\n\t\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\t\"AppNotAuthorized\",\n\t\t\t\t\t\t\"App is not authorized for this space\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst authorized = await authorizeUser(\n\t\t\t\tconfig,\n\t\t\t\tref,\n\t\t\t\tdelegation.userDid,\n\t\t\t\tclientId,\n\t\t\t\tstub,\n\t\t\t);\n\t\t\tif (!authorized) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"UserNotAuthorized\",\n\t\t\t\t\t\"User is not authorized for this space\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst keypair = await host.getKeypair();\n\t\t\tconst credential = await createSpaceToken(\n\t\t\t\t\"credential\",\n\t\t\t\t{\n\t\t\t\t\tiss: host.operatorDid,\n\t\t\t\t\tsub: ref.uri,\n\t\t\t\t\tdpopJkt: delegation.dpopJkt,\n\t\t\t\t},\n\t\t\t\tkeypair,\n\t\t\t);\n\t\t\treturn c.json({ credential });\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.get(\"/xrpc/com.atproto.space.listRepos\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tassertSpaceHost(ref);\n\t\t\tconst authHeader = c.req.header(\"Authorization\");\n\t\t\tif (!isSpaceCredentialAuth(authHeader)) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"InvalidCredential\",\n\t\t\t\t\t\"listRepos requires a space credential\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tawait verifySpaceCredentialAuth(\n\t\t\t\tauthHeader!.slice(5),\n\t\t\t\tref,\n\t\t\t\tverifyOpts(c, stub),\n\t\t\t);\n\t\t\tconst limit = clampLimit(c.req.query(\"limit\"), 100, 1000);\n\t\t\tconst page = await stub.rpcListWriters({\n\t\t\t\tlimit,\n\t\t\t\tafterDid: c.req.query(\"cursor\"),\n\t\t\t});\n\t\t\tconst last = page.repos[page.repos.length - 1];\n\t\t\treturn c.json({\n\t\t\t\trepos: page.repos.map((repo) => ({\n\t\t\t\t\tdid: repo.did,\n\t\t\t\t\trev: repo.rev,\n\t\t\t\t\thash: bytesToJson(new Uint8Array(repo.hash)),\n\t\t\t\t})),\n\t\t\t\t...(page.hasMore && last ? { cursor: last.did } : {}),\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.space.registerNotify\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{ space?: string; service?: string }>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\tassertSpaceHost(ref);\n\t\t\trequireString(body.service, \"service\");\n\t\t\tconst authHeader = c.req.header(\"Authorization\");\n\t\t\tif (!isSpaceCredentialAuth(authHeader)) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"InvalidCredential\",\n\t\t\t\t\t\"registerNotify requires a space credential\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tawait verifySpaceCredentialAuth(\n\t\t\t\tauthHeader!.slice(5),\n\t\t\t\tref,\n\t\t\t\tverifyOpts(c, stub),\n\t\t\t);\n\t\t\t// Resolve now and store both, so fan-out never resolves DIDs.\n\t\t\tconst endpoint = await host.resolveServiceEndpoint(body.service!);\n\t\t\tif (!endpoint) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"ServiceNotResolvable\",\n\t\t\t\t\t`Could not resolve service: ${body.service}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst result = await stub.rpcRegisterNotify(body.service!, endpoint);\n\t\t\treturn c.json({ expiresAt: result.expiresAt });\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.space.unregisterNotify\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{ space?: string; service?: string }>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\tassertSpaceHost(ref);\n\t\t\trequireString(body.service, \"service\");\n\t\t\tconst authHeader = c.req.header(\"Authorization\");\n\t\t\tif (!isSpaceCredentialAuth(authHeader)) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"InvalidCredential\",\n\t\t\t\t\t\"unregisterNotify requires a space credential\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tawait verifySpaceCredentialAuth(\n\t\t\t\tauthHeader!.slice(5),\n\t\t\t\tref,\n\t\t\t\tverifyOpts(c, stub),\n\t\t\t);\n\t\t\t// No endpoint resolution: a subscriber whose DID doc changed must\n\t\t\t// still be able to withdraw. Idempotent.\n\t\t\tawait stub.rpcUnregisterNotify(body.service!);\n\t\t\treturn c.json({});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.space.notifyWrite\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{\n\t\t\t\tspace?: string;\n\t\t\t\trepo?: string;\n\t\t\t\trev?: string;\n\t\t\t\thash?: { $bytes?: string };\n\t\t\t}>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\tassertSpaceHost(ref);\n\t\t\trequireString(body.repo, \"repo\");\n\t\t\trequireString(body.rev, \"rev\");\n\t\t\tif (typeof body.hash?.$bytes !== \"string\") {\n\t\t\t\tthrow new SpaceError(\"InvalidRequest\", \"Missing hash bytes\");\n\t\t\t}\n\n\t\t\tconst authHeader = c.req.header(\"Authorization\");\n\t\t\tif (!authHeader?.startsWith(\"Bearer \")) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror: \"AuthenticationRequired\",\n\t\t\t\t\t\tmessage: \"Service auth required\",\n\t\t\t\t\t},\n\t\t\t\t\t401,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst serviceAuth = await host.verifyServiceJwt(\n\t\t\t\tauthHeader.slice(7),\n\t\t\t\tNOTIFY_WRITE_LXM,\n\t\t\t);\n\t\t\tif (serviceAuth.iss !== body.repo) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror: \"Forbidden\",\n\t\t\t\t\t\tmessage: \"notifyWrite iss does not match claimed writer\",\n\t\t\t\t\t},\n\t\t\t\t\t403,\n\t\t\t\t);\n\t\t\t}\n\t\t\t// The reference checks the bare DID as audience, not the\n\t\t\t// #atproto_space_host fragment, and we match it.\n\t\t\tif (serviceAuth.aud !== host.operatorDid) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror: \"Forbidden\",\n\t\t\t\t\t\tmessage: \"notifyWrite aud does not match the space authority\",\n\t\t\t\t\t},\n\t\t\t\t\t403,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tconst { meta, config } = await stub.rpcGetAuthorityState();\n\t\t\tif (!meta || meta.deletedAt || !config) {\n\t\t\t\t// Silently ignore notifications for spaces this host does not\n\t\t\t\t// (or no longer) governs.\n\t\t\t\treturn c.json({});\n\t\t\t}\n\t\t\tconst authorized = await authorizeUser(\n\t\t\t\tconfig,\n\t\t\t\tref,\n\t\t\t\tbody.repo!,\n\t\t\t\tundefined,\n\t\t\t\tstub,\n\t\t\t);\n\t\t\tif (!authorized) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror: \"Forbidden\",\n\t\t\t\t\t\tmessage: \"notifyWrite writer is not authorized\",\n\t\t\t\t\t},\n\t\t\t\t\t403,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst hash = fromBase64(body.hash.$bytes);\n\t\t\tconst { advanced } = await stub.rpcRecordWriter(\n\t\t\t\tbody.repo!,\n\t\t\t\tbody.rev!,\n\t\t\t\thash,\n\t\t\t);\n\t\t\t// A delayed or replayed notification carrying an older rev did not\n\t\t\t// change the writer set; do not fan stale state out again.\n\t\t\tif (!advanced) {\n\t\t\t\treturn c.json({});\n\t\t\t}\n\n\t\t\t// Fan out to every registration except the sender.\n\t\t\tconst registrations = await stub.rpcGetActiveRegistrations();\n\t\t\tconst senderDid = body.repo!;\n\t\t\tconst targets = registrations.filter(\n\t\t\t\t(registration) => registration.service.split(\"#\")[0] !== senderDid,\n\t\t\t);\n\t\t\tif (targets.length > 0) {\n\t\t\t\tconst notifyBody = {\n\t\t\t\t\tspace: ref.uri,\n\t\t\t\t\trepo: body.repo!,\n\t\t\t\t\trev: body.rev!,\n\t\t\t\t\thash: body.hash,\n\t\t\t\t};\n\t\t\t\tawait stub.rpcEnqueueNotify(\n\t\t\t\t\ttargets.map((registration) => ({\n\t\t\t\t\t\tservice: registration.service,\n\t\t\t\t\t\tendpoint: registration.endpoint,\n\t\t\t\t\t\tlxm: NOTIFY_WRITE_LXM,\n\t\t\t\t\t\tbody: notifyBody,\n\t\t\t\t\t})),\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn c.json({});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.space.notifySpaceDeleted\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{ space?: string }>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\n\t\t\tconst authHeader = c.req.header(\"Authorization\");\n\t\t\tif (!authHeader?.startsWith(\"Bearer \")) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror: \"AuthenticationRequired\",\n\t\t\t\t\t\tmessage: \"Service auth required\",\n\t\t\t\t\t},\n\t\t\t\t\t401,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst serviceAuth = await host.verifyServiceJwt(\n\t\t\t\tauthHeader.slice(7),\n\t\t\t\tSPACE_DELETED_LXM,\n\t\t\t);\n\t\t\t// Only the space's authority may tell us to drop our copy.\n\t\t\tif (serviceAuth.iss !== ref.authority) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror: \"Forbidden\",\n\t\t\t\t\t\tmessage: \"notifySpaceDeleted iss is not the space authority\",\n\t\t\t\t\t},\n\t\t\t\t\t403,\n\t\t\t\t);\n\t\t\t}\n\t\t\t// And only when the notification was addressed to us: without the\n\t\t\t// audience check, an authority-signed token minted for a different\n\t\t\t// service could be replayed here to tombstone our repo and delete\n\t\t\t// its blobs. Registrations use service identifiers, so accept the\n\t\t\t// bare DID or any of our own #fragment forms.\n\t\t\tif (\n\t\t\t\tserviceAuth.aud !== host.operatorDid &&\n\t\t\t\t!serviceAuth.aud.startsWith(`${host.operatorDid}#`)\n\t\t\t) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror: \"Forbidden\",\n\t\t\t\t\t\tmessage: \"notifySpaceDeleted aud does not match this service\",\n\t\t\t\t\t},\n\t\t\t\t\t403,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (ref.authority === host.operatorDid) {\n\t\t\t\t// We are the authority; nothing to drop from elsewhere.\n\t\t\t\treturn c.json({});\n\t\t\t}\n\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tconst meta = await stub.rpcGetMeta();\n\t\t\tif (meta && !meta.deletedAt) {\n\t\t\t\tawait stub.rpcDeleteSpace();\n\t\t\t\tawait host.getIndexDO().rpcMarkDeleted(ref.uri);\n\t\t\t\tif (host.blobs) {\n\t\t\t\t\twaitUntil(\n\t\t\t\t\t\tc,\n\t\t\t\t\t\tdeleteR2Prefix(\n\t\t\t\t\t\t\thost.blobs,\n\t\t\t\t\t\t\tspaceBlobPrefix(host.operatorDid, await spaceId(ref.uri)),\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\treturn c.json({});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\t// ---------------------------------------------------------------\n\t// simplespace management (authority role, session auth)\n\t// ---------------------------------------------------------------\n\n\tapp.post(\"/xrpc/com.atproto.simplespace.createSpace\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{\n\t\t\t\ttype?: string;\n\t\t\t\tskey?: string;\n\t\t\t\tpolicy?: unknown;\n\t\t\t\tappAccess?: unknown;\n\t\t\t}>();\n\t\t\trequireString(body.type, \"type\");\n\t\t\tconst skey = body.skey ?? tidNow();\n\t\t\tconst session = await sessionAuth(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\ttype: body.type!,\n\t\t\t\tauthority: host.operatorDid,\n\t\t\t\tskey,\n\t\t\t\tmanage: \"create\",\n\t\t\t});\n\t\t\tif (scopeError) return scopeError;\n\n\t\t\tconst config: SpaceConfig = {\n\t\t\t\tpolicy: parsePolicy(body.policy),\n\t\t\t\tappAccess: parseAppAccess(body.appAccess),\n\t\t\t};\n\t\t\tconst uri = `at://${host.operatorDid}/space/${body.type}/${skey}`;\n\t\t\tconst ref = requireSpaceUri(uri);\n\n\t\t\t// Two-step creation: index entry `pending`, then the DO, then\n\t\t\t// `active`. Reads never depend on the index, so a crash between\n\t\t\t// steps leaves only a pending entry for the alarm to reap.\n\t\t\tconst index = host.getIndexDO();\n\t\t\tawait index.rpcRegister({\n\t\t\t\turi: ref.uri,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\ttype: ref.type,\n\t\t\t\tskey: ref.skey,\n\t\t\t\tisAuthority: true,\n\t\t\t});\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tawait stub.rpcInit({\n\t\t\t\turi: ref.uri,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\ttype: ref.type,\n\t\t\t\tskey: ref.skey,\n\t\t\t\tisAuthority: true,\n\t\t\t\tconfig,\n\t\t\t});\n\t\t\tawait index.rpcActivate(ref.uri);\n\t\t\treturn c.json({ uri: ref.uri });\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.simplespace.updateSpace\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{\n\t\t\t\tspace?: string;\n\t\t\t\tpolicy?: unknown;\n\t\t\t\tappAccess?: unknown;\n\t\t\t}>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\tconst session = await sessionAuth(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tassertOwner(ref, session);\n\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\ttype: ref.type,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\tskey: ref.skey,\n\t\t\t\tmanage: \"update\",\n\t\t\t});\n\t\t\tif (scopeError) return scopeError;\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tawait stub.rpcUpdateConfig({\n\t\t\t\t...(body.policy !== undefined\n\t\t\t\t\t? { policy: parsePolicy(body.policy) }\n\t\t\t\t\t: {}),\n\t\t\t\t...(body.appAccess !== undefined\n\t\t\t\t\t? { appAccess: parseAppAccess(body.appAccess) }\n\t\t\t\t\t: {}),\n\t\t\t});\n\t\t\treturn c.json({});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.simplespace.deleteSpace\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{ space?: string }>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\tconst session = await sessionAuth(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tassertOwner(ref, session);\n\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\ttype: ref.type,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\tskey: ref.skey,\n\t\t\t\tmanage: \"delete\",\n\t\t\t});\n\t\t\tif (scopeError) return scopeError;\n\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tconst { registrations } = await stub.rpcDeleteSpace();\n\t\t\tawait host.getIndexDO().rpcMarkDeleted(ref.uri);\n\t\t\t// Stop credential issuance happened with the tombstone; tell every\n\t\t\t// registered syncer to drop its copy, then reap the blob prefix.\n\t\t\tif (registrations.length > 0) {\n\t\t\t\tawait stub.rpcEnqueueNotify(\n\t\t\t\t\tregistrations.map((registration) => ({\n\t\t\t\t\t\tservice: registration.service,\n\t\t\t\t\t\tendpoint: registration.endpoint,\n\t\t\t\t\t\tlxm: SPACE_DELETED_LXM,\n\t\t\t\t\t\tbody: { space: ref.uri },\n\t\t\t\t\t})),\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (host.blobs) {\n\t\t\t\twaitUntil(\n\t\t\t\t\tc,\n\t\t\t\t\tdeleteR2Prefix(\n\t\t\t\t\t\thost.blobs,\n\t\t\t\t\t\tspaceBlobPrefix(host.operatorDid, await spaceId(ref.uri)),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn c.json({});\n\t\t} catch (err) {\n\t\t\t// deleteSpace is idempotent: a second delete of a tombstoned space\n\t\t\t// (or a never-created one) reports SpaceNotFound per the lexicon.\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.simplespace.addMember\", async (c) => {\n\t\treturn memberChange(c, \"add\");\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.simplespace.removeMember\", async (c) => {\n\t\treturn memberChange(c, \"remove\");\n\t});\n\n\tasync function memberChange(\n\t\tc: Context,\n\t\top: \"add\" | \"remove\",\n\t): Promise<Response> {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{ space?: string; did?: string }>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\trequireString(body.did, \"did\");\n\t\t\tconst session = await sessionAuth(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tassertOwner(ref, session);\n\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\ttype: ref.type,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\tskey: ref.skey,\n\t\t\t\tmanage: \"update\",\n\t\t\t});\n\t\t\tif (scopeError) return scopeError;\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tawait requireConfigured(stub, ref);\n\t\t\tif (op === \"add\") {\n\t\t\t\tawait stub.rpcAddMember(body.did!);\n\t\t\t} else {\n\t\t\t\tawait stub.rpcRemoveMember(body.did!);\n\t\t\t}\n\t\t\treturn c.json({});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t}\n\n\tapp.get(\"/xrpc/com.atproto.simplespace.getSpace\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tassertSpaceHost(ref);\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\n\t\t\tconst authHeader = c.req.header(\"Authorization\");\n\t\t\tif (isSpaceCredentialAuth(authHeader)) {\n\t\t\t\tawait verifySpaceCredentialAuth(\n\t\t\t\t\tauthHeader!.slice(5),\n\t\t\t\t\tref,\n\t\t\t\t\tverifyOpts(c, stub),\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tconst session = await sessionAuth(c);\n\t\t\t\tif (session instanceof Response) return session;\n\t\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\t\ttype: ref.type,\n\t\t\t\t\tauthority: ref.authority,\n\t\t\t\t\tskey: ref.skey,\n\t\t\t\t\taction: \"read_self\",\n\t\t\t\t});\n\t\t\t\tif (scopeError) return scopeError;\n\t\t\t}\n\n\t\t\tconst config = await requireConfigured(stub, ref);\n\t\t\treturn c.json({\n\t\t\t\turi: ref.uri,\n\t\t\t\tpolicy: policyToJson(config.policy),\n\t\t\t\tappAccess: appAccessToJson(config.appAccess),\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.get(\"/xrpc/com.atproto.simplespace.listMembers\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tconst session = await sessionAuth(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tassertOwner(ref, session);\n\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\ttype: ref.type,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\tskey: ref.skey,\n\t\t\t\taction: \"read_self\",\n\t\t\t});\n\t\t\tif (scopeError) return scopeError;\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tawait requireConfigured(stub, ref);\n\t\t\tconst limit = clampLimit(c.req.query(\"limit\"), 100, 1000);\n\t\t\tconst page = await stub.rpcListMembers({\n\t\t\t\tlimit,\n\t\t\t\tafterDid: c.req.query(\"cursor\"),\n\t\t\t});\n\t\t\tconst last = page.dids[page.dids.length - 1];\n\t\t\treturn c.json({\n\t\t\t\tmembers: page.dids.map((did) => ({ did })),\n\t\t\t\t...(page.hasMore && last ? { cursor: last } : {}),\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tfunction assertOwner(ref: SpaceRef, session: SpaceSessionAuth): void {\n\t\tassertSpaceHost(ref);\n\t\tif (session.did !== ref.authority) {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"NotSpaceOwner\",\n\t\t\t\t\"Only the space owner may manage the space\",\n\t\t\t);\n\t\t}\n\t}\n\n\tasync function requireConfigured(\n\t\tstub: SpaceStub,\n\t\tref: SpaceRef,\n\t): Promise<SpaceConfig> {\n\t\tconst { meta, config } = await stub.rpcGetAuthorityState();\n\t\tif (!meta || meta.deletedAt || !config) {\n\t\t\tthrow new SpaceError(\"SpaceNotFound\", `Space not found: ${ref.uri}`);\n\t\t}\n\t\treturn config;\n\t}\n\n\t/**\n\t * A repo exists in a space once the operator has written into it (or\n\t * the space was created here). RepoNotFound deliberately covers both\n\t * \"no such repo\" and \"space unknown to this host\".\n\t */\n\tasync function requireRepoExists(\n\t\tstub: SpaceStub,\n\t\tref: SpaceRef,\n\t): Promise<void> {\n\t\tconst meta = await stub.rpcGetMeta();\n\t\tif (meta?.deletedAt) {\n\t\t\t// After deletion, reads against the space fail with SpaceNotFound.\n\t\t\tthrow new SpaceError(\"SpaceNotFound\", `Space not found: ${ref.uri}`);\n\t\t}\n\t\tif (!meta) {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"RepoNotFound\",\n\t\t\t\t`Could not find repo for space: ${ref.uri}`,\n\t\t\t);\n\t\t}\n\t}\n\n\treturn app;\n}\n\n// ---------------------------------------------------------------------\n// Small parsing helpers\n// ---------------------------------------------------------------------\n\nfunction requireString(\n\tvalue: unknown,\n\tname: string,\n): asserts value is string {\n\tif (typeof value !== \"string\" || value.length === 0) {\n\t\tthrow new SpaceError(\"InvalidRequest\", `Missing required parameter: ${name}`);\n\t}\n}\n\nfunction clampLimit(\n\traw: string | undefined,\n\tfallback: number,\n\tmax: number,\n): number {\n\tconst parsed = raw ? Number.parseInt(raw, 10) : fallback;\n\tif (Number.isNaN(parsed) || parsed < 1) return fallback;\n\treturn Math.min(parsed, max);\n}\n\nfunction parseRecordCursor(\n\tcursor: string | undefined,\n): { collection: string; rkey: string } | undefined {\n\tif (!cursor) return undefined;\n\tconst slash = cursor.lastIndexOf(\"/\");\n\tif (slash <= 0 || slash === cursor.length - 1) {\n\t\tthrow new SpaceError(\"MalformedCursor\", `Malformed cursor: ${cursor}`);\n\t}\n\treturn {\n\t\tcollection: cursor.slice(0, slash),\n\t\trkey: cursor.slice(slash + 1),\n\t};\n}\n\nfunction parseOpsCursor(\n\tcursor: string | undefined,\n): { rev: string; idx: number } | undefined {\n\tif (!cursor) return undefined;\n\tconst slash = cursor.indexOf(\"/\");\n\tconst idx = slash === -1 ? NaN : Number.parseInt(cursor.slice(slash + 1), 10);\n\tif (slash <= 0 || Number.isNaN(idx)) {\n\t\tthrow new SpaceError(\"MalformedCursor\", `Malformed cursor: ${cursor}`);\n\t}\n\treturn { rev: cursor.slice(0, slash), idx };\n}\n\nconst POLICY_PREFIX = \"com.atproto.simplespace.defs#\";\n\nfunction parsePolicy(input: unknown): SpacePolicy {\n\tconst type = (input as { $type?: string } | undefined)?.$type;\n\tswitch (type) {\n\t\tcase `${POLICY_PREFIX}publicPolicy`:\n\t\t\treturn { kind: \"public\" };\n\t\tcase `${POLICY_PREFIX}memberListPolicy`:\n\t\t\treturn { kind: \"member-list\" };\n\t\tcase `${POLICY_PREFIX}managingAppPolicy`: {\n\t\t\tconst managingApp = (input as { managingApp?: unknown }).managingApp;\n\t\t\tif (typeof managingApp !== \"string\" || !managingApp.startsWith(\"did:\")) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"UnsupportedPolicy\",\n\t\t\t\t\t\"managingApp must be a DID service identifier\",\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn { kind: \"managing-app\", managingApp };\n\t\t}\n\t\tdefault:\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"UnsupportedPolicy\",\n\t\t\t\t`Unsupported policy: ${String(type)}`,\n\t\t\t);\n\t}\n}\n\nfunction policyToJson(policy: SpacePolicy): Record<string, unknown> {\n\tswitch (policy.kind) {\n\t\tcase \"public\":\n\t\t\treturn { $type: `${POLICY_PREFIX}publicPolicy` };\n\t\tcase \"member-list\":\n\t\t\treturn { $type: `${POLICY_PREFIX}memberListPolicy` };\n\t\tcase \"managing-app\":\n\t\t\treturn {\n\t\t\t\t$type: `${POLICY_PREFIX}managingAppPolicy`,\n\t\t\t\tmanagingApp: policy.managingApp,\n\t\t\t};\n\t}\n}\n\nfunction appAccessToJson(appAccess: SpaceAppAccess): Record<string, unknown> {\n\tswitch (appAccess.kind) {\n\t\tcase \"open\":\n\t\t\treturn { $type: `${POLICY_PREFIX}open` };\n\t\tcase \"allowList\":\n\t\t\treturn {\n\t\t\t\t$type: `${POLICY_PREFIX}allowList`,\n\t\t\t\tallowed: appAccess.allowed,\n\t\t\t};\n\t}\n}\n\nfunction parseAppAccess(input: unknown): SpaceAppAccess {\n\tconst type = (input as { $type?: string } | undefined)?.$type;\n\tswitch (type) {\n\t\tcase `${POLICY_PREFIX}open`:\n\t\t\treturn { kind: \"open\" };\n\t\tcase `${POLICY_PREFIX}allowList`: {\n\t\t\tconst allowed = (input as { allowed?: unknown }).allowed;\n\t\t\tif (\n\t\t\t\t!Array.isArray(allowed) ||\n\t\t\t\tallowed.some((entry) => typeof entry !== \"string\")\n\t\t\t) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"UnsupportedAppAccess\",\n\t\t\t\t\t\"allowList requires an array of client IDs\",\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn { kind: \"allowList\", allowed: allowed as string[] };\n\t\t}\n\t\tdefault:\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"UnsupportedAppAccess\",\n\t\t\t\t`Unsupported appAccess: ${String(type)}`,\n\t\t\t);\n\t}\n}\n\nasync function deleteR2Prefix(bucket: R2Bucket, prefix: string): Promise<void> {\n\tlet cursor: string | undefined;\n\tdo {\n\t\tconst listed = await bucket.list({ prefix, cursor, limit: 500 });\n\t\tif (listed.objects.length > 0) {\n\t\t\tawait bucket.delete(listed.objects.map((object) => object.key));\n\t\t}\n\t\tcursor = listed.truncated ? listed.cursor : undefined;\n\t} while (cursor);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAWA,MAAa,oBAAoB;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;C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Ac;GACxB,SAAS,UAAU;GACnB;;;AAIJ,SAAS,eAAe,OAAgC;CACvD,MAAM,OAAQ,OAA0C;AACxD,SAAQ,MAAR;EACC,KAAK,GAAG,cAAc,MACrB,QAAO,EAAE,MAAM,QAAQ;EACxB,KAAK,GAAG,cAAc,YAAY;GACjC,MAAM,UAAW,MAAgC;AACjD,OACC,CAAC,MAAM,QAAQ,QAAQ,IACvB,QAAQ,MAAM,UAAU,OAAO,UAAU,SAAS,CAElD,OAAM,IAAI,WACT,wBACA,4CACA;AAEF,UAAO;IAAE,MAAM;IAAsB;IAAqB;;EAE3D,QACC,OAAM,IAAI,WACT,wBACA,0BAA0B,OAAO,KAAK,GACtC;;;AAIJ,eAAe,eAAe,QAAkB,QAA+B;CAC9E,IAAIC;AACJ,IAAG;EACF,MAAM,SAAS,MAAM,OAAO,KAAK;GAAE;GAAQ;GAAQ,OAAO;GAAK,CAAC;AAChE,MAAI,OAAO,QAAQ,SAAS,EAC3B,OAAM,OAAO,OAAO,OAAO,QAAQ,KAAK,WAAW,OAAO,IAAI,CAAC;AAEhE,WAAS,OAAO,YAAY,OAAO,SAAS;UACpC"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["CODE_SET: ReadonlySet<string>","ERROR_STATUS: Partial<Record<SpaceErrorCode, number>>","code: SpaceErrorCode","PUBLISHED_COLLECTIONS: readonly string[]","blobCids: string[]","tidNow","payload: Record<string, unknown>","results: ApplyWritesResult[\"results\"]","args: unknown[]","ops: OplogEntry[]","writes: PreparedSpaceWrite[]","sequence","now","headers: Record<string, string>","now","args: unknown[]","spaceHostAud","clientUrl: URL","metadata: { jwks?: unknown; jwks_uri?: string }","jwksUrl: URL","doFetch: typeof fetch","kemKeypair: Promise<P256Keypair | null> | null","missing: string[]","spaceHostAud","retry: NotifyItem","prepared: PreparedSpaceWrite[]","statuses: Array<string | undefined>","tidNow","records: ImportedRecord[]","space: string","repo: string","blobCids: string[]","ref","repo: string | undefined","clientId: string | undefined","revMs: number","url: URL","cursor: string | undefined","upstreamSpaceHostAud","upstreamCreateDelegationToken"],"sources":["../src/errors.ts","../src/types.ts","../src/policy.ts","../src/records.ts","../src/schema.ts","../src/mac.ts","../src/tid.ts","../src/service-jwt.ts","../src/space-do.ts","../src/index-do.ts","../src/space-uri.ts","../src/blob-keys.ts","../src/auth.ts","../src/attestation.ts","../src/routes.ts","../src/tokens.ts"],"sourcesContent":["/**\n * Typed errors for the spaces engine.\n *\n * Durable Object RPC flattens thrown errors into a wrapper `Error` whose\n * message is `\"${name}: ${message}\"`, so every error here encodes its\n * protocol error name as a message prefix. Worker-side handlers recover the\n * name with {@link parseSpaceErrorCode} and map it onto the lexicon error\n * shape.\n */\n\n/** Protocol error names used across the space and policy endpoints. */\nexport const SPACE_ERROR_CODES = [\n\t\"SpaceNotFound\",\n\t\"SpaceDeleted\",\n\t\"SpaceAlreadyExists\",\n\t\"RepoNotFound\",\n\t\"RepoDeactivated\",\n\t\"RepoTakendown\",\n\t\"RecordNotFound\",\n\t\"RecordAlreadyExists\",\n\t\"BlobNotFound\",\n\t\"AppNotAuthorized\",\n\t\"NotAuthorized\",\n\t\"AccountNotAuthorized\",\n\t\"InvalidDelegationToken\",\n\t\"InvalidClientAttestation\",\n\t\"InvalidCredential\",\n\t\"PolicyMismatch\",\n\t\"UnsupportedPolicy\",\n\t\"ServiceNotResolvable\",\n\t\"InvalidCursor\",\n\t\"InvalidRequest\",\n\t\"FutureRev\",\n\t\"InvalidSpaceMac\",\n\t\"InvalidRepoFile\",\n\t\"RepoMismatch\",\n\t\"InvalidSpaceMeta\",\n\t\"RegistrationNotConfirmed\",\n\t\"UpstreamFailure\",\n\t// Space credential authentication failures, named as the reference\n\t// names them (all 401).\n\t\"MissingJwt\",\n\t\"BadJwt\",\n\t\"BadJwtType\",\n\t\"BadJwtIss\",\n\t\"BadJwtSub\",\n\t\"BadJwtAudience\",\n\t\"BadJwtCnf\",\n\t\"BadJwtSignature\",\n\t\"JwtExpired\",\n\t\"BadSpaceSignature\",\n\t\"BadSpaceAudience\",\n\t\"CredentialRevoked\",\n\t\"Forbidden\",\n\t\"KemKeyUnavailable\",\n\t\"SpacesSchemaOutdated\",\n] as const;\n\nexport type SpaceErrorCode = (typeof SPACE_ERROR_CODES)[number];\n\nconst CODE_SET: ReadonlySet<string> = new Set(SPACE_ERROR_CODES);\n\n/** HTTP status for each error name when it isn't the default 400. */\nconst ERROR_STATUS: Partial<Record<SpaceErrorCode, number>> = {\n\tSpaceNotFound: 404,\n\tRepoNotFound: 404,\n\tBlobNotFound: 404,\n\tRecordAlreadyExists: 409,\n\tSpaceAlreadyExists: 409,\n\tAppNotAuthorized: 403,\n\t// NotAuthorized is the management methods' \"not the space authority\",\n\t// a 400 as the reference answers it.\n\tAccountNotAuthorized: 403,\n\tForbidden: 403,\n\tUpstreamFailure: 502,\n\tInvalidClientAttestation: 401,\n\tMissingJwt: 401,\n\tBadJwt: 401,\n\tBadJwtType: 401,\n\tBadJwtIss: 401,\n\tBadJwtSub: 401,\n\tBadJwtAudience: 401,\n\tBadJwtCnf: 401,\n\tBadJwtSignature: 401,\n\tJwtExpired: 401,\n\tBadSpaceSignature: 401,\n\tBadSpaceAudience: 401,\n\tCredentialRevoked: 401,\n\tKemKeyUnavailable: 503,\n\tSpacesSchemaOutdated: 503,\n};\n\nexport class SpaceError extends Error {\n\toverride name = \"SpaceError\";\n\tconstructor(\n\t\treadonly code: SpaceErrorCode,\n\t\tmessage: string,\n\t) {\n\t\t// The `${code}: ` prefix survives the DO RPC boundary.\n\t\tsuper(`${code}: ${message}`);\n\t}\n\n\tget status(): number {\n\t\treturn ERROR_STATUS[this.code] ?? 400;\n\t}\n\n\t/** The human message without the code prefix. */\n\tget detail(): string {\n\t\treturn this.message.slice(this.code.length + 2);\n\t}\n}\n\n/**\n * Recover the space error name from an error that may have crossed a DO RPC\n * boundary. Returns null for errors that aren't space errors.\n */\nexport function parseSpaceErrorCode(\n\terr: unknown,\n): { code: SpaceErrorCode; message: string } | null {\n\tif (err instanceof SpaceError) {\n\t\treturn { code: err.code, message: err.detail };\n\t}\n\tif (err instanceof Error) {\n\t\t// Durable Object RPC re-throws errors with the class name folded into\n\t\t// the message (\"SpaceError: RecordNotFound: ...\"), so scan the first\n\t\t// few prefix segments for a known code.\n\t\tlet message = err.message;\n\t\tfor (let hop = 0; hop < 3; hop++) {\n\t\t\tconst colon = message.indexOf(\": \");\n\t\t\tif (colon <= 0) break;\n\t\t\tconst code = message.slice(0, colon);\n\t\t\tif (CODE_SET.has(code)) {\n\t\t\t\treturn {\n\t\t\t\t\tcode: code as SpaceErrorCode,\n\t\t\t\t\tmessage: message.slice(colon + 2),\n\t\t\t\t};\n\t\t\t}\n\t\t\tmessage = message.slice(colon + 2);\n\t\t}\n\t}\n\treturn null;\n}\n\n/** HTTP status for a recovered space error name. */\nexport function spaceErrorStatus(code: SpaceErrorCode): number {\n\treturn ERROR_STATUS[code] ?? 400;\n}\n","/**\n * Shared types crossing the Worker ↔ Durable Object RPC boundary.\n */\n\n/**\n * The minimal keypair shape the engine signs with: the account's\n * `#atproto` key, for space tokens and service-auth JWTs. Structural, so a\n * host can pass any `@atproto/crypto` keypair without the engine's public\n * types depending on a particular build of that package.\n */\nexport interface SpaceSigningKeypair {\n\tjwtAlg: string;\n\tdid(): string;\n\tsign(msg: Uint8Array): Promise<Uint8Array>;\n}\n\n/** A write prepared by the Worker: validated, CBOR-encoded, CID computed. */\nexport type PreparedSpaceWrite =\n\t| {\n\t\t\taction: \"create\" | \"update\";\n\t\t\tcollection: string;\n\t\t\trkey: string;\n\t\t\tcid: string;\n\t\t\tbytes: Uint8Array;\n\t\t\t/** Blob CIDs referenced by the record. */\n\t\t\tblobCids: string[];\n\t }\n\t| {\n\t\t\taction: \"delete\";\n\t\t\tcollection: string;\n\t\t\trkey: string;\n\t };\n\n/** A repo revision that is owed a write notification. */\nexport interface RepoCommitResult {\n\trev: string;\n\t/** sha256 digest of the LtHash state: the commit's `data`. */\n\tdata: Uint8Array;\n}\n\nexport interface ApplyWritesResult extends RepoCommitResult {\n\tresults: Array<{\n\t\taction: \"create\" | \"update\" | \"delete\";\n\t\tcollection: string;\n\t\trkey: string;\n\t\tcid: string | null;\n\t}>;\n}\n\nexport interface SpaceMeta {\n\turi: string;\n\tauthority: string;\n\ttype: string;\n\tskey: string;\n\tisAuthority: boolean;\n\tcreatedAt: string;\n\tdeletedAt: string | null;\n}\n\nexport const PERSONALSPACE_POLICY = \"com.atproto.personalspace.policy\";\nexport const MEMBERSPACE_POLICY = \"com.atproto.memberspace.policy\";\nexport const MANAGEDSPACE_POLICY = \"com.atproto.managedspace.policy\";\n\n/**\n * A space policy as stored and enforced: one of the three baseline\n * policies, normalised with its defaults filled in. The wire shape and the\n * stored shape are the same object.\n */\nexport type SpacePolicy =\n\t| { $type: typeof PERSONALSPACE_POLICY }\n\t| {\n\t\t\t$type: typeof MEMBERSPACE_POLICY;\n\t\t\tpublicRead: boolean;\n\t\t\tpublicWrite: boolean;\n\t\t\tallowedApps?: string[];\n\t\t\tpublishPolicy: boolean;\n\t\t\tpublishMembers: boolean;\n\t }\n\t| {\n\t\t\t$type: typeof MANAGEDSPACE_POLICY;\n\t\t\tmanagingApp: string;\n\t\t\tpublishPolicy: boolean;\n\t };\n\nexport interface SpaceMember {\n\tdid: string;\n\tread: boolean;\n\twrite: boolean;\n}\n\nexport interface SpaceWriter {\n\tdid: string;\n\trepoRev: string;\n\tdata: Uint8Array;\n\tspaceRev: string;\n\t/** Removed from the writer set at `spaceRev`, until it writes again. */\n\tremoved: boolean;\n}\n\n/** A syncer's webhook registration (`authorizeSpaceSync`'s `notify`). */\nexport interface NotifyRegistration {\n\tendpoint: string;\n\ttoken: string;\n}\n\n/** The space sequence position assigned to an accepted repo update. */\nexport interface SpaceSequence {\n\tspaceRev: string;\n\tprevSpaceRev?: string;\n}\n\nexport interface RepoState {\n\tsetHash: Uint8Array;\n\trev: string;\n}\n\nexport interface SpaceRecordRow {\n\tcollection: string;\n\trkey: string;\n\tcid: string;\n\tbytes?: Uint8Array;\n}\n\nexport interface OplogEntry {\n\trev: string;\n\tidx: number;\n\tcollection: string;\n\trkey: string;\n\tcid: string | null;\n\tprev: string | null;\n\t/** Current record bytes for creates/updates that are not stale. */\n\tbytes?: Uint8Array;\n}\n\n/** A record imported from a repo archive, prepared by the Worker. */\nexport interface ImportedRecord {\n\tcollection: string;\n\trkey: string;\n\tcid: string;\n\tbytes: Uint8Array;\n\tblobCids: string[];\n}\n\nexport interface NotifyItem {\n\tservice: string;\n\tendpoint: string;\n\tlxm: string;\n\tbody: Record<string, unknown>;\n\t/**\n\t * Pending items sharing a key are coalesced: a newer one replaces the\n\t * older, resetting its backoff and deadline — unless `keepPending`, when\n\t * a pending item wins.\n\t */\n\tcoalesceKey?: string;\n\tkeepPending?: boolean;\n\t/** Give up retrying after this time (ms since epoch). */\n\tdeadline?: number;\n\t/**\n\t * Retry schedule: `fanout` (best effort, a few attempts), `repo` (a repo\n\t * host's notifyRepoUpdate, exponential up to the deadline) or `syncer`\n\t * (a syncer's deletion or expiry notice, 1 minute to 12 hours).\n\t */\n\tpolicy?: \"fanout\" | \"repo\" | \"syncer\";\n\t/** `service` signs a service JWT; `none` sends a token-bearing webhook. */\n\tauth?: \"service\" | \"none\";\n}\n\n/**\n * Host configuration for the space engine's Durable Objects. Supplied by\n * the host Worker's subclass — the engine never reads env vars itself, so\n * the same class can later serve a dedicated authority DID with no account\n * attached.\n */\nexport interface SpaceHostConfig {\n\t/** The DID whose permissioned repos this engine serves. */\n\toperatorDid: string;\n\t/** Signing keypair provider (service JWTs for notification delivery). */\n\tgetKeypair(): Promise<SpaceSigningKeypair>;\n}\n","/**\n * Space policies: the three baseline policies every PDS supports, as\n * `com.atproto.space.createSpace` / `updateSpace` take them. A policy is an\n * open union discriminated by `$type` that both selects the policy and\n * carries its configuration.\n *\n * What is stored is exactly what is enforced: {@link normalizePolicy}\n * refuses a policy this host doesn't implement and fills in every default.\n * Unknown fields are dropped, as Lexicon evolution allows.\n */\n\nimport { SpaceError } from \"./errors.js\";\nimport {\n\tMANAGEDSPACE_POLICY,\n\tMEMBERSPACE_POLICY,\n\tPERSONALSPACE_POLICY,\n\ttype SpacePolicy,\n} from \"./types.js\";\n\n/** The collection a published policy record lives in (rkey `self`). */\nexport const POLICY_COLLECTION = \"com.atproto.space.policy\";\nexport const POLICY_RKEY = \"self\";\n/** The collection published member records live in (rkey = member DID). */\nexport const MEMBER_COLLECTION = \"com.atproto.memberspace.member\";\n/** The collections the host publishes a space's configuration to. */\nexport const PUBLISHED_COLLECTIONS: readonly string[] = [\n\tPOLICY_COLLECTION,\n\tMEMBER_COLLECTION,\n];\n\nconst isBool = (value: unknown): value is boolean => typeof value === \"boolean\";\n\nfunction isUri(value: unknown): value is string {\n\tif (typeof value !== \"string\") return false;\n\ttry {\n\t\tnew URL(value);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction optionalBool(input: Record<string, unknown>, key: string): boolean {\n\tconst value = input[key];\n\tif (value === undefined) return false;\n\tif (!isBool(value)) {\n\t\tthrow new SpaceError(\"InvalidRequest\", `Policy ${key} must be a boolean`);\n\t}\n\treturn value;\n}\n\n/** Validate and normalise a policy from a request or an archive. */\nexport function normalizePolicy(input: unknown): SpacePolicy {\n\tif (!input || typeof input !== \"object\" || Array.isArray(input)) {\n\t\tthrow new SpaceError(\"InvalidRequest\", \"policy must be an object\");\n\t}\n\tconst policy = input as Record<string, unknown>;\n\tswitch (policy.$type) {\n\t\tcase PERSONALSPACE_POLICY:\n\t\t\treturn { $type: PERSONALSPACE_POLICY };\n\t\tcase MEMBERSPACE_POLICY: {\n\t\t\tconst allowedApps = policy.allowedApps;\n\t\t\tif (\n\t\t\t\tallowedApps !== undefined &&\n\t\t\t\t(!Array.isArray(allowedApps) || allowedApps.some((app) => !isUri(app)))\n\t\t\t) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"InvalidRequest\",\n\t\t\t\t\t\"allowedApps must be an array of OAuth client ID URIs\",\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\t$type: MEMBERSPACE_POLICY,\n\t\t\t\tpublicRead: optionalBool(policy, \"publicRead\"),\n\t\t\t\tpublicWrite: optionalBool(policy, \"publicWrite\"),\n\t\t\t\t...(allowedApps !== undefined\n\t\t\t\t\t? { allowedApps: [...(allowedApps as string[])] }\n\t\t\t\t\t: {}),\n\t\t\t\tpublishPolicy: optionalBool(policy, \"publishPolicy\"),\n\t\t\t\tpublishMembers: optionalBool(policy, \"publishMembers\"),\n\t\t\t};\n\t\t}\n\t\tcase MANAGEDSPACE_POLICY: {\n\t\t\tconst managingApp = policy.managingApp;\n\t\t\t// A did#serviceId reference: the app's service entry, which a bare\n\t\t\t// DID (an account's #atproto_pds) is not.\n\t\t\tconst [did, fragment, extra] =\n\t\t\t\ttypeof managingApp === \"string\" ? managingApp.split(\"#\") : [];\n\t\t\tif (!did?.startsWith(\"did:\") || !fragment || extra !== undefined) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"InvalidRequest\",\n\t\t\t\t\t`managingApp must be a did#serviceId reference, got: ${String(managingApp)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\t$type: MANAGEDSPACE_POLICY,\n\t\t\t\tmanagingApp: managingApp as string,\n\t\t\t\tpublishPolicy: optionalBool(policy, \"publishPolicy\"),\n\t\t\t};\n\t\t}\n\t\tdefault:\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"UnsupportedPolicy\",\n\t\t\t\t`Unsupported policy: ${String(policy.$type)}`,\n\t\t\t);\n\t}\n}\n\n/** The member list and its methods belong to the memberspace policy. */\nexport function assertMemberspace(\n\tpolicy: SpacePolicy,\n): asserts policy is Extract<\n\tSpacePolicy,\n\t{ $type: typeof MEMBERSPACE_POLICY }\n> {\n\tif (policy.$type !== MEMBERSPACE_POLICY) {\n\t\tthrow new SpaceError(\n\t\t\t\"PolicyMismatch\",\n\t\t\t\"Space is not governed by the memberspace policy\",\n\t\t);\n\t}\n}\n\n/**\n * Whether any user may read. Only then can a credential be minted without\n * a delegation token saying who the user is.\n */\nexport function isPublicRead(policy: SpacePolicy): boolean {\n\treturn policy.$type === MEMBERSPACE_POLICY && policy.publicRead;\n}\n\nexport function isPolicyPublished(policy: SpacePolicy): boolean {\n\treturn policy.$type !== PERSONALSPACE_POLICY && policy.publishPolicy;\n}\n\nexport function areMembersPublished(policy: SpacePolicy): boolean {\n\treturn policy.$type === MEMBERSPACE_POLICY && policy.publishMembers;\n}\n\n/**\n * Only memberspace restricts apps, against the attested client_id, so an\n * app that presents no attestation is never one of the allowed apps.\n */\nexport function isAppAuthorized(\n\tpolicy: SpacePolicy,\n\tclientId: string | undefined,\n): boolean {\n\tif (policy.$type !== MEMBERSPACE_POLICY || !policy.allowedApps) return true;\n\treturn clientId !== undefined && policy.allowedApps.includes(clientId);\n}\n\n/**\n * A DID as a record key, for published member records. A record key can't\n * contain `%`, so the percent-encoded port of a localhost did:web is left\n * unencoded, as the reference does. Unambiguous because the unencoded form\n * would otherwise be a did:web path, which atproto doesn't support.\n */\nexport function didToRecordKey(did: string): string {\n\treturn did.replace(\"%3A\", \":\");\n}\n\nexport function recordKeyToDid(rkey: string): string {\n\treturn rkey.replace(/^(did:web:[^:]+):(\\d+)$/, \"$1%3A$2\");\n}\n\n/** Records published from a space's configuration are the host's to write. */\nexport function assertNotPublishedCollection(collection: string): void {\n\tif (PUBLISHED_COLLECTIONS.includes(collection)) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidRequest\",\n\t\t\t`${collection} records are published by the PDS from a space's configuration and cannot be written directly`,\n\t\t);\n\t}\n}\n","/**\n * Record preparation and serialization for the Worker side of the write\n * and read paths. Records are stored as dag-cbor bytes with their CID,\n * computed here — the same encoding path the reference uses.\n */\n\nimport { encode, decode, cidForLex } from \"@atproto/lex-cbor\";\nimport { enumBlobRefs, getBlobCidString } from \"@atproto/lex-data\";\nimport type { LexValue } from \"@atproto/lex-data\";\nimport { jsonToLex, lexToJson } from \"@atproto/lex-json\";\nimport type { JsonValue } from \"@atproto/lex-json\";\n\nexport interface PreparedRecord {\n\tcid: string;\n\tbytes: Uint8Array;\n\tblobCids: string[];\n\t/** The lex-normalised record, for echoing back in responses. */\n\tjson: unknown;\n}\n\n/**\n * Convert a client-supplied JSON record into its stored form: lex value →\n * dag-cbor bytes → CID, with blob references enumerated for the space's\n * blob tracking.\n */\nexport async function prepareRecord(record: unknown): Promise<PreparedRecord> {\n\tconst lex = jsonToLex(record as JsonValue) as LexValue;\n\tconst bytes = encode(lex);\n\tconst cid = await cidForLex(lex);\n\tconst blobCids: string[] = [];\n\tfor (const ref of enumBlobRefs(lex)) {\n\t\tblobCids.push(getBlobCidString(ref));\n\t}\n\treturn { cid: cid.toString(), bytes, blobCids, json: lexToJson(lex) };\n}\n\n/** Decode stored record bytes back into response JSON. */\nexport function recordBytesToJson(bytes: Uint8Array): unknown {\n\treturn lexToJson(decode(bytes));\n}\n","/**\n * SQLite schema for SpaceDurableObject.\n *\n * Mirrors the reference PDS's `002-space` migration table for table, minus\n * the `space` column on every row — one DO per space makes it redundant.\n *\n * There is no migration path between alpha schema versions: bumping\n * {@link SPACE_SCHEMA_VERSION} puts existing DOs into a refusing state until\n * `pds spaces reset` wipes them. That is the alpha policy, applied honestly.\n */\n\n/**\n * Bump on any breaking change to the tables below.\n *\n * 2: baseline policies replace simplespace config; members carry\n * read/write access; writers carry space revisions; revoked\n * credentials; coalescing notification queue.\n * 3: webhook registrations (endpoint + token) replace registerNotify;\n * writers keep a removal marker; queue rows carry their retry policy\n * and authentication.\n * 4: space URIs move to `at:space/{did}/{type}/{skey}`. Space DOs are\n * named by URI, so spaces stored under the old form are unreachable.\n */\nexport const SPACE_SCHEMA_VERSION = 4;\n\nexport const SPACE_DO_SCHEMA = `\n\t-- One row. schema_version is checked on every open.\n\tCREATE TABLE IF NOT EXISTS meta (\n\t\turi TEXT NOT NULL,\n\t\tauthority TEXT NOT NULL,\n\t\ttype TEXT NOT NULL,\n\t\tskey TEXT NOT NULL,\n\t\tis_authority INTEGER NOT NULL,\n\t\tcreated_at TEXT NOT NULL,\n\t\tdeleted_at TEXT,\n\t\tschema_version INTEGER NOT NULL\n\t);\n\n\t-- Operator's permissioned repo in this space.\n\tCREATE TABLE IF NOT EXISTS record (\n\t\tcollection TEXT NOT NULL,\n\t\trkey TEXT NOT NULL,\n\t\tcid TEXT NOT NULL,\n\t\tbytes BLOB NOT NULL,\n\t\trev TEXT NOT NULL,\n\t\tindexed_at TEXT NOT NULL,\n\t\tPRIMARY KEY (collection, rkey)\n\t);\n\tCREATE INDEX IF NOT EXISTS idx_record_rev ON record(rev);\n\n\tCREATE TABLE IF NOT EXISTS record_blob (\n\t\tblob_cid TEXT NOT NULL,\n\t\tcollection TEXT NOT NULL,\n\t\trkey TEXT NOT NULL,\n\t\tPRIMARY KEY (blob_cid, collection, rkey)\n\t);\n\tCREATE INDEX IF NOT EXISTS idx_record_blob_record ON record_blob(collection, rkey);\n\n\tCREATE TABLE IF NOT EXISTS repo_state (\n\t\tid INTEGER PRIMARY KEY CHECK (id = 1),\n\t\tset_hash BLOB NOT NULL,\n\t\trev TEXT NOT NULL\n\t);\n\n\tCREATE TABLE IF NOT EXISTS oplog (\n\t\trev TEXT NOT NULL,\n\t\tidx INTEGER NOT NULL,\n\t\tcollection TEXT NOT NULL,\n\t\trkey TEXT NOT NULL,\n\t\tcid TEXT,\n\t\tprev TEXT,\n\t\tPRIMARY KEY (rev, idx)\n\t);\n\n\t-- Authority role only. The policy is stored as its normalised lexicon\n\t-- object (com.atproto.{personal,member,managed}space.policy).\n\tCREATE TABLE IF NOT EXISTS config (\n\t\tid INTEGER PRIMARY KEY CHECK (id = 1),\n\t\tpolicy TEXT NOT NULL\n\t);\n\n\t-- memberspace member list.\n\tCREATE TABLE IF NOT EXISTS member (\n\t\tdid TEXT PRIMARY KEY,\n\t\tcan_read INTEGER NOT NULL,\n\t\tcan_write INTEGER NOT NULL\n\t);\n\n\t-- The writer set, sequenced by space revision. A removed writer keeps\n\t-- its row, marked removed at the revision of its removal, so listWriters\n\t-- can report the removal until it writes again.\n\tCREATE TABLE IF NOT EXISTS writer (\n\t\tdid TEXT PRIMARY KEY,\n\t\trepo_rev TEXT NOT NULL,\n\t\tdata BLOB NOT NULL,\n\t\tspace_rev TEXT NOT NULL,\n\t\tremoved_at INTEGER\n\t);\n\tCREATE INDEX IF NOT EXISTS idx_writer_space_rev ON writer(space_rev);\n\n\t-- Syncer webhook registrations, made through authorizeSpaceSync. Active\n\t-- until the credential of their latest authorization expires\n\t-- (expires_at, ms); expiry_notified marks a lapse already announced.\n\tCREATE TABLE IF NOT EXISTS notify_registration (\n\t\tendpoint TEXT NOT NULL,\n\t\ttoken TEXT NOT NULL,\n\t\texpires_at INTEGER NOT NULL,\n\t\texpiry_notified INTEGER NOT NULL DEFAULT 0,\n\t\tPRIMARY KEY (endpoint, token)\n\t);\n\n\t-- Outbound notifications, both roles. A row with a coalesce_key is\n\t-- replaced by a newer one with the same key; deadline (ms) is when\n\t-- retrying stops. policy picks the retry schedule ('fanout' | 'repo' |\n\t-- 'syncer'); auth is 'service' (a service JWT from the operator) or\n\t-- 'none' (a syncer webhook, authenticated by the token in its body).\n\tCREATE TABLE IF NOT EXISTS notify_queue (\n\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\tservice TEXT NOT NULL,\n\t\tbody TEXT NOT NULL,\n\t\tattempts INTEGER NOT NULL DEFAULT 0,\n\t\tnext_at INTEGER NOT NULL,\n\t\tdeadline INTEGER,\n\t\tcoalesce_key TEXT UNIQUE,\n\t\tpolicy TEXT NOT NULL DEFAULT 'fanout',\n\t\tauth TEXT NOT NULL DEFAULT 'service'\n\t);\n\tCREATE INDEX IF NOT EXISTS idx_notify_queue_next ON notify_queue(next_at);\n\n\t-- Credentials for this space revoked by its authority (repo-host role).\n\tCREATE TABLE IF NOT EXISTS revoked_credential (\n\t\tjti TEXT PRIMARY KEY,\n\t\texpires_at INTEGER NOT NULL\n\t);\n\n\t-- Replay protection, both roles.\n\tCREATE TABLE IF NOT EXISTS replay (\n\t\tkind TEXT NOT NULL,\n\t\tkey TEXT NOT NULL,\n\t\texpires_at INTEGER NOT NULL,\n\t\tPRIMARY KEY (kind, key)\n\t);\n`;\n\n/** Retain oplog entries for at most this many days. */\nexport const OPLOG_RETENTION_DAYS = 30;\n/** Retain at most this many oplog entries. */\nexport const OPLOG_RETENTION_OPS = 10_000;\n/**\n * Give up delivering a notification without its own deadline after this\n * many attempts: syncer fan-out is reasonable-effort, and a syncer that\n * misses one recovers through listRepos.\n */\nexport const NOTIFY_MAX_ATTEMPTS = 5;\n/** A repo host retries its write notification to the authority this long. */\nexport const NOTIFY_WRITE_RETRY_MS = 24 * 60 * 60 * 1000;\n/**\n * A syncer's deletion or expiry notice is retried after each of these\n * delays in turn, repeating the last, for at least\n * {@link SYNCER_NOTICE_RETRY_WINDOW_MS}.\n */\nexport const SYNCER_NOTICE_RETRY_DELAYS_MS = [\n\t60_000,\n\t10 * 60_000,\n\t60 * 60_000,\n\t6 * 60 * 60_000,\n\t12 * 60 * 60_000,\n];\nexport const SYNCER_NOTICE_RETRY_WINDOW_MS = 72 * 60 * 60 * 1000;\n/** The largest notify token a syncer may register. */\nexport const MAX_NOTIFY_TOKEN_LENGTH = 512;\n/** Cap on the backoff between notification retries. */\nexport const NOTIFY_BACKOFF_MAX_MS = 60 * 60 * 1000;\n/** notifyWrite refuses repo revisions this far ahead of the clock. */\nexport const MAX_REV_CLOCK_SKEW_MS = 5 * 60 * 1000;\n/** The largest record a space repo accepts, as its DRISL encoding. */\nexport const MAX_SPACE_RECORD_BYTES = 1024 * 1024;\n/** Base delay for notification retry backoff, in milliseconds. */\nexport const NOTIFY_BACKOFF_BASE_MS = 30_000;\n\nexport const INDEX_DO_SCHEMA = `\n\tCREATE TABLE IF NOT EXISTS space (\n\t\turi TEXT PRIMARY KEY,\n\t\tauthority TEXT NOT NULL,\n\t\ttype TEXT NOT NULL,\n\t\tskey TEXT NOT NULL,\n\t\tis_authority INTEGER NOT NULL,\n\t\tstate TEXT NOT NULL, -- 'pending' | 'active' | 'deleted'\n\t\tcreated_at TEXT NOT NULL,\n\t\tupdated_at TEXT NOT NULL,\n\t\tschema_version INTEGER NOT NULL\n\t);\n\tCREATE INDEX IF NOT EXISTS idx_space_state ON space(state);\n\n\t-- Blobs referenced by an imported space repo that had not been uploaded\n\t-- yet. uploadBlob claims them and promotes the staged copy into each\n\t-- space's blob prefix.\n\tCREATE TABLE IF NOT EXISTS pending_blob (\n\t\tcid TEXT NOT NULL,\n\t\turi TEXT NOT NULL,\n\t\tcreated_at INTEGER NOT NULL,\n\t\tPRIMARY KEY (cid, uri)\n\t);\n`;\n\n/** Forget pending imported-space blobs that were never uploaded. */\nexport const PENDING_BLOB_TTL_MS = 30 * 24 * 60 * 60 * 1000;\n\n/** Remove `pending` index entries that never activated after this long. */\nexport const PENDING_ENTRY_TTL_MS = 24 * 60 * 60 * 1000;\n","/**\n * Commits and MACs.\n *\n * A space repo commit carries no signature. A syncer authenticates what a\n * repo host serves with a MAC instead: an HTTP message signature (RFC 9421)\n * using `hmac-sha256`, keyed by a per-request secret both sides derive with\n * HPKE secret export against the account's `#atproto_kem` key. The syncer\n * asks with `Accept-Signature`, naming its ephemeral key and a profile tag;\n * the host answers with a header describing the commit or record\n * (`Atproto-Space-Commit` / `Atproto-Space-Record`) and a MAC covering it.\n * A leaked response proves nothing to a third party. The KEM key is the only\n * secret here, and it lives with the Worker.\n */\n\nimport {\n\tCOMMIT_MAC_PROFILE,\n\tMAC_COVERED_HEADER,\n\tRECORD_MAC_PROFILE,\n\tRepoCommit,\n\tSpaceKemError,\n\tSpaceMacError,\n\tcreateCommitMacHeaders,\n\tcreateRecordMacHeaders,\n\tdecapsulate,\n\tparseMacRequest,\n} from \"@atproto/space\";\nimport type { CreateMacParams, MacProfile } from \"@atproto/space\";\nimport { P256Keypair } from \"@atproto/crypto\";\nimport { parseCid, toBase64 } from \"@atproto/lex-data\";\nimport { SpaceError } from \"./errors.js\";\nimport type { RepoState } from \"./types.js\";\n\nexport { COMMIT_MAC_PROFILE, RECORD_MAC_PROFILE };\nexport type { MacProfile };\n\n/** The MAC profiles, as plain strings for the public API. */\nexport type SpaceMacProfile = \"atproto-space-commit\" | \"atproto-space-record\";\n\n/** The request header a syncer asks for a MAC with. */\nexport const MAC_REQUEST_HEADER = \"accept-signature\";\n\n/** The response headers a browser syncer must read to check a MAC. */\nexport function macExposedHeaders(profile: SpaceMacProfile): string[] {\n\treturn [\n\t\tMAC_COVERED_HEADER[profile as MacProfile],\n\t\t\"signature-input\",\n\t\t\"signature\",\n\t];\n}\n\n/** A space repo commit (`com.atproto.space.defs#commit`). */\nexport interface SpaceCommit {\n\tver: number;\n\trepo: string;\n\tspace: string;\n\trev: string;\n\t/** sha256 digest of the LtHash state. */\n\tdata: Uint8Array;\n}\n\n/** The commit over a repo's persisted state. */\nexport function buildCommit(params: {\n\tspaceUri: string;\n\t/** The repo author (the operator DID for every repo Cirrus serves). */\n\trepo: string;\n\tstate: RepoState;\n}): SpaceCommit {\n\treturn RepoCommit.fromState(params.state.setHash).toCommit({\n\t\tspace: params.spaceUri as never,\n\t\trepo: params.repo as never,\n\t\trev: params.state.rev as never,\n\t});\n}\n\n/**\n * Lexicon JSON form of a commit (`com.atproto.space.defs#commit`): bytes\n * fields encode as `{\"$bytes\": \"<base64>\"}`.\n */\nexport function commitToJson(commit: SpaceCommit): Record<string, unknown> {\n\treturn {\n\t\tver: commit.ver,\n\t\trepo: commit.repo,\n\t\tspace: commit.space,\n\t\trev: commit.rev,\n\t\tdata: bytesToJson(commit.data),\n\t};\n}\n\n/** Lexicon JSON form of a bare bytes value. */\nexport function bytesToJson(bytes: Uint8Array): { $bytes: string } {\n\treturn { $bytes: toBase64(bytes) };\n}\n\n/** Import the account's `#atproto_kem` keypair from its hex private key. */\nexport async function importKemKeypair(\n\tprivateKeyHex: string,\n): Promise<P256Keypair> {\n\treturn P256Keypair.import(privateKeyHex);\n}\n\n/** Generate a fresh `#atproto_kem` keypair. */\nexport async function generateKemKey(): Promise<{\n\tprivateKeyHex: string;\n\t/** The public key as a did:key. */\n\tdidKey: string;\n\t/** The public key multibase, for a DID document verification method. */\n\tpublicKeyMultibase: string;\n}> {\n\tconst keypair = await P256Keypair.create({ exportable: true });\n\tconst exported = await keypair.export();\n\tconst didKey = keypair.did();\n\treturn {\n\t\tprivateKeyHex: Array.from(exported, (b) =>\n\t\t\tb.toString(16).padStart(2, \"0\"),\n\t\t).join(\"\"),\n\t\tdidKey,\n\t\tpublicKeyMultibase: didKey.slice(\"did:key:\".length),\n\t};\n}\n\n/** The public half of a KEM private key, as a did:key. */\nexport async function kemDidKey(privateKeyHex: string): Promise<string> {\n\treturn (await importKemKeypair(privateKeyHex)).did();\n}\n\nexport interface MacRequestInput {\n\t/** The `Accept-Signature` request header, if any. */\n\tacceptSignature: string | undefined;\n\t/** Whether the request was authorised by a space credential. */\n\tcredential: boolean;\n\tprofile: MacProfile;\n\tgetKemKeypair: () => Promise<P256Keypair | null>;\n}\n\n/** What a MAC is computed with, once requested and decapsulated. */\nexport type MacParams = CreateMacParams;\n\n/**\n * The MAC owed by a read that returns a commit or record. A space\n * credential must ask for one with the profile's tag; an account reading its\n * own data gets one only if it asks. Requests with other tags are ignored.\n * Returns undefined when no MAC is owed.\n */\nexport async function macRequest(\n\treq: MacRequestInput,\n): Promise<MacParams | undefined> {\n\tlet request;\n\ttry {\n\t\trequest = parseMacRequest(req.acceptSignature, req.profile);\n\t} catch (err) {\n\t\tthrow invalidMac(err);\n\t}\n\tif (!request) {\n\t\tif (!req.credential) return undefined;\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidSpaceMac\",\n\t\t\t`A MAC must be requested with tag \"${req.profile}\"`,\n\t\t);\n\t}\n\tconst keypair = await req.getKemKeypair();\n\tif (!keypair) {\n\t\tthrow new SpaceError(\n\t\t\t\"KemKeyUnavailable\",\n\t\t\t\"This host has no #atproto_kem key configured, so it cannot authenticate space data to syncers\",\n\t\t);\n\t}\n\ttry {\n\t\treturn { ...request, sharedSecret: decapsulate(keypair, request.keyShare) };\n\t} catch (err) {\n\t\tthrow invalidMac(err);\n\t}\n}\n\nfunction invalidMac(err: unknown): SpaceError {\n\tif (err instanceof SpaceMacError || err instanceof SpaceKemError) {\n\t\treturn new SpaceError(\"InvalidSpaceMac\", err.message);\n\t}\n\treturn new SpaceError(\"InvalidSpaceMac\", \"Invalid Accept-Signature header\");\n}\n\n/** The MAC response headers for a commit, when one is owed. */\nexport function commitMacHeaders(\n\tmac: MacParams | undefined,\n\tcommit: SpaceCommit,\n): Record<string, string> {\n\tif (!mac) return {};\n\treturn createCommitMacHeaders(\n\t\tcommit as Parameters<typeof createCommitMacHeaders>[0],\n\t\tmac,\n\t).headers;\n}\n\n/** The MAC response headers for a record, when one is owed. */\nexport function recordMacHeaders(\n\tmac: MacParams | undefined,\n\turi: string,\n\tcid: string,\n): Record<string, string> {\n\tif (!mac) return {};\n\treturn createRecordMacHeaders(uri as never, parseCid(cid), mac).headers;\n}\n","/**\n * Revision (TID) helpers for the space repo.\n */\n\nimport { now as tidNow } from \"@atcute/tid\";\n\nconst S32_CHAR = \"234567abcdefghijklmnopqrstuvwxyz\";\n\n/**\n * Next revision: a fresh TID guaranteed strictly greater than `prev`.\n * `@atcute/tid`'s clock is monotonic within an isolate, but the previous\n * rev may come from a different isolate's clock (e.g. after a DO restart),\n * so bump lexicographically when needed.\n */\nexport function nextRev(prev: string | null | undefined): string {\n\tconst candidate = tidNow();\n\tif (!prev || candidate > prev) return candidate;\n\t// Increment the previous TID by one in s32 space.\n\tconst chars = prev.split(\"\");\n\tfor (let i = chars.length - 1; i >= 0; i--) {\n\t\tconst idx = S32_CHAR.indexOf(chars[i]!);\n\t\tif (idx < S32_CHAR.length - 1) {\n\t\t\tchars[i] = S32_CHAR[idx + 1]!;\n\t\t\treturn chars.join(\"\");\n\t\t}\n\t\tchars[i] = S32_CHAR[0]!;\n\t}\n\t// prev was the maximal TID; not reachable with real clocks.\n\treturn candidate;\n}\n\n/**\n * The smallest TID whose timestamp is `ms` milliseconds in the past, with a\n * zero clockid. Used as a deletion cutoff for oplog compaction.\n */\nexport function tidCutoff(msAgo: number): string {\n\tconst micros = BigInt(Math.max(0, Date.now() - msAgo)) * 1000n;\n\t// TID layout: 53 bits of microseconds followed by 10 bits of clockid,\n\t// encoded as 13 sortable-base32 characters.\n\tlet value = (micros << 10n) & ((1n << 63n) - 1n);\n\tlet out = \"\";\n\tfor (let i = 12; i >= 0; i--) {\n\t\tout = S32_CHAR[Number(value & 31n)] + out;\n\t\tvalue >>= 5n;\n\t}\n\treturn out;\n}\n\n/** The timestamp a TID encodes, in milliseconds since the epoch. */\nexport function tidTimestampMs(tid: string): number {\n\tlet value = 0n;\n\tfor (const char of tid) {\n\t\tconst idx = S32_CHAR.indexOf(char);\n\t\tif (idx === -1) throw new Error(`Invalid TID: ${tid}`);\n\t\tvalue = (value << 5n) | BigInt(idx);\n\t}\n\treturn Number(value >> 10n) / 1000;\n}\n","/**\n * Minimal atproto service-auth JWT creation, used for outbound\n * `com.atproto.space.notifyWrite` / `notifySpaceDeleted` calls. Matches the\n * shape `verifyServiceJwt` implementations expect: `{iss, aud, lxm?, jti,\n * iat, exp}` signed with the account signing key (alg from the keypair).\n */\n\nimport type { SpaceSigningKeypair } from \"./types.js\";\n\nconst encoder = new TextEncoder();\n\nfunction base64url(bytes: Uint8Array): string {\n\tlet bin = \"\";\n\tfor (const b of bytes) bin += String.fromCharCode(b);\n\treturn btoa(bin).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nexport interface ServiceJwtParams {\n\tiss: string;\n\taud: string;\n\tlxm?: string;\n\t/** Lifetime in seconds (default 60). */\n\texpiresInSec?: number;\n}\n\nexport async function createServiceJwt(\n\tparams: ServiceJwtParams,\n\tkeypair: SpaceSigningKeypair,\n): Promise<string> {\n\tconst iat = Math.floor(Date.now() / 1000);\n\tconst header = { typ: \"JWT\", alg: keypair.jwtAlg };\n\tconst payload: Record<string, unknown> = {\n\t\tiat,\n\t\tiss: params.iss,\n\t\taud: params.aud,\n\t\texp: iat + (params.expiresInSec ?? 60),\n\t\tjti: crypto.randomUUID(),\n\t};\n\tif (params.lxm) payload.lxm = params.lxm;\n\n\tconst signingInput = `${base64url(encoder.encode(JSON.stringify(header)))}.${base64url(\n\t\tencoder.encode(JSON.stringify(payload)),\n\t)}`;\n\tconst sig = await keypair.sign(encoder.encode(signingInput));\n\treturn `${signingInput}.${base64url(sig)}`;\n}\n","/**\n * SpaceDurableObject – one instance per space, addressed by\n * `idFromName(spaceUri)`.\n *\n * Holds everything Cirrus knows about that space: the operator's\n * permissioned repo (records, oplog, LtHash state, blob references) and,\n * when the operator is the authority, the space's policy, member list,\n * writer set (sequenced by space revision) and notification registrations.\n * Both roles share the outbound notification queue, and the replay and\n * revocation tables for tokens presented against the space.\n *\n * Constraints inherited from the Cirrus architecture:\n * - No R2 I/O in here, ever. Blobs are the Worker's job.\n * - No key material in here except through\n * {@link SpaceHostConfig.getKeypair}, used only for outbound notification\n * service JWTs from the alarm. Commits are unsigned and MACs are the\n * Worker's, so the KEM key never enters this class.\n * - The host supplies its identity via {@link getHostConfig}; this class\n * must not read `env.DID`. If it ever contains a branch on which host is\n * running it, the boundary has failed.\n */\n\nimport { DurableObject } from \"cloudflare:workers\";\nimport { RepoCommit } from \"@atproto/space\";\nimport { SpaceError } from \"./errors.js\";\nimport {\n\tMEMBER_COLLECTION,\n\tPOLICY_COLLECTION,\n\tPOLICY_RKEY,\n\tPUBLISHED_COLLECTIONS,\n\tareMembersPublished,\n\tassertMemberspace,\n\tdidToRecordKey,\n\tisPolicyPublished,\n} from \"./policy.js\";\nimport { prepareRecord } from \"./records.js\";\nimport {\n\tNOTIFY_BACKOFF_BASE_MS,\n\tNOTIFY_BACKOFF_MAX_MS,\n\tNOTIFY_MAX_ATTEMPTS,\n\tOPLOG_RETENTION_DAYS,\n\tOPLOG_RETENTION_OPS,\n\tSPACE_DO_SCHEMA,\n\tSPACE_SCHEMA_VERSION,\n\tSYNCER_NOTICE_RETRY_DELAYS_MS,\n\tSYNCER_NOTICE_RETRY_WINDOW_MS,\n} from \"./schema.js\";\nimport { bytesToJson } from \"./mac.js\";\nimport { nextRev, tidCutoff } from \"./tid.js\";\nimport { createServiceJwt } from \"./service-jwt.js\";\nimport type {\n\tApplyWritesResult,\n\tImportedRecord,\n\tNotifyItem,\n\tNotifyRegistration,\n\tOplogEntry,\n\tPreparedSpaceWrite,\n\tRepoCommitResult,\n\tRepoState,\n\tSpaceHostConfig,\n\tSpaceMember,\n\tSpaceMeta,\n\tSpacePolicy,\n\tSpaceRecordRow,\n\tSpaceSequence,\n\tSpaceWriter,\n} from \"./types.js\";\n\nconst DAY_MS = 24 * 60 * 60 * 1000;\n/** Interval between maintenance passes (compaction, replay cleanup). */\nconst MAINTENANCE_INTERVAL_MS = DAY_MS;\n/** How many queued notifications to attempt per alarm invocation. */\nconst NOTIFY_BATCH = 20;\n\ninterface QueueRow {\n\tid: number;\n\tservice: string;\n\tbody: string;\n\tattempts: number;\n\tnext_at: number;\n\tdeadline: number | null;\n\tpolicy: \"fanout\" | \"repo\" | \"syncer\";\n\tauth: \"service\" | \"none\";\n}\n\nconst NOTIFY_SPACE_UPDATE_LXM = \"com.atproto.space.notifySpaceUpdate\";\nconst REPO_WRITE = \"com.atproto.space.defs#repoWrite\";\nconst REPO_REMOVED = \"com.atproto.space.defs#repoRemoved\";\nconst SPACE_DELETED = \"com.atproto.space.notifySpaceUpdate#spaceDeleted\";\nconst REGISTRATION_EXPIRED =\n\t\"com.atproto.space.notifySpaceUpdate#registrationExpired\";\n\n/** 50-100% of a delay, so retries from many spaces don't align. */\nfunction jitter(delay: number): number {\n\treturn Math.floor(delay * (0.5 + Math.random() / 2));\n}\n\n/** HTTP statuses worth retrying; anything else is a permanent refusal. */\nexport function isRetryableStatus(status: number): boolean {\n\treturn status === 408 || status === 425 || status === 429 || status >= 500;\n}\n\nexport abstract class SpaceDurableObject<\n\tEnv = unknown,\n> extends DurableObject<Env> {\n\tprivate sql: SqlStorage;\n\tprivate initialized = false;\n\tprivate outdated = false;\n\n\tconstructor(ctx: DurableObjectState, env: Env) {\n\t\tsuper(ctx, env);\n\t\tthis.sql = ctx.storage.sql;\n\t}\n\n\t/**\n\t * Host identity and signing configuration. Implemented by the host\n\t * Worker's subclass; see {@link SpaceHostConfig}.\n\t */\n\tprotected abstract getHostConfig():\n\t\t| SpaceHostConfig\n\t\t| Promise<SpaceHostConfig>;\n\n\t// ------------------------------------------------------------------\n\t// Initialisation and schema versioning\n\t// ------------------------------------------------------------------\n\n\tprivate async ensureInitialized(): Promise<void> {\n\t\tif (this.initialized) return;\n\t\tawait this.ctx.blockConcurrencyWhile(async () => {\n\t\t\tif (this.initialized) return;\n\t\t\tconst hasMeta =\n\t\t\t\tthis.sql\n\t\t\t\t\t.exec(\n\t\t\t\t\t\t\"SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'meta'\",\n\t\t\t\t\t)\n\t\t\t\t\t.toArray().length > 0;\n\t\t\tif (hasMeta) {\n\t\t\t\tconst row = this.sql\n\t\t\t\t\t.exec(\"SELECT schema_version FROM meta LIMIT 1\")\n\t\t\t\t\t.toArray()[0];\n\t\t\t\tif (row && (row.schema_version as number) !== SPACE_SCHEMA_VERSION) {\n\t\t\t\t\t// Alpha policy: no migrations between schema versions. The DO\n\t\t\t\t\t// refuses every RPC until `pds spaces reset` wipes it.\n\t\t\t\t\tthis.outdated = true;\n\t\t\t\t\tthis.initialized = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.sql.exec(SPACE_DO_SCHEMA);\n\t\t\tthis.initialized = true;\n\t\t});\n\t}\n\n\t/**\n\t * Gate every RPC: initialise storage and refuse when the stored schema\n\t * belongs to a different alpha build.\n\t */\n\tprivate async ensureOpen(): Promise<void> {\n\t\tawait this.ensureInitialized();\n\t\tif (this.outdated) {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"SpacesSchemaOutdated\",\n\t\t\t\t\"Space data was written by an incompatible alpha build. Run `pds spaces reset` to wipe space data (the public repo is unaffected).\",\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate readMeta(): SpaceMeta | null {\n\t\tconst row = this.sql.exec(\"SELECT * FROM meta LIMIT 1\").toArray()[0];\n\t\tif (!row) return null;\n\t\treturn {\n\t\t\turi: row.uri as string,\n\t\t\tauthority: row.authority as string,\n\t\t\ttype: row.type as string,\n\t\t\tskey: row.skey as string,\n\t\t\tisAuthority: (row.is_authority as number) === 1,\n\t\t\tcreatedAt: row.created_at as string,\n\t\t\tdeletedAt: (row.deleted_at as string | null) ?? null,\n\t\t};\n\t}\n\n\t/** Meta for an existing, non-deleted space, or throw. */\n\tprivate requireLiveMeta(): SpaceMeta {\n\t\tconst meta = this.readMeta();\n\t\tif (!meta) {\n\t\t\tthrow new SpaceError(\"SpaceNotFound\", \"Space is not initialised\");\n\t\t}\n\t\tif (meta.deletedAt) {\n\t\t\tthrow new SpaceError(\"SpaceNotFound\", \"Space has been deleted\");\n\t\t}\n\t\treturn meta;\n\t}\n\n\t/** The policy of a live space this host governs, or SpaceNotFound. */\n\tprivate requirePolicy(): { meta: SpaceMeta; policy: SpacePolicy } {\n\t\tconst meta = this.requireLiveMeta();\n\t\tconst policy = this.readPolicy();\n\t\tif (!policy) {\n\t\t\tthrow new SpaceError(\"SpaceNotFound\", \"Space not found\");\n\t\t}\n\t\treturn { meta, policy };\n\t}\n\n\tasync rpcGetMeta(): Promise<SpaceMeta | null> {\n\t\tawait this.ensureOpen();\n\t\treturn this.readMeta();\n\t}\n\n\t/**\n\t * Initialise this DO as the operator's repo in a space (either role).\n\t * For the authority role a policy creates the space: refused when a live\n\t * space already has one. A deleted space may be created again; its\n\t * tables were wiped at deletion, so reviving is a fresh start. Returns\n\t * the commit when publishing the policy wrote to the repo.\n\t */\n\tasync rpcInit(params: {\n\t\turi: string;\n\t\tauthority: string;\n\t\ttype: string;\n\t\tskey: string;\n\t\tisAuthority: boolean;\n\t\tpolicy?: SpacePolicy;\n\t}): Promise<RepoCommitResult | null> {\n\t\tawait this.ensureOpen();\n\t\tconst existing = this.readMeta();\n\t\tif (existing && existing.uri !== params.uri) {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"InvalidRequest\",\n\t\t\t\t`Space DO already holds ${existing.uri}`,\n\t\t\t);\n\t\t}\n\t\tif (existing && !existing.deletedAt && params.policy && this.readPolicy()) {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"SpaceAlreadyExists\",\n\t\t\t\t`Space already exists: ${params.uri}`,\n\t\t\t);\n\t\t}\n\t\tconst publishWrites = params.policy\n\t\t\t? await this.preparePolicyRecordWrites(params.policy)\n\t\t\t: [];\n\t\treturn this.ctx.storage.transactionSync(() => {\n\t\t\tif (!existing) {\n\t\t\t\tthis.sql.exec(\n\t\t\t\t\t`INSERT INTO meta (uri, authority, type, skey, is_authority, created_at, deleted_at, schema_version)\n\t\t\t\t\t VALUES (?, ?, ?, ?, ?, ?, NULL, ?)`,\n\t\t\t\t\tparams.uri,\n\t\t\t\t\tparams.authority,\n\t\t\t\t\tparams.type,\n\t\t\t\t\tparams.skey,\n\t\t\t\t\tparams.isAuthority ? 1 : 0,\n\t\t\t\t\tnew Date().toISOString(),\n\t\t\t\t\tSPACE_SCHEMA_VERSION,\n\t\t\t\t);\n\t\t\t} else if (existing.deletedAt) {\n\t\t\t\tthis.sql.exec(\n\t\t\t\t\t\"UPDATE meta SET deleted_at = NULL, created_at = ?, is_authority = ?\",\n\t\t\t\t\tnew Date().toISOString(),\n\t\t\t\t\tparams.isAuthority ? 1 : 0,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!params.policy) return null;\n\t\t\tthis.writePolicy(params.policy);\n\t\t\treturn this.applyWritesSync(publishWrites);\n\t\t});\n\t}\n\n\t// ------------------------------------------------------------------\n\t// Permissioned repo: writes\n\t// ------------------------------------------------------------------\n\n\tasync rpcApplyWrites(\n\t\twrites: PreparedSpaceWrite[],\n\t): Promise<ApplyWritesResult> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\treturn this.ctx.storage.transactionSync(\n\t\t\t() => this.applyWritesSync(writes)!,\n\t\t);\n\t}\n\n\t/**\n\t * Apply a batch as one commit sharing a single rev. Must run in a\n\t * transaction. Returns null for an empty batch. Each write lands before\n\t * the next is read, so a batch can create and then update a record, and\n\t * a repeated create is refused rather than counted twice.\n\t */\n\tprivate applyWritesSync(\n\t\twrites: PreparedSpaceWrite[],\n\t): ApplyWritesResult | null {\n\t\tif (writes.length === 0) return null;\n\t\tconst state = this.readRepoState();\n\t\tconst commit = RepoCommit.fromState(state?.setHash ?? null);\n\t\tconst rev = nextRev(state?.rev ?? null);\n\t\tconst indexedAt = new Date().toISOString();\n\t\tconst results: ApplyWritesResult[\"results\"] = [];\n\t\tlet idx = 0;\n\n\t\tfor (const write of writes) {\n\t\t\tconst prevRow = this.sql\n\t\t\t\t.exec(\n\t\t\t\t\t\"SELECT cid FROM record WHERE collection = ? AND rkey = ?\",\n\t\t\t\t\twrite.collection,\n\t\t\t\t\twrite.rkey,\n\t\t\t\t)\n\t\t\t\t.toArray()[0];\n\t\t\tconst prev = prevRow ? (prevRow.cid as string) : null;\n\n\t\t\tif (write.action === \"create\" && prev) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"RecordAlreadyExists\",\n\t\t\t\t\t`Record already exists: ${write.collection}/${write.rkey}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (write.action !== \"create\" && !prev) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"RecordNotFound\",\n\t\t\t\t\t`Record not found: ${write.collection}/${write.rkey}`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (write.action === \"delete\") {\n\t\t\t\tthis.deleteRecordRow(write.collection, write.rkey);\n\t\t\t\tcommit.setHash.remove(`${write.collection}/${write.rkey}/${prev}`);\n\t\t\t\tthis.appendOplog(rev, idx++, write.collection, write.rkey, null, prev);\n\t\t\t\tresults.push({\n\t\t\t\t\taction: \"delete\",\n\t\t\t\t\tcollection: write.collection,\n\t\t\t\t\trkey: write.rkey,\n\t\t\t\t\tcid: null,\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tthis.sql.exec(\n\t\t\t\t`INSERT OR REPLACE INTO record (collection, rkey, cid, bytes, rev, indexed_at)\n\t\t\t\t VALUES (?, ?, ?, ?, ?, ?)`,\n\t\t\t\twrite.collection,\n\t\t\t\twrite.rkey,\n\t\t\t\twrite.cid,\n\t\t\t\twrite.bytes,\n\t\t\t\trev,\n\t\t\t\tindexedAt,\n\t\t\t);\n\t\t\tthis.replaceRecordBlobs(write.collection, write.rkey, write.blobCids);\n\t\t\tif (prev) {\n\t\t\t\tcommit.setHash.remove(`${write.collection}/${write.rkey}/${prev}`);\n\t\t\t}\n\t\t\tcommit.setHash.add(`${write.collection}/${write.rkey}/${write.cid}`);\n\t\t\tthis.appendOplog(\n\t\t\t\trev,\n\t\t\t\tidx++,\n\t\t\t\twrite.collection,\n\t\t\t\twrite.rkey,\n\t\t\t\twrite.cid,\n\t\t\t\tprev,\n\t\t\t);\n\t\t\tresults.push({\n\t\t\t\taction: write.action,\n\t\t\t\tcollection: write.collection,\n\t\t\t\trkey: write.rkey,\n\t\t\t\tcid: write.cid,\n\t\t\t});\n\t\t}\n\n\t\tthis.writeRepoState(commit.setHash.state(), rev);\n\t\treturn { rev, data: commit.setHash.digest(), results };\n\t}\n\n\tprivate deleteRecordRow(collection: string, rkey: string): void {\n\t\tthis.sql.exec(\n\t\t\t\"DELETE FROM record WHERE collection = ? AND rkey = ?\",\n\t\t\tcollection,\n\t\t\trkey,\n\t\t);\n\t\tthis.sql.exec(\n\t\t\t\"DELETE FROM record_blob WHERE collection = ? AND rkey = ?\",\n\t\t\tcollection,\n\t\t\trkey,\n\t\t);\n\t}\n\n\tprivate replaceRecordBlobs(\n\t\tcollection: string,\n\t\trkey: string,\n\t\tblobCids: string[],\n\t): void {\n\t\tthis.sql.exec(\n\t\t\t\"DELETE FROM record_blob WHERE collection = ? AND rkey = ?\",\n\t\t\tcollection,\n\t\t\trkey,\n\t\t);\n\t\tfor (const blobCid of blobCids) {\n\t\t\tthis.sql.exec(\n\t\t\t\t\"INSERT OR IGNORE INTO record_blob (blob_cid, collection, rkey) VALUES (?, ?, ?)\",\n\t\t\t\tblobCid,\n\t\t\t\tcollection,\n\t\t\t\trkey,\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate writeRepoState(setHash: Uint8Array, rev: string): void {\n\t\tthis.sql.exec(\n\t\t\t`INSERT INTO repo_state (id, set_hash, rev) VALUES (1, ?, ?)\n\t\t\t ON CONFLICT (id) DO UPDATE SET set_hash = excluded.set_hash, rev = excluded.rev`,\n\t\t\tsetHash,\n\t\t\trev,\n\t\t);\n\t}\n\n\tprivate appendOplog(\n\t\trev: string,\n\t\tidx: number,\n\t\tcollection: string,\n\t\trkey: string,\n\t\tcid: string | null,\n\t\tprev: string | null,\n\t): void {\n\t\tthis.sql.exec(\n\t\t\t\"INSERT INTO oplog (rev, idx, collection, rkey, cid, prev) VALUES (?, ?, ?, ?, ?, ?)\",\n\t\t\trev,\n\t\t\tidx,\n\t\t\tcollection,\n\t\t\trkey,\n\t\t\tcid,\n\t\t\tprev,\n\t\t);\n\t}\n\n\t/** The collections the repo holds records in, for clearRecords' grants. */\n\tasync rpcListCollections(): Promise<string[]> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\treturn this.sql\n\t\t\t.exec(\"SELECT DISTINCT collection FROM record ORDER BY collection\")\n\t\t\t.toArray()\n\t\t\t.map((row) => row.collection as string);\n\t}\n\n\t/**\n\t * Delete every record outside `keep` and clear the oplog, leaving the\n\t * repo at a new rev with the digest of what remains. Returns null when\n\t * there was nothing to delete.\n\t */\n\tasync rpcClearRecords(keep: string[]): Promise<RepoCommitResult | null> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\treturn this.ctx.storage.transactionSync(() => {\n\t\t\tconst state = this.readRepoState();\n\t\t\tif (!state) return null;\n\t\t\tconst placeholders = keep.map(() => \"?\").join(\", \");\n\t\t\tconst notKept =\n\t\t\t\tkeep.length > 0 ? `collection NOT IN (${placeholders})` : \"1=1\";\n\t\t\tconst doomed = this.sql\n\t\t\t\t.exec(`SELECT COUNT(*) AS n FROM record WHERE ${notKept}`, ...keep)\n\t\t\t\t.toArray()[0]?.n as number;\n\t\t\tif (!doomed) return null;\n\t\t\tthis.sql.exec(`DELETE FROM record_blob WHERE ${notKept}`, ...keep);\n\t\t\tthis.sql.exec(`DELETE FROM record WHERE ${notKept}`, ...keep);\n\t\t\tthis.sql.exec(\"DELETE FROM oplog\");\n\t\t\tconst commit = new RepoCommit();\n\t\t\tfor (const row of this.sql\n\t\t\t\t.exec(\"SELECT collection, rkey, cid FROM record\")\n\t\t\t\t.toArray()) {\n\t\t\t\tcommit.setHash.add(`${row.collection}/${row.rkey}/${row.cid}`);\n\t\t\t}\n\t\t\tconst rev = nextRev(state.rev);\n\t\t\tthis.writeRepoState(commit.setHash.state(), rev);\n\t\t\treturn { rev, data: commit.setHash.digest() };\n\t\t});\n\t}\n\n\t/**\n\t * Replace the repo with records imported from its previous host. Takes a\n\t * new rev here and none of its history, so the oplog starts empty.\n\t *\n\t * Policy and member records are only ever written by the host, so the\n\t * archive's are left out. In the authority's own repo they are published\n\t * again, in a commit of their own, from the configuration importSpaceMeta\n\t * set, as the reference does.\n\t */\n\tasync rpcImportRepo(records: ImportedRecord[]): Promise<RepoCommitResult> {\n\t\tawait this.ensureOpen();\n\t\tconst meta = this.requireLiveMeta();\n\t\tconst imported = records.filter(\n\t\t\t(record) => !PUBLISHED_COLLECTIONS.includes(record.collection),\n\t\t);\n\t\tconst policy = meta.isAuthority ? this.readPolicy() : null;\n\t\tconst publishWrites = policy\n\t\t\t? await this.preparePublishedRecordCreates(policy)\n\t\t\t: [];\n\t\treturn this.ctx.storage.transactionSync(() => {\n\t\t\tconst state = this.readRepoState();\n\t\t\tthis.sql.exec(\"DELETE FROM record_blob\");\n\t\t\tthis.sql.exec(\"DELETE FROM record\");\n\t\t\tthis.sql.exec(\"DELETE FROM oplog\");\n\t\t\tconst rev = nextRev(state?.rev ?? null);\n\t\t\tconst indexedAt = new Date().toISOString();\n\t\t\tconst commit = new RepoCommit();\n\t\t\tfor (const record of imported) {\n\t\t\t\tthis.sql.exec(\n\t\t\t\t\t`INSERT INTO record (collection, rkey, cid, bytes, rev, indexed_at)\n\t\t\t\t\t VALUES (?, ?, ?, ?, ?, ?)`,\n\t\t\t\t\trecord.collection,\n\t\t\t\t\trecord.rkey,\n\t\t\t\t\trecord.cid,\n\t\t\t\t\trecord.bytes,\n\t\t\t\t\trev,\n\t\t\t\t\tindexedAt,\n\t\t\t\t);\n\t\t\t\tthis.replaceRecordBlobs(\n\t\t\t\t\trecord.collection,\n\t\t\t\t\trecord.rkey,\n\t\t\t\t\trecord.blobCids,\n\t\t\t\t);\n\t\t\t\tcommit.setHash.add(`${record.collection}/${record.rkey}/${record.cid}`);\n\t\t\t}\n\t\t\tthis.writeRepoState(commit.setHash.state(), rev);\n\t\t\tconst published = this.applyWritesSync(publishWrites);\n\t\t\treturn published\n\t\t\t\t? { rev: published.rev, data: published.data }\n\t\t\t\t: { rev, data: commit.setHash.digest() };\n\t\t});\n\t}\n\n\t// ------------------------------------------------------------------\n\t// Permissioned repo: reads\n\t// ------------------------------------------------------------------\n\n\tprivate readRepoState(): RepoState | null {\n\t\tconst row = this.sql\n\t\t\t.exec(\"SELECT set_hash, rev FROM repo_state WHERE id = 1\")\n\t\t\t.toArray()[0];\n\t\tif (!row) return null;\n\t\treturn {\n\t\t\tsetHash: new Uint8Array(row.set_hash as ArrayBuffer),\n\t\t\trev: row.rev as string,\n\t\t};\n\t}\n\n\tasync rpcGetRecord(\n\t\tcollection: string,\n\t\trkey: string,\n\t): Promise<{ cid: string; bytes: Uint8Array } | null> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\tconst row = this.sql\n\t\t\t.exec(\n\t\t\t\t\"SELECT cid, bytes FROM record WHERE collection = ? AND rkey = ?\",\n\t\t\t\tcollection,\n\t\t\t\trkey,\n\t\t\t)\n\t\t\t.toArray()[0];\n\t\tif (!row) return null;\n\t\treturn {\n\t\t\tcid: row.cid as string,\n\t\t\tbytes: new Uint8Array(row.bytes as ArrayBuffer),\n\t\t};\n\t}\n\n\t/**\n\t * List records ordered by (collection, rkey) — equivalent to record-URI\n\t * order since every record shares the space and repo prefix. Descending\n\t * by default, matching the reference; `reverse` flips to ascending.\n\t */\n\tasync rpcListRecords(params: {\n\t\tcollection?: string;\n\t\tlimit: number;\n\t\tafter?: { collection: string; rkey: string };\n\t\treverse?: boolean;\n\t\texcludeValues?: boolean;\n\t}): Promise<{ records: SpaceRecordRow[]; hasMore: boolean }> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\tconst asc = params.reverse === true;\n\t\tconst op = asc ? \">\" : \"<\";\n\t\tconst order = asc ? \"ASC\" : \"DESC\";\n\t\tconst args: unknown[] = [];\n\t\tlet where = \"1=1\";\n\t\tif (params.collection) {\n\t\t\twhere += \" AND collection = ?\";\n\t\t\targs.push(params.collection);\n\t\t}\n\t\tif (params.after) {\n\t\t\twhere += ` AND (collection ${op} ? OR (collection = ? AND rkey ${op} ?))`;\n\t\t\targs.push(\n\t\t\t\tparams.after.collection,\n\t\t\t\tparams.after.collection,\n\t\t\t\tparams.after.rkey,\n\t\t\t);\n\t\t}\n\t\tconst rows = this.sql\n\t\t\t.exec(\n\t\t\t\t`SELECT collection, rkey, cid${params.excludeValues ? \"\" : \", bytes\"} FROM record\n\t\t\t\t WHERE ${where}\n\t\t\t\t ORDER BY collection ${order}, rkey ${order}\n\t\t\t\t LIMIT ?`,\n\t\t\t\t...args,\n\t\t\t\tparams.limit + 1,\n\t\t\t)\n\t\t\t.toArray();\n\t\tconst hasMore = rows.length > params.limit;\n\t\tconst page = hasMore ? rows.slice(0, params.limit) : rows;\n\t\treturn {\n\t\t\trecords: page.map((row) => ({\n\t\t\t\tcollection: row.collection as string,\n\t\t\t\trkey: row.rkey as string,\n\t\t\t\tcid: row.cid as string,\n\t\t\t\t...(params.excludeValues\n\t\t\t\t\t? {}\n\t\t\t\t\t: { bytes: new Uint8Array(row.bytes as ArrayBuffer) }),\n\t\t\t})),\n\t\t\thasMore,\n\t\t};\n\t}\n\n\t/**\n\t * Records in strict byte order of their `{collection}/{rkey}` path, as a\n\t * repo archive requires — not (collection, rkey) order, which differs\n\t * when one collection NSID prefixes another. `state` is the repo state\n\t * the page was read at: the page and the state are one snapshot\n\t * (synchronous reads, single-threaded DO), so a streaming export can\n\t * fence against concurrent writes.\n\t */\n\tasync rpcListRecordsByPath(params: {\n\t\tafterPath?: string;\n\t\tlimit: number;\n\t}): Promise<{\n\t\trecords: Array<{ collection: string; rkey: string; bytes: Uint8Array }>;\n\t\thasMore: boolean;\n\t\tstate: RepoState | null;\n\t}> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\tconst state = this.readRepoState();\n\t\t// SQLite's default BINARY collation compares UTF-8 bytes, which is\n\t\t// the archive's order.\n\t\tconst rows = this.sql\n\t\t\t.exec(\n\t\t\t\t`SELECT collection, rkey, bytes FROM record\n\t\t\t\t ${params.afterPath !== undefined ? \"WHERE collection || '/' || rkey > ?\" : \"\"}\n\t\t\t\t ORDER BY collection || '/' || rkey ASC\n\t\t\t\t LIMIT ?`,\n\t\t\t\t...(params.afterPath !== undefined ? [params.afterPath] : []),\n\t\t\t\tparams.limit + 1,\n\t\t\t)\n\t\t\t.toArray();\n\t\tconst hasMore = rows.length > params.limit;\n\t\tconst page = hasMore ? rows.slice(0, params.limit) : rows;\n\t\treturn {\n\t\t\trecords: page.map((row) => ({\n\t\t\t\tcollection: row.collection as string,\n\t\t\t\trkey: row.rkey as string,\n\t\t\t\tbytes: new Uint8Array(row.bytes as ArrayBuffer),\n\t\t\t})),\n\t\t\thasMore,\n\t\t\tstate,\n\t\t};\n\t}\n\n\t/**\n\t * What listSpaces reports for this space: the operator's repo state in\n\t * it and, for a space the operator is the authority of, its revision.\n\t */\n\tasync rpcGetSpaceView(): Promise<{\n\t\trepoRev?: string;\n\t\tdata?: Uint8Array;\n\t\tspaceRev?: string;\n\t} | null> {\n\t\tawait this.ensureOpen();\n\t\tconst meta = this.readMeta();\n\t\tif (!meta || meta.deletedAt) return null;\n\t\tconst state = this.readRepoState();\n\t\tconst spaceRev = meta.isAuthority ? this.currentSpaceRev() : null;\n\t\treturn {\n\t\t\t...(state\n\t\t\t\t? {\n\t\t\t\t\t\trepoRev: state.rev,\n\t\t\t\t\t\tdata: RepoCommit.fromState(state.setHash).setHash.digest(),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\t...(spaceRev ? { spaceRev } : {}),\n\t\t};\n\t}\n\n\tasync rpcGetRepoState(): Promise<RepoState | null> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\treturn this.readRepoState();\n\t}\n\n\t/**\n\t * List oplog entries after `since` (a rev) or `after` (an exact cursor\n\t * position). Creates and updates carry the record's current bytes when\n\t * the oplog cid still matches the live record; superseded values are\n\t * omitted. When the page reaches the head, `head` carries the repo\n\t * state read in the same transaction so the Worker can attach the\n\t * commit without a state race.\n\t */\n\tasync rpcListRepoOps(params: {\n\t\tsince?: string;\n\t\tafter?: { rev: string; idx: number };\n\t\tlimit: number;\n\t\texcludeValues?: boolean;\n\t}): Promise<{ ops: OplogEntry[]; hasMore: boolean; head?: RepoState }> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\treturn this.ctx.storage.transactionSync(() => {\n\t\t\tconst args: unknown[] = [];\n\t\t\tlet where = \"1=1\";\n\t\t\tif (params.after) {\n\t\t\t\twhere += \" AND (o.rev > ? OR (o.rev = ? AND o.idx > ?))\";\n\t\t\t\targs.push(params.after.rev, params.after.rev, params.after.idx);\n\t\t\t} else if (params.since) {\n\t\t\t\twhere += \" AND o.rev > ?\";\n\t\t\t\targs.push(params.since);\n\t\t\t}\n\t\t\tconst values = params.excludeValues ? \"\" : \", r.bytes AS live_bytes\";\n\t\t\tconst rows = this.sql\n\t\t\t\t.exec(\n\t\t\t\t\t`SELECT o.rev, o.idx, o.collection, o.rkey, o.cid, o.prev${values}\n\t\t\t\t\t FROM oplog o\n\t\t\t\t\t ${params.excludeValues ? \"\" : \"LEFT JOIN record r ON r.collection = o.collection AND r.rkey = o.rkey AND r.cid = o.cid\"}\n\t\t\t\t\t WHERE ${where}\n\t\t\t\t\t ORDER BY o.rev ASC, o.idx ASC\n\t\t\t\t\t LIMIT ?`,\n\t\t\t\t\t...args,\n\t\t\t\t\tparams.limit + 1,\n\t\t\t\t)\n\t\t\t\t.toArray();\n\t\t\tconst hasMore = rows.length > params.limit;\n\t\t\tconst page = hasMore ? rows.slice(0, params.limit) : rows;\n\t\t\tconst ops: OplogEntry[] = page.map((row) => ({\n\t\t\t\trev: row.rev as string,\n\t\t\t\tidx: row.idx as number,\n\t\t\t\tcollection: row.collection as string,\n\t\t\t\trkey: row.rkey as string,\n\t\t\t\tcid: (row.cid as string | null) ?? null,\n\t\t\t\tprev: (row.prev as string | null) ?? null,\n\t\t\t\t...(row.live_bytes\n\t\t\t\t\t? { bytes: new Uint8Array(row.live_bytes as ArrayBuffer) }\n\t\t\t\t\t: {}),\n\t\t\t}));\n\t\t\t// The commit is returned on every page, read in the same\n\t\t\t// transaction so it never races the page.\n\t\t\tconst head = this.readRepoState();\n\t\t\treturn { ops, hasMore, ...(head ? { head } : {}) };\n\t\t});\n\t}\n\n\t/** Distinct blob CIDs referenced by records, ascending, paged. */\n\tasync rpcListBlobs(params: {\n\t\tsince?: string;\n\t\tlimit: number;\n\t\tafterCid?: string;\n\t}): Promise<{ cids: string[]; hasMore: boolean }> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\tconst args: unknown[] = [];\n\t\tlet where = \"1=1\";\n\t\tif (params.since) {\n\t\t\twhere += \" AND r.rev > ?\";\n\t\t\targs.push(params.since);\n\t\t}\n\t\tif (params.afterCid) {\n\t\t\twhere += \" AND b.blob_cid > ?\";\n\t\t\targs.push(params.afterCid);\n\t\t}\n\t\tconst rows = this.sql\n\t\t\t.exec(\n\t\t\t\t`SELECT DISTINCT b.blob_cid FROM record_blob b\n\t\t\t\t JOIN record r ON r.collection = b.collection AND r.rkey = b.rkey\n\t\t\t\t WHERE ${where}\n\t\t\t\t ORDER BY b.blob_cid ASC\n\t\t\t\t LIMIT ?`,\n\t\t\t\t...args,\n\t\t\t\tparams.limit + 1,\n\t\t\t)\n\t\t\t.toArray();\n\t\tconst hasMore = rows.length > params.limit;\n\t\tconst page = hasMore ? rows.slice(0, params.limit) : rows;\n\t\treturn { cids: page.map((r) => r.blob_cid as string), hasMore };\n\t}\n\n\t/** Whether a blob CID is referenced by any record in this space. */\n\tasync rpcHasSpaceBlob(cid: string): Promise<boolean> {\n\t\tawait this.ensureOpen();\n\t\tthis.requireLiveMeta();\n\t\treturn (\n\t\t\tthis.sql\n\t\t\t\t.exec(\"SELECT 1 FROM record_blob WHERE blob_cid = ? LIMIT 1\", cid)\n\t\t\t\t.toArray().length > 0\n\t\t);\n\t}\n\n\t// ------------------------------------------------------------------\n\t// Replay protection and revocation\n\t// ------------------------------------------------------------------\n\n\t/**\n\t * Record a single-use key. Returns true when the key was fresh (now\n\t * recorded), false when it was already seen and must be refused.\n\t */\n\tasync rpcCheckReplay(\n\t\tkind: string,\n\t\tkey: string,\n\t\texpiresAtSec: number,\n\t): Promise<boolean> {\n\t\tawait this.ensureOpen();\n\t\tconst result = this.sql.exec(\n\t\t\t\"INSERT OR IGNORE INTO replay (kind, key, expires_at) VALUES (?, ?, ?)\",\n\t\t\tkind,\n\t\t\tkey,\n\t\t\texpiresAtSec,\n\t\t);\n\t\treturn result.rowsWritten > 0;\n\t}\n\n\t/**\n\t * Record credentials the authority revoked (repo-host role). Held until\n\t * any credential with that jti must have expired anyway. Needs no live\n\t * repo: a revocation can precede the first write.\n\t */\n\tasync rpcRevokeCredentials(\n\t\tjtis: string[],\n\t\texpiresAtSec: number,\n\t): Promise<void> {\n\t\tawait this.ensureOpen();\n\t\tfor (const jti of jtis) {\n\t\t\tthis.sql.exec(\n\t\t\t\t`INSERT INTO revoked_credential (jti, expires_at) VALUES (?, ?)\n\t\t\t\t ON CONFLICT (jti) DO UPDATE SET expires_at = excluded.expires_at`,\n\t\t\t\tjti,\n\t\t\t\texpiresAtSec,\n\t\t\t);\n\t\t}\n\t\tawait this.scheduleNextAlarm();\n\t}\n\n\tasync rpcIsCredentialRevoked(jti: string): Promise<boolean> {\n\t\tawait this.ensureOpen();\n\t\treturn (\n\t\t\tthis.sql\n\t\t\t\t.exec(\n\t\t\t\t\t\"SELECT 1 FROM revoked_credential WHERE jti = ? AND expires_at > ?\",\n\t\t\t\t\tjti,\n\t\t\t\t\tMath.floor(Date.now() / 1000),\n\t\t\t\t)\n\t\t\t\t.toArray().length > 0\n\t\t);\n\t}\n\n\t// ------------------------------------------------------------------\n\t// Authority role: policy, members, writers, notifications\n\t// ------------------------------------------------------------------\n\n\tprivate writePolicy(policy: SpacePolicy): void {\n\t\tthis.sql.exec(\n\t\t\t`INSERT INTO config (id, policy) VALUES (1, ?)\n\t\t\t ON CONFLICT (id) DO UPDATE SET policy = excluded.policy`,\n\t\t\tJSON.stringify(policy),\n\t\t);\n\t}\n\n\tprivate readPolicy(): SpacePolicy | null {\n\t\tconst row = this.sql\n\t\t\t.exec(\"SELECT policy FROM config WHERE id = 1\")\n\t\t\t.toArray()[0];\n\t\treturn row ? (JSON.parse(row.policy as string) as SpacePolicy) : null;\n\t}\n\n\t/**\n\t * State needed to answer getSpaceCredential and notifyWrite: meta\n\t * (including the deletion tombstone) and the policy. Never throws on a\n\t * deleted space — a late credential request must get SpaceDeleted, not\n\t * SpaceNotFound, and that mapping is the caller's.\n\t */\n\tasync rpcGetAuthorityState(): Promise<{\n\t\tmeta: SpaceMeta | null;\n\t\tpolicy: SpacePolicy | null;\n\t}> {\n\t\tawait this.ensureOpen();\n\t\treturn { meta: this.readMeta(), policy: this.readPolicy() };\n\t}\n\n\tprivate hasRecord(collection: string, rkey: string): boolean {\n\t\treturn (\n\t\t\tthis.sql\n\t\t\t\t.exec(\n\t\t\t\t\t\"SELECT 1 FROM record WHERE collection = ? AND rkey = ?\",\n\t\t\t\t\tcollection,\n\t\t\t\t\trkey,\n\t\t\t\t)\n\t\t\t\t.toArray().length > 0\n\t\t);\n\t}\n\n\tprivate async preparePut(\n\t\tcollection: string,\n\t\trkey: string,\n\t\trecord: Record<string, unknown>,\n\t): Promise<PreparedSpaceWrite> {\n\t\tconst prepared = await prepareRecord(record);\n\t\treturn {\n\t\t\taction: this.hasRecord(collection, rkey) ? \"update\" : \"create\",\n\t\t\tcollection,\n\t\t\trkey,\n\t\t\tcid: prepared.cid,\n\t\t\tbytes: prepared.bytes,\n\t\t\tblobCids: prepared.blobCids,\n\t\t};\n\t}\n\n\tprivate prepareDeleteIfExists(\n\t\tcollection: string,\n\t\trkey: string,\n\t): PreparedSpaceWrite[] {\n\t\treturn this.hasRecord(collection, rkey)\n\t\t\t? [{ action: \"delete\", collection, rkey }]\n\t\t\t: [];\n\t}\n\n\t/** Publish, update or withdraw the policy record to match the policy. */\n\tprivate async preparePolicyRecordWrites(\n\t\tpolicy: SpacePolicy,\n\t): Promise<PreparedSpaceWrite[]> {\n\t\tif (isPolicyPublished(policy)) {\n\t\t\treturn [\n\t\t\t\tawait this.preparePut(POLICY_COLLECTION, POLICY_RKEY, {\n\t\t\t\t\t$type: POLICY_COLLECTION,\n\t\t\t\t\tpolicy,\n\t\t\t\t}),\n\t\t\t];\n\t\t}\n\t\treturn this.prepareDeleteIfExists(POLICY_COLLECTION, POLICY_RKEY);\n\t}\n\n\t/**\n\t * Publish, update or withdraw a member's record to match their entry.\n\t * `access` is omitted for a DID that is no longer a member.\n\t */\n\tprivate async prepareMemberRecordWrites(\n\t\tpolicy: SpacePolicy,\n\t\tdid: string,\n\t\taccess?: { read: boolean; write: boolean },\n\t): Promise<PreparedSpaceWrite[]> {\n\t\tconst rkey = didToRecordKey(did);\n\t\tif (access && areMembersPublished(policy)) {\n\t\t\treturn [\n\t\t\t\tawait this.preparePut(MEMBER_COLLECTION, rkey, {\n\t\t\t\t\t$type: MEMBER_COLLECTION,\n\t\t\t\t\tread: access.read,\n\t\t\t\t\twrite: access.write,\n\t\t\t\t}),\n\t\t\t];\n\t\t}\n\t\treturn this.prepareDeleteIfExists(MEMBER_COLLECTION, rkey);\n\t}\n\n\t/**\n\t * The policy and member records the policy publishes, as creates into a\n\t * repo that holds none (an import has just cleared it).\n\t */\n\tprivate async preparePublishedRecordCreates(\n\t\tpolicy: SpacePolicy,\n\t): Promise<PreparedSpaceWrite[]> {\n\t\tconst writes = await this.preparePolicyRecordWrites(policy);\n\t\tfor (const member of this.readMembers()) {\n\t\t\twrites.push(\n\t\t\t\t...(await this.prepareMemberRecordWrites(policy, member.did, member)),\n\t\t\t);\n\t\t}\n\t\treturn writes.flatMap((write) =>\n\t\t\twrite.action === \"delete\"\n\t\t\t\t? []\n\t\t\t\t: [{ ...write, action: \"create\" as const }],\n\t\t);\n\t}\n\n\tprivate readMembers(): SpaceMember[] {\n\t\treturn this.sql\n\t\t\t.exec(\"SELECT did, can_read, can_write FROM member ORDER BY did\")\n\t\t\t.toArray()\n\t\t\t.map((row) => ({\n\t\t\t\tdid: row.did as string,\n\t\t\t\tread: (row.can_read as number) === 1,\n\t\t\t\twrite: (row.can_write as number) === 1,\n\t\t\t}));\n\t}\n\n\t/**\n\t * Replace the policy wholesale. A different `$type` migrates the space:\n\t * state held by the previous policy (the member list) is discarded, and\n\t * a published member list is withdrawn with it.\n\t */\n\tasync rpcUpdatePolicy(next: SpacePolicy): Promise<RepoCommitResult | null> {\n\t\tawait this.ensureOpen();\n\t\tconst { policy: current } = this.requirePolicy();\n\t\tconst writes = await this.preparePolicyRecordWrites(next);\n\t\tif (areMembersPublished(current) !== areMembersPublished(next)) {\n\t\t\tfor (const member of this.readMembers()) {\n\t\t\t\twrites.push(\n\t\t\t\t\t...(await this.prepareMemberRecordWrites(next, member.did, member)),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\treturn this.ctx.storage.transactionSync(() => {\n\t\t\tthis.writePolicy(next);\n\t\t\tif (current.$type !== next.$type) {\n\t\t\t\tthis.sql.exec(\"DELETE FROM member\");\n\t\t\t}\n\t\t\treturn this.applyWritesSync(writes);\n\t\t});\n\t}\n\n\t/**\n\t * Add members or replace their access, in one commit. A DID listed twice\n\t * takes its last entry. Revoking write access removes the member from\n\t * the writer set, sequenced and announced like any removal.\n\t */\n\tasync rpcPutMembers(\n\t\tmembers: SpaceMember[],\n\t): Promise<RepoCommitResult | null> {\n\t\tawait this.ensureOpen();\n\t\tconst { policy } = this.requirePolicy();\n\t\tassertMemberspace(policy);\n\t\tconst byDid = new Map(members.map((m) => [m.did, m]));\n\t\tconst writes: PreparedSpaceWrite[] = [];\n\t\tfor (const member of byDid.values()) {\n\t\t\twrites.push(\n\t\t\t\t...(await this.prepareMemberRecordWrites(policy, member.did, member)),\n\t\t\t);\n\t\t}\n\t\tconst commit = this.ctx.storage.transactionSync(() => {\n\t\t\tfor (const member of byDid.values()) {\n\t\t\t\tthis.sql.exec(\n\t\t\t\t\t`INSERT INTO member (did, can_read, can_write) VALUES (?, ?, ?)\n\t\t\t\t\t ON CONFLICT (did) DO UPDATE SET can_read = excluded.can_read, can_write = excluded.can_write`,\n\t\t\t\t\tmember.did,\n\t\t\t\t\tmember.read ? 1 : 0,\n\t\t\t\t\tmember.write ? 1 : 0,\n\t\t\t\t);\n\t\t\t\tif (!member.write) this.removeWriterSync(member.did);\n\t\t\t}\n\t\t\treturn this.applyWritesSync(writes);\n\t\t});\n\t\tawait this.scheduleNextAlarm();\n\t\treturn commit;\n\t}\n\n\t/**\n\t * Remove members, in one commit, and from the writer set. DIDs that are\n\t * not members are ignored, leaving any writer set entry alone.\n\t */\n\tasync rpcRemoveMembers(dids: string[]): Promise<RepoCommitResult | null> {\n\t\tawait this.ensureOpen();\n\t\tconst { policy } = this.requirePolicy();\n\t\tassertMemberspace(policy);\n\t\tconst members = [...new Set(dids)].filter(\n\t\t\t(did) =>\n\t\t\t\tthis.sql.exec(\"SELECT 1 FROM member WHERE did = ?\", did).toArray()\n\t\t\t\t\t.length > 0,\n\t\t);\n\t\tconst writes: PreparedSpaceWrite[] = [];\n\t\tfor (const did of members) {\n\t\t\twrites.push(...(await this.prepareMemberRecordWrites(policy, did)));\n\t\t}\n\t\tconst commit = this.ctx.storage.transactionSync(() => {\n\t\t\tfor (const did of members) {\n\t\t\t\tthis.sql.exec(\"DELETE FROM member WHERE did = ?\", did);\n\t\t\t\tthis.removeWriterSync(did);\n\t\t\t}\n\t\t\treturn this.applyWritesSync(writes);\n\t\t});\n\t\tawait this.scheduleNextAlarm();\n\t\treturn commit;\n\t}\n\n\tasync rpcGetMember(did: string): Promise<SpaceMember | null> {\n\t\tawait this.ensureOpen();\n\t\tthis.requirePolicy();\n\t\tconst row = this.sql\n\t\t\t.exec(\"SELECT did, can_read, can_write FROM member WHERE did = ?\", did)\n\t\t\t.toArray()[0];\n\t\tif (!row) return null;\n\t\treturn {\n\t\t\tdid: row.did as string,\n\t\t\tread: (row.can_read as number) === 1,\n\t\t\twrite: (row.can_write as number) === 1,\n\t\t};\n\t}\n\n\tasync rpcListMembers(params: {\n\t\tlimit: number;\n\t\tafterDid?: string;\n\t}): Promise<{ members: SpaceMember[]; hasMore: boolean }> {\n\t\tawait this.ensureOpen();\n\t\tconst { policy } = this.requirePolicy();\n\t\tassertMemberspace(policy);\n\t\tconst args: unknown[] = [];\n\t\tlet where = \"1=1\";\n\t\tif (params.afterDid) {\n\t\t\twhere += \" AND did > ?\";\n\t\t\targs.push(params.afterDid);\n\t\t}\n\t\tconst rows = this.sql\n\t\t\t.exec(\n\t\t\t\t`SELECT did, can_read, can_write FROM member WHERE ${where} ORDER BY did ASC LIMIT ?`,\n\t\t\t\t...args,\n\t\t\t\tparams.limit + 1,\n\t\t\t)\n\t\t\t.toArray();\n\t\tconst hasMore = rows.length > params.limit;\n\t\tconst page = hasMore ? rows.slice(0, params.limit) : rows;\n\t\treturn {\n\t\t\tmembers: page.map((row) => ({\n\t\t\t\tdid: row.did as string,\n\t\t\t\tread: (row.can_read as number) === 1,\n\t\t\t\twrite: (row.can_write as number) === 1,\n\t\t\t})),\n\t\t\thasMore,\n\t\t};\n\t}\n\n\t/** The space's current revision: the latest in its writer set, removals included. */\n\tprivate currentSpaceRev(): string | null {\n\t\treturn (\n\t\t\t(this.sql.exec(\"SELECT MAX(space_rev) AS rev FROM writer\").toArray()[0]\n\t\t\t\t?.rev as string | null) ?? null\n\t\t);\n\t}\n\n\tasync rpcGetSpaceRev(): Promise<string | null> {\n\t\tawait this.ensureOpen();\n\t\tthis.requirePolicy();\n\t\treturn this.currentSpaceRev();\n\t}\n\n\t/**\n\t * Record a writer's latest (repoRev, data), from notifyRepoUpdate or own\n\t * writes, advance the space sequence, and queue the update for the\n\t * registered syncers in the same transaction. Monotonic per writer: a\n\t * delayed or replayed notification with an older (or equal) rev changes\n\t * nothing and returns null. A newer write from a removed writer re-adds\n\t * it.\n\t */\n\tasync rpcRecordWriter(\n\t\tdid: string,\n\t\trepoRev: string,\n\t\tdata: Uint8Array,\n\t): Promise<SpaceSequence | null> {\n\t\tawait this.ensureOpen();\n\t\tconst { meta } = this.requirePolicy();\n\t\tconst sequence = this.ctx.storage.transactionSync(() => {\n\t\t\tconst existing = this.sql\n\t\t\t\t.exec(\"SELECT repo_rev FROM writer WHERE did = ?\", did)\n\t\t\t\t.toArray()[0];\n\t\t\tif (existing && (existing.repo_rev as string) >= repoRev) return null;\n\t\t\tconst prevSpaceRev = this.currentSpaceRev();\n\t\t\tconst spaceRev = nextRev(prevSpaceRev);\n\t\t\tthis.sql.exec(\n\t\t\t\t`INSERT INTO writer (did, repo_rev, data, space_rev, removed_at) VALUES (?, ?, ?, ?, NULL)\n\t\t\t\t ON CONFLICT (did) DO UPDATE SET repo_rev = excluded.repo_rev, data = excluded.data,\n\t\t\t\t\tspace_rev = excluded.space_rev, removed_at = NULL`,\n\t\t\t\tdid,\n\t\t\t\trepoRev,\n\t\t\t\tdata,\n\t\t\t\tspaceRev,\n\t\t\t);\n\t\t\tconst sequence = { spaceRev, ...(prevSpaceRev ? { prevSpaceRev } : {}) };\n\t\t\tthis.queueSpaceUpdate(meta.uri, {\n\t\t\t\t$type: REPO_WRITE,\n\t\t\t\trepo: did,\n\t\t\t\trepoRev,\n\t\t\t\tdata: bytesToJson(data),\n\t\t\t\t...sequence,\n\t\t\t});\n\t\t\treturn sequence;\n\t\t});\n\t\tif (sequence) await this.scheduleNextAlarm();\n\t\treturn sequence;\n\t}\n\n\t/**\n\t * Remove a repo from the writer set at a new space revision, keeping its\n\t * row marked removed so listWriters reports the removal, and announce it.\n\t * Returns false when the repo is not in the writer set. Must run in a\n\t * transaction.\n\t */\n\tprivate removeWriterSync(did: string): boolean {\n\t\tconst meta = this.readMeta();\n\t\tconst row = this.sql\n\t\t\t.exec(\"SELECT removed_at FROM writer WHERE did = ?\", did)\n\t\t\t.toArray()[0];\n\t\tif (!meta || !row || row.removed_at !== null) return false;\n\t\tconst prevSpaceRev = this.currentSpaceRev();\n\t\tconst spaceRev = nextRev(prevSpaceRev);\n\t\tthis.sql.exec(\n\t\t\t\"UPDATE writer SET space_rev = ?, removed_at = ? WHERE did = ?\",\n\t\t\tspaceRev,\n\t\t\tDate.now(),\n\t\t\tdid,\n\t\t);\n\t\tthis.queueSpaceUpdate(meta.uri, {\n\t\t\t$type: REPO_REMOVED,\n\t\t\trepo: did,\n\t\t\tspaceRev,\n\t\t\t...(prevSpaceRev ? { prevSpaceRev } : {}),\n\t\t});\n\t\treturn true;\n\t}\n\n\t/**\n\t * Drop an account from the writer set. It is tracked again if it later\n\t * writes while still authorised. Idempotent.\n\t */\n\tasync rpcRemoveWriter(did: string): Promise<void> {\n\t\tawait this.ensureOpen();\n\t\tthis.requirePolicy();\n\t\tthis.ctx.storage.transactionSync(() => this.removeWriterSync(did));\n\t\tawait this.scheduleNextAlarm();\n\t}\n\n\tprivate readWriter(row: Record<string, SqlStorageValue>): SpaceWriter {\n\t\treturn {\n\t\t\tdid: row.did as string,\n\t\t\trepoRev: row.repo_rev as string,\n\t\t\tdata: new Uint8Array(row.data as ArrayBuffer),\n\t\t\tspaceRev: row.space_rev as string,\n\t\t\tremoved: row.removed_at !== null,\n\t\t};\n\t}\n\n\t/** The writer set, removals included, in ascending space revision after `cursor`. */\n\tasync rpcListWriters(params: {\n\t\tlimit: number;\n\t\tcursor?: string;\n\t}): Promise<SpaceWriter[]> {\n\t\tawait this.ensureOpen();\n\t\tthis.requirePolicy();\n\t\treturn this.sql\n\t\t\t.exec(\n\t\t\t\t`SELECT did, repo_rev, data, space_rev, removed_at FROM writer\n\t\t\t\t ${params.cursor ? \"WHERE space_rev > ?\" : \"\"}\n\t\t\t\t ORDER BY space_rev ASC LIMIT ?`,\n\t\t\t\t...(params.cursor ? [params.cursor] : []),\n\t\t\t\tparams.limit,\n\t\t\t)\n\t\t\t.toArray()\n\t\t\t.map((row) => this.readWriter(row));\n\t}\n\n\t/** The space's host-side state, for migrating its authority's account. */\n\tasync rpcExportMeta(): Promise<{\n\t\tpolicy: SpacePolicy;\n\t\tmembers: SpaceMember[];\n\t\twriters: SpaceWriter[];\n\t}> {\n\t\tawait this.ensureOpen();\n\t\tconst { policy } = this.requirePolicy();\n\t\t// Removed writers stay behind: the archive carries only the writer\n\t\t// set itself.\n\t\tconst writers = this.sql\n\t\t\t.exec(\n\t\t\t\t\"SELECT did, repo_rev, data, space_rev, removed_at FROM writer WHERE removed_at IS NULL ORDER BY did\",\n\t\t\t)\n\t\t\t.toArray()\n\t\t\t.map((row) => this.readWriter(row));\n\t\treturn { policy, members: this.readMembers(), writers };\n\t}\n\n\t/**\n\t * Import a space exported by its previous host, replacing whatever this\n\t * host held for it, so a migration step can be retried. Nothing is\n\t * published here: the authority's repo arrives afterwards with\n\t * importRepo, which publishes the policy and member records from what is\n\t * set here.\n\t * Registrations, revocations and tombstones are not carried over.\n\t */\n\tasync rpcImportMeta(params: {\n\t\turi: string;\n\t\tauthority: string;\n\t\ttype: string;\n\t\tskey: string;\n\t\tpolicy: SpacePolicy;\n\t\tmembers: SpaceMember[];\n\t\twriters: SpaceWriter[];\n\t}): Promise<void> {\n\t\tawait this.ensureOpen();\n\t\tconst existing = this.readMeta();\n\t\tif (existing && existing.uri !== params.uri) {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"InvalidRequest\",\n\t\t\t\t`Space DO already holds ${existing.uri}`,\n\t\t\t);\n\t\t}\n\t\tthis.ctx.storage.transactionSync(() => {\n\t\t\tif (!existing) {\n\t\t\t\tthis.sql.exec(\n\t\t\t\t\t`INSERT INTO meta (uri, authority, type, skey, is_authority, created_at, deleted_at, schema_version)\n\t\t\t\t\t VALUES (?, ?, ?, ?, 1, ?, NULL, ?)`,\n\t\t\t\t\tparams.uri,\n\t\t\t\t\tparams.authority,\n\t\t\t\t\tparams.type,\n\t\t\t\t\tparams.skey,\n\t\t\t\t\tnew Date().toISOString(),\n\t\t\t\t\tSPACE_SCHEMA_VERSION,\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tthis.sql.exec(\"UPDATE meta SET deleted_at = NULL, is_authority = 1\");\n\t\t\t}\n\t\t\tthis.writePolicy(params.policy);\n\t\t\tthis.sql.exec(\"DELETE FROM member\");\n\t\t\tfor (const member of params.members) {\n\t\t\t\tthis.sql.exec(\n\t\t\t\t\t\"INSERT INTO member (did, can_read, can_write) VALUES (?, ?, ?)\",\n\t\t\t\t\tmember.did,\n\t\t\t\t\tmember.read ? 1 : 0,\n\t\t\t\t\tmember.write ? 1 : 0,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis.sql.exec(\"DELETE FROM writer\");\n\t\t\tfor (const writer of params.writers) {\n\t\t\t\tthis.sql.exec(\n\t\t\t\t\t\"INSERT INTO writer (did, repo_rev, data, space_rev, removed_at) VALUES (?, ?, ?, ?, NULL)\",\n\t\t\t\t\twriter.did,\n\t\t\t\t\twriter.repoRev,\n\t\t\t\t\twriter.data,\n\t\t\t\t\twriter.spaceRev,\n\t\t\t\t);\n\t\t\t}\n\t\t});\n\t}\n\n\tasync rpcGetNotifyRegistration(\n\t\tregistration: NotifyRegistration,\n\t): Promise<{ expiresAt: number } | null> {\n\t\tawait this.ensureOpen();\n\t\tconst row = this.sql\n\t\t\t.exec(\n\t\t\t\t\"SELECT expires_at FROM notify_registration WHERE endpoint = ? AND token = ?\",\n\t\t\t\tregistration.endpoint,\n\t\t\t\tregistration.token,\n\t\t\t)\n\t\t\t.toArray()[0];\n\t\treturn row ? { expiresAt: row.expires_at as number } : null;\n\t}\n\n\t/**\n\t * Register a syncer's webhook, or renew it, to the expiry of the\n\t * credential it was authorised with. Renewal clears a lapse already\n\t * announced, so the next lapse is announced too.\n\t */\n\tasync rpcPutNotifyRegistration(\n\t\tregistration: NotifyRegistration,\n\t\texpiresAt: number,\n\t): Promise<void> {\n\t\tawait this.ensureOpen();\n\t\tconst meta = this.readMeta();\n\t\tif (!meta) throw new SpaceError(\"SpaceNotFound\", \"Space not found\");\n\t\tif (meta.deletedAt) {\n\t\t\tthrow new SpaceError(\"SpaceDeleted\", \"Space has been deleted\");\n\t\t}\n\t\tthis.sql.exec(\n\t\t\t`INSERT INTO notify_registration (endpoint, token, expires_at, expiry_notified) VALUES (?, ?, ?, 0)\n\t\t\t ON CONFLICT (endpoint, token) DO UPDATE SET expires_at = excluded.expires_at, expiry_notified = 0`,\n\t\t\tregistration.endpoint,\n\t\t\tregistration.token,\n\t\t\texpiresAt,\n\t\t);\n\t}\n\n\t/** Withdraw a registration, as when its syncer is denied access. */\n\tasync rpcRemoveNotifyRegistration(\n\t\tregistration: NotifyRegistration,\n\t): Promise<void> {\n\t\tawait this.ensureOpen();\n\t\tthis.sql.exec(\n\t\t\t\"DELETE FROM notify_registration WHERE endpoint = ? AND token = ?\",\n\t\t\tregistration.endpoint,\n\t\t\tregistration.token,\n\t\t);\n\t}\n\n\t/**\n\t * Queue a sequenced writer-set change for the registered syncers: best\n\t * effort to each active registration, and in place of the update an\n\t * expiry notice, delivered reliably, to each registration that has\n\t * lapsed since the last one. Each lapse is claimed once. Must run in a\n\t * transaction.\n\t */\n\tprivate queueSpaceUpdate(\n\t\tspace: string,\n\t\tupdate: Record<string, unknown>,\n\t): void {\n\t\tconst now = Date.now();\n\t\tconst registrations = this.sql\n\t\t\t.exec(\n\t\t\t\t\"SELECT endpoint, token, expires_at, expiry_notified FROM notify_registration\",\n\t\t\t)\n\t\t\t.toArray();\n\t\tfor (const row of registrations) {\n\t\t\tconst endpoint = row.endpoint as string;\n\t\t\tconst token = row.token as string;\n\t\t\tif ((row.expires_at as number) > now) {\n\t\t\t\tthis.insertNotify({\n\t\t\t\t\tservice: endpoint,\n\t\t\t\t\tendpoint,\n\t\t\t\t\tlxm: NOTIFY_SPACE_UPDATE_LXM,\n\t\t\t\t\tbody: { space, token, update },\n\t\t\t\t\tpolicy: \"fanout\",\n\t\t\t\t\tauth: \"none\",\n\t\t\t\t});\n\t\t\t} else if ((row.expiry_notified as number) === 0) {\n\t\t\t\tthis.sql.exec(\n\t\t\t\t\t\"UPDATE notify_registration SET expiry_notified = 1 WHERE endpoint = ? AND token = ?\",\n\t\t\t\t\tendpoint,\n\t\t\t\t\ttoken,\n\t\t\t\t);\n\t\t\t\tthis.queueSyncerNotice({ endpoint, token }, space, {\n\t\t\t\t\t$type: REGISTRATION_EXPIRED,\n\t\t\t\t\tspaceRev: update.spaceRev,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\t/** A deletion or expiry notice, delivered reliably for 72 hours. */\n\tprivate queueSyncerNotice(\n\t\tregistration: NotifyRegistration,\n\t\tspace: string,\n\t\tnotice: Record<string, unknown>,\n\t): void {\n\t\tthis.insertNotify({\n\t\t\tservice: registration.endpoint,\n\t\t\tendpoint: registration.endpoint,\n\t\t\tlxm: NOTIFY_SPACE_UPDATE_LXM,\n\t\t\tbody: { space, token: registration.token, update: notice },\n\t\t\tpolicy: \"syncer\",\n\t\t\tauth: \"none\",\n\t\t\t// A deletion notice replaces whatever is pending; an expiry notice\n\t\t\t// never replaces one, so a deletion notice is never lost.\n\t\t\tcoalesceKey: `syncer\\n${registration.endpoint}\\n${registration.token}`,\n\t\t\tkeepPending: notice.$type !== SPACE_DELETED,\n\t\t\tdeadline: Date.now() + SYNCER_NOTICE_RETRY_WINDOW_MS,\n\t\t});\n\t}\n\n\t/**\n\t * Queue outbound notifications for the alarm to deliver with bounded\n\t * retries. An item with a coalesce key replaces any pending item with\n\t * the same key, resetting its backoff and deadline.\n\t */\n\tasync rpcEnqueueNotify(\n\t\titems: NotifyItem[],\n\t\topts: { delayMs?: number } = {},\n\t): Promise<void> {\n\t\tawait this.ensureOpen();\n\t\tif (items.length === 0) return;\n\t\tconst nextAt = Date.now() + (opts.delayMs ?? 0);\n\t\tfor (const item of items) this.insertNotify(item, nextAt);\n\t\tawait this.scheduleNextAlarm();\n\t}\n\n\tprivate insertNotify(item: NotifyItem, nextAt = Date.now()): void {\n\t\tconst body = JSON.stringify({\n\t\t\tendpoint: item.endpoint,\n\t\t\tlxm: item.lxm,\n\t\t\tbody: item.body,\n\t\t});\n\t\tthis.sql.exec(\n\t\t\t`INSERT INTO notify_queue (service, body, attempts, next_at, deadline, coalesce_key, policy, auth)\n\t\t\t VALUES (?, ?, 0, ?, ?, ?, ?, ?)\n\t\t\t ON CONFLICT (coalesce_key) DO ${\n\t\t\t\t\titem.keepPending\n\t\t\t\t\t\t? \"NOTHING\"\n\t\t\t\t\t\t: `UPDATE SET\n\t\t\t\tservice = excluded.service, body = excluded.body, attempts = 0,\n\t\t\t\tnext_at = excluded.next_at, deadline = excluded.deadline,\n\t\t\t\tpolicy = excluded.policy, auth = excluded.auth`\n\t\t\t\t}`,\n\t\t\titem.service,\n\t\t\tbody,\n\t\t\tnextAt,\n\t\t\titem.deadline ?? null,\n\t\t\titem.coalesceKey ?? null,\n\t\t\titem.policy ?? \"fanout\",\n\t\t\titem.auth ?? \"service\",\n\t\t);\n\t}\n\n\t/** Drop a pending coalesced notification, e.g. once a newer one landed. */\n\tasync rpcClearNotify(coalesceKey: string): Promise<void> {\n\t\tawait this.ensureOpen();\n\t\tthis.sql.exec(\n\t\t\t\"DELETE FROM notify_queue WHERE coalesce_key = ?\",\n\t\t\tcoalesceKey,\n\t\t);\n\t}\n\n\t// ------------------------------------------------------------------\n\t// Deletion and status\n\t// ------------------------------------------------------------------\n\n\t/**\n\t * Tombstone the space (authority role), delete the authority's own repo\n\t * in it, and queue a deletion notice to every registered syncer, lapsed\n\t * registrations included. The meta row is retained so a late\n\t * authorizeSpaceSync can answer SpaceDeleted rather than SpaceNotFound.\n\t * Idempotent.\n\t */\n\tasync rpcDeleteSpace(): Promise<void> {\n\t\tawait this.ensureOpen();\n\t\tconst meta = this.readMeta();\n\t\tif (!meta) {\n\t\t\tthrow new SpaceError(\"SpaceNotFound\", \"Space is not initialised\");\n\t\t}\n\t\tif (meta.deletedAt) return;\n\t\tthis.ctx.storage.transactionSync(() => {\n\t\t\tfor (const row of this.sql\n\t\t\t\t.exec(\"SELECT endpoint, token FROM notify_registration\")\n\t\t\t\t.toArray()) {\n\t\t\t\tthis.queueSyncerNotice(\n\t\t\t\t\t{ endpoint: row.endpoint as string, token: row.token as string },\n\t\t\t\t\tmeta.uri,\n\t\t\t\t\t{ $type: SPACE_DELETED },\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis.sql.exec(\"UPDATE meta SET deleted_at = ?\", new Date().toISOString());\n\t\t\tfor (const table of [\n\t\t\t\t\"record\",\n\t\t\t\t\"record_blob\",\n\t\t\t\t\"repo_state\",\n\t\t\t\t\"oplog\",\n\t\t\t\t\"config\",\n\t\t\t\t\"member\",\n\t\t\t\t\"writer\",\n\t\t\t\t\"notify_registration\",\n\t\t\t\t\"replay\",\n\t\t\t]) {\n\t\t\t\tthis.sql.exec(`DELETE FROM ${table}`);\n\t\t\t}\n\t\t});\n\t\tawait this.scheduleNextAlarm();\n\t}\n\n\t/** Wipe everything, including queued notifications and alarms. */\n\tasync rpcDestroy(): Promise<void> {\n\t\tawait this.ctx.storage.deleteAlarm();\n\t\tawait this.ctx.storage.deleteAll();\n\t\tthis.initialized = false;\n\t\tthis.outdated = false;\n\t}\n\n\tasync rpcStatus(): Promise<{\n\t\tmeta: SpaceMeta | null;\n\t\toutdated: boolean;\n\t\tpolicyType: string | null;\n\t\trecordCount: number;\n\t\tmemberCount: number;\n\t\twriterCount: number;\n\t\tqueuedNotifications: number;\n\t}> {\n\t\tawait this.ensureInitialized();\n\t\tif (this.outdated) {\n\t\t\treturn {\n\t\t\t\tmeta: null,\n\t\t\t\toutdated: true,\n\t\t\t\tpolicyType: null,\n\t\t\t\trecordCount: 0,\n\t\t\t\tmemberCount: 0,\n\t\t\t\twriterCount: 0,\n\t\t\t\tqueuedNotifications: 0,\n\t\t\t};\n\t\t}\n\t\tconst count = (table: string): number =>\n\t\t\t(this.sql.exec(`SELECT COUNT(*) AS n FROM ${table}`).toArray()[0]\n\t\t\t\t?.n as number) ?? 0;\n\t\treturn {\n\t\t\tmeta: this.readMeta(),\n\t\t\toutdated: false,\n\t\t\tpolicyType: this.readPolicy()?.$type ?? null,\n\t\t\trecordCount: count(\"record\"),\n\t\t\tmemberCount: count(\"member\"),\n\t\t\twriterCount: count(\"writer WHERE removed_at IS NULL\"),\n\t\t\tqueuedNotifications: count(\"notify_queue\"),\n\t\t};\n\t}\n\n\t// ------------------------------------------------------------------\n\t// Alarm: notification delivery, oplog compaction, expiry cleanup\n\t// ------------------------------------------------------------------\n\n\toverride async alarm(): Promise<void> {\n\t\tawait this.ensureInitialized();\n\t\tif (this.outdated) return;\n\n\t\tawait this.deliverQueuedNotifications();\n\t\tthis.runMaintenanceIfDue();\n\t\tawait this.scheduleNextAlarm();\n\t}\n\n\tprivate async deliverQueuedNotifications(): Promise<void> {\n\t\tconst now = Date.now();\n\t\t// Syncer notices are tried once more after their window closes.\n\t\tthis.sql.exec(\n\t\t\t\"DELETE FROM notify_queue WHERE deadline IS NOT NULL AND deadline <= ? AND policy != 'syncer'\",\n\t\t\tnow,\n\t\t);\n\t\tconst due = this.sql\n\t\t\t.exec(\n\t\t\t\t\"SELECT id, service, body, attempts, next_at, deadline, policy, auth FROM notify_queue WHERE next_at <= ? ORDER BY next_at ASC LIMIT ?\",\n\t\t\t\tnow,\n\t\t\t\tNOTIFY_BATCH,\n\t\t\t)\n\t\t\t.toArray() as unknown as QueueRow[];\n\t\tif (due.length === 0) return;\n\n\t\tconst host = await this.getHostConfig();\n\t\tconst keypair = await host.getKeypair();\n\n\t\t// In parallel, so a slow endpoint doesn't hold up the others.\n\t\tawait Promise.all(\n\t\t\tdue.map(async (row) => {\n\t\t\t\tconst parsed = JSON.parse(row.body) as {\n\t\t\t\t\tendpoint: string;\n\t\t\t\t\tlxm: string;\n\t\t\t\t\tbody: Record<string, unknown>;\n\t\t\t\t};\n\t\t\t\tif (\n\t\t\t\t\trow.policy === \"syncer\" &&\n\t\t\t\t\t!this.isSyncerNoticeOwed(parsed.endpoint, parsed.body)\n\t\t\t\t) {\n\t\t\t\t\tthis.sql.exec(\"DELETE FROM notify_queue WHERE id = ?\", row.id);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tlet delivered = false;\n\t\t\t\tlet retryable = true;\n\t\t\t\ttry {\n\t\t\t\t\tconst headers: Record<string, string> = {\n\t\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t};\n\t\t\t\t\tif (row.auth === \"service\") {\n\t\t\t\t\t\tconst token = await createServiceJwt(\n\t\t\t\t\t\t\t{ iss: host.operatorDid, aud: row.service, lxm: parsed.lxm },\n\t\t\t\t\t\t\tkeypair,\n\t\t\t\t\t\t);\n\t\t\t\t\t\theaders.Authorization = `Bearer ${token}`;\n\t\t\t\t\t}\n\t\t\t\t\tconst res = await fetch(`${parsed.endpoint}/xrpc/${parsed.lxm}`, {\n\t\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\t\theaders,\n\t\t\t\t\t\tbody: JSON.stringify(parsed.body),\n\t\t\t\t\t\t// A syncer chose this endpoint: never follow it elsewhere.\n\t\t\t\t\t\tredirect: row.auth === \"none\" ? \"manual\" : \"follow\",\n\t\t\t\t\t\tsignal: AbortSignal.timeout(10_000),\n\t\t\t\t\t});\n\t\t\t\t\tdelivered = res.ok;\n\t\t\t\t\tif (!res.ok) {\n\t\t\t\t\t\tretryable = isRetryableStatus(res.status);\n\t\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\t`notify ${parsed.lxm} to ${row.service} failed: ${res.status}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconsole.warn(`notify to ${row.service} errored:`, err);\n\t\t\t\t}\n\t\t\t\tthis.settleNotify(row, parsed, delivered, retryable);\n\t\t\t}),\n\t\t);\n\t}\n\n\t/** A deletion or expiry notice that no longer applies is dropped unsent. */\n\tprivate isSyncerNoticeOwed(\n\t\tendpoint: string,\n\t\tbody: Record<string, unknown>,\n\t): boolean {\n\t\tconst update = body.update as { $type?: string } | undefined;\n\t\tif (update?.$type === SPACE_DELETED) {\n\t\t\t// Not owed if the space has been recreated since.\n\t\t\treturn Boolean(this.readMeta()?.deletedAt);\n\t\t}\n\t\t// An expiry notice: not owed if the syncer has renewed since.\n\t\tconst row = this.sql\n\t\t\t.exec(\n\t\t\t\t\"SELECT expires_at FROM notify_registration WHERE endpoint = ? AND token = ?\",\n\t\t\t\tendpoint,\n\t\t\t\tbody.token as string,\n\t\t\t)\n\t\t\t.toArray()[0];\n\t\treturn Boolean(row && (row.expires_at as number) <= Date.now());\n\t}\n\n\tprivate settleNotify(\n\t\trow: QueueRow,\n\t\tparsed: { endpoint: string; body: Record<string, unknown> },\n\t\tdelivered: boolean,\n\t\tretryable: boolean,\n\t): void {\n\t\tconst attempts = row.attempts + 1;\n\t\tconst now = Date.now();\n\t\tconst remove = () =>\n\t\t\tthis.sql.exec(\"DELETE FROM notify_queue WHERE id = ?\", row.id);\n\t\tif (delivered) return void remove();\n\t\tif (row.policy === \"syncer\") {\n\t\t\tif (!retryable || (row.deadline !== null && row.deadline <= now)) {\n\t\t\t\tremove();\n\t\t\t\tthis.abandonSyncerNotice(parsed.endpoint, parsed.body);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst delays = SYNCER_NOTICE_RETRY_DELAYS_MS;\n\t\t\tconst delay = delays[Math.min(attempts, delays.length) - 1]!;\n\t\t\tthis.sql.exec(\n\t\t\t\t\"UPDATE notify_queue SET attempts = ?, next_at = ? WHERE id = ?\",\n\t\t\t\tattempts,\n\t\t\t\tnow + jitter(delay),\n\t\t\t\trow.id,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tconst exhausted =\n\t\t\trow.deadline === null ? attempts >= NOTIFY_MAX_ATTEMPTS : false;\n\t\tif (!retryable || exhausted) return void remove();\n\t\tthis.sql.exec(\n\t\t\t\"UPDATE notify_queue SET attempts = ?, next_at = ? WHERE id = ?\",\n\t\t\tattempts,\n\t\t\tnow +\n\t\t\t\tjitter(\n\t\t\t\t\tMath.min(\n\t\t\t\t\t\tNOTIFY_BACKOFF_BASE_MS * 2 ** row.attempts,\n\t\t\t\t\t\tNOTIFY_BACKOFF_MAX_MS,\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\trow.id,\n\t\t);\n\t}\n\n\t/**\n\t * Give up on a notice. A syncer that rejects its expiry notice, or can't\n\t * be reached, is unregistered, unless it has renewed since.\n\t */\n\tprivate abandonSyncerNotice(\n\t\tendpoint: string,\n\t\tbody: Record<string, unknown>,\n\t): void {\n\t\tconst update = body.update as { $type?: string } | undefined;\n\t\tif (update?.$type !== REGISTRATION_EXPIRED) return;\n\t\tthis.sql.exec(\n\t\t\t\"DELETE FROM notify_registration WHERE endpoint = ? AND token = ? AND expires_at <= ?\",\n\t\t\tendpoint,\n\t\t\tbody.token as string,\n\t\t\tDate.now(),\n\t\t);\n\t}\n\n\tprivate runMaintenanceIfDue(): void {\n\t\tconst now = Date.now();\n\t\tconst last =\n\t\t\t(this.sql\n\t\t\t\t.exec(\n\t\t\t\t\t\"SELECT expires_at FROM replay WHERE kind = '__maintenance' AND key = 'last' LIMIT 1\",\n\t\t\t\t)\n\t\t\t\t.toArray()[0]?.expires_at as number | undefined) ?? 0;\n\t\tif (now - last < MAINTENANCE_INTERVAL_MS) return;\n\n\t\t// Oplog compaction: 30 days or 10,000 ops, whichever is smaller.\n\t\t// DO SQLite is billed and capped; the reference has no compaction\n\t\t// yet, ours must.\n\t\tthis.sql.exec(\n\t\t\t\"DELETE FROM oplog WHERE rev < ?\",\n\t\t\ttidCutoff(OPLOG_RETENTION_DAYS * DAY_MS),\n\t\t);\n\t\tconst excess = this.sql\n\t\t\t.exec(\n\t\t\t\t\"SELECT rev, idx FROM oplog ORDER BY rev DESC, idx DESC LIMIT 1 OFFSET ?\",\n\t\t\t\tOPLOG_RETENTION_OPS,\n\t\t\t)\n\t\t\t.toArray()[0];\n\t\tif (excess) {\n\t\t\tthis.sql.exec(\n\t\t\t\t\"DELETE FROM oplog WHERE rev < ? OR (rev = ? AND idx <= ?)\",\n\t\t\t\texcess.rev,\n\t\t\t\texcess.rev,\n\t\t\t\texcess.idx,\n\t\t\t);\n\t\t}\n\n\t\tconst nowSec = Math.floor(now / 1000);\n\t\t// Replay and revocation entries expire on their own clock.\n\t\tthis.sql.exec(\n\t\t\t\"DELETE FROM replay WHERE kind != '__maintenance' AND expires_at < ?\",\n\t\t\tnowSec,\n\t\t);\n\t\tthis.sql.exec(\n\t\t\t\"DELETE FROM revoked_credential WHERE expires_at <= ?\",\n\t\t\tnowSec,\n\t\t);\n\t\t// Lapsed registrations are kept on purpose: the next update to the\n\t\t// space owes each an expiry notice, and abandoning that notice is what\n\t\t// unregisters it.\n\n\t\tthis.sql.exec(\n\t\t\t`INSERT INTO replay (kind, key, expires_at) VALUES ('__maintenance', 'last', ?)\n\t\t\t ON CONFLICT (kind, key) DO UPDATE SET expires_at = excluded.expires_at`,\n\t\t\tnow,\n\t\t);\n\t}\n\n\tprivate async scheduleNextAlarm(): Promise<void> {\n\t\tconst nextQueue = this.sql\n\t\t\t.exec(\"SELECT MIN(next_at) AS next FROM notify_queue\")\n\t\t\t.toArray()[0]?.next as number | null;\n\t\tconst nextMaintenance = Date.now() + MAINTENANCE_INTERVAL_MS;\n\t\tconst next = nextQueue\n\t\t\t? Math.min(Math.max(nextQueue, Date.now() + 1000), nextMaintenance)\n\t\t\t: nextMaintenance;\n\t\tconst current = await this.ctx.storage.getAlarm();\n\t\tif (current === null || next < current) {\n\t\t\tawait this.ctx.storage.setAlarm(next);\n\t\t}\n\t}\n}\n","/**\n * SpaceIndexDurableObject – singleton registry of space URIs with role\n * flags, timestamps and lifecycle state, addressed by `idFromName(\"spaces\")`.\n *\n * Serves listSpaces, the dashboard, export and reset. Nothing reads it on\n * the hot path: the space DO id is derived from the URI, so reads never\n * depend on the index. Creation is a two-step write — the index entry is\n * written `pending`, the space DO is initialised, then the entry is marked\n * `active`. A `pending` entry that never activates is cleaned up by this\n * DO's alarm.\n */\n\nimport { DurableObject } from \"cloudflare:workers\";\nimport {\n\tINDEX_DO_SCHEMA,\n\tPENDING_BLOB_TTL_MS,\n\tPENDING_ENTRY_TTL_MS,\n\tSPACE_SCHEMA_VERSION,\n} from \"./schema.js\";\n\nexport type SpaceIndexState = \"pending\" | \"active\" | \"deleted\";\n\nexport interface SpaceIndexEntry {\n\turi: string;\n\tauthority: string;\n\ttype: string;\n\tskey: string;\n\tisAuthority: boolean;\n\tstate: SpaceIndexState;\n\tcreatedAt: string;\n\tupdatedAt: string;\n}\n\nconst ALARM_INTERVAL_MS = 6 * 60 * 60 * 1000;\n\nexport class SpaceIndexDurableObject<Env = unknown> extends DurableObject<Env> {\n\tprivate sql: SqlStorage;\n\tprivate initialized = false;\n\n\tconstructor(ctx: DurableObjectState, env: Env) {\n\t\tsuper(ctx, env);\n\t\tthis.sql = ctx.storage.sql;\n\t}\n\n\tprivate async ensureInitialized(): Promise<void> {\n\t\tif (this.initialized) return;\n\t\tawait this.ctx.blockConcurrencyWhile(async () => {\n\t\t\tif (this.initialized) return;\n\t\t\tthis.sql.exec(INDEX_DO_SCHEMA);\n\t\t\tthis.initialized = true;\n\t\t\tconst alarm = await this.ctx.storage.getAlarm();\n\t\t\tif (alarm === null) {\n\t\t\t\tawait this.ctx.storage.setAlarm(Date.now() + ALARM_INTERVAL_MS);\n\t\t\t}\n\t\t});\n\t}\n\n\t/** Register (or revive) an entry in `pending` state. */\n\tasync rpcRegister(entry: {\n\t\turi: string;\n\t\tauthority: string;\n\t\ttype: string;\n\t\tskey: string;\n\t\tisAuthority: boolean;\n\t}): Promise<void> {\n\t\tawait this.ensureInitialized();\n\t\tconst now = new Date().toISOString();\n\t\tthis.sql.exec(\n\t\t\t`INSERT INTO space (uri, authority, type, skey, is_authority, state, created_at, updated_at, schema_version)\n\t\t\t VALUES (?, ?, ?, ?, ?, 'pending', ?, ?, ?)\n\t\t\t ON CONFLICT (uri) DO UPDATE SET\n\t\t\t\tstate = CASE WHEN space.state = 'active' THEN 'active' ELSE 'pending' END,\n\t\t\t\tis_authority = excluded.is_authority,\n\t\t\t\tupdated_at = excluded.updated_at`,\n\t\t\tentry.uri,\n\t\t\tentry.authority,\n\t\t\tentry.type,\n\t\t\tentry.skey,\n\t\t\tentry.isAuthority ? 1 : 0,\n\t\t\tnow,\n\t\t\tnow,\n\t\t\tSPACE_SCHEMA_VERSION,\n\t\t);\n\t}\n\n\tasync rpcActivate(uri: string): Promise<void> {\n\t\tawait this.ensureInitialized();\n\t\tthis.sql.exec(\n\t\t\t\"UPDATE space SET state = 'active', updated_at = ? WHERE uri = ?\",\n\t\t\tnew Date().toISOString(),\n\t\t\turi,\n\t\t);\n\t}\n\n\tasync rpcMarkDeleted(uri: string): Promise<void> {\n\t\tawait this.ensureInitialized();\n\t\tthis.sql.exec(\n\t\t\t\"UPDATE space SET state = 'deleted', updated_at = ? WHERE uri = ?\",\n\t\t\tnew Date().toISOString(),\n\t\t\turi,\n\t\t);\n\t}\n\n\tasync rpcGet(uri: string): Promise<SpaceIndexEntry | null> {\n\t\tawait this.ensureInitialized();\n\t\tconst row = this.sql\n\t\t\t.exec(\"SELECT * FROM space WHERE uri = ?\", uri)\n\t\t\t.toArray()[0];\n\t\treturn row ? toEntry(row) : null;\n\t}\n\n\tasync rpcList(params: {\n\t\ttype?: string;\n\t\tauthority?: string;\n\t\tstate?: SpaceIndexState;\n\t\tlimit: number;\n\t\tafterUri?: string;\n\t}): Promise<{ spaces: SpaceIndexEntry[]; hasMore: boolean }> {\n\t\tawait this.ensureInitialized();\n\t\tconst args: unknown[] = [];\n\t\tlet where = \"1=1\";\n\t\tif (params.type) {\n\t\t\twhere += \" AND type = ?\";\n\t\t\targs.push(params.type);\n\t\t}\n\t\tif (params.authority) {\n\t\t\twhere += \" AND authority = ?\";\n\t\t\targs.push(params.authority);\n\t\t}\n\t\tif (params.state) {\n\t\t\twhere += \" AND state = ?\";\n\t\t\targs.push(params.state);\n\t\t}\n\t\tif (params.afterUri) {\n\t\t\twhere += \" AND uri > ?\";\n\t\t\targs.push(params.afterUri);\n\t\t}\n\t\tconst rows = this.sql\n\t\t\t.exec(\n\t\t\t\t`SELECT * FROM space WHERE ${where} ORDER BY uri ASC LIMIT ?`,\n\t\t\t\t...args,\n\t\t\t\tparams.limit + 1,\n\t\t\t)\n\t\t\t.toArray();\n\t\tconst hasMore = rows.length > params.limit;\n\t\tconst page = hasMore ? rows.slice(0, params.limit) : rows;\n\t\treturn { spaces: page.map(toEntry), hasMore };\n\t}\n\n\tasync rpcStats(): Promise<{\n\t\ttotal: number;\n\t\tactive: number;\n\t\tpending: number;\n\t\tdeleted: number;\n\t\thosted: number;\n\t}> {\n\t\tawait this.ensureInitialized();\n\t\tconst count = (where: string): number =>\n\t\t\t(this.sql\n\t\t\t\t.exec(`SELECT COUNT(*) AS n FROM space WHERE ${where}`)\n\t\t\t\t.toArray()[0]?.n as number) ?? 0;\n\t\treturn {\n\t\t\ttotal: count(\"1=1\"),\n\t\t\tactive: count(\"state = 'active'\"),\n\t\t\tpending: count(\"state = 'pending'\"),\n\t\t\tdeleted: count(\"state = 'deleted'\"),\n\t\t\thosted: count(\"is_authority = 1 AND state = 'active'\"),\n\t\t};\n\t}\n\n\t/**\n\t * Note blobs an imported space repo references but whose bytes have not\n\t * been uploaded yet, so uploadBlob can promote them when they arrive.\n\t */\n\tasync rpcAddPendingBlobs(uri: string, cids: string[]): Promise<void> {\n\t\tawait this.ensureInitialized();\n\t\tconst now = Date.now();\n\t\tfor (const cid of cids) {\n\t\t\tthis.sql.exec(\n\t\t\t\t\"INSERT OR REPLACE INTO pending_blob (cid, uri, created_at) VALUES (?, ?, ?)\",\n\t\t\t\tcid,\n\t\t\t\turi,\n\t\t\t\tnow,\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Claim a freshly uploaded blob: the spaces whose imported records\n\t * reference it. Claimed entries are removed.\n\t */\n\tasync rpcClaimPendingBlob(cid: string): Promise<string[]> {\n\t\tawait this.ensureInitialized();\n\t\tconst uris = this.sql\n\t\t\t.exec(\"SELECT uri FROM pending_blob WHERE cid = ?\", cid)\n\t\t\t.toArray()\n\t\t\t.map((row) => row.uri as string);\n\t\tif (uris.length > 0) {\n\t\t\tthis.sql.exec(\"DELETE FROM pending_blob WHERE cid = ?\", cid);\n\t\t}\n\t\treturn uris;\n\t}\n\n\t/** Wipe the registry (spaces reset). */\n\tasync rpcDestroy(): Promise<void> {\n\t\tawait this.ctx.storage.deleteAlarm();\n\t\tawait this.ctx.storage.deleteAll();\n\t\tthis.initialized = false;\n\t}\n\n\t/**\n\t * Tombstone `pending` entries that never activated. They become\n\t * `deleted` rather than being removed: a crash between the space DO's\n\t * initialisation and the index activation leaves real DO storage\n\t * behind, and the index row is the only durable manifest `spaces reset`\n\t * has for finding and destroying it.\n\t */\n\toverride async alarm(): Promise<void> {\n\t\tawait this.ensureInitialized();\n\t\tconst cutoff = new Date(Date.now() - PENDING_ENTRY_TTL_MS).toISOString();\n\t\tthis.sql.exec(\n\t\t\t\"UPDATE space SET state = 'deleted', updated_at = ? WHERE state = 'pending' AND updated_at < ?\",\n\t\t\tnew Date().toISOString(),\n\t\t\tcutoff,\n\t\t);\n\t\tthis.sql.exec(\n\t\t\t\"DELETE FROM pending_blob WHERE created_at < ?\",\n\t\t\tDate.now() - PENDING_BLOB_TTL_MS,\n\t\t);\n\t\tawait this.ctx.storage.setAlarm(Date.now() + ALARM_INTERVAL_MS);\n\t}\n}\n\nfunction toEntry(row: Record<string, unknown>): SpaceIndexEntry {\n\treturn {\n\t\turi: row.uri as string,\n\t\tauthority: row.authority as string,\n\t\ttype: row.type as string,\n\t\tskey: row.skey as string,\n\t\tisAuthority: (row.is_authority as number) === 1,\n\t\tstate: row.state as SpaceIndexState,\n\t\tcreatedAt: row.created_at as string,\n\t\tupdatedAt: row.updated_at as string,\n\t};\n}\n","/**\n * Space URI handling.\n *\n * A space is addressed as `at:space/{authorityDid}/{typeNsid}/{skey}`, and a\n * record in a space appends `/{authorDid}/{collection}/{rkey}`. The\n * `at:space/` prefix tells it apart from a public `at://` URI.\n *\n * Params are parsed strictly: the alpha's earlier `at://{did}/space/...`\n * form is refused, as the reference refuses it. Only record values written\n * during the alpha may still carry it, and the engine never parses those.\n */\n\n/** The prefix of every space URI. */\nexport const SPACE_URI_PREFIX = \"at:space/\";\n\nimport { isDid, isNsid, isRecordKey } from \"@atcute/lexicons/syntax\";\nimport { SpaceError } from \"./errors.js\";\n\nexport interface SpaceRef {\n\t/** The full space URI. */\n\turi: string;\n\t/** The space authority DID. */\n\tauthority: string;\n\t/** The space type NSID. */\n\ttype: string;\n\t/** The space key (record-key syntax). */\n\tskey: string;\n}\n\n/**\n * Parse a space URI. Returns null when the string is not a valid space\n * reference.\n */\nexport function parseSpaceUri(uri: string): SpaceRef | null {\n\tif (!uri.startsWith(SPACE_URI_PREFIX)) return null;\n\tconst parts = uri.slice(SPACE_URI_PREFIX.length).split(\"/\");\n\tif (parts.length !== 3) return null;\n\tconst [authority, type, skey] = parts as [string, string, string];\n\tif (!isDid(authority) || !isNsid(type) || !isRecordKey(skey)) return null;\n\tconst ref = {\n\t\turi: formatSpaceUri(authority, type, skey),\n\t\tauthority,\n\t\ttype,\n\t\tskey,\n\t};\n\t// Round-trip requirement mirrors the reference's SpaceRef.parse.\n\tif (ref.uri !== uri) return null;\n\treturn ref;\n}\n\n/**\n * Parse a space URI or throw. The error is XRPC's generic InvalidRequest, as\n * the reference answers: no lexicon declares a more specific one.\n */\nexport function requireSpaceUri(uri: string | undefined): SpaceRef {\n\tconst ref = uri ? parseSpaceUri(uri) : null;\n\tif (!ref) {\n\t\tthrow new SpaceError(\"InvalidRequest\", `Invalid space URI: ${uri}`);\n\t}\n\treturn ref;\n}\n\nexport function formatSpaceUri(\n\tauthority: string,\n\ttype: string,\n\tskey: string,\n): string {\n\treturn `${SPACE_URI_PREFIX}${authority}/${type}/${skey}`;\n}\n\n/** URI of a record within a space: `{spaceUri}/{repoDid}/{collection}/{rkey}`. */\nexport function spaceRecordUri(\n\tspaceUri: string,\n\trepo: string,\n\tcollection: string,\n\trkey: string,\n): string {\n\treturn `${spaceUri}/${repo}/${collection}/${rkey}`;\n}\n\nconst BASE32_ALPHABET = \"abcdefghijklmnopqrstuvwxyz234567\";\n\n/**\n * Stable identifier for a space used in R2 key prefixes: the lowercase,\n * unpadded base32 encoding of the SHA-256 of the space URI. Deterministic,\n * filesystem-safe and free of the URI's slashes and colons.\n */\nexport async function spaceId(spaceUri: string): Promise<string> {\n\tconst digest = new Uint8Array(\n\t\tawait crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(spaceUri)),\n\t);\n\tlet out = \"\";\n\tlet bits = 0;\n\tlet value = 0;\n\tfor (const byte of digest) {\n\t\tvalue = (value << 8) | byte;\n\t\tbits += 8;\n\t\twhile (bits >= 5) {\n\t\t\tout += BASE32_ALPHABET[(value >>> (bits - 5)) & 31];\n\t\t\tbits -= 5;\n\t\t}\n\t}\n\tif (bits > 0) {\n\t\tout += BASE32_ALPHABET[(value << (5 - bits)) & 31];\n\t}\n\treturn out;\n}\n","/**\n * R2 key layout for space blobs.\n *\n * A blob referenced by a record in a space lives at\n * `${did}/space/${spaceId}/${cid}` and is served only by the\n * credential-gated `com.atproto.space.getBlob`. The same blob referenced\n * from two spaces is stored twice: per-space prefixes make space deletion\n * and full reset a prefix delete with no cross-space reference counting.\n */\n\nimport { spaceId } from \"./space-uri.js\";\n\n/**\n * Key for a staged (uploaded, not yet referenced) blob. Must match the\n * host's public blob layout: uploads land here and are promoted to their\n * serving key when a record write references them.\n */\nexport function stagedBlobKey(did: string, cid: string): string {\n\treturn `${did}/staged/${cid}`;\n}\n\n/** Prefix holding every space blob for the account. */\nexport function spaceBlobRootPrefix(did: string): string {\n\treturn `${did}/space/`;\n}\n\n/** Prefix holding one space's blobs. `id` comes from {@link spaceId}. */\nexport function spaceBlobPrefix(did: string, id: string): string {\n\treturn `${did}/space/${id}/`;\n}\n\n/** Key for one blob in one space. */\nexport function spaceBlobKey(did: string, id: string, cid: string): string {\n\treturn `${did}/space/${id}/${cid}`;\n}\n\n/** Convenience: key for a blob given the space URI rather than its id. */\nexport async function spaceBlobKeyForUri(\n\tdid: string,\n\tspaceUri: string,\n\tcid: string,\n): Promise<string> {\n\treturn spaceBlobKey(did, await spaceId(spaceUri), cid);\n}\n\n/**\n * Copy a staged upload into a space's blob prefix. Idempotent; returns\n * whether the blob is now at its destination (false when it was neither\n * there nor staged).\n */\nexport async function promoteStagedBlobToSpace(\n\tbucket: R2Bucket,\n\tdid: string,\n\tspaceUri: string,\n\tcid: string,\n): Promise<boolean> {\n\tconst destKey = await spaceBlobKeyForUri(did, spaceUri, cid);\n\tif (await bucket.head(destKey)) return true;\n\tconst staged = await bucket.get(stagedBlobKey(did, cid));\n\tif (!staged) return false;\n\tawait bucket.put(destKey, staged.body, { httpMetadata: staged.httpMetadata });\n\treturn true;\n}\n\n/**\n * Promote a freshly uploaded blob into every space whose imported records\n * reference it (see `com.atproto.space.importRepo`). The host calls this\n * from `com.atproto.repo.uploadBlob`, mirroring how an imported public repo's\n * blobs are made permanent on upload.\n */\nexport async function promotePendingSpaceBlob(params: {\n\tbucket: R2Bucket;\n\tdid: string;\n\tcid: string;\n\tclaimPendingBlob: (cid: string) => Promise<string[]>;\n}): Promise<number> {\n\tconst uris = await params.claimPendingBlob(params.cid);\n\tfor (const uri of uris) {\n\t\tawait promoteStagedBlobToSpace(params.bucket, params.did, uri, params.cid);\n\t}\n\treturn uris.length;\n}\n","/**\n * Worker-side verification of space credentials and delegation tokens.\n *\n * A space credential is presented as `Authorization: Atproto-Space-Credential\n * <jwt>` (scheme case-insensitive), with an `Atproto-Space-Audience` header\n * naming the service being called and an HTTP message signature over both,\n * by the P-256 key the credential is bound to (`cnf.kid`). A delegation\n * token arrives in the `getSpaceCredential` request body.\n *\n * Everything here is stateless except the revocation and replay checks,\n * which are one RPC each to the space DO. Key resolution goes through the\n * host's DID resolver with a forced refresh on signature failure (handled\n * inside `verifySpaceToken`) so key rotation doesn't strand callers.\n */\n\nimport {\n\tSpaceSignatureError,\n\tSpaceTokenError,\n\tspaceHostAud,\n\tverifyCredentialSig,\n\tverifySpaceToken,\n} from \"@atproto/space\";\nimport { SpaceError } from \"./errors.js\";\nimport type { SpaceErrorCode } from \"./errors.js\";\nimport { parseSpaceUri } from \"./space-uri.js\";\nimport type { SpaceRef } from \"./space-uri.js\";\n\n/** Resolve an issuer DID's `#atproto` key to a did:key string. */\nexport type GetSigningKey = (\n\tiss: string,\n\tforceRefresh: boolean,\n) => Promise<string>;\n\n/** Record a single-use key; false when it was already seen. */\nexport type CheckReplay = (\n\tkind: string,\n\tkey: string,\n\texpiresAtSec: number,\n) => Promise<boolean>;\n\n/** Whether a credential has been revoked by the space's authority. */\nexport type CheckRevoked = (jti: string) => Promise<boolean>;\n\nexport const SPACE_CREDENTIAL_SCHEME = \"Atproto-Space-Credential\";\nexport const SPACE_AUDIENCE_HEADER = \"atproto-space-audience\";\n\n/**\n * Split an Authorization header into scheme and token. The scheme is\n * case-insensitive, as for every HTTP authentication scheme.\n */\nfunction splitAuthorization(\n\tauthorization: string | undefined,\n): { scheme: string; token: string } | null {\n\tif (!authorization) return null;\n\tconst parts = authorization.split(\" \");\n\tif (parts.length !== 2 || !parts[0] || !parts[1]) return null;\n\treturn { scheme: parts[0].toLowerCase(), token: parts[1] };\n}\n\n/** Whether an Authorization header carries a space credential. */\nexport function isSpaceCredentialAuth(\n\tauthorization: string | undefined,\n): boolean {\n\treturn (\n\t\tsplitAuthorization(authorization)?.scheme ===\n\t\tSPACE_CREDENTIAL_SCHEME.toLowerCase()\n\t);\n}\n\nexport interface VerifyCredentialOpts {\n\t/** Request headers, lower-cased names. */\n\theaders: Record<string, string | undefined>;\n\t/**\n\t * The DID this request is addressed to: the repo DID for repo-host\n\t * reads, the authority DID for space-host methods. The signed\n\t * `Atproto-Space-Audience` header must name it.\n\t */\n\taudience: string;\n\tgetSigningKey: GetSigningKey;\n\tcheckRevoked: CheckRevoked;\n}\n\nexport interface SpaceCredentialResult {\n\tkind: \"credential\";\n\t/** The credential issuer: the space's authority DID. */\n\tiss: string;\n\tjti: string;\n}\n\n/**\n * Verify a space credential presented against `space`: the token itself\n * (type, signature against the issuer's `#atproto` key, expiry, lifetime),\n * its issuer being the space's authority and its subject the space, the\n * HTTP message signature by its bound key over the credential and the\n * audience, the audience naming this service, and revocation.\n */\nexport async function verifySpaceCredentialAuth(\n\tspace: SpaceRef,\n\topts: VerifyCredentialOpts,\n): Promise<SpaceCredentialResult> {\n\tconst authorization = splitAuthorization(opts.headers.authorization);\n\tif (\n\t\t!authorization ||\n\t\tauthorization.scheme !== SPACE_CREDENTIAL_SCHEME.toLowerCase()\n\t) {\n\t\tthrow new SpaceError(\"MissingJwt\", \"Missing space credential\");\n\t}\n\n\tlet payload;\n\ttry {\n\t\t({ payload } = await verifySpaceToken(\"credential\", authorization.token, {\n\t\t\tgetSigningKey: opts.getSigningKey,\n\t\t}));\n\t} catch (err) {\n\t\tthrow tokenError(err, \"BadJwt\");\n\t}\n\tconst subject = parseSpaceUri(payload.sub);\n\tif (!subject) {\n\t\tthrow new SpaceError(\n\t\t\t\"BadJwtSub\",\n\t\t\t`Space token subject is not a space URI: ${payload.sub}`,\n\t\t);\n\t}\n\tif (payload.iss !== subject.authority) {\n\t\tthrow new SpaceError(\n\t\t\t\"BadJwtIss\",\n\t\t\t\"Space credential issuer is not the space authority\",\n\t\t);\n\t}\n\n\tconst audience = opts.headers[SPACE_AUDIENCE_HEADER];\n\tif (!audience?.startsWith(\"did:\")) {\n\t\tthrow new SpaceError(\n\t\t\t\"BadSpaceSignature\",\n\t\t\t\"Missing or invalid space audience DID\",\n\t\t);\n\t}\n\ttry {\n\t\tawait verifyCredentialSig(opts.headers, payload.cnf.kid);\n\t} catch (err) {\n\t\tif (err instanceof SpaceSignatureError) {\n\t\t\tthrow new SpaceError(\"BadSpaceSignature\", err.message);\n\t\t}\n\t\tthrow err;\n\t}\n\tif (audience !== opts.audience) {\n\t\tthrow new SpaceError(\n\t\t\t\"BadSpaceAudience\",\n\t\t\t\"Space audience does not match the request\",\n\t\t);\n\t}\n\tif (payload.sub !== space.uri) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidCredential\",\n\t\t\t\"Credential is not scoped to this space\",\n\t\t);\n\t}\n\tif (await opts.checkRevoked(payload.jti)) {\n\t\tthrow new SpaceError(\n\t\t\t\"CredentialRevoked\",\n\t\t\t\"Space credential has been revoked\",\n\t\t);\n\t}\n\treturn { kind: \"credential\", iss: payload.iss, jti: payload.jti };\n}\n\nexport interface DelegationResult {\n\t/** The user the delegation token vouches for. */\n\tuserDid: string;\n}\n\n/**\n * Verify a delegation token from a `getSpaceCredential` body: signature\n * against the issuer's `#atproto` key, audience the space authority's\n * `#atproto_pds`, subject the requested space, single use by `(iss, jti)`.\n * Any failure is `InvalidDelegationToken`: the token arrives in the body\n * rather than as the request's authorization, so it is an invalid request,\n * not an authentication failure.\n */\nexport async function verifyDelegationToken(\n\ttoken: string,\n\tspace: SpaceRef,\n\topts: { getSigningKey: GetSigningKey; checkReplay: CheckReplay },\n): Promise<DelegationResult> {\n\tlet payload;\n\ttry {\n\t\t({ payload } = await verifySpaceToken(\"delegation\", token, {\n\t\t\tgetSigningKey: opts.getSigningKey,\n\t\t}));\n\t} catch (err) {\n\t\tthrow tokenError(err, \"InvalidDelegationToken\", \"InvalidDelegationToken\");\n\t}\n\tif (payload.sub !== space.uri) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidDelegationToken\",\n\t\t\t\"Delegation token subject does not match requested space\",\n\t\t);\n\t}\n\tif (\n\t\tpayload.aud !== spaceHostAud(space.authority as `did:${string}:${string}`)\n\t) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidDelegationToken\",\n\t\t\t\"Delegation token audience does not match the space authority\",\n\t\t);\n\t}\n\tif (!payload.iss.startsWith(\"did:\")) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidDelegationToken\",\n\t\t\t\"Delegation token issuer is not a DID\",\n\t\t);\n\t}\n\tconst fresh = await opts.checkReplay(\n\t\t\"delegation\",\n\t\t`${payload.iss}:${payload.jti}`,\n\t\tpayload.exp,\n\t);\n\tif (!fresh) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidDelegationToken\",\n\t\t\t\"Delegation token has already been used\",\n\t\t);\n\t}\n\treturn { userDid: payload.iss };\n}\n\nfunction tokenError(\n\terr: unknown,\n\tfallback: SpaceErrorCode,\n\toverride?: SpaceErrorCode,\n): SpaceError {\n\t// Server-side detail for operators; clients get the token library's\n\t// message, never infrastructure internals.\n\tconsole.warn(\"space token verification failed:\", err);\n\tif (err instanceof SpaceTokenError) {\n\t\treturn new SpaceError(override ?? err.code, err.message);\n\t}\n\t// DID resolution failures and other infrastructure errors must surface\n\t// as auth errors, never 500s.\n\treturn new SpaceError(override ?? fallback, \"Token verification failed\");\n}\n","/**\n * Client attestation verification (app-identity gating, `allowList` app\n * access). The attestation is a short-lived JWT signed by the OAuth\n * client's published JWKS key, with `iss` = `sub` = client_id and `aud`\n * the space host. Verified against the client's `client-metadata.json`.\n *\n * The client_id in the payload is attacker-controlled until the signature\n * verifies, so nothing is fetched before it has been validated as an\n * https client-metadata URL and checked against the caller's allow-list —\n * a space gated on an allow-list never performs network I/O for a client\n * that could not be authorized anyway. All fetches are bounded by a\n * timeout.\n */\n\nimport { createLocalJWKSet, jwtVerify } from \"jose\";\nimport { CLIENT_ATTESTATION_TYP, parseSpaceToken } from \"@atproto/space\";\nimport { SpaceError } from \"./errors.js\";\nimport type { CheckReplay } from \"./auth.js\";\n\n/** Upper bound for each outbound metadata/JWKS fetch. */\nconst FETCH_TIMEOUT_MS = 5000;\n\nexport interface VerifyAttestationOpts {\n\t/** Expected audience: `spaceHostAud(authorityDid)`. */\n\texpectedAud: string;\n\t/**\n\t * When set, an (unverified) client_id outside this list is rejected\n\t * before any network I/O. The membership check runs regardless of\n\t * signature state because the caller re-derives authorization from the\n\t * returned client_id after full verification.\n\t */\n\tallowedClientIds?: readonly string[];\n\tcheckReplay: CheckReplay;\n\t/** Fetch override for tests. */\n\tfetch?: typeof fetch;\n}\n\n/**\n * Verify a client attestation and return the attested client_id.\n * Single-use by `(clientId, jti)`.\n */\nexport async function verifyClientAttestation(\n\tattestation: string,\n\topts: VerifyAttestationOpts,\n): Promise<string> {\n\tlet parsed;\n\ttry {\n\t\tparsed = parseSpaceToken(\"clientAttestation\", attestation);\n\t} catch (err) {\n\t\tthrow invalid(err);\n\t}\n\tconst clientId = parsed.payload.iss;\n\tif (parsed.payload.aud !== opts.expectedAud) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidClientAttestation\",\n\t\t\t\"Attestation audience does not match this space host\",\n\t\t);\n\t}\n\n\t// Everything below this point costs network I/O, so gate on what can be\n\t// decided statically first: the client_id must be a plausible https\n\t// client-metadata URL, and must be one the space could authorize at all.\n\tlet clientUrl: URL;\n\ttry {\n\t\tclientUrl = new URL(clientId);\n\t} catch {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidClientAttestation\",\n\t\t\t\"Attestation client_id is not a URL\",\n\t\t);\n\t}\n\tif (\n\t\tclientUrl.protocol !== \"https:\" ||\n\t\tclientUrl.username ||\n\t\tclientUrl.password\n\t) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidClientAttestation\",\n\t\t\t\"Attestation client_id must be a plain https URL\",\n\t\t);\n\t}\n\tif (opts.allowedClientIds && !opts.allowedClientIds.includes(clientId)) {\n\t\tthrow new SpaceError(\n\t\t\t\"AppNotAuthorized\",\n\t\t\t\"App is not authorized for this space\",\n\t\t);\n\t}\n\n\tconst doFetch = opts.fetch ?? fetch;\n\tconst boundedJson = async (url: string): Promise<unknown> => {\n\t\tconst res = await doFetch(url, {\n\t\t\theaders: { Accept: \"application/json\" },\n\t\t\tsignal: AbortSignal.timeout(FETCH_TIMEOUT_MS),\n\t\t\t// No redirects. Not \"error\": workerd refuses it outright, so every\n\t\t\t// fetch would throw. A 3xx under \"manual\" fails the ok check.\n\t\t\tredirect: \"manual\",\n\t\t});\n\t\tif (!res.ok) {\n\t\t\tthrow new Error(`fetch of ${url} returned ${res.status}`);\n\t\t}\n\t\treturn res.json();\n\t};\n\n\tlet metadata: { jwks?: unknown; jwks_uri?: string };\n\ttry {\n\t\tmetadata = (await boundedJson(clientId)) as typeof metadata;\n\t} catch {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidClientAttestation\",\n\t\t\t\"Could not resolve client metadata\",\n\t\t);\n\t}\n\n\tlet jwks = metadata.jwks;\n\tif (!jwks && typeof metadata.jwks_uri === \"string\") {\n\t\tlet jwksUrl: URL;\n\t\ttry {\n\t\t\tjwksUrl = new URL(metadata.jwks_uri);\n\t\t} catch {\n\t\t\tjwksUrl = null as never;\n\t\t}\n\t\tif (!jwksUrl || jwksUrl.protocol !== \"https:\") {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"InvalidClientAttestation\",\n\t\t\t\t\"Client metadata jwks_uri must be an https URL\",\n\t\t\t);\n\t\t}\n\t\ttry {\n\t\t\tjwks = await boundedJson(metadata.jwks_uri);\n\t\t} catch {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"InvalidClientAttestation\",\n\t\t\t\t\"Could not resolve client JWKS\",\n\t\t\t);\n\t\t}\n\t}\n\tif (!jwks) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidClientAttestation\",\n\t\t\t\"Client metadata declares no JWKS\",\n\t\t);\n\t}\n\n\ttry {\n\t\tconst keySet = createLocalJWKSet(\n\t\t\tjwks as Parameters<typeof createLocalJWKSet>[0],\n\t\t);\n\t\tawait jwtVerify(attestation, keySet, {\n\t\t\tissuer: clientId,\n\t\t\tsubject: clientId,\n\t\t\taudience: opts.expectedAud,\n\t\t\ttyp: CLIENT_ATTESTATION_TYP,\n\t\t\trequiredClaims: [\"jti\", \"exp\"],\n\t\t\tclockTolerance: 5,\n\t\t});\n\t} catch (err) {\n\t\tthrow invalid(err);\n\t}\n\n\tconst fresh = await opts.checkReplay(\n\t\t\"attestation\",\n\t\t`${clientId}:${parsed.payload.jti}`,\n\t\tparsed.payload.exp,\n\t);\n\tif (!fresh) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidClientAttestation\",\n\t\t\t\"Client attestation has already been used\",\n\t\t);\n\t}\n\treturn clientId;\n}\n\nfunction invalid(err: unknown): SpaceError {\n\treturn new SpaceError(\n\t\t\"InvalidClientAttestation\",\n\t\terr instanceof Error ? err.message : \"Invalid client attestation\",\n\t);\n}\n","/**\n * Hono route factory for `com.atproto.space.*` and\n * `com.atproto.memberspace.*`.\n *\n * The factory is host-agnostic: everything account-specific — session\n * authentication, DID resolution, record validation, the operator identity\n * and its keys — arrives through {@link SpaceRoutesHost}. The host mounts\n * the returned app behind its feature flag.\n */\n\nimport { Hono } from \"hono\";\nimport type { Context } from \"hono\";\nimport {\n\tcreateSpaceCredential,\n\tisP256DidKey,\n\tparseSpaceToken,\n\treadRepoStar,\n\treadSpaceMetaStar,\n\tspaceHostAud,\n\twriteRepoStar,\n\twriteSpaceMetaStar,\n} from \"@atproto/space\";\nimport type { P256Keypair } from \"@atproto/crypto\";\nimport { encode } from \"@atproto/lex-cbor\";\nimport {\n\tcidForCbor,\n\tenumBlobRefs,\n\tfromBase64,\n\tgetBlobCidString,\n} from \"@atproto/lex-data\";\nimport type { LexValue } from \"@atproto/lex-data\";\nimport { now as tidNow } from \"@atcute/tid\";\nimport { isDid } from \"@atcute/lexicons/syntax\";\nimport {\n\tisSpaceCredentialAuth,\n\tverifyDelegationToken,\n\tverifySpaceCredentialAuth,\n\ttype GetSigningKey,\n} from \"./auth.js\";\nimport { verifyClientAttestation } from \"./attestation.js\";\nimport {\n\tCOMMIT_MAC_PROFILE,\n\tMAC_REQUEST_HEADER,\n\tRECORD_MAC_PROFILE,\n\tbuildCommit,\n\tbytesToJson,\n\tcommitMacHeaders,\n\tcommitToJson,\n\timportKemKeypair,\n\tmacExposedHeaders,\n\tmacRequest,\n\trecordMacHeaders,\n\ttype MacParams,\n\ttype MacProfile,\n} from \"./mac.js\";\nimport { SpaceError, parseSpaceErrorCode, spaceErrorStatus } from \"./errors.js\";\nimport {\n\tMEMBER_COLLECTION,\n\tPUBLISHED_COLLECTIONS,\n\tassertNotPublishedCollection,\n\tdidToRecordKey,\n\tisAppAuthorized,\n\tisPublicRead,\n\tnormalizePolicy,\n\trecordKeyToDid,\n} from \"./policy.js\";\nimport { prepareRecord, recordBytesToJson } from \"./records.js\";\nimport {\n\tMAX_NOTIFY_TOKEN_LENGTH,\n\tMAX_REV_CLOCK_SKEW_MS,\n\tMAX_SPACE_RECORD_BYTES,\n\tNOTIFY_BACKOFF_BASE_MS,\n\tNOTIFY_WRITE_RETRY_MS,\n} from \"./schema.js\";\nimport { createServiceJwt } from \"./service-jwt.js\";\nimport {\n\tpromoteStagedBlobToSpace,\n\tspaceBlobKey,\n\tspaceBlobPrefix,\n} from \"./blob-keys.js\";\nimport {\n\tformatSpaceUri,\n\tparseSpaceUri,\n\trequireSpaceUri,\n\tspaceId,\n\tspaceRecordUri,\n} from \"./space-uri.js\";\nimport type { SpaceRef } from \"./space-uri.js\";\nimport { isRetryableStatus } from \"./space-do.js\";\nimport type { SpaceDurableObject } from \"./space-do.js\";\nimport type { SpaceIndexDurableObject } from \"./index-do.js\";\nimport { tidTimestampMs } from \"./tid.js\";\nimport {\n\tMANAGEDSPACE_POLICY,\n\tMEMBERSPACE_POLICY,\n\tPERSONALSPACE_POLICY,\n\ttype ImportedRecord,\n\ttype NotifyItem,\n\ttype NotifyRegistration,\n\ttype PreparedSpaceWrite,\n\ttype RepoCommitResult,\n\ttype SpaceMember,\n\ttype SpacePolicy,\n\ttype SpaceSigningKeypair,\n} from \"./types.js\";\n\nconst NOTIFY_REPO_UPDATE_LXM = \"com.atproto.space.notifyRepoUpdate\";\nconst CREDENTIALS_REVOKED_LXM = \"com.atproto.space.notifyCredentialsRevoked\";\nconst CONFIRM_REGISTRATION_LXM = \"com.atproto.space.confirmRegistration\";\nconst CHECK_ACCESS_LXM = \"com.atproto.managedspace.checkAccess\";\n/** A managing app or syncer endpoint that doesn't answer in this window fails. */\nconst UPSTREAM_TIMEOUT_MS = 10_000;\n/** The queue key for this repo's pending update notification to a foreign authority. */\nconst NOTIFY_REPO_UPDATE_COALESCE_KEY = \"notifyRepoUpdate:authority\";\n/** Upper bound on archives accepted by importRepo / importSpaceMeta. */\nconst MAX_IMPORT_BYTES = 100 * 1024 * 1024;\n/** Revocations are held until any credential they name has expired. */\nconst REVOCATION_TTL_SEC = 3600 + 2 * 5;\n/** The media type of STAR archives (repos and space meta). */\nconst STAR_CONTENT_TYPE = \"application/vnd.dasl.star\";\n/** Batched member changes take at most this many entries. */\nconst MAX_MEMBER_BATCH = 100;\n\nexport type SpaceStub = DurableObjectStub<SpaceDurableObject>;\nexport type SpaceIndexStub = DurableObjectStub<SpaceIndexDurableObject>;\n\n/** The operation shapes checked against a session's `space:` grants. */\nexport type SpaceScopeMatch = {\n\ttype: string;\n\tauthority: string;\n\tskey: string;\n} & (\n\t| { action: \"read\" | \"read_self\" }\n\t| { action: \"create\" | \"update\" | \"delete\"; collection: string }\n\t| { manage: \"create\" | \"update\" | \"delete\" }\n);\n\n/**\n * The narrowest `space:` scope that covers an operation, written as\n * `@atproto/oauth-scopes` writes it (`SpacePermission.scopeNeededFor`), so a\n * refusal can tell the app what to ask for. A manage op adds the narrowest\n * action, `read_self`, since a scope with no action defaults to all of them.\n */\nexport function spaceScopeNeededFor(match: SpaceScopeMatch): string {\n\tconst scope = `space:${match.type}?authority=${match.authority}&skey=${match.skey}`;\n\tif (\"manage\" in match) {\n\t\treturn `${scope}&action=read_self&manage=${match.manage}`;\n\t}\n\tif (\"collection\" in match) {\n\t\treturn `${scope}&collection=${match.collection}&action=${match.action}`;\n\t}\n\treturn `${scope}&action=${match.action}`;\n}\n\n/**\n * A host session (OAuth token with `space:` grants, or a fully-trusted\n * operator session). App passwords are excluded in the alpha — the host's\n * authenticate() must not produce one of these for them.\n */\nexport interface SpaceSessionAuth {\n\tdid: string;\n\t/** Fully-trusted operator session: skips scope checks. */\n\tfullTrust: boolean;\n\tallowsSpace(match: SpaceScopeMatch): boolean;\n}\n\nexport interface SpaceRoutesHost {\n\toperatorDid: string;\n\t/** R2 bucket for blobs; space blob endpoints 503 without it. */\n\tblobs?: R2Bucket;\n\t/** The account's `#atproto` keypair: space tokens and service auth. */\n\tgetKeypair(): Promise<SpaceSigningKeypair>;\n\t/**\n\t * The account's `#atproto_kem` P-256 private key (hex), which MACs space\n\t * data for syncers. Null when unconfigured: reads that owe a MAC then\n\t * answer KemKeyUnavailable.\n\t */\n\tgetKemPrivateKey(): string | null | Promise<string | null>;\n\t/** DID-doc `#atproto` key resolution for foreign issuers. */\n\tgetSigningKey: GetSigningKey;\n\t/**\n\t * Resolve a service identifier to an HTTPS endpoint: `did#fragment`\n\t * names that service entry, a bare DID its `#atproto_pds`. Null when\n\t * unresolvable.\n\t */\n\tresolveServiceEndpoint(service: string): Promise<string | null>;\n\t/** Verify an inbound service-auth JWT bound to `lxm`. */\n\tverifyServiceJwt(\n\t\ttoken: string,\n\t\tlxm: string,\n\t): Promise<{ iss: string; aud: string }>;\n\t/**\n\t * Host session authentication (OAuth / operator sessions). Returns a\n\t * Response for authentication failures.\n\t */\n\tauthenticate(c: Context): Promise<SpaceSessionAuth | Response>;\n\t/**\n\t * Whether the operator's account is active. A deactivated authority\n\t * issues no credentials and lists no repos. Treated as active when\n\t * absent.\n\t */\n\tisAccountActive?(): Promise<boolean>;\n\t/**\n\t * Lexicon validation with the host's validator. Throws on invalid\n\t * records; the thrown message is surfaced as an InvalidRecord error.\n\t */\n\tvalidateRecord(input: {\n\t\tcollection: string;\n\t\trecord: unknown;\n\t\trkey: string;\n\t\tvalidate?: boolean;\n\t}): { record: unknown; status?: \"valid\" | \"unknown\" };\n\tgetSpaceDO(uri: string): SpaceStub;\n\tgetIndexDO(): SpaceIndexStub;\n\t/** Fetch override for outbound calls (tests). */\n\toutboundFetch?: typeof fetch;\n}\n\n// ---------------------------------------------------------------------\n// Shared helpers\n// ---------------------------------------------------------------------\n\nfunction errorResponse(c: Context, err: unknown): Response {\n\tconst parsed = parseSpaceErrorCode(err);\n\tif (parsed) {\n\t\treturn c.json(\n\t\t\t{ error: parsed.code, message: parsed.message },\n\t\t\tspaceErrorStatus(parsed.code) as 400,\n\t\t);\n\t}\n\tthrow err;\n}\n\nfunction waitUntil(c: Context, promise: Promise<unknown>): void {\n\ttry {\n\t\tc.executionCtx.waitUntil(promise);\n\t} catch {\n\t\t// No execution context (tests): let it float.\n\t\tvoid promise.catch((err) => console.warn(\"background task failed\", err));\n\t}\n}\n\n/** Request headers as a plain object with lower-cased names. */\nfunction headerRecord(c: Context): Record<string, string | undefined> {\n\treturn Object.fromEntries(c.req.raw.headers);\n}\n\n/** Append to a comma-separated response header without clobbering it. */\nfunction appendHeader(c: Context, name: string, value: string): void {\n\tc.header(name, value, { append: true });\n}\n\ninterface AuthedRead {\n\tkind: \"credential\" | \"session\";\n}\n\ntype ScopeResult = Response | null;\n\nexport function createSpaceRoutes(host: SpaceRoutesHost): Hono {\n\tconst app = new Hono();\n\t// Looked up per call rather than bound here, so a host's tests can stub\n\t// the global fetch after the routes are built.\n\tconst doFetch: typeof fetch =\n\t\thost.outboundFetch ?? ((input, init) => globalThis.fetch(input, init));\n\n\tlet kemKeypair: Promise<P256Keypair | null> | null = null;\n\tfunction getKemKeypair(): Promise<P256Keypair | null> {\n\t\tkemKeypair ??= Promise.resolve(host.getKemPrivateKey()).then((hex) =>\n\t\t\thex ? importKemKeypair(hex) : null,\n\t\t);\n\t\treturn kemKeypair;\n\t}\n\n\t/** The `repo` param on every repo-host method must be the operator DID. */\n\tfunction requireRepoParam(repo: unknown): void {\n\t\tif (repo !== host.operatorDid) {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"RepoNotFound\",\n\t\t\t\t`Repository not found: ${String(repo)}`,\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Verify a space credential addressed to this host. Every audience is\n\t * the operator DID: Cirrus serves only the operator's repos, and hosts\n\t * only spaces under the operator's authority.\n\t */\n\tasync function credentialAuth(c: Context, ref: SpaceRef): Promise<void> {\n\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\tawait verifySpaceCredentialAuth(ref, {\n\t\t\theaders: headerRecord(c),\n\t\t\taudience: host.operatorDid,\n\t\t\tgetSigningKey: host.getSigningKey,\n\t\t\tcheckRevoked: (jti) => stub.rpcIsCredentialRevoked(jti),\n\t\t});\n\t}\n\n\t/**\n\t * Authenticate a read: a space credential for the requested space, or a\n\t * host session covering `read_self` on it. The `repo` param on every\n\t * repo-host method must be the operator DID — anything else is\n\t * RepoNotFound, deliberately indistinguishable from an absent repo.\n\t */\n\tasync function readAuth(\n\t\tc: Context,\n\t\tref: SpaceRef,\n\t\trepo: string | undefined,\n\t): Promise<AuthedRead | Response> {\n\t\trequireRepoParam(repo);\n\t\tif (isSpaceCredentialAuth(c.req.header(\"Authorization\"))) {\n\t\t\tawait credentialAuth(c, ref);\n\t\t\treturn { kind: \"credential\" };\n\t\t}\n\t\tconst session = await host.authenticate(c);\n\t\tif (session instanceof Response) return session;\n\t\tconst scopeError = assertScope(c, session, {\n\t\t\ttype: ref.type,\n\t\t\tauthority: ref.authority,\n\t\t\tskey: ref.skey,\n\t\t\taction: \"read_self\",\n\t\t});\n\t\tif (scopeError) return scopeError;\n\t\treturn { kind: \"session\" };\n\t}\n\n\t/**\n\t * The MAC owed by a read that returns a commit or record, with the\n\t * response headers a browser syncer needs to read the MAC.\n\t */\n\tasync function readMac(\n\t\tc: Context,\n\t\tauth: AuthedRead,\n\t\tprofile: MacProfile,\n\t): Promise<MacParams | undefined> {\n\t\tappendHeader(c, \"Vary\", \"Accept-Signature\");\n\t\tconst mac = await macRequest({\n\t\t\tacceptSignature: c.req.header(MAC_REQUEST_HEADER),\n\t\t\tcredential: auth.kind === \"credential\",\n\t\t\tprofile,\n\t\t\tgetKemKeypair,\n\t\t});\n\t\tif (mac) {\n\t\t\tfor (const header of macExposedHeaders(profile)) {\n\t\t\t\tappendHeader(c, \"Access-Control-Expose-Headers\", header);\n\t\t\t}\n\t\t}\n\t\treturn mac;\n\t}\n\n\tfunction assertScope(\n\t\tc: Context,\n\t\tsession: SpaceSessionAuth,\n\t\tmatch: SpaceScopeMatch,\n\t): ScopeResult {\n\t\tif (session.fullTrust) return null;\n\t\tif (session.allowsSpace(match)) return null;\n\t\treturn c.json(\n\t\t\t{\n\t\t\t\terror: \"InsufficientScope\",\n\t\t\t\tmessage: `Missing required scope: ${spaceScopeNeededFor(match)}`,\n\t\t\t},\n\t\t\t403,\n\t\t);\n\t}\n\n\t/** The operator hosts this space, or SpaceNotFound. */\n\tfunction assertSpaceHost(ref: SpaceRef): void {\n\t\tif (ref.authority !== host.operatorDid) {\n\t\t\tthrow new SpaceError(\"SpaceNotFound\", `Space not found: ${ref.uri}`);\n\t\t}\n\t}\n\n\t/** As assertSpaceHost, and the authority's account must be active. */\n\tasync function assertActiveSpaceHost(ref: SpaceRef): Promise<void> {\n\t\tassertSpaceHost(ref);\n\t\tif (host.isAccountActive && !(await host.isAccountActive())) {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"RepoDeactivated\",\n\t\t\t\t`Repo has been deactivated: ${ref.authority}`,\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * A space created here is anchored on its creator's DID, so ownership\n\t * is a comparison against the space URI, made before anything else.\n\t */\n\tfunction assertOwner(ref: SpaceRef, session: SpaceSessionAuth): void {\n\t\tif (session.did !== ref.authority) {\n\t\t\tthrow new SpaceError(\"NotAuthorized\", \"Not the space authority\");\n\t\t}\n\t\tassertSpaceHost(ref);\n\t}\n\n\t/** The policy of a live space this host governs. */\n\tasync function requirePolicy(\n\t\tstub: SpaceStub,\n\t\tref: SpaceRef,\n\t): Promise<SpacePolicy> {\n\t\tconst { meta, policy } = await stub.rpcGetAuthorityState();\n\t\tif (!meta || meta.deletedAt || !policy) {\n\t\t\tthrow new SpaceError(\"SpaceNotFound\", `Space not found: ${ref.uri}`);\n\t\t}\n\t\treturn policy;\n\t}\n\n\t/**\n\t * Whether a policy authorises an account to read or write. `repo` is\n\t * absent for a read with no delegation token, which a policy authorises\n\t * only if it does not gate on the account. The authority always passes\n\t * under every policy: it alone can reconfigure the space, so it must not\n\t * be able to lock itself out.\n\t *\n\t * A managing app that can't be reached throws UpstreamFailure rather\n\t * than denying: denying would read as a loss of access, withdrawing a\n\t * syncer's registration and making a repo host drop its notification.\n\t */\n\tasync function authorizeRepo(params: {\n\t\tpolicy: SpacePolicy;\n\t\tref: SpaceRef;\n\t\trepo: string | undefined;\n\t\taccess: \"read\" | \"write\";\n\t\tclientId?: string;\n\t\tstub: SpaceStub;\n\t}): Promise<boolean> {\n\t\tconst { policy, ref, repo, access, clientId, stub } = params;\n\t\tif (repo === ref.authority) return true;\n\t\tswitch (policy.$type) {\n\t\t\tcase PERSONALSPACE_POLICY:\n\t\t\t\treturn false;\n\t\t\tcase MEMBERSPACE_POLICY: {\n\t\t\t\tif (access === \"read\" && policy.publicRead) return true;\n\t\t\t\tif (!repo) return false;\n\t\t\t\tconst member = await stub.rpcGetMember(repo);\n\t\t\t\tif (access === \"read\") return member?.read ?? false;\n\t\t\t\t// A member without write access stays excluded even under\n\t\t\t\t// publicWrite.\n\t\t\t\tif (member) return member.write;\n\t\t\t\treturn policy.publicWrite;\n\t\t\t}\n\t\t\tcase MANAGEDSPACE_POLICY:\n\t\t\t\treturn (await checkAccess(policy.managingApp, ref, repo, clientId))[\n\t\t\t\t\taccess\n\t\t\t\t];\n\t\t}\n\t}\n\n\t/** Ask a managed space's managing app for an account's access. */\n\tasync function checkAccess(\n\t\tmanagingApp: string,\n\t\tref: SpaceRef,\n\t\trepo: string | undefined,\n\t\tclientId: string | undefined,\n\t): Promise<{ read: boolean; write: boolean }> {\n\t\ttry {\n\t\t\tconst endpoint = await host.resolveServiceEndpoint(managingApp);\n\t\t\tif (!endpoint) throw new Error(\"could not resolve the managing app\");\n\t\t\tconst token = await createServiceJwt(\n\t\t\t\t{ iss: host.operatorDid, aud: managingApp, lxm: CHECK_ACCESS_LXM },\n\t\t\t\tawait host.getKeypair(),\n\t\t\t);\n\t\t\tconst url = new URL(`${endpoint}/xrpc/${CHECK_ACCESS_LXM}`);\n\t\t\turl.searchParams.set(\"space\", ref.uri);\n\t\t\tif (repo) url.searchParams.set(\"repo\", repo);\n\t\t\tif (clientId) url.searchParams.set(\"clientId\", clientId);\n\t\t\t// No redirects: the endpoint comes from a DID document, and a\n\t\t\t// 3xx answer is a failure like any other.\n\t\t\tconst res = await doFetch(url.toString(), {\n\t\t\t\theaders: { Authorization: `Bearer ${token}` },\n\t\t\t\tredirect: \"manual\",\n\t\t\t\tsignal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS),\n\t\t\t});\n\t\t\tif (!res.ok) throw new Error(`checkAccess answered ${res.status}`);\n\t\t\tconst body = (await res.json()) as { read?: unknown; write?: unknown };\n\t\t\tif (typeof body.read !== \"boolean\" || typeof body.write !== \"boolean\") {\n\t\t\t\tthrow new Error(\"checkAccess answered without read and write\");\n\t\t\t}\n\t\t\treturn { read: body.read, write: body.write };\n\t\t} catch (err) {\n\t\t\tconsole.warn(`managing app check for ${ref.uri} failed:`, err);\n\t\t\tthrow new SpaceError(\"UpstreamFailure\", \"Managing app did not answer\");\n\t\t}\n\t}\n\n\t/**\n\t * Ensure the space DO exists for a write. The first write into a foreign\n\t * space registers it `pending` in the index, initialises the DO as repo\n\t * host, then activates the entry. The operator's own spaces must already\n\t * exist: a write must neither conjure an ungoverned space nor revive a\n\t * deleted one.\n\t */\n\tasync function ensureSpaceForWrite(\n\t\tref: SpaceRef,\n\t\tstub: SpaceStub,\n\t): Promise<void> {\n\t\tconst meta = await stub.rpcGetMeta();\n\t\tif (meta && !meta.deletedAt) return;\n\t\tif (ref.authority === host.operatorDid) {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"SpaceNotFound\",\n\t\t\t\t`Space not found: ${ref.uri}. Create it with com.atproto.space.createSpace.`,\n\t\t\t);\n\t\t}\n\t\tconst index = host.getIndexDO();\n\t\tawait index.rpcRegister({\n\t\t\turi: ref.uri,\n\t\t\tauthority: ref.authority,\n\t\t\ttype: ref.type,\n\t\t\tskey: ref.skey,\n\t\t\tisAuthority: false,\n\t\t});\n\t\tawait stub.rpcInit({\n\t\t\turi: ref.uri,\n\t\t\tauthority: ref.authority,\n\t\t\ttype: ref.type,\n\t\t\tskey: ref.skey,\n\t\t\tisAuthority: false,\n\t\t});\n\t\tawait index.rpcActivate(ref.uri);\n\t}\n\n\t/**\n\t * Promote staged blobs to the space's R2 prefix. Runs before the DO\n\t * commit so nothing reacting to the commit sees a 404. Idempotent per\n\t * CID; CIDs that are neither staged nor at the destination are skipped.\n\t */\n\tasync function promoteSpaceBlobs(\n\t\tref: SpaceRef,\n\t\tblobCids: string[],\n\t): Promise<string[]> {\n\t\tconst missing: string[] = [];\n\t\tif (!host.blobs || blobCids.length === 0) return missing;\n\t\tawait Promise.all(\n\t\t\tblobCids.map(async (cid) => {\n\t\t\t\tconst present = await promoteStagedBlobToSpace(\n\t\t\t\t\thost.blobs!,\n\t\t\t\t\thost.operatorDid,\n\t\t\t\t\tref.uri,\n\t\t\t\t\tcid,\n\t\t\t\t);\n\t\t\t\tif (!present) missing.push(cid);\n\t\t\t}),\n\t\t);\n\t\treturn missing;\n\t}\n\n\t/**\n\t * After a commit: the authority sequences its own update into the writer\n\t * set, which queues it for registered syncers; a repo host in a foreign\n\t * space delivers its latest state to the authority, immediately,\n\t * persisting a retryable failure for the DO's alarm to retry for up to\n\t * 24 hours. Retries coalesce, so only the newest revision is pending.\n\t */\n\tasync function postWrite(\n\t\tref: SpaceRef,\n\t\tstub: SpaceStub,\n\t\tcommit: RepoCommitResult,\n\t): Promise<void> {\n\t\tif (ref.authority === host.operatorDid) {\n\t\t\tawait stub.rpcRecordWriter(host.operatorDid, commit.rev, commit.data);\n\t\t\treturn;\n\t\t}\n\t\tconst body = {\n\t\t\tspace: ref.uri,\n\t\t\trepo: host.operatorDid,\n\t\t\trepoRev: commit.rev,\n\t\t\tdata: bytesToJson(commit.data),\n\t\t};\n\t\tconst aud = spaceHostAud(ref.authority as `did:${string}:${string}`);\n\t\tconst endpoint = await host.resolveServiceEndpoint(aud).catch(() => null);\n\t\tif (!endpoint) {\n\t\t\tconsole.warn(`notifyRepoUpdate: no endpoint for ${ref.authority}`);\n\t\t\treturn;\n\t\t}\n\t\tconst retry: NotifyItem = {\n\t\t\tservice: aud,\n\t\t\tendpoint,\n\t\t\tlxm: NOTIFY_REPO_UPDATE_LXM,\n\t\t\tbody,\n\t\t\tcoalesceKey: NOTIFY_REPO_UPDATE_COALESCE_KEY,\n\t\t\tdeadline: Date.now() + NOTIFY_WRITE_RETRY_MS,\n\t\t\tpolicy: \"repo\",\n\t\t\tauth: \"service\",\n\t\t};\n\t\ttry {\n\t\t\tconst token = await createServiceJwt(\n\t\t\t\t{ iss: host.operatorDid, aud, lxm: NOTIFY_REPO_UPDATE_LXM },\n\t\t\t\tawait host.getKeypair(),\n\t\t\t);\n\t\t\tconst res = await doFetch(`${endpoint}/xrpc/${NOTIFY_REPO_UPDATE_LXM}`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\tAuthorization: `Bearer ${token}`,\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify(body),\n\t\t\t\t// Not re-POSTed elsewhere with service auth: a 3xx is refused.\n\t\t\t\tredirect: \"manual\",\n\t\t\t\tsignal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS),\n\t\t\t});\n\t\t\tif (res.ok || !isRetryableStatus(res.status)) {\n\t\t\t\tif (!res.ok) {\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`notifyRepoUpdate to ${ref.authority} refused: ${res.status}; not retrying`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tawait stub.rpcClearNotify(NOTIFY_REPO_UPDATE_COALESCE_KEY);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconsole.warn(\n\t\t\t\t`notifyRepoUpdate to ${ref.authority} failed: ${res.status}`,\n\t\t\t);\n\t\t} catch (err) {\n\t\t\tconsole.warn(`notifyRepoUpdate to ${ref.authority} errored:`, err);\n\t\t}\n\t\tawait stub.rpcEnqueueNotify([retry], { delayMs: NOTIFY_BACKOFF_BASE_MS });\n\t}\n\n\tinterface WriteInput {\n\t\taction: \"create\" | \"update\" | \"delete\";\n\t\tcollection: string;\n\t\trkey?: string;\n\t\tvalue?: unknown;\n\t}\n\n\t/**\n\t * Common write pipeline for createRecord/putRecord/deleteRecord and\n\t * applyWrites: validate, prepare bytes and CIDs, promote blobs, ensure\n\t * the space DO, apply the batch, notify in the background.\n\t */\n\tasync function runWrites(\n\t\tc: Context,\n\t\tref: SpaceRef,\n\t\tsession: SpaceSessionAuth,\n\t\twrites: WriteInput[],\n\t\tvalidate: boolean | undefined,\n\t): Promise<\n\t\t| Response\n\t\t| {\n\t\t\t\trev: string;\n\t\t\t\tresults: Array<{\n\t\t\t\t\taction: string;\n\t\t\t\t\tcollection: string;\n\t\t\t\t\trkey: string;\n\t\t\t\t\tcid: string | null;\n\t\t\t\t\tvalidationStatus?: string;\n\t\t\t\t}>;\n\t\t }\n\t> {\n\t\tconst prepared: PreparedSpaceWrite[] = [];\n\t\tconst statuses: Array<string | undefined> = [];\n\t\tconst blobCids = new Set<string>();\n\n\t\tfor (const write of writes) {\n\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\ttype: ref.type,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\tskey: ref.skey,\n\t\t\t\taction: write.action,\n\t\t\t\tcollection: write.collection,\n\t\t\t});\n\t\t\tif (scopeError) return scopeError;\n\t\t\tassertNotPublishedCollection(write.collection);\n\n\t\t\tif (write.action === \"delete\") {\n\t\t\t\tprepared.push({\n\t\t\t\t\taction: \"delete\",\n\t\t\t\t\tcollection: write.collection,\n\t\t\t\t\trkey: write.rkey!,\n\t\t\t\t});\n\t\t\t\tstatuses.push(undefined);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst rkey = write.rkey ?? tidNow();\n\t\t\tlet validated;\n\t\t\ttry {\n\t\t\t\tvalidated = host.validateRecord({\n\t\t\t\t\tcollection: write.collection,\n\t\t\t\t\trecord: write.value,\n\t\t\t\t\trkey,\n\t\t\t\t\tvalidate,\n\t\t\t\t});\n\t\t\t} catch (err) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror: \"InvalidRecord\",\n\t\t\t\t\t\tmessage: err instanceof Error ? err.message : String(err),\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst preparedRecord = await prepareRecord(validated.record);\n\t\t\tif (preparedRecord.bytes.length > MAX_SPACE_RECORD_BYTES) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"InvalidRequest\",\n\t\t\t\t\t`Record exceeds the maximum space record size of ${MAX_SPACE_RECORD_BYTES} bytes`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tfor (const cid of preparedRecord.blobCids) blobCids.add(cid);\n\t\t\tprepared.push({\n\t\t\t\taction: write.action,\n\t\t\t\tcollection: write.collection,\n\t\t\t\trkey,\n\t\t\t\tcid: preparedRecord.cid,\n\t\t\t\tbytes: preparedRecord.bytes,\n\t\t\t\tblobCids: preparedRecord.blobCids,\n\t\t\t});\n\t\t\tstatuses.push(validated.status);\n\t\t}\n\n\t\t// The copy completes before the DO commit is applied, so a relay or\n\t\t// syncer reacting to the commit never sees a 404.\n\t\tawait promoteSpaceBlobs(ref, Array.from(blobCids));\n\n\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\tawait ensureSpaceForWrite(ref, stub);\n\t\tconst result = await stub.rpcApplyWrites(prepared);\n\n\t\twaitUntil(c, postWrite(ref, stub, result));\n\n\t\treturn {\n\t\t\trev: result.rev,\n\t\t\tresults: result.results.map((r, i) => ({\n\t\t\t\t...r,\n\t\t\t\t...(statuses[i] !== undefined ? { validationStatus: statuses[i] } : {}),\n\t\t\t})),\n\t\t};\n\t}\n\n\t/** Notify after a configuration change that published to the repo. */\n\tfunction afterConfigCommit(\n\t\tc: Context,\n\t\tref: SpaceRef,\n\t\tstub: SpaceStub,\n\t\tcommit: RepoCommitResult | null,\n\t): void {\n\t\tif (commit) waitUntil(c, postWrite(ref, stub, commit));\n\t}\n\n\t// ---------------------------------------------------------------\n\t// Write endpoints (repo host, session auth)\n\t// ---------------------------------------------------------------\n\n\tapp.post(\"/xrpc/com.atproto.space.createRecord\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{\n\t\t\t\tspace?: string;\n\t\t\t\trepo?: string;\n\t\t\t\tcollection?: string;\n\t\t\t\trkey?: string;\n\t\t\t\tvalidate?: boolean;\n\t\t\t\trecord?: unknown;\n\t\t\t}>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\trequireRepoParam(body.repo);\n\t\t\trequireString(body.collection, \"collection\");\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst result = await runWrites(\n\t\t\t\tc,\n\t\t\t\tref,\n\t\t\t\tsession,\n\t\t\t\t[\n\t\t\t\t\t{\n\t\t\t\t\t\taction: \"create\",\n\t\t\t\t\t\tcollection: body.collection!,\n\t\t\t\t\t\trkey: body.rkey,\n\t\t\t\t\t\tvalue: body.record,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tbody.validate,\n\t\t\t);\n\t\t\tif (result instanceof Response) return result;\n\t\t\tconst write = result.results[0]!;\n\t\t\treturn c.json({\n\t\t\t\turi: spaceRecordUri(\n\t\t\t\t\tref.uri,\n\t\t\t\t\thost.operatorDid,\n\t\t\t\t\twrite.collection,\n\t\t\t\t\twrite.rkey,\n\t\t\t\t),\n\t\t\t\tcid: write.cid,\n\t\t\t\t...(write.validationStatus\n\t\t\t\t\t? { validationStatus: write.validationStatus }\n\t\t\t\t\t: {}),\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.space.putRecord\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{\n\t\t\t\tspace?: string;\n\t\t\t\trepo?: string;\n\t\t\t\tcollection?: string;\n\t\t\t\trkey?: string;\n\t\t\t\tvalidate?: boolean;\n\t\t\t\trecord?: unknown;\n\t\t\t}>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\trequireRepoParam(body.repo);\n\t\t\trequireString(body.collection, \"collection\");\n\t\t\trequireString(body.rkey, \"rkey\");\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\n\t\t\t// Upsert: the scope asserted is the operation actually performed.\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tconst meta = await stub.rpcGetMeta();\n\t\t\tconst exists =\n\t\t\t\tmeta && !meta.deletedAt\n\t\t\t\t\t? (await stub.rpcGetRecord(body.collection!, body.rkey!)) !== null\n\t\t\t\t\t: false;\n\n\t\t\tconst result = await runWrites(\n\t\t\t\tc,\n\t\t\t\tref,\n\t\t\t\tsession,\n\t\t\t\t[\n\t\t\t\t\t{\n\t\t\t\t\t\taction: exists ? \"update\" : \"create\",\n\t\t\t\t\t\tcollection: body.collection!,\n\t\t\t\t\t\trkey: body.rkey,\n\t\t\t\t\t\tvalue: body.record,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tbody.validate,\n\t\t\t);\n\t\t\tif (result instanceof Response) return result;\n\t\t\tconst write = result.results[0]!;\n\t\t\treturn c.json({\n\t\t\t\turi: spaceRecordUri(\n\t\t\t\t\tref.uri,\n\t\t\t\t\thost.operatorDid,\n\t\t\t\t\twrite.collection,\n\t\t\t\t\twrite.rkey,\n\t\t\t\t),\n\t\t\t\tcid: write.cid,\n\t\t\t\t...(write.validationStatus\n\t\t\t\t\t? { validationStatus: write.validationStatus }\n\t\t\t\t\t: {}),\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.space.deleteRecord\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{\n\t\t\t\tspace?: string;\n\t\t\t\trepo?: string;\n\t\t\t\tcollection?: string;\n\t\t\t\trkey?: string;\n\t\t\t}>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\trequireRepoParam(body.repo);\n\t\t\trequireString(body.collection, \"collection\");\n\t\t\trequireString(body.rkey, \"rkey\");\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst result = await runWrites(\n\t\t\t\tc,\n\t\t\t\tref,\n\t\t\t\tsession,\n\t\t\t\t[{ action: \"delete\", collection: body.collection!, rkey: body.rkey }],\n\t\t\t\tundefined,\n\t\t\t);\n\t\t\tif (result instanceof Response) return result;\n\t\t\treturn c.json({});\n\t\t} catch (err) {\n\t\t\t// Deleting an absent record succeeds: nothing committed, nothing\n\t\t\t// notified.\n\t\t\tif (parseSpaceErrorCode(err)?.code === \"RecordNotFound\") {\n\t\t\t\treturn c.json({});\n\t\t\t}\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.space.applyWrites\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{\n\t\t\t\tspace?: string;\n\t\t\t\trepo?: string;\n\t\t\t\tvalidate?: boolean;\n\t\t\t\twrites?: Array<{\n\t\t\t\t\t$type?: string;\n\t\t\t\t\tcollection?: string;\n\t\t\t\t\trkey?: string;\n\t\t\t\t\tvalue?: unknown;\n\t\t\t\t}>;\n\t\t\t}>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\trequireRepoParam(body.repo);\n\t\t\tif (!Array.isArray(body.writes)) {\n\t\t\t\tthrow new SpaceError(\"InvalidRequest\", \"writes must be an array\");\n\t\t\t}\n\t\t\tif (body.writes.length > 200) {\n\t\t\t\tthrow new SpaceError(\"InvalidRequest\", \"Too many writes. Max: 200\");\n\t\t\t}\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\n\t\t\tconst inputs: WriteInput[] = body.writes.map((write, i) => {\n\t\t\t\tconst action =\n\t\t\t\t\twrite.$type === \"com.atproto.space.applyWrites#create\"\n\t\t\t\t\t\t? (\"create\" as const)\n\t\t\t\t\t\t: write.$type === \"com.atproto.space.applyWrites#update\"\n\t\t\t\t\t\t\t? (\"update\" as const)\n\t\t\t\t\t\t\t: write.$type === \"com.atproto.space.applyWrites#delete\"\n\t\t\t\t\t\t\t\t? (\"delete\" as const)\n\t\t\t\t\t\t\t\t: null;\n\t\t\t\tif (!action || !write.collection) {\n\t\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\t\"InvalidRequest\",\n\t\t\t\t\t\t`Write ${i}: unknown $type or missing collection`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (action !== \"create\" && !write.rkey) {\n\t\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\t\"InvalidRequest\",\n\t\t\t\t\t\t`Write ${i}: ${action} requires rkey`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\taction,\n\t\t\t\t\tcollection: write.collection,\n\t\t\t\t\trkey: write.rkey,\n\t\t\t\t\tvalue: write.value,\n\t\t\t\t};\n\t\t\t});\n\n\t\t\tconst result = await runWrites(c, ref, session, inputs, body.validate);\n\t\t\tif (result instanceof Response) return result;\n\t\t\treturn c.json({\n\t\t\t\tresults: result.results.map((write) => {\n\t\t\t\t\tif (write.action === \"delete\") {\n\t\t\t\t\t\treturn { $type: \"com.atproto.space.applyWrites#deleteResult\" };\n\t\t\t\t\t}\n\t\t\t\t\treturn {\n\t\t\t\t\t\t$type: `com.atproto.space.applyWrites#${write.action}Result`,\n\t\t\t\t\t\turi: spaceRecordUri(\n\t\t\t\t\t\t\tref.uri,\n\t\t\t\t\t\t\thost.operatorDid,\n\t\t\t\t\t\t\twrite.collection,\n\t\t\t\t\t\t\twrite.rkey,\n\t\t\t\t\t\t),\n\t\t\t\t\t\tcid: write.cid,\n\t\t\t\t\t\t...(write.validationStatus\n\t\t\t\t\t\t\t? { validationStatus: write.validationStatus }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t};\n\t\t\t\t}),\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.space.clearRecords\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{ space?: string; repo?: string }>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\trequireString(body.repo, \"repo\");\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tif (body.repo !== session.did) {\n\t\t\t\tthrow new SpaceError(\"Forbidden\", \"repo must match authenticated user\");\n\t\t\t}\n\t\t\trequireRepoParam(body.repo);\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tconst meta = await stub.rpcGetMeta();\n\t\t\tif (!meta || meta.deletedAt) return c.json({});\n\n\t\t\t// In the authority's own repo the published policy and member\n\t\t\t// records are the host's copy of the space's configuration, not\n\t\t\t// the account's records, so they stay, and keeping them takes no\n\t\t\t// grant.\n\t\t\tconst keep =\n\t\t\t\tref.authority === host.operatorDid ? [...PUBLISHED_COLLECTIONS] : [];\n\t\t\tfor (const collection of await stub.rpcListCollections()) {\n\t\t\t\tif (keep.includes(collection)) continue;\n\t\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\t\ttype: ref.type,\n\t\t\t\t\tauthority: ref.authority,\n\t\t\t\t\tskey: ref.skey,\n\t\t\t\t\taction: \"delete\",\n\t\t\t\t\tcollection,\n\t\t\t\t});\n\t\t\t\tif (scopeError) return scopeError;\n\t\t\t}\n\t\t\tconst commit = await stub.rpcClearRecords(keep);\n\t\t\tif (commit) waitUntil(c, postWrite(ref, stub, commit));\n\t\t\treturn c.json({});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.space.importRepo\", async (c) => {\n\t\ttry {\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst bytes = await readBody(c);\n\n\t\t\tlet records: ImportedRecord[];\n\t\t\tlet space: string;\n\t\t\tlet repo: string;\n\t\t\ttry {\n\t\t\t\tconst archive = await readRepoStar([bytes]);\n\t\t\t\ttry {\n\t\t\t\t\tspace = archive.commit.space;\n\t\t\t\t\trepo = archive.commit.repo;\n\t\t\t\t\trecords = [];\n\t\t\t\t\tfor await (const record of archive.records) {\n\t\t\t\t\t\t// Stored re-encoded, as any other write is. A record that\n\t\t\t\t\t\t// wasn't canonical DRISL in the archive would no longer match\n\t\t\t\t\t\t// its cid, nor the commit data.\n\t\t\t\t\t\tconst encoded = encode(record.record as LexValue);\n\t\t\t\t\t\tconst cid = await cidForCbor(encoded);\n\t\t\t\t\t\tif (!cid.equals(record.cid)) {\n\t\t\t\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\t\t\t\"InvalidRequest\",\n\t\t\t\t\t\t\t\t`Invalid STAR: record is not canonical DRISL at ${record.collection}/${record.rkey}`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst blobCids: string[] = [];\n\t\t\t\t\t\tfor (const ref of enumBlobRefs(record.record as LexValue, {\n\t\t\t\t\t\t\tstrict: false,\n\t\t\t\t\t\t})) {\n\t\t\t\t\t\t\tblobCids.push(getBlobCidString(ref));\n\t\t\t\t\t\t}\n\t\t\t\t\t\trecords.push({\n\t\t\t\t\t\t\tcollection: record.collection,\n\t\t\t\t\t\t\trkey: record.rkey,\n\t\t\t\t\t\t\tcid: cid.toString(),\n\t\t\t\t\t\t\tbytes: encoded,\n\t\t\t\t\t\t\tblobCids,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t} finally {\n\t\t\t\t\tawait archive[Symbol.asyncDispose]();\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tthrow invalidArchive(err, \"InvalidRepoFile\");\n\t\t\t}\n\n\t\t\tif (repo !== host.operatorDid || repo !== session.did) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"RepoMismatch\",\n\t\t\t\t\t\"Repo does not match the authenticated account\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst ref = requireSpaceUri(space);\n\t\t\t// Importing replaces the whole repo, so it takes full access to the\n\t\t\t// space: read, and every write on every collection (\"*\" matches\n\t\t\t// only a grant covering them all), as the reference requires.\n\t\t\tfor (const match of [\n\t\t\t\t{ action: \"read\" },\n\t\t\t\t{ action: \"create\", collection: \"*\" },\n\t\t\t\t{ action: \"update\", collection: \"*\" },\n\t\t\t\t{ action: \"delete\", collection: \"*\" },\n\t\t\t] as const) {\n\t\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\t\ttype: ref.type,\n\t\t\t\t\tauthority: ref.authority,\n\t\t\t\t\tskey: ref.skey,\n\t\t\t\t\t...match,\n\t\t\t\t});\n\t\t\t\tif (scopeError) return scopeError;\n\t\t\t}\n\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tif (ref.authority === host.operatorDid) {\n\t\t\t\t// The authority's space must arrive first, via importSpaceMeta.\n\t\t\t\tawait requirePolicy(stub, ref);\n\t\t\t} else {\n\t\t\t\tawait ensureSpaceForWrite(ref, stub);\n\t\t\t}\n\t\t\tawait stub.rpcImportRepo(records);\n\n\t\t\t// Blobs are uploaded separately. Those already staged are promoted\n\t\t\t// now; the rest are claimed by uploadBlob when they arrive.\n\t\t\tconst missing = await promoteSpaceBlobs(\n\t\t\t\tref,\n\t\t\t\tArray.from(new Set(records.flatMap((r) => r.blobCids))),\n\t\t\t);\n\t\t\tif (missing.length > 0) {\n\t\t\t\tawait host.getIndexDO().rpcAddPendingBlobs(ref.uri, missing);\n\t\t\t}\n\t\t\treturn c.json({});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\t// ---------------------------------------------------------------\n\t// Read and sync endpoints (credential or session auth)\n\t// ---------------------------------------------------------------\n\n\tapp.get(\"/xrpc/com.atproto.space.getRecord\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tconst auth = await readAuth(c, ref, c.req.query(\"repo\"));\n\t\t\tif (auth instanceof Response) return auth;\n\t\t\tconst collection = c.req.query(\"collection\");\n\t\t\tconst rkey = c.req.query(\"rkey\");\n\t\t\trequireString(collection, \"collection\");\n\t\t\trequireString(rkey, \"rkey\");\n\t\t\tconst mac = await readMac(c, auth, RECORD_MAC_PROFILE);\n\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tawait requireRepoExists(stub, ref);\n\t\t\tconst record = await stub.rpcGetRecord(collection!, rkey!);\n\t\t\tconst uri = spaceRecordUri(ref.uri, host.operatorDid, collection!, rkey!);\n\t\t\tif (!record) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"RecordNotFound\",\n\t\t\t\t\t`Could not locate record: ${uri}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn c.json(\n\t\t\t\t{ uri, cid: record.cid, value: recordBytesToJson(record.bytes) },\n\t\t\t\t200,\n\t\t\t\trecordMacHeaders(mac, uri, record.cid),\n\t\t\t);\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.get(\"/xrpc/com.atproto.space.listRecords\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tconst auth = await readAuth(c, ref, c.req.query(\"repo\"));\n\t\t\tif (auth instanceof Response) return auth;\n\t\t\tconst collection = c.req.query(\"collection\");\n\t\t\tconst limit = clampLimit(c.req.query(\"limit\"), 50, 1000);\n\t\t\tconst excludeValues = c.req.query(\"excludeValues\") === \"true\";\n\t\t\tconst after = parseRecordCursor(c.req.query(\"cursor\"));\n\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tawait requireRepoExists(stub, ref);\n\t\t\tconst page = await stub.rpcListRecords({\n\t\t\t\tcollection,\n\t\t\t\tlimit,\n\t\t\t\tafter,\n\t\t\t\texcludeValues,\n\t\t\t});\n\t\t\tconst records = page.records.map((record) => ({\n\t\t\t\tcollection: record.collection,\n\t\t\t\trkey: record.rkey,\n\t\t\t\tcid: record.cid,\n\t\t\t\t...(record.bytes\n\t\t\t\t\t? { value: recordBytesToJson(new Uint8Array(record.bytes)) }\n\t\t\t\t\t: {}),\n\t\t\t}));\n\t\t\tconst last = page.records[page.records.length - 1];\n\t\t\treturn c.json({\n\t\t\t\trecords,\n\t\t\t\t...(page.hasMore && last\n\t\t\t\t\t? { cursor: `${last.collection}/${last.rkey}` }\n\t\t\t\t\t: {}),\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.get(\"/xrpc/com.atproto.space.getLatestCommit\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tconst auth = await readAuth(c, ref, c.req.query(\"repo\"));\n\t\t\tif (auth instanceof Response) return auth;\n\t\t\tconst mac = await readMac(c, auth, COMMIT_MAC_PROFILE);\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tawait requireRepoExists(stub, ref);\n\t\t\tconst state = await stub.rpcGetRepoState();\n\t\t\tif (!state) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"RepoNotFound\",\n\t\t\t\t\t`Could not find repo for space: ${ref.uri}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst commit = buildCommit({\n\t\t\t\tspaceUri: ref.uri,\n\t\t\t\trepo: host.operatorDid,\n\t\t\t\tstate: { setHash: new Uint8Array(state.setHash), rev: state.rev },\n\t\t\t});\n\t\t\treturn c.json(\n\t\t\t\t{ commit: commitToJson(commit) },\n\t\t\t\t200,\n\t\t\t\tcommitMacHeaders(mac, commit),\n\t\t\t);\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.get(\"/xrpc/com.atproto.space.listRepoOps\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tconst auth = await readAuth(c, ref, c.req.query(\"repo\"));\n\t\t\tif (auth instanceof Response) return auth;\n\t\t\tconst limit = clampLimit(c.req.query(\"limit\"), 100, 1000);\n\t\t\tconst since = c.req.query(\"since\");\n\t\t\tconst excludeValues = c.req.query(\"excludeValues\") === \"true\";\n\t\t\tconst after = parseOpsCursor(c.req.query(\"cursor\"));\n\t\t\tconst mac = await readMac(c, auth, COMMIT_MAC_PROFILE);\n\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tawait requireRepoExists(stub, ref);\n\t\t\tconst page = await stub.rpcListRepoOps({\n\t\t\t\tsince,\n\t\t\t\tafter,\n\t\t\t\tlimit,\n\t\t\t\texcludeValues,\n\t\t\t});\n\t\t\tconst ops = page.ops.map((op) => ({\n\t\t\t\trev: op.rev,\n\t\t\t\tcollection: op.collection,\n\t\t\t\trkey: op.rkey,\n\t\t\t\tcid: op.cid,\n\t\t\t\tprev: op.prev,\n\t\t\t\t...(op.bytes\n\t\t\t\t\t? { value: recordBytesToJson(new Uint8Array(op.bytes)) }\n\t\t\t\t\t: {}),\n\t\t\t}));\n\t\t\t// Never written: no commit to answer with.\n\t\t\tif (!page.head) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"RepoNotFound\",\n\t\t\t\t\t`Could not find repo for space: ${ref.uri}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\t// The commit, with its MAC, is on every page. A full page carries a\n\t\t\t// cursor, so the last page may be empty.\n\t\t\tconst last = page.ops[page.ops.length - 1];\n\t\t\tconst cursor =\n\t\t\t\tlast && page.ops.length === limit\n\t\t\t\t\t? `${last.rev}/${last.idx}`\n\t\t\t\t\t: undefined;\n\t\t\tconst commit = buildCommit({\n\t\t\t\tspaceUri: ref.uri,\n\t\t\t\trepo: host.operatorDid,\n\t\t\t\tstate: {\n\t\t\t\t\tsetHash: new Uint8Array(page.head.setHash),\n\t\t\t\t\trev: page.head.rev,\n\t\t\t\t},\n\t\t\t});\n\t\t\treturn c.json(\n\t\t\t\t{ ops, commit: commitToJson(commit), ...(cursor ? { cursor } : {}) },\n\t\t\t\t200,\n\t\t\t\tcommitMacHeaders(mac, commit),\n\t\t\t);\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.get(\"/xrpc/com.atproto.space.getRepo\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tconst auth = await readAuth(c, ref, c.req.query(\"repo\"));\n\t\t\tif (auth instanceof Response) return auth;\n\t\t\tconst mac = await readMac(c, auth, COMMIT_MAC_PROFILE);\n\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tawait requireRepoExists(stub, ref);\n\n\t\t\t// The archive streams page by page. Each page reports the repo\n\t\t\t// state it was read at; a page from a later state means a write\n\t\t\t// landed mid-export, and the stream errors rather than serve\n\t\t\t// records that don't match the commit. The syncer's verification\n\t\t\t// would refuse such an archive anyway; failing loudly lets it\n\t\t\t// retry at once.\n\t\t\tconst PAGE = 500;\n\t\t\tconst first = await stub.rpcListRecordsByPath({ limit: PAGE });\n\t\t\tconst state = first.state;\n\t\t\tif (!state) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"RepoNotFound\",\n\t\t\t\t\t`Could not find repo for space: ${ref.uri}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst commit = buildCommit({\n\t\t\t\tspaceUri: ref.uri,\n\t\t\t\trepo: host.operatorDid,\n\t\t\t\tstate: { setHash: new Uint8Array(state.setHash), rev: state.rev },\n\t\t\t});\n\t\t\tasync function* records() {\n\t\t\t\tlet page = first;\n\t\t\t\tfor (;;) {\n\t\t\t\t\tfor (const record of page.records) {\n\t\t\t\t\t\tyield {\n\t\t\t\t\t\t\tcollection: record.collection as never,\n\t\t\t\t\t\t\trkey: record.rkey as never,\n\t\t\t\t\t\t\tbytes: new Uint8Array(record.bytes),\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\tconst last = page.records[page.records.length - 1];\n\t\t\t\t\tif (!page.hasMore || !last) return;\n\t\t\t\t\tpage = await stub.rpcListRecordsByPath({\n\t\t\t\t\t\tafterPath: `${last.collection}/${last.rkey}`,\n\t\t\t\t\t\tlimit: PAGE,\n\t\t\t\t\t});\n\t\t\t\t\tif (page.state?.rev !== state!.rev) {\n\t\t\t\t\t\tthrow new Error(\"The repo changed during export; retry getRepo\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst star = writeRepoStar(\n\t\t\t\tcommit as Parameters<typeof writeRepoStar>[0],\n\t\t\t\trecords(),\n\t\t\t);\n\t\t\treturn c.body(asyncIterableToStream(star), 200, {\n\t\t\t\t\"Content-Type\": STAR_CONTENT_TYPE,\n\t\t\t\t...commitMacHeaders(mac, commit),\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.get(\"/xrpc/com.atproto.space.listBlobs\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tconst auth = await readAuth(c, ref, c.req.query(\"repo\"));\n\t\t\tif (auth instanceof Response) return auth;\n\t\t\tconst limit = clampLimit(c.req.query(\"limit\"), 500, 1000);\n\t\t\tconst afterCid = c.req.query(\"cursor\");\n\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tawait requireRepoExists(stub, ref);\n\t\t\tconst page = await stub.rpcListBlobs({ limit, afterCid });\n\t\t\tconst last = page.cids[page.cids.length - 1];\n\t\t\treturn c.json({\n\t\t\t\tcids: page.cids,\n\t\t\t\t...(page.hasMore && last ? { cursor: last } : {}),\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.get(\"/xrpc/com.atproto.space.getBlob\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tconst auth = await readAuth(c, ref, c.req.query(\"repo\"));\n\t\t\tif (auth instanceof Response) return auth;\n\t\t\tconst cid = c.req.query(\"cid\");\n\t\t\trequireString(cid, \"cid\");\n\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tawait requireRepoExists(stub, ref);\n\t\t\t// Refuse before touching the blobstore: do not reveal whether an\n\t\t\t// unreferenced blob exists.\n\t\t\tif (!(await stub.rpcHasSpaceBlob(cid!))) {\n\t\t\t\tthrow new SpaceError(\"BlobNotFound\", `Blob not found: ${cid}`);\n\t\t\t}\n\t\t\tif (!host.blobs) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror: \"ServiceUnavailable\",\n\t\t\t\t\t\tmessage: \"Blob storage is not configured\",\n\t\t\t\t\t},\n\t\t\t\t\t503,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst key = spaceBlobKey(host.operatorDid, await spaceId(ref.uri), cid!);\n\t\t\tlet blob = await host.blobs.get(key);\n\t\t\tif (!blob) {\n\t\t\t\t// Referenced but never promoted (an imported record whose blob\n\t\t\t\t// arrived through another path): promote on first read.\n\t\t\t\tif (\n\t\t\t\t\tawait promoteStagedBlobToSpace(\n\t\t\t\t\t\thost.blobs,\n\t\t\t\t\t\thost.operatorDid,\n\t\t\t\t\t\tref.uri,\n\t\t\t\t\t\tcid!,\n\t\t\t\t\t)\n\t\t\t\t) {\n\t\t\t\t\tblob = await host.blobs.get(key);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!blob) {\n\t\t\t\tthrow new SpaceError(\"BlobNotFound\", `Blob not found: ${cid}`);\n\t\t\t}\n\t\t\treturn new Response(blob.body, {\n\t\t\t\tstatus: 200,\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\":\n\t\t\t\t\t\tblob.httpMetadata?.contentType ?? \"application/octet-stream\",\n\t\t\t\t\t\"Content-Length\": blob.size.toString(),\n\t\t\t\t\t// A shared cache in front of the PDS must never store a\n\t\t\t\t\t// response whose authorisation was per-credential.\n\t\t\t\t\t\"Cache-Control\": \"private, no-store\",\n\t\t\t\t\tVary: \"Authorization\",\n\t\t\t\t\t\"X-Content-Type-Options\": \"nosniff\",\n\t\t\t\t\t\"Content-Disposition\": `attachment; filename=\"${cid}\"`,\n\t\t\t\t\t\"Content-Security-Policy\": \"default-src 'none'; sandbox\",\n\t\t\t\t},\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\t// ---------------------------------------------------------------\n\t// Space host endpoints (authority role)\n\t// ---------------------------------------------------------------\n\n\tapp.post(\"/xrpc/com.atproto.space.authorizeSpaceSync\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{\n\t\t\t\tspace?: string;\n\t\t\t\tcredentialKey?: string;\n\t\t\t\tdelegationToken?: string;\n\t\t\t\tclientAttestation?: string;\n\t\t\t\tnotify?: unknown;\n\t\t\t}>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\trequireString(body.credentialKey, \"credentialKey\");\n\t\t\tif (!isP256DidKey(body.credentialKey!)) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"InvalidRequest\",\n\t\t\t\t\t\"credentialKey must be a P-256 did:key\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst notify =\n\t\t\t\tbody.notify === undefined ? undefined : parseNotify(body.notify);\n\n\t\t\t// Before anything touches the space DO: a space this host doesn't\n\t\t\t// govern must not get one created for it by a well-formed request.\n\t\t\tawait assertActiveSpaceHost(ref);\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tconst { meta, policy } = await stub.rpcGetAuthorityState();\n\t\t\t// The durable signal that a space is gone: a syncer that missed\n\t\t\t// its deletion notice learns it here, the next time it\n\t\t\t// reauthorises, whatever the request's authorisation.\n\t\t\tif (meta?.deletedAt) {\n\t\t\t\tthrow new SpaceError(\"SpaceDeleted\", `Space deleted: ${ref.uri}`);\n\t\t\t}\n\n\t\t\t// Absent when the request carries no delegation token, which only\n\t\t\t// a space that does not gate on the account accepts.\n\t\t\tlet repo: string | undefined;\n\t\t\tif (body.delegationToken) {\n\t\t\t\t({ userDid: repo } = await verifyDelegationToken(\n\t\t\t\t\tbody.delegationToken,\n\t\t\t\t\tref,\n\t\t\t\t\t{\n\t\t\t\t\t\tgetSigningKey: host.getSigningKey,\n\t\t\t\t\t\tcheckReplay: (kind, key, exp) =>\n\t\t\t\t\t\t\tstub.rpcCheckReplay(kind, key, exp),\n\t\t\t\t\t},\n\t\t\t\t));\n\t\t\t}\n\n\t\t\tlet clientId: string | undefined;\n\t\t\tif (body.clientAttestation) {\n\t\t\t\tclientId = await verifyClientAttestation(body.clientAttestation, {\n\t\t\t\t\texpectedAud: spaceHostAud(ref.authority as `did:${string}:${string}`),\n\t\t\t\t\t// Checked pre-verification inside, so a client the space could\n\t\t\t\t\t// never authorise never triggers network I/O.\n\t\t\t\t\tallowedClientIds:\n\t\t\t\t\t\tpolicy?.$type === MEMBERSPACE_POLICY\n\t\t\t\t\t\t\t? policy.allowedApps\n\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\tcheckReplay: (kind, key, exp) => stub.rpcCheckReplay(kind, key, exp),\n\t\t\t\t\tfetch: host.outboundFetch,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (!meta || !policy) {\n\t\t\t\tthrow new SpaceError(\"SpaceNotFound\", `Space not found: ${ref.uri}`);\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\t// The account goes first, and one the policy refuses is answered\n\t\t\t\t// as though the space does not exist, so that a refusal\n\t\t\t\t// discloses nothing to someone without access to it.\n\t\t\t\tconst authorized = await authorizeRepo({\n\t\t\t\t\tpolicy,\n\t\t\t\t\tref,\n\t\t\t\t\trepo,\n\t\t\t\t\taccess: \"read\",\n\t\t\t\t\tclientId,\n\t\t\t\t\tstub,\n\t\t\t\t});\n\t\t\t\tif (!authorized) {\n\t\t\t\t\tthrow new SpaceError(\"SpaceNotFound\", `Space not found: ${ref.uri}`);\n\t\t\t\t}\n\t\t\t\tif (!isAppAuthorized(policy, clientId)) {\n\t\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\t\"AppNotAuthorized\",\n\t\t\t\t\t\t\"Application not authorized for this space\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\t// A refusal withdraws the registration the request carries, so a\n\t\t\t\t// syncer that has lost access stops being notified. A failure to\n\t\t\t\t// decide, such as an unreachable managing app, is not a refusal.\n\t\t\t\tif (notify && parseSpaceErrorCode(err)?.code !== \"UpstreamFailure\") {\n\t\t\t\t\tawait stub.rpcRemoveNotifyRegistration(notify);\n\t\t\t\t}\n\t\t\t\tthrow err;\n\t\t\t}\n\n\t\t\tif (notify && !(await stub.rpcGetNotifyRegistration(notify))) {\n\t\t\t\tawait confirmRegistration(ref, notify);\n\t\t\t}\n\n\t\t\tconst credential = await createSpaceCredential({\n\t\t\t\tiss: host.operatorDid as `did:${string}:${string}`,\n\t\t\t\tsub: ref.uri as never,\n\t\t\t\tkeyId: body.credentialKey as `did:${string}:${string}`,\n\t\t\t\tkeypair: (await host.getKeypair()) as never,\n\t\t\t});\n\n\t\t\tif (notify) {\n\t\t\t\t// Renewed by each authorisation, to the credential's expiry, so a\n\t\t\t\t// syncer that keeps reauthorising stays registered.\n\t\t\t\tconst { exp } = parseSpaceToken(\"credential\", credential).payload;\n\t\t\t\tawait stub.rpcPutNotifyRegistration(notify, exp * 1000);\n\t\t\t}\n\t\t\t// Read after registering, so any update past this revision is\n\t\t\t// notified.\n\t\t\tconst spaceRev = await stub.rpcGetSpaceRev();\n\t\t\treturn c.json({ credential, ...(spaceRev ? { spaceRev } : {}) });\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.get(\"/xrpc/com.atproto.space.listWriters\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tawait credentialAuth(c, ref);\n\t\t\tawait assertActiveSpaceHost(ref);\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tawait requirePolicy(stub, ref);\n\t\t\tconst limit = clampLimit(c.req.query(\"limit\"), 500, 1000);\n\t\t\tconst writers = await stub.rpcListWriters({\n\t\t\t\tlimit,\n\t\t\t\tcursor: c.req.query(\"cursor\") || undefined,\n\t\t\t});\n\t\t\tconst last = writers[writers.length - 1];\n\t\t\treturn c.json({\n\t\t\t\trepos: writers.map((writer) =>\n\t\t\t\t\twriter.removed\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t$type: \"com.atproto.space.defs#repoRemoved\",\n\t\t\t\t\t\t\t\trepo: writer.did,\n\t\t\t\t\t\t\t\tspaceRev: writer.spaceRev,\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t$type: \"com.atproto.space.defs#repoWrite\",\n\t\t\t\t\t\t\t\trepo: writer.did,\n\t\t\t\t\t\t\t\trepoRev: writer.repoRev,\n\t\t\t\t\t\t\t\tdata: bytesToJson(new Uint8Array(writer.data)),\n\t\t\t\t\t\t\t\tspaceRev: writer.spaceRev,\n\t\t\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t\t// Nonempty pages carry a cursor and empty pages omit it.\n\t\t\t\t...(last ? { cursor: last.spaceRev } : {}),\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.space.notifyRepoUpdate\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{\n\t\t\t\tspace?: string;\n\t\t\t\trepo?: string;\n\t\t\t\trepoRev?: string;\n\t\t\t\tdata?: { $bytes?: string };\n\t\t\t}>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\trequireString(body.repo, \"repo\");\n\t\t\trequireString(body.repoRev, \"repoRev\");\n\t\t\tif (typeof body.data?.$bytes !== \"string\") {\n\t\t\t\tthrow new SpaceError(\"InvalidRequest\", \"Missing data bytes\");\n\t\t\t}\n\n\t\t\tconst serviceAuth = await requireServiceAuth(c, NOTIFY_REPO_UPDATE_LXM);\n\t\t\tif (serviceAuth instanceof Response) return serviceAuth;\n\t\t\t// iss is the signer, so requiring it to match keeps a PDS from\n\t\t\t// notifying on another account's behalf.\n\t\t\tif (serviceAuth.iss !== body.repo) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"Forbidden\",\n\t\t\t\t\t\"notifyRepoUpdate iss does not match the repo\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (\n\t\t\t\tserviceAuth.aud !== ref.authority &&\n\t\t\t\tserviceAuth.aud !==\n\t\t\t\t\tspaceHostAud(ref.authority as `did:${string}:${string}`)\n\t\t\t) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"Forbidden\",\n\t\t\t\t\t\"notifyRepoUpdate aud does not match the space authority\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tassertSpaceHost(ref);\n\t\t\tlet revMs: number;\n\t\t\ttry {\n\t\t\t\trevMs = tidTimestampMs(body.repoRev!);\n\t\t\t} catch {\n\t\t\t\tthrow new SpaceError(\"InvalidRequest\", \"repoRev must be a TID\");\n\t\t\t}\n\t\t\tif (revMs > Date.now() + MAX_REV_CLOCK_SKEW_MS) {\n\t\t\t\tthrow new SpaceError(\"FutureRev\", \"Repo revision is in the future\");\n\t\t\t}\n\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tconst policy = await requirePolicy(stub, ref);\n\t\t\t// The same account perimeter used when minting credentials. The\n\t\t\t// notification comes from a PDS rather than an app, so there is no\n\t\t\t// attestation. An unreachable managing app is an UpstreamFailure,\n\t\t\t// which the repo host retries.\n\t\t\tconst authorized = await authorizeRepo({\n\t\t\t\tpolicy,\n\t\t\t\tref,\n\t\t\t\trepo: body.repo!,\n\t\t\t\taccess: \"write\",\n\t\t\t\tstub,\n\t\t\t});\n\t\t\tif (!authorized) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"Forbidden\",\n\t\t\t\t\t\"Repo is not authorized to write to the space\",\n\t\t\t\t);\n\t\t\t}\n\t\t\t// Sequenced, and queued for registered syncers, in one transaction.\n\t\t\t// A delayed or replayed notification with an older rev changes\n\t\t\t// nothing.\n\t\t\tawait stub.rpcRecordWriter(\n\t\t\t\tbody.repo!,\n\t\t\t\tbody.repoRev!,\n\t\t\t\tfromBase64(body.data.$bytes),\n\t\t\t);\n\t\t\treturn c.json({});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.space.notifyCredentialsRevoked\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{\n\t\t\t\tspace?: string;\n\t\t\t\tcredentials?: unknown;\n\t\t\t}>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\tconst credentials = body.credentials;\n\t\t\tif (\n\t\t\t\t!Array.isArray(credentials) ||\n\t\t\t\tcredentials.length < 1 ||\n\t\t\t\tcredentials.length > 100 ||\n\t\t\t\tcredentials.some((jti) => typeof jti !== \"string\" || jti.length === 0)\n\t\t\t) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"InvalidRequest\",\n\t\t\t\t\t\"credentials must be 1 to 100 credential jti strings\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst serviceAuth = await requireServiceAuth(c, CREDENTIALS_REVOKED_LXM);\n\t\t\tif (serviceAuth instanceof Response) return serviceAuth;\n\t\t\tif (serviceAuth.iss !== ref.authority) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"Forbidden\",\n\t\t\t\t\t\"Revocation issuer is not the space authority\",\n\t\t\t\t);\n\t\t\t}\n\t\t\t// Addressed to the repo DID, which here is always the operator.\n\t\t\tif (serviceAuth.aud !== host.operatorDid) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"Forbidden\",\n\t\t\t\t\t\"Revocation audience does not match a repo hosted here\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tawait host\n\t\t\t\t.getSpaceDO(ref.uri)\n\t\t\t\t.rpcRevokeCredentials(\n\t\t\t\t\tcredentials as string[],\n\t\t\t\t\tMath.floor(Date.now() / 1000) + REVOCATION_TTL_SEC,\n\t\t\t\t);\n\t\t\treturn c.json({});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\t// ---------------------------------------------------------------\n\t// Space management (authority role, session auth)\n\t// ---------------------------------------------------------------\n\n\tapp.post(\"/xrpc/com.atproto.space.createSpace\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{\n\t\t\t\tspaceType?: string;\n\t\t\t\tskey?: string;\n\t\t\t\tpolicy?: unknown;\n\t\t\t}>();\n\t\t\trequireString(body.spaceType, \"spaceType\");\n\t\t\tconst skey = body.skey ?? tidNow();\n\t\t\tconst ref = requireSpaceUri(\n\t\t\t\tformatSpaceUri(host.operatorDid, body.spaceType!, skey),\n\t\t\t);\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\ttype: ref.type,\n\t\t\t\tauthority: host.operatorDid,\n\t\t\t\tskey: ref.skey,\n\t\t\t\tmanage: \"create\",\n\t\t\t});\n\t\t\tif (scopeError) return scopeError;\n\t\t\tawait assertActiveSpaceHost(ref);\n\t\t\tconst policy = normalizePolicy(body.policy);\n\n\t\t\t// Two-step creation: index entry `pending`, then the DO, then\n\t\t\t// `active`. Reads never depend on the index, so a crash between\n\t\t\t// steps leaves only a pending entry for the alarm to reap.\n\t\t\tconst index = host.getIndexDO();\n\t\t\tawait index.rpcRegister({\n\t\t\t\turi: ref.uri,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\ttype: ref.type,\n\t\t\t\tskey: ref.skey,\n\t\t\t\tisAuthority: true,\n\t\t\t});\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tconst commit = await stub.rpcInit({\n\t\t\t\turi: ref.uri,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\ttype: ref.type,\n\t\t\t\tskey: ref.skey,\n\t\t\t\tisAuthority: true,\n\t\t\t\tpolicy,\n\t\t\t});\n\t\t\tawait index.rpcActivate(ref.uri);\n\t\t\tafterConfigCommit(c, ref, stub, commit);\n\t\t\treturn c.json({ space: ref.uri });\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.space.updateSpace\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{ space?: string; policy?: unknown }>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\ttype: ref.type,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\tskey: ref.skey,\n\t\t\t\tmanage: \"update\",\n\t\t\t});\n\t\t\tif (scopeError) return scopeError;\n\t\t\tassertOwner(ref, session);\n\t\t\tawait assertActiveSpaceHost(ref);\n\t\t\tconst policy = normalizePolicy(body.policy);\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tconst commit = await stub.rpcUpdatePolicy(policy);\n\t\t\tafterConfigCommit(c, ref, stub, commit);\n\t\t\treturn c.json({});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.space.deleteSpace\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{ space?: string }>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\ttype: ref.type,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\tskey: ref.skey,\n\t\t\t\tmanage: \"delete\",\n\t\t\t});\n\t\t\tif (scopeError) return scopeError;\n\t\t\tassertOwner(ref, session);\n\t\t\tawait assertActiveSpaceHost(ref);\n\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\t// Credential issuance stops with the tombstone, and every registered\n\t\t\t// syncer, lapsed or not, is queued a deletion notice delivered\n\t\t\t// reliably for 72 hours. Then reap the blob prefix.\n\t\t\tawait stub.rpcDeleteSpace();\n\t\t\tawait host.getIndexDO().rpcMarkDeleted(ref.uri);\n\t\t\tif (host.blobs) {\n\t\t\t\twaitUntil(\n\t\t\t\t\tc,\n\t\t\t\t\tdeleteR2Prefix(\n\t\t\t\t\t\thost.blobs,\n\t\t\t\t\t\tspaceBlobPrefix(host.operatorDid, await spaceId(ref.uri)),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn c.json({});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.get(\"/xrpc/com.atproto.space.getSpace\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\ttype: ref.type,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\tskey: ref.skey,\n\t\t\t\taction: \"read_self\",\n\t\t\t});\n\t\t\tif (scopeError) return scopeError;\n\t\t\tassertOwner(ref, session);\n\t\t\tconst policy = await requirePolicy(host.getSpaceDO(ref.uri), ref);\n\t\t\treturn c.json({ space: ref.uri, policy });\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.space.removeWriter\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{ space?: string; repo?: string }>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\trequireDid(body.repo, \"repo\");\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\ttype: ref.type,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\tskey: ref.skey,\n\t\t\t\tmanage: \"update\",\n\t\t\t});\n\t\t\tif (scopeError) return scopeError;\n\t\t\tassertOwner(ref, session);\n\t\t\tawait assertActiveSpaceHost(ref);\n\t\t\t// Sequenced and announced to syncers as a repoRemoved.\n\t\t\tawait host.getSpaceDO(ref.uri).rpcRemoveWriter(body.repo!);\n\t\t\treturn c.json({});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.get(\"/xrpc/com.atproto.space.exportSpaceMeta\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\ttype: ref.type,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\tskey: ref.skey,\n\t\t\t\taction: \"read_self\",\n\t\t\t});\n\t\t\tif (scopeError) return scopeError;\n\t\t\tassertOwner(ref, session);\n\t\t\tconst exported = await host.getSpaceDO(ref.uri).rpcExportMeta();\n\t\t\tconst star = writeSpaceMetaStar({\n\t\t\t\tspace: ref.uri as never,\n\t\t\t\tpolicy: exported.policy as never,\n\t\t\t\tpolicyState: exported.members.map((member) => ({\n\t\t\t\t\tkey: `${MEMBER_COLLECTION}/${didToRecordKey(member.did)}`,\n\t\t\t\t\tvalue: {\n\t\t\t\t\t\t$type: MEMBER_COLLECTION,\n\t\t\t\t\t\tread: member.read,\n\t\t\t\t\t\twrite: member.write,\n\t\t\t\t\t},\n\t\t\t\t})),\n\t\t\t\twriters: exported.writers.map((writer) => ({\n\t\t\t\t\tdid: writer.did as never,\n\t\t\t\t\trepoRev: writer.repoRev,\n\t\t\t\t\tdata: new Uint8Array(writer.data),\n\t\t\t\t\tspaceRev: writer.spaceRev,\n\t\t\t\t})),\n\t\t\t});\n\t\t\treturn c.body(asyncIterableToStream(star), 200, {\n\t\t\t\t\"Content-Type\": STAR_CONTENT_TYPE,\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.space.importSpaceMeta\", async (c) => {\n\t\ttry {\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst bytes = await readBody(c);\n\t\t\tlet archive;\n\t\t\ttry {\n\t\t\t\tarchive = await readSpaceMetaStar([bytes]);\n\t\t\t} catch (err) {\n\t\t\t\tthrow invalidArchive(err, \"InvalidSpaceMeta\");\n\t\t\t}\n\t\t\tconst ref = requireSpaceUri(archive.space);\n\t\t\t// Importing both creates the space here and sets its configuration.\n\t\t\tfor (const manage of [\"create\", \"update\"] as const) {\n\t\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\t\ttype: ref.type,\n\t\t\t\t\tauthority: ref.authority,\n\t\t\t\t\tskey: ref.skey,\n\t\t\t\t\tmanage,\n\t\t\t\t});\n\t\t\t\tif (scopeError) return scopeError;\n\t\t\t}\n\t\t\tif (ref.authority !== session.did || ref.authority !== host.operatorDid) {\n\t\t\t\tthrow new SpaceError(\"NotAuthorized\", \"Not the space authority\");\n\t\t\t}\n\t\t\tconst policy = normalizePolicy(archive.policy);\n\t\t\tconst members = parsePolicyState(policy, archive.policyState);\n\n\t\t\tconst index = host.getIndexDO();\n\t\t\tawait index.rpcRegister({\n\t\t\t\turi: ref.uri,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\ttype: ref.type,\n\t\t\t\tskey: ref.skey,\n\t\t\t\tisAuthority: true,\n\t\t\t});\n\t\t\tawait host.getSpaceDO(ref.uri).rpcImportMeta({\n\t\t\t\turi: ref.uri,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\ttype: ref.type,\n\t\t\t\tskey: ref.skey,\n\t\t\t\tpolicy,\n\t\t\t\tmembers,\n\t\t\t\twriters: archive.writers.map((writer) => ({\n\t\t\t\t\tdid: writer.did,\n\t\t\t\t\trepoRev: writer.repoRev,\n\t\t\t\t\tdata: writer.data,\n\t\t\t\t\tspaceRev: writer.spaceRev,\n\t\t\t\t\tremoved: false,\n\t\t\t\t})),\n\t\t\t});\n\t\t\tawait index.rpcActivate(ref.uri);\n\t\t\treturn c.json({});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.get(\"/xrpc/com.atproto.space.listSpaces\", async (c) => {\n\t\ttry {\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst type = c.req.query(\"spaceType\") || undefined;\n\t\t\tconst authority = c.req.query(\"spaceDid\") || undefined;\n\t\t\t// No one space to check against, so the filters are the target:\n\t\t\t// an unfiltered listing needs a wildcard grant. It lists only the\n\t\t\t// caller's own spaces, so read_self is the grant that fits.\n\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\ttype: type ?? \"*\",\n\t\t\t\tauthority: authority ?? \"*\",\n\t\t\t\tskey: \"*\",\n\t\t\t\taction: \"read_self\",\n\t\t\t});\n\t\t\tif (scopeError) return scopeError;\n\t\t\tconst limit = clampLimit(c.req.query(\"limit\"), 50, 100);\n\t\t\tconst cursor = c.req.query(\"cursor\") || undefined;\n\t\t\tif (cursor && !parseSpaceUri(cursor)) {\n\t\t\t\tthrow new SpaceError(\"InvalidCursor\", `Malformed cursor: ${cursor}`);\n\t\t\t}\n\t\t\tconst page = await host.getIndexDO().rpcList({\n\t\t\t\ttype,\n\t\t\t\tauthority,\n\t\t\t\tstate: \"active\",\n\t\t\t\tlimit,\n\t\t\t\tafterUri: cursor,\n\t\t\t});\n\t\t\t// The caller's repo state in each space, and the space's revision\n\t\t\t// where the caller is its authority.\n\t\t\tconst spaces = await Promise.all(\n\t\t\t\tpage.spaces.map(async (space) => {\n\t\t\t\t\tconst view = await host.getSpaceDO(space.uri).rpcGetSpaceView();\n\t\t\t\t\treturn {\n\t\t\t\t\t\tspace: space.uri,\n\t\t\t\t\t\t...(view?.repoRev ? { repoRev: view.repoRev } : {}),\n\t\t\t\t\t\t...(view?.data\n\t\t\t\t\t\t\t? { data: bytesToJson(new Uint8Array(view.data)) }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t...(view?.spaceRev ? { spaceRev: view.spaceRev } : {}),\n\t\t\t\t\t};\n\t\t\t\t}),\n\t\t\t);\n\t\t\tconst last = page.spaces[page.spaces.length - 1];\n\t\t\treturn c.json({\n\t\t\t\tspaces,\n\t\t\t\t...(page.hasMore && last ? { cursor: last.uri } : {}),\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\t// ---------------------------------------------------------------\n\t// memberspace (authority role, session auth)\n\t// ---------------------------------------------------------------\n\n\tapp.post(\"/xrpc/com.atproto.memberspace.putMembers\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{ space?: string; members?: unknown }>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\tconst members = parseMemberBatch(body.members);\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\ttype: ref.type,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\tskey: ref.skey,\n\t\t\t\tmanage: \"update\",\n\t\t\t});\n\t\t\tif (scopeError) return scopeError;\n\t\t\tassertOwner(ref, session);\n\t\t\tawait assertActiveSpaceHost(ref);\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tconst commit = await stub.rpcPutMembers(members);\n\t\t\tafterConfigCommit(c, ref, stub, commit);\n\t\t\treturn c.json({});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.post(\"/xrpc/com.atproto.memberspace.removeMembers\", async (c) => {\n\t\ttry {\n\t\t\tconst body = await c.req.json<{ space?: string; dids?: unknown }>();\n\t\t\tconst ref = requireSpaceUri(body.space);\n\t\t\tconst dids = body.dids;\n\t\t\tif (\n\t\t\t\t!Array.isArray(dids) ||\n\t\t\t\tdids.length > MAX_MEMBER_BATCH ||\n\t\t\t\tdids.some((did) => typeof did !== \"string\" || !did.startsWith(\"did:\"))\n\t\t\t) {\n\t\t\t\tthrow new SpaceError(\n\t\t\t\t\t\"InvalidRequest\",\n\t\t\t\t\t`dids must be an array of at most ${MAX_MEMBER_BATCH} DIDs`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\ttype: ref.type,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\tskey: ref.skey,\n\t\t\t\tmanage: \"update\",\n\t\t\t});\n\t\t\tif (scopeError) return scopeError;\n\t\t\tassertOwner(ref, session);\n\t\t\tawait assertActiveSpaceHost(ref);\n\t\t\tconst stub = host.getSpaceDO(ref.uri);\n\t\t\tconst commit = await stub.rpcRemoveMembers(dids as string[]);\n\t\t\tafterConfigCommit(c, ref, stub, commit);\n\t\t\treturn c.json({});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\tapp.get(\"/xrpc/com.atproto.memberspace.listMembers\", async (c) => {\n\t\ttry {\n\t\t\tconst ref = requireSpaceUri(c.req.query(\"space\"));\n\t\t\tconst session = await host.authenticate(c);\n\t\t\tif (session instanceof Response) return session;\n\t\t\tconst scopeError = assertScope(c, session, {\n\t\t\t\ttype: ref.type,\n\t\t\t\tauthority: ref.authority,\n\t\t\t\tskey: ref.skey,\n\t\t\t\taction: \"read_self\",\n\t\t\t});\n\t\t\tif (scopeError) return scopeError;\n\t\t\tassertOwner(ref, session);\n\t\t\tconst limit = clampLimit(c.req.query(\"limit\"), 100, 1000);\n\t\t\t// The cursor is the last member DID of the previous page.\n\t\t\tconst cursor = c.req.query(\"cursor\");\n\t\t\tif (cursor !== undefined && !isDid(cursor)) {\n\t\t\t\tthrow new SpaceError(\"InvalidCursor\", `Malformed cursor: ${cursor}`);\n\t\t\t}\n\t\t\tconst page = await host.getSpaceDO(ref.uri).rpcListMembers({\n\t\t\t\tlimit,\n\t\t\t\tafterDid: cursor,\n\t\t\t});\n\t\t\tconst last = page.members[page.members.length - 1];\n\t\t\treturn c.json({\n\t\t\t\tmembers: page.members.map((member) => ({\n\t\t\t\t\tdid: member.did,\n\t\t\t\t\tread: member.read,\n\t\t\t\t\twrite: member.write,\n\t\t\t\t})),\n\t\t\t\t...(page.hasMore && last ? { cursor: last.did } : {}),\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn errorResponse(c, err);\n\t\t}\n\t});\n\n\t// ---------------------------------------------------------------\n\t// Helpers that need the host\n\t// ---------------------------------------------------------------\n\n\t/**\n\t * Before registering a webhook, check it asked to be: the endpoint must\n\t * recognise the token as one it issued for this space and echo back a\n\t * random challenge. The endpoint is the requester's choice, so it is\n\t * fetched as untrusted: https only, no redirects, bounded in time.\n\t */\n\tasync function confirmRegistration(\n\t\tref: SpaceRef,\n\t\tnotify: NotifyRegistration,\n\t): Promise<void> {\n\t\tconst challenge = crypto.randomUUID();\n\t\ttry {\n\t\t\tconst res = await doFetch(\n\t\t\t\t`${notify.endpoint.replace(/\\/$/, \"\")}/xrpc/${CONFIRM_REGISTRATION_LXM}`,\n\t\t\t\t{\n\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\t\tspace: ref.uri,\n\t\t\t\t\t\ttoken: notify.token,\n\t\t\t\t\t\tchallenge,\n\t\t\t\t\t}),\n\t\t\t\t\tredirect: \"manual\",\n\t\t\t\t\tsignal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS),\n\t\t\t\t},\n\t\t\t);\n\t\t\tif (res.ok) {\n\t\t\t\tconst body = (await res.json()) as { challenge?: unknown };\n\t\t\t\tif (body.challenge === challenge) return;\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tconsole.warn(`registration for ${ref.uri} not confirmed:`, err);\n\t\t}\n\t\tthrow new SpaceError(\n\t\t\t\"RegistrationNotConfirmed\",\n\t\t\t\"Notify endpoint did not confirm the registration\",\n\t\t);\n\t}\n\n\t/** Service auth for inbound notifications; a Response on failure. */\n\tasync function requireServiceAuth(\n\t\tc: Context,\n\t\tlxm: string,\n\t): Promise<{ iss: string; aud: string } | Response> {\n\t\tconst authHeader = c.req.header(\"Authorization\");\n\t\tif (!authHeader?.startsWith(\"Bearer \")) {\n\t\t\treturn c.json(\n\t\t\t\t{ error: \"AuthenticationRequired\", message: \"Service auth required\" },\n\t\t\t\t401,\n\t\t\t);\n\t\t}\n\t\ttry {\n\t\t\treturn await host.verifyServiceJwt(authHeader.slice(7), lxm);\n\t\t} catch (err) {\n\t\t\treturn c.json(\n\t\t\t\t{\n\t\t\t\t\terror: \"AuthenticationRequired\",\n\t\t\t\t\tmessage: err instanceof Error ? err.message : \"Invalid service auth\",\n\t\t\t\t},\n\t\t\t\t401,\n\t\t\t);\n\t\t}\n\t}\n\n\tfunction isOwnAudience(aud: string): boolean {\n\t\treturn aud === host.operatorDid || aud.startsWith(`${host.operatorDid}#`);\n\t}\n\n\t/**\n\t * A repo exists in a space once the operator has written into it (or\n\t * the space was created here). RepoNotFound deliberately covers both\n\t * \"no such repo\" and \"space unknown to this host\".\n\t */\n\tasync function requireRepoExists(\n\t\tstub: SpaceStub,\n\t\tref: SpaceRef,\n\t): Promise<void> {\n\t\tconst meta = await stub.rpcGetMeta();\n\t\tif (meta?.deletedAt) {\n\t\t\t// After deletion, reads against the space fail with SpaceNotFound.\n\t\t\tthrow new SpaceError(\"SpaceNotFound\", `Space not found: ${ref.uri}`);\n\t\t}\n\t\tif (!meta) {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"RepoNotFound\",\n\t\t\t\t`Could not find repo for space: ${ref.uri}`,\n\t\t\t);\n\t\t}\n\t}\n\n\treturn app;\n}\n\n// ---------------------------------------------------------------------\n// Small parsing helpers\n// ---------------------------------------------------------------------\n\nfunction requireString(value: unknown, name: string): asserts value is string {\n\tif (typeof value !== \"string\" || value.length === 0) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidRequest\",\n\t\t\t`Missing required parameter: ${name}`,\n\t\t);\n\t}\n}\n\n/**\n * An authorizeSpaceSync `notify`: an https base URL the space host calls\n * XRPC methods against, and the opaque token that authenticates them.\n */\nfunction parseNotify(input: unknown): NotifyRegistration {\n\tconst notify = input as { endpoint?: unknown; token?: unknown } | null;\n\tconst endpoint = notify?.endpoint;\n\tconst token = notify?.token;\n\tif (typeof endpoint !== \"string\" || typeof token !== \"string\") {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidRequest\",\n\t\t\t\"notify requires an endpoint and a token\",\n\t\t);\n\t}\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(endpoint);\n\t} catch {\n\t\tthrow new SpaceError(\"InvalidRequest\", \"notify endpoint must be a URL\");\n\t}\n\tif (url.protocol !== \"https:\" || url.username || url.password) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidRequest\",\n\t\t\t\"notify endpoint must be a plain https URL\",\n\t\t);\n\t}\n\tif (token.length === 0 || token.length > MAX_NOTIFY_TOKEN_LENGTH) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidRequest\",\n\t\t\t`notify token must be 1 to ${MAX_NOTIFY_TOKEN_LENGTH} characters`,\n\t\t);\n\t}\n\treturn { endpoint, token };\n}\n\nfunction requireDid(value: unknown, name: string): asserts value is string {\n\trequireString(value, name);\n\tif (!value.startsWith(\"did:\")) {\n\t\tthrow new SpaceError(\"InvalidRequest\", `${name} must be a DID`);\n\t}\n}\n\nfunction clampLimit(\n\traw: string | undefined,\n\tfallback: number,\n\tmax: number,\n): number {\n\tconst parsed = raw ? Number.parseInt(raw, 10) : fallback;\n\tif (Number.isNaN(parsed) || parsed < 1) return fallback;\n\treturn Math.min(parsed, max);\n}\n\nfunction parseRecordCursor(\n\tcursor: string | undefined,\n): { collection: string; rkey: string } | undefined {\n\tif (!cursor) return undefined;\n\tconst slash = cursor.lastIndexOf(\"/\");\n\tif (slash <= 0 || slash === cursor.length - 1) {\n\t\tthrow new SpaceError(\"InvalidCursor\", `Malformed cursor: ${cursor}`);\n\t}\n\treturn { collection: cursor.slice(0, slash), rkey: cursor.slice(slash + 1) };\n}\n\nfunction parseOpsCursor(\n\tcursor: string | undefined,\n): { rev: string; idx: number } | undefined {\n\tif (!cursor) return undefined;\n\tconst slash = cursor.indexOf(\"/\");\n\tconst idx = slash === -1 ? NaN : Number.parseInt(cursor.slice(slash + 1), 10);\n\tif (slash <= 0 || Number.isNaN(idx)) {\n\t\tthrow new SpaceError(\"InvalidCursor\", `Malformed cursor: ${cursor}`);\n\t}\n\treturn { rev: cursor.slice(0, slash), idx };\n}\n\n/**\n * Read the members out of a space meta archive's policy state. A key the\n * policy doesn't define is refused rather than dropped, since dropping it\n * would quietly change who has access to the space.\n */\nfunction parsePolicyState(\n\tpolicy: SpacePolicy,\n\tentries: Array<{ key: string; value: Record<string, unknown> }>,\n): SpaceMember[] {\n\tconst prefix = `${MEMBER_COLLECTION}/`;\n\treturn entries.map(({ key, value }) => {\n\t\tconst did = key.startsWith(prefix)\n\t\t\t? recordKeyToDid(key.slice(prefix.length))\n\t\t\t: undefined;\n\t\tif (policy.$type !== MEMBERSPACE_POLICY || !did?.startsWith(\"did:\")) {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"InvalidRequest\",\n\t\t\t\t`Unrecognized policy state: ${key}`,\n\t\t\t);\n\t\t}\n\t\tif (typeof value.read !== \"boolean\" || typeof value.write !== \"boolean\") {\n\t\t\tthrow new SpaceError(\"InvalidRequest\", `Invalid member at ${key}`);\n\t\t}\n\t\treturn { did, read: value.read, write: value.write };\n\t});\n}\n\n/**\n * A malformed archive in a request body is the caller's error, reported\n * under the error name the method declares for it.\n */\nfunction invalidArchive(\n\terr: unknown,\n\tcode: \"InvalidRepoFile\" | \"InvalidSpaceMeta\",\n): unknown {\n\tif (parseSpaceErrorCode(err)) return err;\n\treturn new SpaceError(\n\t\tcode,\n\t\t`Invalid archive: ${err instanceof Error ? err.message : String(err)}`,\n\t);\n}\n\n/** A putMembers batch: at most 100 `{did, read, write}` entries. */\nfunction parseMemberBatch(input: unknown): SpaceMember[] {\n\tif (!Array.isArray(input) || input.length > MAX_MEMBER_BATCH) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidRequest\",\n\t\t\t`members must be an array of at most ${MAX_MEMBER_BATCH} entries`,\n\t\t);\n\t}\n\treturn input.map((entry, i) => {\n\t\tconst member = entry as { did?: unknown; read?: unknown; write?: unknown };\n\t\tif (\n\t\t\ttypeof member?.did !== \"string\" ||\n\t\t\t!member.did.startsWith(\"did:\") ||\n\t\t\ttypeof member.read !== \"boolean\" ||\n\t\t\ttypeof member.write !== \"boolean\"\n\t\t) {\n\t\t\tthrow new SpaceError(\n\t\t\t\t\"InvalidRequest\",\n\t\t\t\t`members[${i}] must be {did, read, write}`,\n\t\t\t);\n\t\t}\n\t\treturn { did: member.did, read: member.read, write: member.write };\n\t});\n}\n\nasync function readBody(c: Context): Promise<Uint8Array> {\n\tconst contentType = c.req.header(\"Content-Type\")?.split(\";\")[0]?.trim();\n\tif (contentType !== STAR_CONTENT_TYPE) {\n\t\tthrow new SpaceError(\n\t\t\t\"InvalidRequest\",\n\t\t\t`Content-Type must be ${STAR_CONTENT_TYPE}`,\n\t\t);\n\t}\n\tconst declared = Number.parseInt(c.req.header(\"Content-Length\") ?? \"\", 10);\n\tif (declared > MAX_IMPORT_BYTES) {\n\t\tthrow new SpaceError(\"InvalidRequest\", \"Archive is too large\");\n\t}\n\tconst bytes = new Uint8Array(await c.req.arrayBuffer());\n\tif (bytes.length === 0) {\n\t\tthrow new SpaceError(\"InvalidRequest\", \"Empty archive\");\n\t}\n\tif (bytes.length > MAX_IMPORT_BYTES) {\n\t\tthrow new SpaceError(\"InvalidRequest\", \"Archive is too large\");\n\t}\n\treturn bytes;\n}\n\n/** A pull-based stream over an async iterable, cancelling it on abort. */\nfunction asyncIterableToStream(\n\titerable: AsyncIterable<Uint8Array>,\n): ReadableStream<Uint8Array> {\n\tconst iterator = iterable[Symbol.asyncIterator]();\n\treturn new ReadableStream<Uint8Array>({\n\t\tasync pull(controller) {\n\t\t\ttry {\n\t\t\t\tconst { value, done } = await iterator.next();\n\t\t\t\tif (done) controller.close();\n\t\t\t\telse controller.enqueue(value);\n\t\t\t} catch (err) {\n\t\t\t\tcontroller.error(err);\n\t\t\t}\n\t\t},\n\t\tasync cancel() {\n\t\t\tawait iterator.return?.();\n\t\t},\n\t});\n}\n\nasync function deleteR2Prefix(bucket: R2Bucket, prefix: string): Promise<void> {\n\tlet cursor: string | undefined;\n\tdo {\n\t\tconst listed = await bucket.list({ prefix, cursor, limit: 500 });\n\t\tif (listed.objects.length > 0) {\n\t\t\tawait bucket.delete(listed.objects.map((object) => object.key));\n\t\t}\n\t\tcursor = listed.truncated ? listed.cursor : undefined;\n\t} while (cursor);\n}\n","/**\n * Delegation tokens, minted by the user's PDS for a space hosted anywhere.\n *\n * Thin wrappers over `@atproto/space`, so a host gets them without\n * depending on that package's types directly.\n */\n\nimport {\n\tcreateDelegationToken as upstreamCreateDelegationToken,\n\tspaceHostAud as upstreamSpaceHostAud,\n} from \"@atproto/space\";\nimport type { SpaceSigningKeypair } from \"./types.js\";\n\n/**\n * How a space authority is addressed as the space host: its `#atproto_pds`\n * service entry, the audience of delegation tokens and client attestations.\n */\nexport function spaceHostAud(authority: string): string {\n\treturn upstreamSpaceHostAud(authority as `did:${string}:${string}`);\n}\n\n/**\n * Mint a delegation token: the user's PDS vouching, for 60 seconds and one\n * use, that `iss` wants a credential for `space` from its authority.\n */\nexport function createDelegationToken(\n\tparams: { iss: string; space: string; authority: string },\n\tkeypair: SpaceSigningKeypair,\n): Promise<string> {\n\treturn upstreamCreateDelegationToken({\n\t\tiss: params.iss as `did:${string}:${string}`,\n\t\tsub: params.space as never,\n\t\taud: spaceHostAud(params.authority) as never,\n\t\tkeyp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