@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.
package/dist/index.js ADDED
@@ -0,0 +1,2519 @@
1
+ import { DurableObject } from "cloudflare:workers";
2
+ import { DpopProofError, RepoCommit, SPACE_TOKEN_TYPES, SpaceTokenError, createSpaceToken, parseSpaceToken, serializeRepo, spaceHostAud, verifyDpopProof, verifySpaceToken } from "@atproto/space";
3
+ import { now } from "@atcute/tid";
4
+ import { isDid, isNsid, isRecordKey } from "@atcute/lexicons/syntax";
5
+ import { Hono } from "hono";
6
+ import { enumBlobRefs, fromBase64, getBlobCidString, parseCid, toBase64 } from "@atproto/lex-data";
7
+ import { createLocalJWKSet, jwtVerify } from "jose";
8
+ import { cidForLex, decode, encode } from "@atproto/lex-cbor";
9
+ import { jsonToLex, lexToJson } from "@atproto/lex-json";
10
+
11
+ //#region src/errors.ts
12
+ /**
13
+ * Typed errors for the spaces engine.
14
+ *
15
+ * Durable Object RPC flattens thrown errors into a wrapper `Error` whose
16
+ * message is `"${name}: ${message}"`, so every error here encodes its
17
+ * protocol error name as a message prefix. Worker-side handlers recover the
18
+ * name with {@link parseSpaceErrorCode} and map it onto the lexicon error
19
+ * shape.
20
+ */
21
+ /** Protocol error names used across space and simplespace endpoints. */
22
+ const SPACE_ERROR_CODES = [
23
+ "SpaceNotFound",
24
+ "SpaceDeleted",
25
+ "SpaceAlreadyExists",
26
+ "RepoNotFound",
27
+ "RecordNotFound",
28
+ "RecordAlreadyExists",
29
+ "BlobNotFound",
30
+ "UserNotAuthorized",
31
+ "AppNotAuthorized",
32
+ "NotAuthorized",
33
+ "InvalidDelegationToken",
34
+ "InvalidClientAttestation",
35
+ "InvalidCredential",
36
+ "NotSpaceOwner",
37
+ "UnsupportedPolicy",
38
+ "UnsupportedAppAccess",
39
+ "ServiceNotResolvable",
40
+ "MalformedCursor",
41
+ "InvalidSpaceUri",
42
+ "InvalidRequest",
43
+ "SpacesSchemaOutdated"
44
+ ];
45
+ const CODE_SET = new Set(SPACE_ERROR_CODES);
46
+ /** HTTP status for each error name when it isn't the default 400. */
47
+ const ERROR_STATUS = {
48
+ SpaceNotFound: 404,
49
+ RepoNotFound: 404,
50
+ BlobNotFound: 404,
51
+ RecordAlreadyExists: 409,
52
+ SpaceAlreadyExists: 409,
53
+ UserNotAuthorized: 403,
54
+ AppNotAuthorized: 403,
55
+ NotAuthorized: 403,
56
+ NotSpaceOwner: 403,
57
+ InvalidDelegationToken: 401,
58
+ InvalidClientAttestation: 401,
59
+ InvalidCredential: 401,
60
+ SpacesSchemaOutdated: 503
61
+ };
62
+ var SpaceError = class extends Error {
63
+ name = "SpaceError";
64
+ constructor(code, message) {
65
+ super(`${code}: ${message}`);
66
+ this.code = code;
67
+ }
68
+ get status() {
69
+ return ERROR_STATUS[this.code] ?? 400;
70
+ }
71
+ /** The human message without the code prefix. */
72
+ get detail() {
73
+ return this.message.slice(this.code.length + 2);
74
+ }
75
+ };
76
+ /**
77
+ * Recover the space error name from an error that may have crossed a DO RPC
78
+ * boundary. Returns null for errors that aren't space errors.
79
+ */
80
+ function parseSpaceErrorCode(err) {
81
+ if (err instanceof SpaceError) return {
82
+ code: err.code,
83
+ message: err.detail
84
+ };
85
+ if (err instanceof Error) {
86
+ let message = err.message;
87
+ for (let hop = 0; hop < 3; hop++) {
88
+ const colon = message.indexOf(": ");
89
+ if (colon <= 0) break;
90
+ const code = message.slice(0, colon);
91
+ if (CODE_SET.has(code)) return {
92
+ code,
93
+ message: message.slice(colon + 2)
94
+ };
95
+ message = message.slice(colon + 2);
96
+ }
97
+ }
98
+ return null;
99
+ }
100
+ /** HTTP status for a recovered space error name. */
101
+ function spaceErrorStatus(code) {
102
+ return ERROR_STATUS[code] ?? 400;
103
+ }
104
+
105
+ //#endregion
106
+ //#region src/schema.ts
107
+ /**
108
+ * SQLite schema for SpaceDurableObject.
109
+ *
110
+ * Mirrors the reference PDS's `002-space` migration table for table, minus
111
+ * the `space` column on every row — one DO per space makes it redundant.
112
+ *
113
+ * There is no migration path between alpha schema versions: bumping
114
+ * {@link SPACE_SCHEMA_VERSION} puts existing DOs into a refusing state until
115
+ * `pds spaces reset` wipes them. That is the alpha policy, applied honestly.
116
+ */
117
+ /** Bump on any breaking change to the tables below. */
118
+ const SPACE_SCHEMA_VERSION = 1;
119
+ const SPACE_DO_SCHEMA = `
120
+ -- One row. schema_version is checked on every open.
121
+ CREATE TABLE IF NOT EXISTS meta (
122
+ uri TEXT NOT NULL,
123
+ authority TEXT NOT NULL,
124
+ type TEXT NOT NULL,
125
+ skey TEXT NOT NULL,
126
+ is_authority INTEGER NOT NULL,
127
+ created_at TEXT NOT NULL,
128
+ deleted_at TEXT,
129
+ schema_version INTEGER NOT NULL
130
+ );
131
+
132
+ -- Operator's permissioned repo in this space.
133
+ CREATE TABLE IF NOT EXISTS record (
134
+ collection TEXT NOT NULL,
135
+ rkey TEXT NOT NULL,
136
+ cid TEXT NOT NULL,
137
+ bytes BLOB NOT NULL,
138
+ rev TEXT NOT NULL,
139
+ indexed_at TEXT NOT NULL,
140
+ PRIMARY KEY (collection, rkey)
141
+ );
142
+ CREATE INDEX IF NOT EXISTS idx_record_rev ON record(rev);
143
+
144
+ CREATE TABLE IF NOT EXISTS record_blob (
145
+ blob_cid TEXT NOT NULL,
146
+ collection TEXT NOT NULL,
147
+ rkey TEXT NOT NULL,
148
+ PRIMARY KEY (blob_cid, collection, rkey)
149
+ );
150
+ CREATE INDEX IF NOT EXISTS idx_record_blob_record ON record_blob(collection, rkey);
151
+
152
+ CREATE TABLE IF NOT EXISTS repo_state (
153
+ id INTEGER PRIMARY KEY CHECK (id = 1),
154
+ set_hash BLOB NOT NULL,
155
+ rev TEXT NOT NULL
156
+ );
157
+
158
+ CREATE TABLE IF NOT EXISTS oplog (
159
+ rev TEXT NOT NULL,
160
+ idx INTEGER NOT NULL,
161
+ collection TEXT NOT NULL,
162
+ rkey TEXT NOT NULL,
163
+ cid TEXT,
164
+ prev TEXT,
165
+ PRIMARY KEY (rev, idx)
166
+ );
167
+
168
+ -- Authority role only.
169
+ CREATE TABLE IF NOT EXISTS config (
170
+ id INTEGER PRIMARY KEY CHECK (id = 1),
171
+ policy TEXT NOT NULL,
172
+ managing_app TEXT,
173
+ app_access TEXT NOT NULL,
174
+ app_allowed TEXT NOT NULL
175
+ );
176
+
177
+ CREATE TABLE IF NOT EXISTS member (did TEXT PRIMARY KEY);
178
+
179
+ CREATE TABLE IF NOT EXISTS writer (
180
+ did TEXT PRIMARY KEY,
181
+ rev TEXT NOT NULL,
182
+ hash BLOB NOT NULL
183
+ );
184
+
185
+ CREATE TABLE IF NOT EXISTS notify_registration (
186
+ service TEXT PRIMARY KEY,
187
+ endpoint TEXT NOT NULL,
188
+ expires_at TEXT NOT NULL
189
+ );
190
+
191
+ CREATE TABLE IF NOT EXISTS notify_queue (
192
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
193
+ service TEXT NOT NULL,
194
+ body TEXT NOT NULL,
195
+ attempts INTEGER NOT NULL DEFAULT 0,
196
+ next_at INTEGER NOT NULL
197
+ );
198
+ CREATE INDEX IF NOT EXISTS idx_notify_queue_next ON notify_queue(next_at);
199
+
200
+ -- Replay protection, both roles.
201
+ CREATE TABLE IF NOT EXISTS replay (
202
+ kind TEXT NOT NULL,
203
+ key TEXT NOT NULL,
204
+ expires_at INTEGER NOT NULL,
205
+ PRIMARY KEY (kind, key)
206
+ );
207
+ `;
208
+ /** Retain oplog entries for at most this many days. */
209
+ const OPLOG_RETENTION_DAYS = 30;
210
+ /** Retain at most this many oplog entries. */
211
+ const OPLOG_RETENTION_OPS = 1e4;
212
+ /** Notify registrations expire after this many days. */
213
+ const NOTIFY_REGISTRATION_DAYS = 7;
214
+ /** Give up delivering a notification after this many attempts. */
215
+ const NOTIFY_MAX_ATTEMPTS = 5;
216
+ /** Base delay for notification retry backoff, in milliseconds. */
217
+ const NOTIFY_BACKOFF_BASE_MS = 3e4;
218
+ const INDEX_DO_SCHEMA = `
219
+ CREATE TABLE IF NOT EXISTS space (
220
+ uri TEXT PRIMARY KEY,
221
+ authority TEXT NOT NULL,
222
+ type TEXT NOT NULL,
223
+ skey TEXT NOT NULL,
224
+ is_authority INTEGER NOT NULL,
225
+ state TEXT NOT NULL, -- 'pending' | 'active' | 'deleted'
226
+ created_at TEXT NOT NULL,
227
+ updated_at TEXT NOT NULL,
228
+ schema_version INTEGER NOT NULL
229
+ );
230
+ CREATE INDEX IF NOT EXISTS idx_space_state ON space(state);
231
+ `;
232
+ /** Remove `pending` index entries that never activated after this long. */
233
+ const PENDING_ENTRY_TTL_MS = 1440 * 60 * 1e3;
234
+
235
+ //#endregion
236
+ //#region src/tid.ts
237
+ /**
238
+ * Revision (TID) helpers for the space repo.
239
+ */
240
+ const S32_CHAR = "234567abcdefghijklmnopqrstuvwxyz";
241
+ /**
242
+ * Next revision: a fresh TID guaranteed strictly greater than `prev`.
243
+ * `@atcute/tid`'s clock is monotonic within an isolate, but the previous
244
+ * rev may come from a different isolate's clock (e.g. after a DO restart),
245
+ * so bump lexicographically when needed.
246
+ */
247
+ function nextRev(prev) {
248
+ const candidate = now();
249
+ if (!prev || candidate > prev) return candidate;
250
+ const chars = prev.split("");
251
+ for (let i = chars.length - 1; i >= 0; i--) {
252
+ const idx = S32_CHAR.indexOf(chars[i]);
253
+ if (idx < 31) {
254
+ chars[i] = S32_CHAR[idx + 1];
255
+ return chars.join("");
256
+ }
257
+ chars[i] = S32_CHAR[0];
258
+ }
259
+ return candidate;
260
+ }
261
+ /**
262
+ * The smallest TID whose timestamp is `ms` milliseconds in the past, with a
263
+ * zero clockid. Used as a deletion cutoff for oplog compaction.
264
+ */
265
+ function tidCutoff(msAgo) {
266
+ let value = BigInt(Math.max(0, Date.now() - msAgo)) * 1000n << 10n & (1n << 63n) - 1n;
267
+ let out = "";
268
+ for (let i = 12; i >= 0; i--) {
269
+ out = S32_CHAR[Number(value & 31n)] + out;
270
+ value >>= 5n;
271
+ }
272
+ return out;
273
+ }
274
+
275
+ //#endregion
276
+ //#region src/service-jwt.ts
277
+ const encoder = new TextEncoder();
278
+ function base64url(bytes) {
279
+ let bin = "";
280
+ for (const b of bytes) bin += String.fromCharCode(b);
281
+ return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
282
+ }
283
+ async function createServiceJwt(params, keypair) {
284
+ const iat = Math.floor(Date.now() / 1e3);
285
+ const header = {
286
+ typ: "JWT",
287
+ alg: keypair.jwtAlg
288
+ };
289
+ const payload = {
290
+ iat,
291
+ iss: params.iss,
292
+ aud: params.aud,
293
+ exp: iat + (params.expiresInSec ?? 60),
294
+ jti: crypto.randomUUID()
295
+ };
296
+ if (params.lxm) payload.lxm = params.lxm;
297
+ const signingInput = `${base64url(encoder.encode(JSON.stringify(header)))}.${base64url(encoder.encode(JSON.stringify(payload)))}`;
298
+ return `${signingInput}.${base64url(await keypair.sign(encoder.encode(signingInput)))}`;
299
+ }
300
+
301
+ //#endregion
302
+ //#region src/space-do.ts
303
+ /**
304
+ * SpaceDurableObject – one instance per space, addressed by
305
+ * `idFromName(spaceUri)`.
306
+ *
307
+ * Holds everything Cirrus knows about that space: the operator's
308
+ * permissioned repo (records, oplog, LtHash state, blob references) and,
309
+ * when the operator is the authority, the simplespace config, member list,
310
+ * writer set, notification registrations and the outbound notification
311
+ * queue. Also the replay tables for DPoP proofs and delegation tokens
312
+ * presented against the space.
313
+ *
314
+ * Constraints inherited from the Cirrus architecture:
315
+ * - No R2 I/O in here, ever. Blobs are the Worker's job.
316
+ * - Commits are never signed here; the signing key never enters this class
317
+ * except through {@link SpaceHostConfig.getKeypair}, which is used only
318
+ * for outbound notification service JWTs from the alarm.
319
+ * - The host supplies its identity via {@link getHostConfig}; this class
320
+ * must not read `env.DID`. If it ever contains a branch on which host is
321
+ * running it, the boundary has failed.
322
+ */
323
+ const DAY_MS = 1440 * 60 * 1e3;
324
+ /** Interval between maintenance passes (compaction, replay cleanup). */
325
+ const MAINTENANCE_INTERVAL_MS = DAY_MS;
326
+ /** How many queued notifications to attempt per alarm invocation. */
327
+ const NOTIFY_BATCH = 20;
328
+ var SpaceDurableObject = class extends DurableObject {
329
+ sql;
330
+ initialized = false;
331
+ outdated = false;
332
+ constructor(ctx, env) {
333
+ super(ctx, env);
334
+ this.sql = ctx.storage.sql;
335
+ }
336
+ async ensureInitialized() {
337
+ if (this.initialized) return;
338
+ await this.ctx.blockConcurrencyWhile(async () => {
339
+ if (this.initialized) return;
340
+ if (this.sql.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'meta'").toArray().length > 0) {
341
+ const row = this.sql.exec("SELECT schema_version FROM meta LIMIT 1").toArray()[0];
342
+ if (row && row.schema_version !== SPACE_SCHEMA_VERSION) {
343
+ this.outdated = true;
344
+ this.initialized = true;
345
+ return;
346
+ }
347
+ }
348
+ this.sql.exec(SPACE_DO_SCHEMA);
349
+ this.initialized = true;
350
+ });
351
+ }
352
+ /**
353
+ * Gate every RPC: initialise storage and refuse when the stored schema
354
+ * belongs to a different alpha build.
355
+ */
356
+ async ensureOpen() {
357
+ await this.ensureInitialized();
358
+ if (this.outdated) throw new SpaceError("SpacesSchemaOutdated", "Space data was written by an incompatible alpha build. Run `pds spaces reset` to wipe space data (the public repo is unaffected).");
359
+ }
360
+ readMeta() {
361
+ const row = this.sql.exec("SELECT * FROM meta LIMIT 1").toArray()[0];
362
+ if (!row) return null;
363
+ return {
364
+ uri: row.uri,
365
+ authority: row.authority,
366
+ type: row.type,
367
+ skey: row.skey,
368
+ isAuthority: row.is_authority === 1,
369
+ createdAt: row.created_at,
370
+ deletedAt: row.deleted_at ?? null
371
+ };
372
+ }
373
+ /** Meta for an existing, non-deleted space, or throw. */
374
+ requireLiveMeta() {
375
+ const meta = this.readMeta();
376
+ if (!meta) throw new SpaceError("SpaceNotFound", "Space is not initialised");
377
+ if (meta.deletedAt) throw new SpaceError("SpaceNotFound", "Space has been deleted");
378
+ return meta;
379
+ }
380
+ async rpcGetMeta() {
381
+ await this.ensureOpen();
382
+ return this.readMeta();
383
+ }
384
+ /**
385
+ * Initialise this DO as the operator's repo in a space (either role).
386
+ * Idempotent for an existing live space with matching identity.
387
+ */
388
+ async rpcInit(params) {
389
+ await this.ensureOpen();
390
+ const existing = this.readMeta();
391
+ if (existing) {
392
+ if (existing.uri !== params.uri) throw new SpaceError("InvalidSpaceUri", `Space DO already holds ${existing.uri}`);
393
+ if (!existing.deletedAt) {
394
+ if (params.isAuthority && params.config) {
395
+ if (this.sql.exec("SELECT id FROM config").toArray().length > 0) throw new SpaceError("SpaceAlreadyExists", `Space already exists: ${params.uri}`);
396
+ this.writeConfig(params.config);
397
+ }
398
+ return;
399
+ }
400
+ this.sql.exec("UPDATE meta SET deleted_at = NULL, created_at = ?, is_authority = ?", (/* @__PURE__ */ new Date()).toISOString(), params.isAuthority ? 1 : 0);
401
+ if (params.config) this.writeConfig(params.config);
402
+ return;
403
+ }
404
+ this.sql.exec(`INSERT INTO meta (uri, authority, type, skey, is_authority, created_at, deleted_at, schema_version)
405
+ VALUES (?, ?, ?, ?, ?, ?, NULL, ?)`, params.uri, params.authority, params.type, params.skey, params.isAuthority ? 1 : 0, (/* @__PURE__ */ new Date()).toISOString(), SPACE_SCHEMA_VERSION);
406
+ if (params.config) this.writeConfig(params.config);
407
+ }
408
+ async rpcApplyWrites(writes) {
409
+ await this.ensureOpen();
410
+ this.requireLiveMeta();
411
+ return this.ctx.storage.transactionSync(() => {
412
+ const stateRow = this.sql.exec("SELECT set_hash, rev FROM repo_state WHERE id = 1").toArray()[0];
413
+ const prevRev = stateRow ? stateRow.rev : null;
414
+ const commit = RepoCommit.fromState(stateRow ? new Uint8Array(stateRow.set_hash) : null);
415
+ const rev = nextRev(prevRev);
416
+ const indexedAt = (/* @__PURE__ */ new Date()).toISOString();
417
+ const results = [];
418
+ let idx = 0;
419
+ for (const write of writes) {
420
+ const prevRow = this.sql.exec("SELECT cid FROM record WHERE collection = ? AND rkey = ?", write.collection, write.rkey).toArray()[0];
421
+ const prev = prevRow ? prevRow.cid : null;
422
+ if (write.action === "create" && prev) throw new SpaceError("RecordAlreadyExists", `Record already exists: ${write.collection}/${write.rkey}`);
423
+ if (write.action !== "create" && !prev) throw new SpaceError("RecordNotFound", `Record not found: ${write.collection}/${write.rkey}`);
424
+ if (write.action === "delete") {
425
+ this.sql.exec("DELETE FROM record WHERE collection = ? AND rkey = ?", write.collection, write.rkey);
426
+ this.sql.exec("DELETE FROM record_blob WHERE collection = ? AND rkey = ?", write.collection, write.rkey);
427
+ commit.setHash.remove(`${write.collection}/${write.rkey}/${prev}`);
428
+ this.appendOplog(rev, idx++, write.collection, write.rkey, null, prev);
429
+ results.push({
430
+ action: "delete",
431
+ collection: write.collection,
432
+ rkey: write.rkey,
433
+ cid: null
434
+ });
435
+ continue;
436
+ }
437
+ this.sql.exec(`INSERT OR REPLACE INTO record (collection, rkey, cid, bytes, rev, indexed_at)
438
+ VALUES (?, ?, ?, ?, ?, ?)`, write.collection, write.rkey, write.cid, write.bytes, rev, indexedAt);
439
+ this.sql.exec("DELETE FROM record_blob WHERE collection = ? AND rkey = ?", write.collection, write.rkey);
440
+ for (const blobCid of write.blobCids) this.sql.exec("INSERT OR IGNORE INTO record_blob (blob_cid, collection, rkey) VALUES (?, ?, ?)", blobCid, write.collection, write.rkey);
441
+ if (prev) commit.setHash.remove(`${write.collection}/${write.rkey}/${prev}`);
442
+ commit.setHash.add(`${write.collection}/${write.rkey}/${write.cid}`);
443
+ this.appendOplog(rev, idx++, write.collection, write.rkey, write.cid, prev);
444
+ results.push({
445
+ action: write.action,
446
+ collection: write.collection,
447
+ rkey: write.rkey,
448
+ cid: write.cid
449
+ });
450
+ }
451
+ this.sql.exec(`INSERT INTO repo_state (id, set_hash, rev) VALUES (1, ?, ?)
452
+ ON CONFLICT (id) DO UPDATE SET set_hash = excluded.set_hash, rev = excluded.rev`, commit.setHash.state(), rev);
453
+ return {
454
+ rev,
455
+ hash: commit.setHash.digest(),
456
+ results
457
+ };
458
+ });
459
+ }
460
+ appendOplog(rev, idx, collection, rkey, cid, prev) {
461
+ this.sql.exec("INSERT INTO oplog (rev, idx, collection, rkey, cid, prev) VALUES (?, ?, ?, ?, ?, ?)", rev, idx, collection, rkey, cid, prev);
462
+ }
463
+ async rpcGetRecord(collection, rkey) {
464
+ await this.ensureOpen();
465
+ this.requireLiveMeta();
466
+ const row = this.sql.exec("SELECT cid, bytes FROM record WHERE collection = ? AND rkey = ?", collection, rkey).toArray()[0];
467
+ if (!row) return null;
468
+ return {
469
+ cid: row.cid,
470
+ bytes: new Uint8Array(row.bytes)
471
+ };
472
+ }
473
+ /**
474
+ * List records ordered by (collection, rkey) — equivalent to record-URI
475
+ * order since every record shares the space and repo prefix. Descending
476
+ * by default, matching the reference; `reverse` flips to ascending.
477
+ *
478
+ * `rev` is the repo revision the page was read at — the page and the
479
+ * revision are one snapshot (synchronous reads, single-threaded DO), so
480
+ * a paged reader can fence against concurrent writes.
481
+ */
482
+ async rpcListRecords(params) {
483
+ await this.ensureOpen();
484
+ this.requireLiveMeta();
485
+ const stateRow = this.sql.exec("SELECT rev FROM repo_state WHERE id = 1").toArray()[0];
486
+ const rev = stateRow ? stateRow.rev : null;
487
+ const asc = params.reverse === true;
488
+ const op = asc ? ">" : "<";
489
+ const order = asc ? "ASC" : "DESC";
490
+ const args = [];
491
+ let where = "1=1";
492
+ if (params.collection) {
493
+ where += " AND collection = ?";
494
+ args.push(params.collection);
495
+ }
496
+ if (params.after) {
497
+ where += ` AND (collection ${op} ? OR (collection = ? AND rkey ${op} ?))`;
498
+ args.push(params.after.collection, params.after.collection, params.after.rkey);
499
+ }
500
+ const rows = this.sql.exec(`SELECT collection, rkey, cid${params.excludeValues ? "" : ", bytes"} FROM record
501
+ WHERE ${where}
502
+ ORDER BY collection ${order}, rkey ${order}
503
+ LIMIT ?`, ...args, params.limit + 1).toArray();
504
+ const hasMore = rows.length > params.limit;
505
+ return {
506
+ records: (hasMore ? rows.slice(0, params.limit) : rows).map((row) => ({
507
+ collection: row.collection,
508
+ rkey: row.rkey,
509
+ cid: row.cid,
510
+ ...params.excludeValues ? {} : { bytes: new Uint8Array(row.bytes) }
511
+ })),
512
+ hasMore,
513
+ rev
514
+ };
515
+ }
516
+ async rpcGetRepoState() {
517
+ await this.ensureOpen();
518
+ this.requireLiveMeta();
519
+ const row = this.sql.exec("SELECT set_hash, rev FROM repo_state WHERE id = 1").toArray()[0];
520
+ if (!row) return null;
521
+ return {
522
+ setHash: new Uint8Array(row.set_hash),
523
+ rev: row.rev
524
+ };
525
+ }
526
+ /**
527
+ * List oplog entries after `since` (a rev) or `after` (an exact cursor
528
+ * position). Creates and updates carry the record's current bytes when
529
+ * the oplog cid still matches the live record; superseded values are
530
+ * omitted. When the page reaches the head, `head` carries the repo
531
+ * state read in the same transaction so the Worker can attach a freshly
532
+ * signed commit without a state race.
533
+ */
534
+ async rpcListRepoOps(params) {
535
+ await this.ensureOpen();
536
+ this.requireLiveMeta();
537
+ return this.ctx.storage.transactionSync(() => {
538
+ const args = [];
539
+ let where = "1=1";
540
+ if (params.after) {
541
+ where += " AND (o.rev > ? OR (o.rev = ? AND o.idx > ?))";
542
+ args.push(params.after.rev, params.after.rev, params.after.idx);
543
+ } else if (params.since) {
544
+ where += " AND o.rev > ?";
545
+ args.push(params.since);
546
+ }
547
+ const values = params.excludeValues ? "" : ", r.bytes AS live_bytes";
548
+ const rows = this.sql.exec(`SELECT o.rev, o.idx, o.collection, o.rkey, o.cid, o.prev${values}
549
+ FROM oplog o
550
+ ${params.excludeValues ? "" : "LEFT JOIN record r ON r.collection = o.collection AND r.rkey = o.rkey AND r.cid = o.cid"}
551
+ WHERE ${where}
552
+ ORDER BY o.rev ASC, o.idx ASC
553
+ LIMIT ?`, ...args, params.limit + 1).toArray();
554
+ const hasMore = rows.length > params.limit;
555
+ const ops = (hasMore ? rows.slice(0, params.limit) : rows).map((row) => ({
556
+ rev: row.rev,
557
+ idx: row.idx,
558
+ collection: row.collection,
559
+ rkey: row.rkey,
560
+ cid: row.cid ?? null,
561
+ prev: row.prev ?? null,
562
+ ...row.live_bytes ? { bytes: new Uint8Array(row.live_bytes) } : {}
563
+ }));
564
+ if (hasMore) return { ops };
565
+ const stateRow = this.sql.exec("SELECT set_hash, rev FROM repo_state WHERE id = 1").toArray()[0];
566
+ return {
567
+ ops,
568
+ ...stateRow ? { head: {
569
+ setHash: new Uint8Array(stateRow.set_hash),
570
+ rev: stateRow.rev
571
+ } } : {}
572
+ };
573
+ });
574
+ }
575
+ /** Distinct blob CIDs referenced by records, ascending, paged. */
576
+ async rpcListBlobs(params) {
577
+ await this.ensureOpen();
578
+ this.requireLiveMeta();
579
+ const args = [];
580
+ let where = "1=1";
581
+ if (params.since) {
582
+ where += " AND r.rev > ?";
583
+ args.push(params.since);
584
+ }
585
+ if (params.afterCid) {
586
+ where += " AND b.blob_cid > ?";
587
+ args.push(params.afterCid);
588
+ }
589
+ const rows = this.sql.exec(`SELECT DISTINCT b.blob_cid FROM record_blob b
590
+ JOIN record r ON r.collection = b.collection AND r.rkey = b.rkey
591
+ WHERE ${where}
592
+ ORDER BY b.blob_cid ASC
593
+ LIMIT ?`, ...args, params.limit + 1).toArray();
594
+ const hasMore = rows.length > params.limit;
595
+ return {
596
+ cids: (hasMore ? rows.slice(0, params.limit) : rows).map((r) => r.blob_cid),
597
+ hasMore
598
+ };
599
+ }
600
+ /** Whether a blob CID is referenced by any record in this space. */
601
+ async rpcHasSpaceBlob(cid) {
602
+ await this.ensureOpen();
603
+ this.requireLiveMeta();
604
+ return this.sql.exec("SELECT 1 FROM record_blob WHERE blob_cid = ? LIMIT 1", cid).toArray().length > 0;
605
+ }
606
+ /**
607
+ * Record a single-use key. Returns true when the key was fresh (now
608
+ * recorded), false when it was already seen and must be refused.
609
+ */
610
+ async rpcCheckReplay(kind, key, expiresAtSec) {
611
+ await this.ensureOpen();
612
+ return this.sql.exec("INSERT OR IGNORE INTO replay (kind, key, expires_at) VALUES (?, ?, ?)", kind, key, expiresAtSec).rowsWritten > 0;
613
+ }
614
+ writeConfig(config) {
615
+ this.sql.exec(`INSERT INTO config (id, policy, managing_app, app_access, app_allowed)
616
+ VALUES (1, ?, ?, ?, ?)
617
+ ON CONFLICT (id) DO UPDATE SET
618
+ policy = excluded.policy,
619
+ managing_app = excluded.managing_app,
620
+ app_access = excluded.app_access,
621
+ app_allowed = excluded.app_allowed`, config.policy.kind, config.policy.kind === "managing-app" ? config.policy.managingApp : null, config.appAccess.kind, JSON.stringify(config.appAccess.kind === "allowList" ? config.appAccess.allowed : []));
622
+ }
623
+ readConfig() {
624
+ const row = this.sql.exec("SELECT * FROM config WHERE id = 1").toArray()[0];
625
+ if (!row) return null;
626
+ const policyKind = row.policy;
627
+ return {
628
+ policy: policyKind === "managing-app" ? {
629
+ kind: "managing-app",
630
+ managingApp: row.managing_app
631
+ } : policyKind === "member-list" ? { kind: "member-list" } : { kind: "public" },
632
+ appAccess: row.app_access === "allowList" ? {
633
+ kind: "allowList",
634
+ allowed: JSON.parse(row.app_allowed)
635
+ } : { kind: "open" }
636
+ };
637
+ }
638
+ /**
639
+ * State needed to answer getSpaceCredential: meta (including the
640
+ * deletion tombstone) and the simplespace config. Never throws on a
641
+ * deleted space — a late credential request must get SpaceDeleted, not
642
+ * SpaceNotFound, and that mapping is the caller's.
643
+ */
644
+ async rpcGetAuthorityState() {
645
+ await this.ensureOpen();
646
+ return {
647
+ meta: this.readMeta(),
648
+ config: this.readConfig()
649
+ };
650
+ }
651
+ async rpcUpdateConfig(update) {
652
+ await this.ensureOpen();
653
+ this.requireLiveMeta();
654
+ const current = this.readConfig();
655
+ if (!current) throw new SpaceError("SpaceNotFound", "Space has no configuration");
656
+ this.writeConfig({
657
+ policy: update.policy ?? current.policy,
658
+ appAccess: update.appAccess ?? current.appAccess
659
+ });
660
+ }
661
+ async rpcAddMember(did) {
662
+ await this.ensureOpen();
663
+ this.requireLiveMeta();
664
+ this.sql.exec("INSERT OR IGNORE INTO member (did) VALUES (?)", did);
665
+ }
666
+ async rpcRemoveMember(did) {
667
+ await this.ensureOpen();
668
+ this.requireLiveMeta();
669
+ this.sql.exec("DELETE FROM member WHERE did = ?", did);
670
+ }
671
+ async rpcIsMember(did) {
672
+ await this.ensureOpen();
673
+ this.requireLiveMeta();
674
+ return this.sql.exec("SELECT 1 FROM member WHERE did = ?", did).toArray().length > 0;
675
+ }
676
+ async rpcListMembers(params) {
677
+ await this.ensureOpen();
678
+ this.requireLiveMeta();
679
+ const args = [];
680
+ let where = "1=1";
681
+ if (params.afterDid) {
682
+ where += " AND did > ?";
683
+ args.push(params.afterDid);
684
+ }
685
+ const rows = this.sql.exec(`SELECT did FROM member WHERE ${where} ORDER BY did ASC LIMIT ?`, ...args, params.limit + 1).toArray();
686
+ const hasMore = rows.length > params.limit;
687
+ return {
688
+ dids: (hasMore ? rows.slice(0, params.limit) : rows).map((r) => r.did),
689
+ hasMore
690
+ };
691
+ }
692
+ /**
693
+ * Record a writer's latest (rev, hash), from notifyWrite or own writes.
694
+ * Monotonic per writer: a delayed or replayed notification with an older
695
+ * rev never rolls the writer set backwards. Returns whether the write
696
+ * advanced state, so callers can skip fan-out for stale notifications.
697
+ */
698
+ async rpcRecordWriter(did, rev, hash) {
699
+ await this.ensureOpen();
700
+ this.requireLiveMeta();
701
+ return { advanced: this.sql.exec(`INSERT INTO writer (did, rev, hash) VALUES (?, ?, ?)
702
+ ON CONFLICT (did) DO UPDATE SET rev = excluded.rev, hash = excluded.hash
703
+ WHERE excluded.rev > writer.rev`, did, rev, hash).rowsWritten > 0 };
704
+ }
705
+ async rpcListWriters(params) {
706
+ await this.ensureOpen();
707
+ this.requireLiveMeta();
708
+ const args = [];
709
+ let where = "1=1";
710
+ if (params.afterDid) {
711
+ where += " AND did > ?";
712
+ args.push(params.afterDid);
713
+ }
714
+ const rows = this.sql.exec(`SELECT did, rev, hash FROM writer WHERE ${where} ORDER BY did ASC LIMIT ?`, ...args, params.limit + 1).toArray();
715
+ const hasMore = rows.length > params.limit;
716
+ return {
717
+ repos: (hasMore ? rows.slice(0, params.limit) : rows).map((r) => ({
718
+ did: r.did,
719
+ rev: r.rev,
720
+ hash: new Uint8Array(r.hash)
721
+ })),
722
+ hasMore
723
+ };
724
+ }
725
+ /**
726
+ * Register a syncing service for write notifications. The endpoint was
727
+ * resolved by the Worker at registration time so fan-out never resolves
728
+ * DIDs. Re-registration replaces the endpoint and extends the expiry.
729
+ */
730
+ async rpcRegisterNotify(service, endpoint) {
731
+ await this.ensureOpen();
732
+ this.requireLiveMeta();
733
+ const expiresAt = new Date(Date.now() + NOTIFY_REGISTRATION_DAYS * DAY_MS).toISOString();
734
+ this.sql.exec(`INSERT INTO notify_registration (service, endpoint, expires_at) VALUES (?, ?, ?)
735
+ ON CONFLICT (service) DO UPDATE SET endpoint = excluded.endpoint, expires_at = excluded.expires_at`, service, endpoint, expiresAt);
736
+ return { expiresAt };
737
+ }
738
+ /** Idempotent: succeeds whether or not a registration existed. */
739
+ async rpcUnregisterNotify(service) {
740
+ await this.ensureOpen();
741
+ this.requireLiveMeta();
742
+ this.sql.exec("DELETE FROM notify_registration WHERE service = ?", service);
743
+ }
744
+ async rpcGetActiveRegistrations() {
745
+ await this.ensureOpen();
746
+ return this.sql.exec("SELECT service, endpoint FROM notify_registration WHERE expires_at > ?", (/* @__PURE__ */ new Date()).toISOString()).toArray().map((r) => ({
747
+ service: r.service,
748
+ endpoint: r.endpoint
749
+ }));
750
+ }
751
+ /**
752
+ * Queue outbound notifications for the alarm to deliver with bounded
753
+ * retries. The Worker only enqueues; delivery happens here because this
754
+ * DO holds no WebSocket and does no storage-bound work that a slow
755
+ * outbound fetch could pin.
756
+ */
757
+ async rpcEnqueueNotify(items) {
758
+ await this.ensureOpen();
759
+ if (items.length === 0) return;
760
+ const now$1 = Date.now();
761
+ for (const item of items) this.sql.exec("INSERT INTO notify_queue (service, body, attempts, next_at) VALUES (?, ?, 0, ?)", item.service, JSON.stringify({
762
+ endpoint: item.endpoint,
763
+ lxm: item.lxm,
764
+ body: item.body
765
+ }), now$1);
766
+ await this.scheduleNextAlarm();
767
+ }
768
+ /**
769
+ * Tombstone the space (authority role). Enqueues nothing itself — the
770
+ * caller reads the registrations from the result and enqueues
771
+ * `notifySpaceDeleted` before the queue rows would be unreachable. The
772
+ * meta row is retained so a late getSpaceCredential can answer
773
+ * SpaceDeleted rather than SpaceNotFound. Idempotent.
774
+ */
775
+ async rpcDeleteSpace() {
776
+ await this.ensureOpen();
777
+ const meta = this.readMeta();
778
+ if (!meta) throw new SpaceError("SpaceNotFound", "Space is not initialised");
779
+ if (meta.deletedAt) return { registrations: [] };
780
+ const registrations = await this.rpcGetActiveRegistrations();
781
+ this.ctx.storage.transactionSync(() => {
782
+ this.sql.exec("UPDATE meta SET deleted_at = ?", (/* @__PURE__ */ new Date()).toISOString());
783
+ for (const table of [
784
+ "record",
785
+ "record_blob",
786
+ "repo_state",
787
+ "oplog",
788
+ "config",
789
+ "member",
790
+ "writer",
791
+ "notify_registration",
792
+ "replay"
793
+ ]) this.sql.exec(`DELETE FROM ${table}`);
794
+ });
795
+ return { registrations };
796
+ }
797
+ /** Wipe everything, including queued notifications and alarms. */
798
+ async rpcDestroy() {
799
+ await this.ctx.storage.deleteAlarm();
800
+ await this.ctx.storage.deleteAll();
801
+ this.initialized = false;
802
+ this.outdated = false;
803
+ }
804
+ async rpcStatus() {
805
+ await this.ensureInitialized();
806
+ if (this.outdated) return {
807
+ meta: null,
808
+ outdated: true,
809
+ recordCount: 0,
810
+ memberCount: 0,
811
+ writerCount: 0,
812
+ queuedNotifications: 0
813
+ };
814
+ const count = (table) => this.sql.exec(`SELECT COUNT(*) AS n FROM ${table}`).toArray()[0]?.n ?? 0;
815
+ return {
816
+ meta: this.readMeta(),
817
+ outdated: false,
818
+ recordCount: count("record"),
819
+ memberCount: count("member"),
820
+ writerCount: count("writer"),
821
+ queuedNotifications: count("notify_queue")
822
+ };
823
+ }
824
+ async alarm() {
825
+ await this.ensureInitialized();
826
+ if (this.outdated) return;
827
+ await this.deliverQueuedNotifications();
828
+ this.runMaintenanceIfDue();
829
+ await this.scheduleNextAlarm();
830
+ }
831
+ async deliverQueuedNotifications() {
832
+ const due = this.sql.exec("SELECT id, service, body, attempts, next_at FROM notify_queue WHERE next_at <= ? ORDER BY next_at ASC LIMIT ?", Date.now(), NOTIFY_BATCH).toArray();
833
+ if (due.length === 0) return;
834
+ const meta = this.readMeta();
835
+ if (!meta) {
836
+ this.sql.exec("DELETE FROM notify_queue");
837
+ return;
838
+ }
839
+ const keypair = await (await this.getHostConfig()).getKeypair();
840
+ for (const row of due) {
841
+ let delivered = false;
842
+ try {
843
+ const parsed = JSON.parse(row.body);
844
+ const token = await createServiceJwt({
845
+ iss: meta.authority,
846
+ aud: row.service,
847
+ lxm: parsed.lxm
848
+ }, keypair);
849
+ const res = await fetch(`${parsed.endpoint}/xrpc/${parsed.lxm}`, {
850
+ method: "POST",
851
+ headers: {
852
+ "Content-Type": "application/json",
853
+ Authorization: `Bearer ${token}`
854
+ },
855
+ body: JSON.stringify(parsed.body)
856
+ });
857
+ delivered = res.ok;
858
+ if (!res.ok) console.warn(`notify ${parsed.lxm} to ${row.service} failed: ${res.status}`);
859
+ } catch (err) {
860
+ console.warn(`notify to ${row.service} errored:`, err);
861
+ }
862
+ if (delivered || row.attempts + 1 >= NOTIFY_MAX_ATTEMPTS) this.sql.exec("DELETE FROM notify_queue WHERE id = ?", row.id);
863
+ else this.sql.exec("UPDATE notify_queue SET attempts = ?, next_at = ? WHERE id = ?", row.attempts + 1, Date.now() + NOTIFY_BACKOFF_BASE_MS * 2 ** row.attempts, row.id);
864
+ }
865
+ }
866
+ runMaintenanceIfDue() {
867
+ const now$1 = Date.now();
868
+ if (now$1 - (this.sql.exec("SELECT expires_at FROM replay WHERE kind = '__maintenance' AND key = 'last' LIMIT 1").toArray()[0]?.expires_at ?? 0) < MAINTENANCE_INTERVAL_MS) return;
869
+ this.sql.exec("DELETE FROM oplog WHERE rev < ?", tidCutoff(OPLOG_RETENTION_DAYS * DAY_MS));
870
+ const excess = this.sql.exec("SELECT rev, idx FROM oplog ORDER BY rev DESC, idx DESC LIMIT 1 OFFSET ?", OPLOG_RETENTION_OPS).toArray()[0];
871
+ if (excess) this.sql.exec("DELETE FROM oplog WHERE rev < ? OR (rev = ? AND idx <= ?)", excess.rev, excess.rev, excess.idx);
872
+ this.sql.exec("DELETE FROM replay WHERE kind != '__maintenance' AND expires_at < ?", Math.floor(now$1 / 1e3));
873
+ this.sql.exec("DELETE FROM notify_registration WHERE expires_at <= ?", new Date(now$1).toISOString());
874
+ this.sql.exec(`INSERT INTO replay (kind, key, expires_at) VALUES ('__maintenance', 'last', ?)
875
+ ON CONFLICT (kind, key) DO UPDATE SET expires_at = excluded.expires_at`, now$1);
876
+ }
877
+ async scheduleNextAlarm() {
878
+ const nextQueue = this.sql.exec("SELECT MIN(next_at) AS next FROM notify_queue").toArray()[0]?.next;
879
+ const nextMaintenance = Date.now() + MAINTENANCE_INTERVAL_MS;
880
+ const next = nextQueue ? Math.min(Math.max(nextQueue, Date.now() + 1e3), nextMaintenance) : nextMaintenance;
881
+ const current = await this.ctx.storage.getAlarm();
882
+ if (current === null || next < current) await this.ctx.storage.setAlarm(next);
883
+ }
884
+ };
885
+
886
+ //#endregion
887
+ //#region src/index-do.ts
888
+ /**
889
+ * SpaceIndexDurableObject – singleton registry of space URIs with role
890
+ * flags, timestamps and lifecycle state, addressed by `idFromName("spaces")`.
891
+ *
892
+ * Serves listSpaces, the dashboard, export and reset. Nothing reads it on
893
+ * the hot path: the space DO id is derived from the URI, so reads never
894
+ * depend on the index. Creation is a two-step write — the index entry is
895
+ * written `pending`, the space DO is initialised, then the entry is marked
896
+ * `active`. A `pending` entry that never activates is cleaned up by this
897
+ * DO's alarm.
898
+ */
899
+ const ALARM_INTERVAL_MS = 360 * 60 * 1e3;
900
+ var SpaceIndexDurableObject = class extends DurableObject {
901
+ sql;
902
+ initialized = false;
903
+ constructor(ctx, env) {
904
+ super(ctx, env);
905
+ this.sql = ctx.storage.sql;
906
+ }
907
+ async ensureInitialized() {
908
+ if (this.initialized) return;
909
+ await this.ctx.blockConcurrencyWhile(async () => {
910
+ if (this.initialized) return;
911
+ this.sql.exec(INDEX_DO_SCHEMA);
912
+ this.initialized = true;
913
+ if (await this.ctx.storage.getAlarm() === null) await this.ctx.storage.setAlarm(Date.now() + ALARM_INTERVAL_MS);
914
+ });
915
+ }
916
+ /** Register (or revive) an entry in `pending` state. */
917
+ async rpcRegister(entry) {
918
+ await this.ensureInitialized();
919
+ const now$1 = (/* @__PURE__ */ new Date()).toISOString();
920
+ this.sql.exec(`INSERT INTO space (uri, authority, type, skey, is_authority, state, created_at, updated_at, schema_version)
921
+ VALUES (?, ?, ?, ?, ?, 'pending', ?, ?, ?)
922
+ ON CONFLICT (uri) DO UPDATE SET
923
+ state = CASE WHEN space.state = 'active' THEN 'active' ELSE 'pending' END,
924
+ is_authority = excluded.is_authority,
925
+ updated_at = excluded.updated_at`, entry.uri, entry.authority, entry.type, entry.skey, entry.isAuthority ? 1 : 0, now$1, now$1, SPACE_SCHEMA_VERSION);
926
+ }
927
+ async rpcActivate(uri) {
928
+ await this.ensureInitialized();
929
+ this.sql.exec("UPDATE space SET state = 'active', updated_at = ? WHERE uri = ?", (/* @__PURE__ */ new Date()).toISOString(), uri);
930
+ }
931
+ async rpcMarkDeleted(uri) {
932
+ await this.ensureInitialized();
933
+ this.sql.exec("UPDATE space SET state = 'deleted', updated_at = ? WHERE uri = ?", (/* @__PURE__ */ new Date()).toISOString(), uri);
934
+ }
935
+ async rpcGet(uri) {
936
+ await this.ensureInitialized();
937
+ const row = this.sql.exec("SELECT * FROM space WHERE uri = ?", uri).toArray()[0];
938
+ return row ? toEntry(row) : null;
939
+ }
940
+ async rpcList(params) {
941
+ await this.ensureInitialized();
942
+ const args = [];
943
+ let where = "1=1";
944
+ if (params.type) {
945
+ where += " AND type = ?";
946
+ args.push(params.type);
947
+ }
948
+ if (params.authority) {
949
+ where += " AND authority = ?";
950
+ args.push(params.authority);
951
+ }
952
+ if (params.state) {
953
+ where += " AND state = ?";
954
+ args.push(params.state);
955
+ }
956
+ if (params.afterUri) {
957
+ where += " AND uri > ?";
958
+ args.push(params.afterUri);
959
+ }
960
+ const rows = this.sql.exec(`SELECT * FROM space WHERE ${where} ORDER BY uri ASC LIMIT ?`, ...args, params.limit + 1).toArray();
961
+ const hasMore = rows.length > params.limit;
962
+ return {
963
+ spaces: (hasMore ? rows.slice(0, params.limit) : rows).map(toEntry),
964
+ hasMore
965
+ };
966
+ }
967
+ async rpcStats() {
968
+ await this.ensureInitialized();
969
+ const count = (where) => this.sql.exec(`SELECT COUNT(*) AS n FROM space WHERE ${where}`).toArray()[0]?.n ?? 0;
970
+ return {
971
+ total: count("1=1"),
972
+ active: count("state = 'active'"),
973
+ pending: count("state = 'pending'"),
974
+ deleted: count("state = 'deleted'"),
975
+ hosted: count("is_authority = 1 AND state = 'active'")
976
+ };
977
+ }
978
+ /** Wipe the registry (spaces reset). */
979
+ async rpcDestroy() {
980
+ await this.ctx.storage.deleteAlarm();
981
+ await this.ctx.storage.deleteAll();
982
+ this.initialized = false;
983
+ }
984
+ /**
985
+ * Tombstone `pending` entries that never activated. They become
986
+ * `deleted` rather than being removed: a crash between the space DO's
987
+ * initialisation and the index activation leaves real DO storage
988
+ * behind, and the index row is the only durable manifest `spaces reset`
989
+ * has for finding and destroying it.
990
+ */
991
+ async alarm() {
992
+ await this.ensureInitialized();
993
+ const cutoff = new Date(Date.now() - PENDING_ENTRY_TTL_MS).toISOString();
994
+ this.sql.exec("UPDATE space SET state = 'deleted', updated_at = ? WHERE state = 'pending' AND updated_at < ?", (/* @__PURE__ */ new Date()).toISOString(), cutoff);
995
+ await this.ctx.storage.setAlarm(Date.now() + ALARM_INTERVAL_MS);
996
+ }
997
+ };
998
+ function toEntry(row) {
999
+ return {
1000
+ uri: row.uri,
1001
+ authority: row.authority,
1002
+ type: row.type,
1003
+ skey: row.skey,
1004
+ isAuthority: row.is_authority === 1,
1005
+ state: row.state,
1006
+ createdAt: row.created_at,
1007
+ updatedAt: row.updated_at
1008
+ };
1009
+ }
1010
+
1011
+ //#endregion
1012
+ //#region src/space-uri.ts
1013
+ /**
1014
+ * Space URI handling.
1015
+ *
1016
+ * A space is addressed as `at://{authorityDid}/space/{typeNsid}/{skey}` —
1017
+ * the literal `space` marker keeps it unambiguous with public record URIs
1018
+ * because a collection NSID always contains at least two dots. A record in
1019
+ * a space appends `/{authorDid}/{collection}/{rkey}`.
1020
+ */
1021
+ /**
1022
+ * Parse a space URI. Returns null when the string is not a valid space
1023
+ * reference.
1024
+ */
1025
+ function parseSpaceUri(uri) {
1026
+ if (!uri.startsWith("at://")) return null;
1027
+ const parts = uri.slice(5).split("/");
1028
+ if (parts.length !== 4) return null;
1029
+ const [authority, marker, type, skey] = parts;
1030
+ if (marker !== "space") return null;
1031
+ if (!isDid(authority) || !isNsid(type) || !isRecordKey(skey)) return null;
1032
+ const ref = {
1033
+ uri: formatSpaceUri(authority, type, skey),
1034
+ authority,
1035
+ type,
1036
+ skey
1037
+ };
1038
+ if (ref.uri !== uri) return null;
1039
+ return ref;
1040
+ }
1041
+ /** Parse a space URI or throw an InvalidSpaceUri error. */
1042
+ function requireSpaceUri(uri) {
1043
+ const ref = uri ? parseSpaceUri(uri) : null;
1044
+ if (!ref) throw new SpaceError("InvalidSpaceUri", `Invalid space URI: ${uri}`);
1045
+ return ref;
1046
+ }
1047
+ function formatSpaceUri(authority, type, skey) {
1048
+ return `at://${authority}/space/${type}/${skey}`;
1049
+ }
1050
+ /** URI of a record within a space: `{spaceUri}/{repoDid}/{collection}/{rkey}`. */
1051
+ function spaceRecordUri(spaceUri, repo, collection, rkey) {
1052
+ return `${spaceUri}/${repo}/${collection}/${rkey}`;
1053
+ }
1054
+ const BASE32_ALPHABET = "abcdefghijklmnopqrstuvwxyz234567";
1055
+ /**
1056
+ * Stable identifier for a space used in R2 key prefixes: the lowercase,
1057
+ * unpadded base32 encoding of the SHA-256 of the space URI. Deterministic,
1058
+ * filesystem-safe and free of the URI's slashes and colons.
1059
+ */
1060
+ async function spaceId(spaceUri) {
1061
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(spaceUri)));
1062
+ let out = "";
1063
+ let bits = 0;
1064
+ let value = 0;
1065
+ for (const byte of digest) {
1066
+ value = value << 8 | byte;
1067
+ bits += 8;
1068
+ while (bits >= 5) {
1069
+ out += BASE32_ALPHABET[value >>> bits - 5 & 31];
1070
+ bits -= 5;
1071
+ }
1072
+ }
1073
+ if (bits > 0) out += BASE32_ALPHABET[value << 5 - bits & 31];
1074
+ return out;
1075
+ }
1076
+
1077
+ //#endregion
1078
+ //#region src/blob-keys.ts
1079
+ /**
1080
+ * R2 key layout for space blobs.
1081
+ *
1082
+ * A blob referenced by a record in a space lives at
1083
+ * `${did}/space/${spaceId}/${cid}` and is served only by the
1084
+ * credential-gated `com.atproto.space.getBlob`. The same blob referenced
1085
+ * from two spaces is stored twice: per-space prefixes make space deletion
1086
+ * and full reset a prefix delete with no cross-space reference counting.
1087
+ */
1088
+ /**
1089
+ * Key for a staged (uploaded, not yet referenced) blob. Must match the
1090
+ * host's public blob layout: uploads land here and are promoted to their
1091
+ * serving key when a record write references them.
1092
+ */
1093
+ function stagedBlobKey(did, cid) {
1094
+ return `${did}/staged/${cid}`;
1095
+ }
1096
+ /** Prefix holding every space blob for the account. */
1097
+ function spaceBlobRootPrefix(did) {
1098
+ return `${did}/space/`;
1099
+ }
1100
+ /** Prefix holding one space's blobs. `id` comes from {@link spaceId}. */
1101
+ function spaceBlobPrefix(did, id) {
1102
+ return `${did}/space/${id}/`;
1103
+ }
1104
+ /** Key for one blob in one space. */
1105
+ function spaceBlobKey(did, id, cid) {
1106
+ return `${did}/space/${id}/${cid}`;
1107
+ }
1108
+ /** Convenience: key for a blob given the space URI rather than its id. */
1109
+ async function spaceBlobKeyForUri(did, spaceUri, cid) {
1110
+ return spaceBlobKey(did, await spaceId(spaceUri), cid);
1111
+ }
1112
+
1113
+ //#endregion
1114
+ //#region src/auth.ts
1115
+ /**
1116
+ * Worker-side verification of space credentials and delegation tokens.
1117
+ *
1118
+ * Everything here is stateless except the replay checks, which are one RPC
1119
+ * to the space DO's `replay` table. Key resolution goes through the host's
1120
+ * DID resolver with a forced refresh on signature failure (handled inside
1121
+ * `verifySpaceToken`) so key rotation doesn't strand callers.
1122
+ */
1123
+ /**
1124
+ * Peek at an unverified JWT's `typ` header. Used only for routing between
1125
+ * authentication schemes — safe because neither token type verifies as the
1126
+ * other.
1127
+ */
1128
+ function unverifiedJwtTyp(token) {
1129
+ const dot = token.indexOf(".");
1130
+ if (dot <= 0) return null;
1131
+ try {
1132
+ const header = JSON.parse(atob(token.slice(0, dot).replace(/-/g, "+").replace(/_/g, "/")));
1133
+ return typeof header.typ === "string" ? header.typ : null;
1134
+ } catch {
1135
+ return null;
1136
+ }
1137
+ }
1138
+ /** Whether an Authorization header carries a space credential. */
1139
+ function isSpaceCredentialAuth(authorization) {
1140
+ if (!authorization?.startsWith("DPoP ")) return false;
1141
+ return unverifiedJwtTyp(authorization.slice(5)) === SPACE_TOKEN_TYPES.credential.typ;
1142
+ }
1143
+ function htuFor(opts) {
1144
+ return `${opts.publicOrigin}${new URL(opts.url).pathname}`;
1145
+ }
1146
+ const nowSec = () => Math.floor(Date.now() / 1e3);
1147
+ /**
1148
+ * Verify a space credential (`Authorization: DPoP <jwt>` + `DPoP` proof)
1149
+ * presented against `space`. Checks, per the proposal: signature against
1150
+ * the issuer's `#atproto_space` / `#atproto` key, `sub` equal to the
1151
+ * requested space, `iss` equal to the space's authority, `cnf.jkt` equal
1152
+ * to the proof key's thumbprint, proof `htm`/`htu`/`ath`/`iat` valid and
1153
+ * proof `jti` unseen.
1154
+ */
1155
+ async function verifySpaceCredentialAuth(credential, space, opts) {
1156
+ let payload;
1157
+ try {
1158
+ ({payload} = await verifySpaceToken("credential", credential, {
1159
+ getSigningKey: opts.getSigningKey,
1160
+ sub: space.uri
1161
+ }));
1162
+ } catch (err) {
1163
+ throw invalidCredential(err);
1164
+ }
1165
+ if (payload.iss !== space.authority) throw new SpaceError("InvalidCredential", "Space credential issuer is not the space authority");
1166
+ const jkt = payload.cnf?.jkt;
1167
+ if (!jkt) throw new SpaceError("InvalidCredential", "Space credential is missing its cnf.jkt binding");
1168
+ if (!opts.dpopProof) throw new SpaceError("InvalidCredential", "Missing DPoP proof");
1169
+ let proof;
1170
+ try {
1171
+ proof = await verifyDpopProof(opts.dpopProof, {
1172
+ htm: opts.htm,
1173
+ htu: htuFor(opts),
1174
+ credential,
1175
+ jkt
1176
+ });
1177
+ } catch (err) {
1178
+ throw invalidCredential(err);
1179
+ }
1180
+ if (!await opts.checkReplay("dpop", proof.jti, nowSec() + 300)) throw new SpaceError("InvalidCredential", "DPoP proof replayed");
1181
+ return {
1182
+ kind: "credential",
1183
+ iss: payload.iss
1184
+ };
1185
+ }
1186
+ /**
1187
+ * Verify a delegation token (`Authorization: Bearer <jwt>` on
1188
+ * getSpaceCredential) plus its DPoP proof (no `ath` when obtaining a
1189
+ * credential). Single use by `(iss, jti)`.
1190
+ */
1191
+ async function verifyDelegationAuth(token, space, opts) {
1192
+ let payload;
1193
+ try {
1194
+ ({payload} = await verifySpaceToken("delegation", token, {
1195
+ getSigningKey: opts.getSigningKey,
1196
+ aud: spaceHostAud(space.authority),
1197
+ sub: space.uri
1198
+ }));
1199
+ } catch (err) {
1200
+ throw invalidDelegation(err);
1201
+ }
1202
+ if (!payload.iss.startsWith("did:")) throw new SpaceError("InvalidDelegationToken", "Delegation token issuer is not a DID");
1203
+ if (!opts.dpopProof) throw new SpaceError("InvalidDelegationToken", "Missing DPoP proof");
1204
+ let proof;
1205
+ try {
1206
+ proof = await verifyDpopProof(opts.dpopProof, {
1207
+ htm: opts.htm,
1208
+ htu: htuFor(opts)
1209
+ });
1210
+ } catch (err) {
1211
+ throw invalidDelegation(err);
1212
+ }
1213
+ if (!await opts.checkReplay("delegation", `${payload.iss}:${payload.jti}`, payload.exp)) throw new SpaceError("InvalidDelegationToken", "Delegation token has already been used");
1214
+ return {
1215
+ userDid: payload.iss,
1216
+ dpopJkt: proof.jkt
1217
+ };
1218
+ }
1219
+ function invalidCredential(err) {
1220
+ return new SpaceError("InvalidCredential", authErrorMessage(err));
1221
+ }
1222
+ function invalidDelegation(err) {
1223
+ return new SpaceError("InvalidDelegationToken", authErrorMessage(err));
1224
+ }
1225
+ function authErrorMessage(err) {
1226
+ if (err instanceof SpaceTokenError || err instanceof DpopProofError) return err.message;
1227
+ return "Token verification failed";
1228
+ }
1229
+
1230
+ //#endregion
1231
+ //#region src/attestation.ts
1232
+ /**
1233
+ * Client attestation verification (app-identity gating, `allowList` app
1234
+ * access). The attestation is a short-lived JWT signed by the OAuth
1235
+ * client's published JWKS key, with `iss` = `sub` = client_id and `aud`
1236
+ * the space host. Verified against the client's `client-metadata.json`.
1237
+ *
1238
+ * The client_id in the payload is attacker-controlled until the signature
1239
+ * verifies, so nothing is fetched before it has been validated as an
1240
+ * https client-metadata URL and checked against the caller's allow-list —
1241
+ * a space gated on an allow-list never performs network I/O for a client
1242
+ * that could not be authorized anyway. All fetches are bounded by a
1243
+ * timeout.
1244
+ */
1245
+ /** Upper bound for each outbound metadata/JWKS fetch. */
1246
+ const FETCH_TIMEOUT_MS = 5e3;
1247
+ /**
1248
+ * Verify a client attestation and return the attested client_id.
1249
+ * Single-use by `(clientId, jti)`.
1250
+ */
1251
+ async function verifyClientAttestation(attestation, opts) {
1252
+ let parsed;
1253
+ try {
1254
+ parsed = parseSpaceToken("clientAttestation", attestation);
1255
+ } catch (err) {
1256
+ throw invalid(err);
1257
+ }
1258
+ const clientId = parsed.payload.iss;
1259
+ if (parsed.payload.aud !== opts.expectedAud) throw new SpaceError("InvalidClientAttestation", "Attestation audience does not match this space host");
1260
+ let clientUrl;
1261
+ try {
1262
+ clientUrl = new URL(clientId);
1263
+ } catch {
1264
+ throw new SpaceError("InvalidClientAttestation", "Attestation client_id is not a URL");
1265
+ }
1266
+ if (clientUrl.protocol !== "https:" || clientUrl.username || clientUrl.password) throw new SpaceError("InvalidClientAttestation", "Attestation client_id must be a plain https URL");
1267
+ if (opts.allowedClientIds && !opts.allowedClientIds.includes(clientId)) throw new SpaceError("AppNotAuthorized", "App is not authorized for this space");
1268
+ const doFetch = opts.fetch ?? fetch;
1269
+ const boundedJson = async (url) => {
1270
+ const res = await doFetch(url, {
1271
+ headers: { Accept: "application/json" },
1272
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
1273
+ redirect: "error"
1274
+ });
1275
+ if (!res.ok) throw new Error(`fetch of ${url} returned ${res.status}`);
1276
+ return res.json();
1277
+ };
1278
+ let metadata;
1279
+ try {
1280
+ metadata = await boundedJson(clientId);
1281
+ } catch {
1282
+ throw new SpaceError("InvalidClientAttestation", "Could not resolve client metadata");
1283
+ }
1284
+ let jwks = metadata.jwks;
1285
+ if (!jwks && typeof metadata.jwks_uri === "string") {
1286
+ let jwksUrl;
1287
+ try {
1288
+ jwksUrl = new URL(metadata.jwks_uri);
1289
+ } catch {
1290
+ jwksUrl = null;
1291
+ }
1292
+ if (!jwksUrl || jwksUrl.protocol !== "https:") throw new SpaceError("InvalidClientAttestation", "Client metadata jwks_uri must be an https URL");
1293
+ try {
1294
+ jwks = await boundedJson(metadata.jwks_uri);
1295
+ } catch {
1296
+ throw new SpaceError("InvalidClientAttestation", "Could not resolve client JWKS");
1297
+ }
1298
+ }
1299
+ if (!jwks) throw new SpaceError("InvalidClientAttestation", "Client metadata declares no JWKS");
1300
+ try {
1301
+ await jwtVerify(attestation, createLocalJWKSet(jwks), {
1302
+ issuer: clientId,
1303
+ subject: clientId,
1304
+ audience: opts.expectedAud,
1305
+ typ: SPACE_TOKEN_TYPES.clientAttestation.typ,
1306
+ requiredClaims: ["jti", "exp"],
1307
+ clockTolerance: 5
1308
+ });
1309
+ } catch (err) {
1310
+ throw invalid(err);
1311
+ }
1312
+ if (!await opts.checkReplay("attestation", `${clientId}:${parsed.payload.jti}`, parsed.payload.exp)) throw new SpaceError("InvalidClientAttestation", "Client attestation has already been used");
1313
+ return clientId;
1314
+ }
1315
+ function invalid(err) {
1316
+ return new SpaceError("InvalidClientAttestation", err instanceof Error ? err.message : "Invalid client attestation");
1317
+ }
1318
+
1319
+ //#endregion
1320
+ //#region src/commit.ts
1321
+ /**
1322
+ * Commit signing.
1323
+ *
1324
+ * Signing happens in the Worker, never in the Durable Object. The proposal
1325
+ * requires a fresh `ikm` per reader, so a signature is never stored — each
1326
+ * response that carries a commit signs the persisted LtHash state anew with
1327
+ * the account keypair the Worker already holds.
1328
+ */
1329
+ async function signCommit(params, keypair) {
1330
+ return RepoCommit.fromState(params.state.setHash).sign({
1331
+ space: params.spaceUri,
1332
+ author: params.author,
1333
+ rev: params.state.rev
1334
+ }, keypair);
1335
+ }
1336
+ /**
1337
+ * Lexicon JSON form of a signed commit (`com.atproto.space.defs#signedCommit`):
1338
+ * bytes fields encode as `{"$bytes": "<base64>"}`.
1339
+ */
1340
+ function commitToJson(commit) {
1341
+ return {
1342
+ ver: commit.ver,
1343
+ hash: { $bytes: toBase64(commit.hash) },
1344
+ ikm: { $bytes: toBase64(commit.ikm) },
1345
+ sig: { $bytes: toBase64(commit.sig) },
1346
+ mac: { $bytes: toBase64(commit.mac) },
1347
+ rev: commit.rev
1348
+ };
1349
+ }
1350
+ /** Lexicon JSON form of a bare bytes value. */
1351
+ function bytesToJson(bytes) {
1352
+ return { $bytes: toBase64(bytes) };
1353
+ }
1354
+
1355
+ //#endregion
1356
+ //#region src/records.ts
1357
+ /**
1358
+ * Record preparation and serialization for the Worker side of the write
1359
+ * and read paths. Records are stored as dag-cbor bytes with their CID,
1360
+ * computed here — the same encoding path the reference uses.
1361
+ */
1362
+ /**
1363
+ * Convert a client-supplied JSON record into its stored form: lex value →
1364
+ * dag-cbor bytes → CID, with blob references enumerated for the space's
1365
+ * blob tracking.
1366
+ */
1367
+ async function prepareRecord(record) {
1368
+ const lex = jsonToLex(record);
1369
+ const bytes = encode(lex);
1370
+ const cid = await cidForLex(lex);
1371
+ const blobCids = [];
1372
+ for (const ref of enumBlobRefs(lex)) blobCids.push(getBlobCidString(ref));
1373
+ return {
1374
+ cid: cid.toString(),
1375
+ bytes,
1376
+ blobCids,
1377
+ json: lexToJson(lex)
1378
+ };
1379
+ }
1380
+ /** Decode stored record bytes back into response JSON. */
1381
+ function recordBytesToJson(bytes) {
1382
+ return lexToJson(decode(bytes));
1383
+ }
1384
+
1385
+ //#endregion
1386
+ //#region src/routes.ts
1387
+ /**
1388
+ * Hono route factory for `com.atproto.space.*` and
1389
+ * `com.atproto.simplespace.*`.
1390
+ *
1391
+ * The factory is host-agnostic: everything account-specific — session
1392
+ * authentication, DID resolution, record validation, the operator identity
1393
+ * — arrives through {@link SpaceRoutesHost}. The host mounts the returned
1394
+ * app behind its feature flag.
1395
+ */
1396
+ const NOTIFY_WRITE_LXM = "com.atproto.space.notifyWrite";
1397
+ const SPACE_DELETED_LXM = "com.atproto.space.notifySpaceDeleted";
1398
+ const CHECK_USER_ACCESS_LXM = "com.atproto.simplespace.checkUserAccess";
1399
+ /** A managing app that doesn't answer within this window denies access. */
1400
+ const CHECK_USER_ACCESS_TIMEOUT_MS = 5e3;
1401
+ function errorResponse(c, err) {
1402
+ const parsed = parseSpaceErrorCode(err);
1403
+ if (parsed) return c.json({
1404
+ error: parsed.code,
1405
+ message: parsed.message
1406
+ }, spaceErrorStatus(parsed.code));
1407
+ throw err;
1408
+ }
1409
+ function waitUntil(c, promise) {
1410
+ try {
1411
+ c.executionCtx.waitUntil(promise);
1412
+ } catch {
1413
+ promise.catch((err) => console.warn("background task failed", err));
1414
+ }
1415
+ }
1416
+ function replayChecker(stub) {
1417
+ return (kind, key, expiresAtSec) => stub.rpcCheckReplay(kind, key, expiresAtSec);
1418
+ }
1419
+ function createSpaceRoutes(host) {
1420
+ const app = new Hono();
1421
+ const doFetch = host.outboundFetch ?? fetch;
1422
+ /** The `repo` param on every repo-host method must be the operator DID. */
1423
+ function requireRepoParam(repo) {
1424
+ if (repo !== host.operatorDid) throw new SpaceError("RepoNotFound", `Repository not found: ${String(repo)}`);
1425
+ }
1426
+ const verifyOpts = (c, stub) => ({
1427
+ htm: c.req.method,
1428
+ url: c.req.url,
1429
+ publicOrigin: host.publicOrigin,
1430
+ dpopProof: c.req.header("DPoP"),
1431
+ getSigningKey: host.getSigningKey,
1432
+ checkReplay: replayChecker(stub)
1433
+ });
1434
+ /**
1435
+ * Authenticate a read: a space credential for the requested space, or a
1436
+ * host session covering `read_self` on it. The `repo` param on every
1437
+ * repo-host method must be the operator DID — anything else is
1438
+ * RepoNotFound, deliberately indistinguishable from an absent repo.
1439
+ */
1440
+ async function readAuth(c, ref, repo) {
1441
+ if (repo !== host.operatorDid) throw new SpaceError("RepoNotFound", `Repository not found: ${repo}`);
1442
+ const authHeader = c.req.header("Authorization");
1443
+ if (isSpaceCredentialAuth(authHeader)) {
1444
+ const stub = host.getSpaceDO(ref.uri);
1445
+ await verifySpaceCredentialAuth(authHeader.slice(5), ref, verifyOpts(c, stub));
1446
+ return { kind: "credential" };
1447
+ }
1448
+ const session = await host.authenticate(c);
1449
+ if (session instanceof Response) return session;
1450
+ if (!session.fullTrust) {
1451
+ if (!session.allowsSpace({
1452
+ type: ref.type,
1453
+ authority: ref.authority,
1454
+ skey: ref.skey,
1455
+ action: "read_self"
1456
+ })) return c.json({
1457
+ error: "InsufficientScope",
1458
+ message: "Token does not cover reading this space"
1459
+ }, 403);
1460
+ }
1461
+ return { kind: "session" };
1462
+ }
1463
+ /** Session-only auth for writes and management. */
1464
+ async function sessionAuth(c) {
1465
+ return host.authenticate(c);
1466
+ }
1467
+ function assertScope(c, session, match) {
1468
+ if (session.fullTrust) return null;
1469
+ if (session.allowsSpace(match)) return null;
1470
+ return c.json({
1471
+ error: "InsufficientScope",
1472
+ message: "Token does not cover this space operation"
1473
+ }, 403);
1474
+ }
1475
+ /** The operator hosts this space, or SpaceNotFound. */
1476
+ function assertSpaceHost(ref) {
1477
+ if (ref.authority !== host.operatorDid) throw new SpaceError("SpaceNotFound", `Space not found: ${ref.uri}`);
1478
+ }
1479
+ /**
1480
+ * The simplespace user-access policy, applied at credential mint and to
1481
+ * inbound notifyWrite writers. The authority itself always passes; a
1482
+ * managing app that errors or times out denies.
1483
+ */
1484
+ async function authorizeUser(config, ref, userDid, clientId, stub) {
1485
+ if (userDid === ref.authority) return true;
1486
+ switch (config.policy.kind) {
1487
+ case "public": return true;
1488
+ case "member-list": return stub.rpcIsMember(userDid);
1489
+ case "managing-app": {
1490
+ const managingApp = config.policy.managingApp;
1491
+ try {
1492
+ const endpoint = await host.resolveServiceEndpoint(managingApp);
1493
+ if (!endpoint) return false;
1494
+ const keypair = await host.getKeypair();
1495
+ const token = await createServiceJwt({
1496
+ iss: host.operatorDid,
1497
+ aud: managingApp,
1498
+ lxm: CHECK_USER_ACCESS_LXM
1499
+ }, keypair);
1500
+ const url = new URL(`${endpoint}/xrpc/${CHECK_USER_ACCESS_LXM}`);
1501
+ url.searchParams.set("space", ref.uri);
1502
+ url.searchParams.set("user", userDid);
1503
+ if (clientId) url.searchParams.set("clientId", clientId);
1504
+ const res = await doFetch(url.toString(), {
1505
+ headers: { Authorization: `Bearer ${token}` },
1506
+ signal: AbortSignal.timeout(CHECK_USER_ACCESS_TIMEOUT_MS)
1507
+ });
1508
+ if (!res.ok) return false;
1509
+ return (await res.json()).authorized === true;
1510
+ } catch {
1511
+ return false;
1512
+ }
1513
+ }
1514
+ }
1515
+ }
1516
+ /**
1517
+ * Ensure the space DO exists for a write. First write into a foreign
1518
+ * space registers it `pending` in the index, initialises the DO as
1519
+ * repo-host, then activates the entry. Spaces under the operator's own
1520
+ * authority must have been created via simplespace first.
1521
+ */
1522
+ async function ensureSpaceForWrite(ref, stub) {
1523
+ const meta = await stub.rpcGetMeta();
1524
+ if (meta && !meta.deletedAt) return;
1525
+ if (ref.authority === host.operatorDid) throw new SpaceError("SpaceNotFound", `Space not found: ${ref.uri}. Create it with com.atproto.simplespace.createSpace.`);
1526
+ const index = host.getIndexDO();
1527
+ await index.rpcRegister({
1528
+ uri: ref.uri,
1529
+ authority: ref.authority,
1530
+ type: ref.type,
1531
+ skey: ref.skey,
1532
+ isAuthority: false
1533
+ });
1534
+ await stub.rpcInit({
1535
+ uri: ref.uri,
1536
+ authority: ref.authority,
1537
+ type: ref.type,
1538
+ skey: ref.skey,
1539
+ isAuthority: false
1540
+ });
1541
+ await index.rpcActivate(ref.uri);
1542
+ }
1543
+ /**
1544
+ * Promote staged blobs to the space's R2 prefix. Runs before the DO
1545
+ * commit so nothing reacting to the commit sees a 404. Idempotent per
1546
+ * CID; CIDs that are neither staged nor at the destination are skipped.
1547
+ */
1548
+ async function promoteSpaceBlobs(ref, blobCids) {
1549
+ if (!host.blobs || blobCids.length === 0) return;
1550
+ const id = await spaceId(ref.uri);
1551
+ await Promise.all(blobCids.map(async (cid) => {
1552
+ const destKey = spaceBlobKey(host.operatorDid, id, cid);
1553
+ if (await host.blobs.head(destKey)) return;
1554
+ const staged = await host.blobs.get(stagedBlobKey(host.operatorDid, cid));
1555
+ if (!staged) return;
1556
+ await host.blobs.put(destKey, staged.body, { httpMetadata: staged.httpMetadata });
1557
+ }));
1558
+ }
1559
+ /**
1560
+ * Step 8 of the write path: after the commit is applied, record the
1561
+ * writer and fan out (own authority) or send one best-effort
1562
+ * notifyWrite to the space's authority (foreign space).
1563
+ */
1564
+ async function postWrite(ref, stub, rev, hash) {
1565
+ if (ref.authority === host.operatorDid) {
1566
+ const { advanced } = await stub.rpcRecordWriter(host.operatorDid, rev, hash);
1567
+ if (!advanced) return;
1568
+ const registrations = await stub.rpcGetActiveRegistrations();
1569
+ if (registrations.length === 0) return;
1570
+ const body = {
1571
+ space: ref.uri,
1572
+ repo: host.operatorDid,
1573
+ rev,
1574
+ hash: bytesToJson(hash)
1575
+ };
1576
+ const items = registrations.map((registration) => ({
1577
+ service: registration.service,
1578
+ endpoint: registration.endpoint,
1579
+ lxm: NOTIFY_WRITE_LXM,
1580
+ body
1581
+ }));
1582
+ await stub.rpcEnqueueNotify(items);
1583
+ return;
1584
+ }
1585
+ try {
1586
+ const endpoint = await host.resolveAuthorityEndpoint(ref.authority);
1587
+ if (!endpoint) {
1588
+ console.warn(`notifyWrite: no endpoint for ${ref.authority}`);
1589
+ return;
1590
+ }
1591
+ const keypair = await host.getKeypair();
1592
+ const token = await createServiceJwt({
1593
+ iss: host.operatorDid,
1594
+ aud: ref.authority,
1595
+ lxm: NOTIFY_WRITE_LXM
1596
+ }, keypair);
1597
+ const res = await doFetch(`${endpoint}/xrpc/${NOTIFY_WRITE_LXM}`, {
1598
+ method: "POST",
1599
+ headers: {
1600
+ "Content-Type": "application/json",
1601
+ Authorization: `Bearer ${token}`
1602
+ },
1603
+ body: JSON.stringify({
1604
+ space: ref.uri,
1605
+ repo: host.operatorDid,
1606
+ rev,
1607
+ hash: bytesToJson(hash)
1608
+ })
1609
+ });
1610
+ if (!res.ok) console.warn(`notifyWrite to ${ref.authority} failed: ${res.status}`);
1611
+ } catch (err) {
1612
+ console.warn(`notifyWrite to ${ref.authority} errored:`, err);
1613
+ }
1614
+ }
1615
+ /**
1616
+ * Common write pipeline for createRecord/putRecord/deleteRecord and
1617
+ * applyWrites: validate, prepare bytes and CIDs, promote blobs, ensure
1618
+ * the space DO, apply the batch, notify in the background.
1619
+ */
1620
+ async function runWrites(c, ref, session, writes, validate) {
1621
+ const prepared = [];
1622
+ const statuses = [];
1623
+ const blobCids = /* @__PURE__ */ new Set();
1624
+ for (const write of writes) {
1625
+ const scopeError = assertScope(c, session, {
1626
+ type: ref.type,
1627
+ authority: ref.authority,
1628
+ skey: ref.skey,
1629
+ action: write.action,
1630
+ collection: write.collection
1631
+ });
1632
+ if (scopeError) return scopeError;
1633
+ if (write.action === "delete") {
1634
+ prepared.push({
1635
+ action: "delete",
1636
+ collection: write.collection,
1637
+ rkey: write.rkey
1638
+ });
1639
+ statuses.push(void 0);
1640
+ continue;
1641
+ }
1642
+ const rkey = write.rkey ?? now();
1643
+ let validated;
1644
+ try {
1645
+ validated = host.validateRecord({
1646
+ collection: write.collection,
1647
+ record: write.value,
1648
+ rkey,
1649
+ validate
1650
+ });
1651
+ } catch (err) {
1652
+ return c.json({
1653
+ error: "InvalidRecord",
1654
+ message: err instanceof Error ? err.message : String(err)
1655
+ }, 400);
1656
+ }
1657
+ const preparedRecord = await prepareRecord(validated.record);
1658
+ for (const cid of preparedRecord.blobCids) blobCids.add(cid);
1659
+ prepared.push({
1660
+ action: write.action,
1661
+ collection: write.collection,
1662
+ rkey,
1663
+ cid: preparedRecord.cid,
1664
+ bytes: preparedRecord.bytes,
1665
+ blobCids: preparedRecord.blobCids
1666
+ });
1667
+ statuses.push(validated.status);
1668
+ }
1669
+ await promoteSpaceBlobs(ref, Array.from(blobCids));
1670
+ const stub = host.getSpaceDO(ref.uri);
1671
+ await ensureSpaceForWrite(ref, stub);
1672
+ const result = await stub.rpcApplyWrites(prepared);
1673
+ waitUntil(c, postWrite(ref, stub, result.rev, result.hash));
1674
+ return {
1675
+ rev: result.rev,
1676
+ results: result.results.map((r, i) => ({
1677
+ ...r,
1678
+ ...statuses[i] !== void 0 ? { validationStatus: statuses[i] } : {}
1679
+ }))
1680
+ };
1681
+ }
1682
+ app.post("/xrpc/com.atproto.space.createRecord", async (c) => {
1683
+ try {
1684
+ const body = await c.req.json();
1685
+ const ref = requireSpaceUri(body.space);
1686
+ requireRepoParam(body.repo);
1687
+ requireString(body.collection, "collection");
1688
+ const session = await sessionAuth(c);
1689
+ if (session instanceof Response) return session;
1690
+ const result = await runWrites(c, ref, session, [{
1691
+ action: "create",
1692
+ collection: body.collection,
1693
+ rkey: body.rkey,
1694
+ value: body.record
1695
+ }], body.validate);
1696
+ if (result instanceof Response) return result;
1697
+ const write = result.results[0];
1698
+ return c.json({
1699
+ uri: spaceRecordUri(ref.uri, host.operatorDid, write.collection, write.rkey),
1700
+ cid: write.cid,
1701
+ ...write.validationStatus ? { validationStatus: write.validationStatus } : {}
1702
+ });
1703
+ } catch (err) {
1704
+ return errorResponse(c, err);
1705
+ }
1706
+ });
1707
+ app.post("/xrpc/com.atproto.space.putRecord", async (c) => {
1708
+ try {
1709
+ const body = await c.req.json();
1710
+ const ref = requireSpaceUri(body.space);
1711
+ requireRepoParam(body.repo);
1712
+ requireString(body.collection, "collection");
1713
+ requireString(body.rkey, "rkey");
1714
+ const session = await sessionAuth(c);
1715
+ if (session instanceof Response) return session;
1716
+ const stub = host.getSpaceDO(ref.uri);
1717
+ const meta = await stub.rpcGetMeta();
1718
+ const result = await runWrites(c, ref, session, [{
1719
+ action: (meta && !meta.deletedAt ? await stub.rpcGetRecord(body.collection, body.rkey) !== null : false) ? "update" : "create",
1720
+ collection: body.collection,
1721
+ rkey: body.rkey,
1722
+ value: body.record
1723
+ }], body.validate);
1724
+ if (result instanceof Response) return result;
1725
+ const write = result.results[0];
1726
+ return c.json({
1727
+ uri: spaceRecordUri(ref.uri, host.operatorDid, write.collection, write.rkey),
1728
+ cid: write.cid,
1729
+ ...write.validationStatus ? { validationStatus: write.validationStatus } : {}
1730
+ });
1731
+ } catch (err) {
1732
+ return errorResponse(c, err);
1733
+ }
1734
+ });
1735
+ app.post("/xrpc/com.atproto.space.deleteRecord", async (c) => {
1736
+ try {
1737
+ const body = await c.req.json();
1738
+ const ref = requireSpaceUri(body.space);
1739
+ requireRepoParam(body.repo);
1740
+ requireString(body.collection, "collection");
1741
+ requireString(body.rkey, "rkey");
1742
+ const session = await sessionAuth(c);
1743
+ if (session instanceof Response) return session;
1744
+ const result = await runWrites(c, ref, session, [{
1745
+ action: "delete",
1746
+ collection: body.collection,
1747
+ rkey: body.rkey
1748
+ }], void 0);
1749
+ if (result instanceof Response) return result;
1750
+ return c.json({});
1751
+ } catch (err) {
1752
+ if (parseSpaceErrorCode(err)?.code === "RecordNotFound") return c.json({});
1753
+ return errorResponse(c, err);
1754
+ }
1755
+ });
1756
+ app.post("/xrpc/com.atproto.space.applyWrites", async (c) => {
1757
+ try {
1758
+ const body = await c.req.json();
1759
+ const ref = requireSpaceUri(body.space);
1760
+ requireRepoParam(body.repo);
1761
+ if (!Array.isArray(body.writes)) throw new SpaceError("InvalidRequest", "writes must be an array");
1762
+ if (body.writes.length > 200) throw new SpaceError("InvalidRequest", "Too many writes. Max: 200");
1763
+ const session = await sessionAuth(c);
1764
+ if (session instanceof Response) return session;
1765
+ const result = await runWrites(c, ref, session, body.writes.map((write, i) => {
1766
+ const action = write.$type === "com.atproto.space.applyWrites#create" ? "create" : write.$type === "com.atproto.space.applyWrites#update" ? "update" : write.$type === "com.atproto.space.applyWrites#delete" ? "delete" : null;
1767
+ if (!action || !write.collection) throw new SpaceError("InvalidRequest", `Write ${i}: unknown $type or missing collection`);
1768
+ if (action !== "create" && !write.rkey) throw new SpaceError("InvalidRequest", `Write ${i}: ${action} requires rkey`);
1769
+ return {
1770
+ action,
1771
+ collection: write.collection,
1772
+ rkey: write.rkey,
1773
+ value: write.value
1774
+ };
1775
+ }), body.validate);
1776
+ if (result instanceof Response) return result;
1777
+ return c.json({ results: result.results.map((write) => {
1778
+ if (write.action === "delete") return { $type: "com.atproto.space.applyWrites#deleteResult" };
1779
+ return {
1780
+ $type: `com.atproto.space.applyWrites#${write.action}Result`,
1781
+ uri: spaceRecordUri(ref.uri, host.operatorDid, write.collection, write.rkey),
1782
+ cid: write.cid,
1783
+ ...write.validationStatus ? { validationStatus: write.validationStatus } : {}
1784
+ };
1785
+ }) });
1786
+ } catch (err) {
1787
+ return errorResponse(c, err);
1788
+ }
1789
+ });
1790
+ app.get("/xrpc/com.atproto.space.getRecord", async (c) => {
1791
+ try {
1792
+ const ref = requireSpaceUri(c.req.query("space"));
1793
+ const auth = await readAuth(c, ref, c.req.query("repo"));
1794
+ if (auth instanceof Response) return auth;
1795
+ const collection = c.req.query("collection");
1796
+ const rkey = c.req.query("rkey");
1797
+ requireString(collection, "collection");
1798
+ requireString(rkey, "rkey");
1799
+ const stub = host.getSpaceDO(ref.uri);
1800
+ await requireRepoExists(stub, ref);
1801
+ const record = await stub.rpcGetRecord(collection, rkey);
1802
+ const uri = spaceRecordUri(ref.uri, host.operatorDid, collection, rkey);
1803
+ if (!record) throw new SpaceError("RecordNotFound", `Could not locate record: ${uri}`);
1804
+ return c.json({
1805
+ uri,
1806
+ cid: record.cid,
1807
+ value: recordBytesToJson(record.bytes)
1808
+ });
1809
+ } catch (err) {
1810
+ return errorResponse(c, err);
1811
+ }
1812
+ });
1813
+ app.get("/xrpc/com.atproto.space.listRecords", async (c) => {
1814
+ try {
1815
+ const ref = requireSpaceUri(c.req.query("space"));
1816
+ const auth = await readAuth(c, ref, c.req.query("repo"));
1817
+ if (auth instanceof Response) return auth;
1818
+ const collection = c.req.query("collection");
1819
+ const limit = clampLimit(c.req.query("limit"), 50, 1e3);
1820
+ const reverse = c.req.query("reverse") === "true";
1821
+ const excludeValues = c.req.query("excludeValues") === "true";
1822
+ const after = parseRecordCursor(c.req.query("cursor"));
1823
+ const stub = host.getSpaceDO(ref.uri);
1824
+ await requireRepoExists(stub, ref);
1825
+ const page = await stub.rpcListRecords({
1826
+ collection,
1827
+ limit,
1828
+ after,
1829
+ reverse,
1830
+ excludeValues
1831
+ });
1832
+ const records = page.records.map((record) => ({
1833
+ collection: record.collection,
1834
+ rkey: record.rkey,
1835
+ cid: record.cid,
1836
+ ...record.bytes ? { value: recordBytesToJson(new Uint8Array(record.bytes)) } : {}
1837
+ }));
1838
+ const last = page.records[page.records.length - 1];
1839
+ return c.json({
1840
+ records,
1841
+ ...page.hasMore && last ? { cursor: `${last.collection}/${last.rkey}` } : {}
1842
+ });
1843
+ } catch (err) {
1844
+ return errorResponse(c, err);
1845
+ }
1846
+ });
1847
+ app.get("/xrpc/com.atproto.space.getLatestCommit", async (c) => {
1848
+ try {
1849
+ const ref = requireSpaceUri(c.req.query("space"));
1850
+ const auth = await readAuth(c, ref, c.req.query("repo"));
1851
+ if (auth instanceof Response) return auth;
1852
+ const stub = host.getSpaceDO(ref.uri);
1853
+ await requireRepoExists(stub, ref);
1854
+ const state = await stub.rpcGetRepoState();
1855
+ if (!state) throw new SpaceError("RepoNotFound", `Could not find repo for space: ${ref.uri}`);
1856
+ const keypair = await host.getKeypair();
1857
+ const commit = await signCommit({
1858
+ spaceUri: ref.uri,
1859
+ author: host.operatorDid,
1860
+ state: {
1861
+ setHash: new Uint8Array(state.setHash),
1862
+ rev: state.rev
1863
+ }
1864
+ }, keypair);
1865
+ return c.json({ commit: commitToJson(commit) });
1866
+ } catch (err) {
1867
+ return errorResponse(c, err);
1868
+ }
1869
+ });
1870
+ app.get("/xrpc/com.atproto.space.listRepoOps", async (c) => {
1871
+ try {
1872
+ const ref = requireSpaceUri(c.req.query("space"));
1873
+ const auth = await readAuth(c, ref, c.req.query("repo"));
1874
+ if (auth instanceof Response) return auth;
1875
+ const limit = clampLimit(c.req.query("limit"), 100, 1e3);
1876
+ const since = c.req.query("since");
1877
+ const excludeValues = c.req.query("excludeValues") === "true";
1878
+ const after = parseOpsCursor(c.req.query("cursor"));
1879
+ const stub = host.getSpaceDO(ref.uri);
1880
+ await requireRepoExists(stub, ref);
1881
+ const page = await stub.rpcListRepoOps({
1882
+ since,
1883
+ after,
1884
+ limit,
1885
+ excludeValues
1886
+ });
1887
+ const ops = page.ops.map((op) => ({
1888
+ rev: op.rev,
1889
+ collection: op.collection,
1890
+ rkey: op.rkey,
1891
+ cid: op.cid,
1892
+ prev: op.prev,
1893
+ ...op.bytes ? { value: recordBytesToJson(new Uint8Array(op.bytes)) } : {}
1894
+ }));
1895
+ if (!page.head) {
1896
+ const last = page.ops[page.ops.length - 1];
1897
+ return c.json({
1898
+ ops,
1899
+ ...last ? { cursor: `${last.rev}/${last.idx}` } : {}
1900
+ });
1901
+ }
1902
+ const keypair = await host.getKeypair();
1903
+ const commit = await signCommit({
1904
+ spaceUri: ref.uri,
1905
+ author: host.operatorDid,
1906
+ state: {
1907
+ setHash: new Uint8Array(page.head.setHash),
1908
+ rev: page.head.rev
1909
+ }
1910
+ }, keypair);
1911
+ return c.json({
1912
+ ops,
1913
+ commit: commitToJson(commit)
1914
+ });
1915
+ } catch (err) {
1916
+ return errorResponse(c, err);
1917
+ }
1918
+ });
1919
+ app.get("/xrpc/com.atproto.space.getRepo", async (c) => {
1920
+ try {
1921
+ const ref = requireSpaceUri(c.req.query("space"));
1922
+ const auth = await readAuth(c, ref, c.req.query("repo"));
1923
+ if (auth instanceof Response) return auth;
1924
+ const excludeValues = c.req.query("excludeValues") === "true";
1925
+ const stub = host.getSpaceDO(ref.uri);
1926
+ await requireRepoExists(stub, ref);
1927
+ let state = null;
1928
+ let records = null;
1929
+ for (let attempt = 0; attempt < 3 && !records; attempt++) {
1930
+ state = await stub.rpcGetRepoState();
1931
+ if (!state) throw new SpaceError("RepoNotFound", `Could not find repo for space: ${ref.uri}`);
1932
+ const collected = [];
1933
+ let after;
1934
+ let fenced = true;
1935
+ for (;;) {
1936
+ const page = await stub.rpcListRecords({
1937
+ limit: 500,
1938
+ after,
1939
+ reverse: true,
1940
+ excludeValues: false
1941
+ });
1942
+ if (page.rev !== state.rev) {
1943
+ fenced = false;
1944
+ break;
1945
+ }
1946
+ for (const record of page.records) collected.push({
1947
+ collection: record.collection,
1948
+ rkey: record.rkey,
1949
+ cid: parseCid(record.cid),
1950
+ bytes: new Uint8Array(record.bytes)
1951
+ });
1952
+ const last = page.records[page.records.length - 1];
1953
+ if (!page.hasMore || !last) break;
1954
+ after = {
1955
+ collection: last.collection,
1956
+ rkey: last.rkey
1957
+ };
1958
+ }
1959
+ if (fenced) records = collected;
1960
+ }
1961
+ if (!records || !state) return c.json({
1962
+ error: "ConcurrentModification",
1963
+ message: "The repo changed repeatedly during export; retry getRepo"
1964
+ }, 409);
1965
+ const keypair = await host.getKeypair();
1966
+ const car = serializeRepo(await signCommit({
1967
+ spaceUri: ref.uri,
1968
+ author: host.operatorDid,
1969
+ state: {
1970
+ setHash: new Uint8Array(state.setHash),
1971
+ rev: state.rev
1972
+ }
1973
+ }, keypair), records, { excludeValues });
1974
+ const stream = new ReadableStream({ async start(controller) {
1975
+ try {
1976
+ for await (const chunk of car) controller.enqueue(chunk);
1977
+ controller.close();
1978
+ } catch (err) {
1979
+ controller.error(err);
1980
+ }
1981
+ } });
1982
+ return new Response(stream, {
1983
+ status: 200,
1984
+ headers: { "Content-Type": "application/vnd.ipld.car" }
1985
+ });
1986
+ } catch (err) {
1987
+ return errorResponse(c, err);
1988
+ }
1989
+ });
1990
+ app.get("/xrpc/com.atproto.space.listBlobs", async (c) => {
1991
+ try {
1992
+ const ref = requireSpaceUri(c.req.query("space"));
1993
+ const auth = await readAuth(c, ref, c.req.query("repo"));
1994
+ if (auth instanceof Response) return auth;
1995
+ const limit = clampLimit(c.req.query("limit"), 500, 1e3);
1996
+ const since = c.req.query("since");
1997
+ const afterCid = c.req.query("cursor");
1998
+ const stub = host.getSpaceDO(ref.uri);
1999
+ await requireRepoExists(stub, ref);
2000
+ const page = await stub.rpcListBlobs({
2001
+ since,
2002
+ limit,
2003
+ afterCid
2004
+ });
2005
+ const last = page.cids[page.cids.length - 1];
2006
+ return c.json({
2007
+ cids: page.cids,
2008
+ ...page.hasMore && last ? { cursor: last } : {}
2009
+ });
2010
+ } catch (err) {
2011
+ return errorResponse(c, err);
2012
+ }
2013
+ });
2014
+ app.get("/xrpc/com.atproto.space.getBlob", async (c) => {
2015
+ try {
2016
+ const ref = requireSpaceUri(c.req.query("space"));
2017
+ const auth = await readAuth(c, ref, c.req.query("repo"));
2018
+ if (auth instanceof Response) return auth;
2019
+ const cid = c.req.query("cid");
2020
+ requireString(cid, "cid");
2021
+ if (!host.blobs) return c.json({
2022
+ error: "ServiceUnavailable",
2023
+ message: "Blob storage is not configured"
2024
+ }, 503);
2025
+ const stub = host.getSpaceDO(ref.uri);
2026
+ await requireRepoExists(stub, ref);
2027
+ if (!await stub.rpcHasSpaceBlob(cid)) throw new SpaceError("BlobNotFound", `Blob not found: ${cid}`);
2028
+ const key = spaceBlobKey(host.operatorDid, await spaceId(ref.uri), cid);
2029
+ const blob = await host.blobs.get(key);
2030
+ if (!blob) throw new SpaceError("BlobNotFound", `Blob not found: ${cid}`);
2031
+ return new Response(blob.body, {
2032
+ status: 200,
2033
+ headers: {
2034
+ "Content-Type": blob.httpMetadata?.contentType ?? "application/octet-stream",
2035
+ "Content-Length": blob.size.toString(),
2036
+ "Cache-Control": "private, no-store",
2037
+ Vary: "Authorization, DPoP",
2038
+ "X-Content-Type-Options": "nosniff",
2039
+ "Content-Disposition": `attachment; filename="${cid}"`,
2040
+ "Content-Security-Policy": "default-src 'none'; sandbox"
2041
+ }
2042
+ });
2043
+ } catch (err) {
2044
+ return errorResponse(c, err);
2045
+ }
2046
+ });
2047
+ app.post("/xrpc/com.atproto.space.getSpaceCredential", async (c) => {
2048
+ try {
2049
+ const body = await c.req.json();
2050
+ const ref = requireSpaceUri(body.space);
2051
+ assertSpaceHost(ref);
2052
+ const authHeader = c.req.header("Authorization");
2053
+ if (!authHeader?.startsWith("Bearer ")) throw new SpaceError("InvalidDelegationToken", "Expected a Bearer delegation token");
2054
+ const stub = host.getSpaceDO(ref.uri);
2055
+ const delegation = await verifyDelegationAuth(authHeader.slice(7), ref, verifyOpts(c, stub));
2056
+ const { meta, config } = await stub.rpcGetAuthorityState();
2057
+ if (meta?.deletedAt) throw new SpaceError("SpaceDeleted", `Space deleted: ${ref.uri}`);
2058
+ if (!meta || !config) throw new SpaceError("SpaceNotFound", `Space not found: ${ref.uri}`);
2059
+ let clientId;
2060
+ if (config.appAccess.kind === "allowList") {
2061
+ if (!body.clientAttestation) throw new SpaceError("AppNotAuthorized", "This space requires a client attestation");
2062
+ clientId = await verifyClientAttestation(body.clientAttestation, {
2063
+ expectedAud: spaceHostAud(ref.authority),
2064
+ allowedClientIds: config.appAccess.allowed,
2065
+ checkReplay: replayChecker(stub),
2066
+ fetch: host.outboundFetch
2067
+ });
2068
+ if (!config.appAccess.allowed.includes(clientId)) throw new SpaceError("AppNotAuthorized", "App is not authorized for this space");
2069
+ }
2070
+ if (!await authorizeUser(config, ref, delegation.userDid, clientId, stub)) throw new SpaceError("UserNotAuthorized", "User is not authorized for this space");
2071
+ const keypair = await host.getKeypair();
2072
+ const credential = await createSpaceToken("credential", {
2073
+ iss: host.operatorDid,
2074
+ sub: ref.uri,
2075
+ dpopJkt: delegation.dpopJkt
2076
+ }, keypair);
2077
+ return c.json({ credential });
2078
+ } catch (err) {
2079
+ return errorResponse(c, err);
2080
+ }
2081
+ });
2082
+ app.get("/xrpc/com.atproto.space.listRepos", async (c) => {
2083
+ try {
2084
+ const ref = requireSpaceUri(c.req.query("space"));
2085
+ assertSpaceHost(ref);
2086
+ const authHeader = c.req.header("Authorization");
2087
+ if (!isSpaceCredentialAuth(authHeader)) throw new SpaceError("InvalidCredential", "listRepos requires a space credential");
2088
+ const stub = host.getSpaceDO(ref.uri);
2089
+ await verifySpaceCredentialAuth(authHeader.slice(5), ref, verifyOpts(c, stub));
2090
+ const limit = clampLimit(c.req.query("limit"), 100, 1e3);
2091
+ const page = await stub.rpcListWriters({
2092
+ limit,
2093
+ afterDid: c.req.query("cursor")
2094
+ });
2095
+ const last = page.repos[page.repos.length - 1];
2096
+ return c.json({
2097
+ repos: page.repos.map((repo) => ({
2098
+ did: repo.did,
2099
+ rev: repo.rev,
2100
+ hash: bytesToJson(new Uint8Array(repo.hash))
2101
+ })),
2102
+ ...page.hasMore && last ? { cursor: last.did } : {}
2103
+ });
2104
+ } catch (err) {
2105
+ return errorResponse(c, err);
2106
+ }
2107
+ });
2108
+ app.post("/xrpc/com.atproto.space.registerNotify", async (c) => {
2109
+ try {
2110
+ const body = await c.req.json();
2111
+ const ref = requireSpaceUri(body.space);
2112
+ assertSpaceHost(ref);
2113
+ requireString(body.service, "service");
2114
+ const authHeader = c.req.header("Authorization");
2115
+ if (!isSpaceCredentialAuth(authHeader)) throw new SpaceError("InvalidCredential", "registerNotify requires a space credential");
2116
+ const stub = host.getSpaceDO(ref.uri);
2117
+ await verifySpaceCredentialAuth(authHeader.slice(5), ref, verifyOpts(c, stub));
2118
+ const endpoint = await host.resolveServiceEndpoint(body.service);
2119
+ if (!endpoint) throw new SpaceError("ServiceNotResolvable", `Could not resolve service: ${body.service}`);
2120
+ const result = await stub.rpcRegisterNotify(body.service, endpoint);
2121
+ return c.json({ expiresAt: result.expiresAt });
2122
+ } catch (err) {
2123
+ return errorResponse(c, err);
2124
+ }
2125
+ });
2126
+ app.post("/xrpc/com.atproto.space.unregisterNotify", async (c) => {
2127
+ try {
2128
+ const body = await c.req.json();
2129
+ const ref = requireSpaceUri(body.space);
2130
+ assertSpaceHost(ref);
2131
+ requireString(body.service, "service");
2132
+ const authHeader = c.req.header("Authorization");
2133
+ if (!isSpaceCredentialAuth(authHeader)) throw new SpaceError("InvalidCredential", "unregisterNotify requires a space credential");
2134
+ const stub = host.getSpaceDO(ref.uri);
2135
+ await verifySpaceCredentialAuth(authHeader.slice(5), ref, verifyOpts(c, stub));
2136
+ await stub.rpcUnregisterNotify(body.service);
2137
+ return c.json({});
2138
+ } catch (err) {
2139
+ return errorResponse(c, err);
2140
+ }
2141
+ });
2142
+ app.post("/xrpc/com.atproto.space.notifyWrite", async (c) => {
2143
+ try {
2144
+ const body = await c.req.json();
2145
+ const ref = requireSpaceUri(body.space);
2146
+ assertSpaceHost(ref);
2147
+ requireString(body.repo, "repo");
2148
+ requireString(body.rev, "rev");
2149
+ if (typeof body.hash?.$bytes !== "string") throw new SpaceError("InvalidRequest", "Missing hash bytes");
2150
+ const authHeader = c.req.header("Authorization");
2151
+ if (!authHeader?.startsWith("Bearer ")) return c.json({
2152
+ error: "AuthenticationRequired",
2153
+ message: "Service auth required"
2154
+ }, 401);
2155
+ const serviceAuth = await host.verifyServiceJwt(authHeader.slice(7), NOTIFY_WRITE_LXM);
2156
+ if (serviceAuth.iss !== body.repo) return c.json({
2157
+ error: "Forbidden",
2158
+ message: "notifyWrite iss does not match claimed writer"
2159
+ }, 403);
2160
+ if (serviceAuth.aud !== host.operatorDid) return c.json({
2161
+ error: "Forbidden",
2162
+ message: "notifyWrite aud does not match the space authority"
2163
+ }, 403);
2164
+ const stub = host.getSpaceDO(ref.uri);
2165
+ const { meta, config } = await stub.rpcGetAuthorityState();
2166
+ if (!meta || meta.deletedAt || !config) return c.json({});
2167
+ if (!await authorizeUser(config, ref, body.repo, void 0, stub)) return c.json({
2168
+ error: "Forbidden",
2169
+ message: "notifyWrite writer is not authorized"
2170
+ }, 403);
2171
+ const hash = fromBase64(body.hash.$bytes);
2172
+ const { advanced } = await stub.rpcRecordWriter(body.repo, body.rev, hash);
2173
+ if (!advanced) return c.json({});
2174
+ const registrations = await stub.rpcGetActiveRegistrations();
2175
+ const senderDid = body.repo;
2176
+ const targets = registrations.filter((registration) => registration.service.split("#")[0] !== senderDid);
2177
+ if (targets.length > 0) {
2178
+ const notifyBody = {
2179
+ space: ref.uri,
2180
+ repo: body.repo,
2181
+ rev: body.rev,
2182
+ hash: body.hash
2183
+ };
2184
+ await stub.rpcEnqueueNotify(targets.map((registration) => ({
2185
+ service: registration.service,
2186
+ endpoint: registration.endpoint,
2187
+ lxm: NOTIFY_WRITE_LXM,
2188
+ body: notifyBody
2189
+ })));
2190
+ }
2191
+ return c.json({});
2192
+ } catch (err) {
2193
+ return errorResponse(c, err);
2194
+ }
2195
+ });
2196
+ app.post("/xrpc/com.atproto.space.notifySpaceDeleted", async (c) => {
2197
+ try {
2198
+ const ref = requireSpaceUri((await c.req.json()).space);
2199
+ const authHeader = c.req.header("Authorization");
2200
+ if (!authHeader?.startsWith("Bearer ")) return c.json({
2201
+ error: "AuthenticationRequired",
2202
+ message: "Service auth required"
2203
+ }, 401);
2204
+ const serviceAuth = await host.verifyServiceJwt(authHeader.slice(7), SPACE_DELETED_LXM);
2205
+ if (serviceAuth.iss !== ref.authority) return c.json({
2206
+ error: "Forbidden",
2207
+ message: "notifySpaceDeleted iss is not the space authority"
2208
+ }, 403);
2209
+ if (serviceAuth.aud !== host.operatorDid && !serviceAuth.aud.startsWith(`${host.operatorDid}#`)) return c.json({
2210
+ error: "Forbidden",
2211
+ message: "notifySpaceDeleted aud does not match this service"
2212
+ }, 403);
2213
+ if (ref.authority === host.operatorDid) return c.json({});
2214
+ const stub = host.getSpaceDO(ref.uri);
2215
+ const meta = await stub.rpcGetMeta();
2216
+ if (meta && !meta.deletedAt) {
2217
+ await stub.rpcDeleteSpace();
2218
+ await host.getIndexDO().rpcMarkDeleted(ref.uri);
2219
+ if (host.blobs) waitUntil(c, deleteR2Prefix(host.blobs, spaceBlobPrefix(host.operatorDid, await spaceId(ref.uri))));
2220
+ }
2221
+ return c.json({});
2222
+ } catch (err) {
2223
+ return errorResponse(c, err);
2224
+ }
2225
+ });
2226
+ app.post("/xrpc/com.atproto.simplespace.createSpace", async (c) => {
2227
+ try {
2228
+ const body = await c.req.json();
2229
+ requireString(body.type, "type");
2230
+ const skey = body.skey ?? now();
2231
+ const session = await sessionAuth(c);
2232
+ if (session instanceof Response) return session;
2233
+ const scopeError = assertScope(c, session, {
2234
+ type: body.type,
2235
+ authority: host.operatorDid,
2236
+ skey,
2237
+ manage: "create"
2238
+ });
2239
+ if (scopeError) return scopeError;
2240
+ const config = {
2241
+ policy: parsePolicy(body.policy),
2242
+ appAccess: parseAppAccess(body.appAccess)
2243
+ };
2244
+ const ref = requireSpaceUri(`at://${host.operatorDid}/space/${body.type}/${skey}`);
2245
+ const index = host.getIndexDO();
2246
+ await index.rpcRegister({
2247
+ uri: ref.uri,
2248
+ authority: ref.authority,
2249
+ type: ref.type,
2250
+ skey: ref.skey,
2251
+ isAuthority: true
2252
+ });
2253
+ await host.getSpaceDO(ref.uri).rpcInit({
2254
+ uri: ref.uri,
2255
+ authority: ref.authority,
2256
+ type: ref.type,
2257
+ skey: ref.skey,
2258
+ isAuthority: true,
2259
+ config
2260
+ });
2261
+ await index.rpcActivate(ref.uri);
2262
+ return c.json({ uri: ref.uri });
2263
+ } catch (err) {
2264
+ return errorResponse(c, err);
2265
+ }
2266
+ });
2267
+ app.post("/xrpc/com.atproto.simplespace.updateSpace", async (c) => {
2268
+ try {
2269
+ const body = await c.req.json();
2270
+ const ref = requireSpaceUri(body.space);
2271
+ const session = await sessionAuth(c);
2272
+ if (session instanceof Response) return session;
2273
+ assertOwner(ref, session);
2274
+ const scopeError = assertScope(c, session, {
2275
+ type: ref.type,
2276
+ authority: ref.authority,
2277
+ skey: ref.skey,
2278
+ manage: "update"
2279
+ });
2280
+ if (scopeError) return scopeError;
2281
+ await host.getSpaceDO(ref.uri).rpcUpdateConfig({
2282
+ ...body.policy !== void 0 ? { policy: parsePolicy(body.policy) } : {},
2283
+ ...body.appAccess !== void 0 ? { appAccess: parseAppAccess(body.appAccess) } : {}
2284
+ });
2285
+ return c.json({});
2286
+ } catch (err) {
2287
+ return errorResponse(c, err);
2288
+ }
2289
+ });
2290
+ app.post("/xrpc/com.atproto.simplespace.deleteSpace", async (c) => {
2291
+ try {
2292
+ const ref = requireSpaceUri((await c.req.json()).space);
2293
+ const session = await sessionAuth(c);
2294
+ if (session instanceof Response) return session;
2295
+ assertOwner(ref, session);
2296
+ const scopeError = assertScope(c, session, {
2297
+ type: ref.type,
2298
+ authority: ref.authority,
2299
+ skey: ref.skey,
2300
+ manage: "delete"
2301
+ });
2302
+ if (scopeError) return scopeError;
2303
+ const stub = host.getSpaceDO(ref.uri);
2304
+ const { registrations } = await stub.rpcDeleteSpace();
2305
+ await host.getIndexDO().rpcMarkDeleted(ref.uri);
2306
+ if (registrations.length > 0) await stub.rpcEnqueueNotify(registrations.map((registration) => ({
2307
+ service: registration.service,
2308
+ endpoint: registration.endpoint,
2309
+ lxm: SPACE_DELETED_LXM,
2310
+ body: { space: ref.uri }
2311
+ })));
2312
+ if (host.blobs) waitUntil(c, deleteR2Prefix(host.blobs, spaceBlobPrefix(host.operatorDid, await spaceId(ref.uri))));
2313
+ return c.json({});
2314
+ } catch (err) {
2315
+ return errorResponse(c, err);
2316
+ }
2317
+ });
2318
+ app.post("/xrpc/com.atproto.simplespace.addMember", async (c) => {
2319
+ return memberChange(c, "add");
2320
+ });
2321
+ app.post("/xrpc/com.atproto.simplespace.removeMember", async (c) => {
2322
+ return memberChange(c, "remove");
2323
+ });
2324
+ async function memberChange(c, op) {
2325
+ try {
2326
+ const body = await c.req.json();
2327
+ const ref = requireSpaceUri(body.space);
2328
+ requireString(body.did, "did");
2329
+ const session = await sessionAuth(c);
2330
+ if (session instanceof Response) return session;
2331
+ assertOwner(ref, session);
2332
+ const scopeError = assertScope(c, session, {
2333
+ type: ref.type,
2334
+ authority: ref.authority,
2335
+ skey: ref.skey,
2336
+ manage: "update"
2337
+ });
2338
+ if (scopeError) return scopeError;
2339
+ const stub = host.getSpaceDO(ref.uri);
2340
+ await requireConfigured(stub, ref);
2341
+ if (op === "add") await stub.rpcAddMember(body.did);
2342
+ else await stub.rpcRemoveMember(body.did);
2343
+ return c.json({});
2344
+ } catch (err) {
2345
+ return errorResponse(c, err);
2346
+ }
2347
+ }
2348
+ app.get("/xrpc/com.atproto.simplespace.getSpace", async (c) => {
2349
+ try {
2350
+ const ref = requireSpaceUri(c.req.query("space"));
2351
+ assertSpaceHost(ref);
2352
+ const stub = host.getSpaceDO(ref.uri);
2353
+ const authHeader = c.req.header("Authorization");
2354
+ if (isSpaceCredentialAuth(authHeader)) await verifySpaceCredentialAuth(authHeader.slice(5), ref, verifyOpts(c, stub));
2355
+ else {
2356
+ const session = await sessionAuth(c);
2357
+ if (session instanceof Response) return session;
2358
+ const scopeError = assertScope(c, session, {
2359
+ type: ref.type,
2360
+ authority: ref.authority,
2361
+ skey: ref.skey,
2362
+ action: "read_self"
2363
+ });
2364
+ if (scopeError) return scopeError;
2365
+ }
2366
+ const config = await requireConfigured(stub, ref);
2367
+ return c.json({
2368
+ uri: ref.uri,
2369
+ policy: policyToJson(config.policy),
2370
+ appAccess: appAccessToJson(config.appAccess)
2371
+ });
2372
+ } catch (err) {
2373
+ return errorResponse(c, err);
2374
+ }
2375
+ });
2376
+ app.get("/xrpc/com.atproto.simplespace.listMembers", async (c) => {
2377
+ try {
2378
+ const ref = requireSpaceUri(c.req.query("space"));
2379
+ const session = await sessionAuth(c);
2380
+ if (session instanceof Response) return session;
2381
+ assertOwner(ref, session);
2382
+ const scopeError = assertScope(c, session, {
2383
+ type: ref.type,
2384
+ authority: ref.authority,
2385
+ skey: ref.skey,
2386
+ action: "read_self"
2387
+ });
2388
+ if (scopeError) return scopeError;
2389
+ const stub = host.getSpaceDO(ref.uri);
2390
+ await requireConfigured(stub, ref);
2391
+ const limit = clampLimit(c.req.query("limit"), 100, 1e3);
2392
+ const page = await stub.rpcListMembers({
2393
+ limit,
2394
+ afterDid: c.req.query("cursor")
2395
+ });
2396
+ const last = page.dids[page.dids.length - 1];
2397
+ return c.json({
2398
+ members: page.dids.map((did) => ({ did })),
2399
+ ...page.hasMore && last ? { cursor: last } : {}
2400
+ });
2401
+ } catch (err) {
2402
+ return errorResponse(c, err);
2403
+ }
2404
+ });
2405
+ function assertOwner(ref, session) {
2406
+ assertSpaceHost(ref);
2407
+ if (session.did !== ref.authority) throw new SpaceError("NotSpaceOwner", "Only the space owner may manage the space");
2408
+ }
2409
+ async function requireConfigured(stub, ref) {
2410
+ const { meta, config } = await stub.rpcGetAuthorityState();
2411
+ if (!meta || meta.deletedAt || !config) throw new SpaceError("SpaceNotFound", `Space not found: ${ref.uri}`);
2412
+ return config;
2413
+ }
2414
+ /**
2415
+ * A repo exists in a space once the operator has written into it (or
2416
+ * the space was created here). RepoNotFound deliberately covers both
2417
+ * "no such repo" and "space unknown to this host".
2418
+ */
2419
+ async function requireRepoExists(stub, ref) {
2420
+ const meta = await stub.rpcGetMeta();
2421
+ if (meta?.deletedAt) throw new SpaceError("SpaceNotFound", `Space not found: ${ref.uri}`);
2422
+ if (!meta) throw new SpaceError("RepoNotFound", `Could not find repo for space: ${ref.uri}`);
2423
+ }
2424
+ return app;
2425
+ }
2426
+ function requireString(value, name) {
2427
+ if (typeof value !== "string" || value.length === 0) throw new SpaceError("InvalidRequest", `Missing required parameter: ${name}`);
2428
+ }
2429
+ function clampLimit(raw, fallback, max) {
2430
+ const parsed = raw ? Number.parseInt(raw, 10) : fallback;
2431
+ if (Number.isNaN(parsed) || parsed < 1) return fallback;
2432
+ return Math.min(parsed, max);
2433
+ }
2434
+ function parseRecordCursor(cursor) {
2435
+ if (!cursor) return void 0;
2436
+ const slash = cursor.lastIndexOf("/");
2437
+ if (slash <= 0 || slash === cursor.length - 1) throw new SpaceError("MalformedCursor", `Malformed cursor: ${cursor}`);
2438
+ return {
2439
+ collection: cursor.slice(0, slash),
2440
+ rkey: cursor.slice(slash + 1)
2441
+ };
2442
+ }
2443
+ function parseOpsCursor(cursor) {
2444
+ if (!cursor) return void 0;
2445
+ const slash = cursor.indexOf("/");
2446
+ const idx = slash === -1 ? NaN : Number.parseInt(cursor.slice(slash + 1), 10);
2447
+ if (slash <= 0 || Number.isNaN(idx)) throw new SpaceError("MalformedCursor", `Malformed cursor: ${cursor}`);
2448
+ return {
2449
+ rev: cursor.slice(0, slash),
2450
+ idx
2451
+ };
2452
+ }
2453
+ const POLICY_PREFIX = "com.atproto.simplespace.defs#";
2454
+ function parsePolicy(input) {
2455
+ const type = input?.$type;
2456
+ switch (type) {
2457
+ case `${POLICY_PREFIX}publicPolicy`: return { kind: "public" };
2458
+ case `${POLICY_PREFIX}memberListPolicy`: return { kind: "member-list" };
2459
+ case `${POLICY_PREFIX}managingAppPolicy`: {
2460
+ const managingApp = input.managingApp;
2461
+ if (typeof managingApp !== "string" || !managingApp.startsWith("did:")) throw new SpaceError("UnsupportedPolicy", "managingApp must be a DID service identifier");
2462
+ return {
2463
+ kind: "managing-app",
2464
+ managingApp
2465
+ };
2466
+ }
2467
+ default: throw new SpaceError("UnsupportedPolicy", `Unsupported policy: ${String(type)}`);
2468
+ }
2469
+ }
2470
+ function policyToJson(policy) {
2471
+ switch (policy.kind) {
2472
+ case "public": return { $type: `${POLICY_PREFIX}publicPolicy` };
2473
+ case "member-list": return { $type: `${POLICY_PREFIX}memberListPolicy` };
2474
+ case "managing-app": return {
2475
+ $type: `${POLICY_PREFIX}managingAppPolicy`,
2476
+ managingApp: policy.managingApp
2477
+ };
2478
+ }
2479
+ }
2480
+ function appAccessToJson(appAccess) {
2481
+ switch (appAccess.kind) {
2482
+ case "open": return { $type: `${POLICY_PREFIX}open` };
2483
+ case "allowList": return {
2484
+ $type: `${POLICY_PREFIX}allowList`,
2485
+ allowed: appAccess.allowed
2486
+ };
2487
+ }
2488
+ }
2489
+ function parseAppAccess(input) {
2490
+ const type = input?.$type;
2491
+ switch (type) {
2492
+ case `${POLICY_PREFIX}open`: return { kind: "open" };
2493
+ case `${POLICY_PREFIX}allowList`: {
2494
+ const allowed = input.allowed;
2495
+ if (!Array.isArray(allowed) || allowed.some((entry) => typeof entry !== "string")) throw new SpaceError("UnsupportedAppAccess", "allowList requires an array of client IDs");
2496
+ return {
2497
+ kind: "allowList",
2498
+ allowed
2499
+ };
2500
+ }
2501
+ default: throw new SpaceError("UnsupportedAppAccess", `Unsupported appAccess: ${String(type)}`);
2502
+ }
2503
+ }
2504
+ async function deleteR2Prefix(bucket, prefix) {
2505
+ let cursor;
2506
+ do {
2507
+ const listed = await bucket.list({
2508
+ prefix,
2509
+ cursor,
2510
+ limit: 500
2511
+ });
2512
+ if (listed.objects.length > 0) await bucket.delete(listed.objects.map((object) => object.key));
2513
+ cursor = listed.truncated ? listed.cursor : void 0;
2514
+ } while (cursor);
2515
+ }
2516
+
2517
+ //#endregion
2518
+ export { NOTIFY_REGISTRATION_DAYS, OPLOG_RETENTION_DAYS, OPLOG_RETENTION_OPS, SPACE_ERROR_CODES, SPACE_SCHEMA_VERSION, SpaceDurableObject, SpaceError, SpaceIndexDurableObject, bytesToJson, commitToJson, createServiceJwt, createSpaceRoutes, formatSpaceUri, isSpaceCredentialAuth, nextRev, parseSpaceErrorCode, parseSpaceUri, prepareRecord, recordBytesToJson, requireSpaceUri, signCommit, spaceBlobKey, spaceBlobKeyForUri, spaceBlobPrefix, spaceBlobRootPrefix, spaceErrorStatus, spaceId, spaceRecordUri, stagedBlobKey, tidCutoff, unverifiedJwtTyp, verifyClientAttestation, verifyDelegationAuth, verifySpaceCredentialAuth };
2519
+ //# sourceMappingURL=index.js.map