@getcirrus/spaces 0.0.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.
@@ -0,0 +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\treturn new SpaceError(\"InvalidCredential\", authErrorMessage(err));\n}\n\nfunction invalidDelegation(err: unknown): SpaceError {\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;CACA;CACA;CACA;CACA;AAID,MAAMA,WAAgC,IAAI,IAAI,kBAAkB;;AAGhE,MAAMC,eAAwD;CAC7D,eAAe;CACf,cAAc;CACd,cAAc;CACd,qBAAqB;CACrB,oBAAoB;CACpB,mBAAmB;CACnB,kBAAkB;CAClB,eAAe;CACf,eAAe;CACf,wBAAwB;CACxB,0BAA0B;CAC1B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AAM,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"}
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "@getcirrus/spaces",
3
+ "version": "0.0.0",
4
+ "description": "Atproto spaces engine (alpha) for Cloudflare Workers – permissioned repos, space hosting and credentials",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "files": [
8
+ "dist"
9
+ ],
10
+ "exports": {
11
+ ".": "./dist/index.js"
12
+ },
13
+ "dependencies": {
14
+ "@atcute/cid": "^2.3.0",
15
+ "@atproto/crypto": "^0.4.5",
16
+ "@atproto/lex-cbor": "^0.1.6",
17
+ "@atproto/lex-data": "^0.1.7",
18
+ "@atproto/lex-json": "^0.1.6",
19
+ "@atproto/space": "0.0.0-spaces-alpha-20260818163953",
20
+ "@atcute/tid": "^1.1.1",
21
+ "hono": "^4.11.3",
22
+ "@atcute/lexicons": "^1.2.6",
23
+ "jose": "^5.2.0"
24
+ },
25
+ "devDependencies": {
26
+ "@arethetypeswrong/cli": "^0.18.2",
27
+ "@cloudflare/vitest-pool-workers": "^0.16.9",
28
+ "@cloudflare/workers-types": "^4.20260524.1",
29
+ "@atproto/jwk-jose": "^0.2.1",
30
+ "publint": "^0.3.16",
31
+ "tsdown": "^0.18.3",
32
+ "typescript": "^5.9.3",
33
+ "vitest": "4.1.0-beta.1",
34
+ "wrangler": "^4.93.0"
35
+ },
36
+ "repository": {
37
+ "type": "git",
38
+ "url": "git+https://github.com/ascorbic/cirrus.git",
39
+ "directory": "packages/spaces"
40
+ },
41
+ "homepage": "https://github.com/ascorbic/cirrus",
42
+ "keywords": [
43
+ "atproto",
44
+ "spaces",
45
+ "permissioned-data",
46
+ "cloudflare-workers"
47
+ ],
48
+ "author": "Matt Kane",
49
+ "license": "MIT",
50
+ "scripts": {
51
+ "build": "tsdown",
52
+ "dev": "tsdown --watch",
53
+ "test": "vitest run",
54
+ "check": "publint && attw --pack --ignore-rules=cjs-resolves-to-esm"
55
+ }
56
+ }