@getcirrus/spaces 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,12 +1,13 @@
1
1
  import { DurableObject } from "cloudflare:workers";
2
- import { DpopProofError, RepoCommit, SPACE_TOKEN_TYPES, SpaceTokenError, createSpaceToken, parseSpaceToken, serializeRepo, spaceHostAud, verifyDpopProof, verifySpaceToken } from "@atproto/space";
2
+ import { CLIENT_ATTESTATION_TYP, COMMIT_MAC_PROFILE, MAC_COVERED_HEADER, RECORD_MAC_PROFILE, RepoCommit, SpaceKemError, SpaceMacError, SpaceSignatureError, SpaceTokenError, createCommitMacHeaders, createDelegationToken as createDelegationToken$1, createRecordMacHeaders, createSpaceCredential, decapsulate, isP256DidKey, parseMacRequest, parseSpaceToken, readRepoStar, readSpaceMetaStar, spaceHostAud as spaceHostAud$1, verifyCredentialSig, verifySpaceToken, writeRepoStar, writeSpaceMetaStar } from "@atproto/space";
3
+ import { cidForLex, decode, encode } from "@atproto/lex-cbor";
4
+ import { cidForCbor, enumBlobRefs, fromBase64, getBlobCidString, parseCid, toBase64 } from "@atproto/lex-data";
5
+ import { jsonToLex, lexToJson } from "@atproto/lex-json";
6
+ import { P256Keypair } from "@atproto/crypto";
3
7
  import { now } from "@atcute/tid";
4
8
  import { isDid, isNsid, isRecordKey } from "@atcute/lexicons/syntax";
5
9
  import { Hono } from "hono";
6
- import { enumBlobRefs, fromBase64, getBlobCidString, parseCid, toBase64 } from "@atproto/lex-data";
7
10
  import { createLocalJWKSet, jwtVerify } from "jose";
8
- import { cidForLex, decode, encode } from "@atproto/lex-cbor";
9
- import { jsonToLex, lexToJson } from "@atproto/lex-json";
10
11
 
11
12
  //#region src/errors.ts
12
13
  /**
@@ -18,28 +19,49 @@ import { jsonToLex, lexToJson } from "@atproto/lex-json";
18
19
  * name with {@link parseSpaceErrorCode} and map it onto the lexicon error
19
20
  * shape.
20
21
  */
21
- /** Protocol error names used across space and simplespace endpoints. */
22
+ /** Protocol error names used across the space and policy endpoints. */
22
23
  const SPACE_ERROR_CODES = [
23
24
  "SpaceNotFound",
24
25
  "SpaceDeleted",
25
26
  "SpaceAlreadyExists",
26
27
  "RepoNotFound",
28
+ "RepoDeactivated",
29
+ "RepoTakendown",
27
30
  "RecordNotFound",
28
31
  "RecordAlreadyExists",
29
32
  "BlobNotFound",
30
- "UserNotAuthorized",
31
33
  "AppNotAuthorized",
32
34
  "NotAuthorized",
35
+ "AccountNotAuthorized",
33
36
  "InvalidDelegationToken",
34
37
  "InvalidClientAttestation",
35
38
  "InvalidCredential",
36
- "NotSpaceOwner",
39
+ "PolicyMismatch",
37
40
  "UnsupportedPolicy",
38
- "UnsupportedAppAccess",
39
41
  "ServiceNotResolvable",
40
- "MalformedCursor",
41
- "InvalidSpaceUri",
42
+ "InvalidCursor",
42
43
  "InvalidRequest",
44
+ "FutureRev",
45
+ "InvalidSpaceMac",
46
+ "InvalidRepoFile",
47
+ "RepoMismatch",
48
+ "InvalidSpaceMeta",
49
+ "RegistrationNotConfirmed",
50
+ "UpstreamFailure",
51
+ "MissingJwt",
52
+ "BadJwt",
53
+ "BadJwtType",
54
+ "BadJwtIss",
55
+ "BadJwtSub",
56
+ "BadJwtAudience",
57
+ "BadJwtCnf",
58
+ "BadJwtSignature",
59
+ "JwtExpired",
60
+ "BadSpaceSignature",
61
+ "BadSpaceAudience",
62
+ "CredentialRevoked",
63
+ "Forbidden",
64
+ "KemKeyUnavailable",
43
65
  "SpacesSchemaOutdated"
44
66
  ];
45
67
  const CODE_SET = new Set(SPACE_ERROR_CODES);
@@ -50,13 +72,24 @@ const ERROR_STATUS = {
50
72
  BlobNotFound: 404,
51
73
  RecordAlreadyExists: 409,
52
74
  SpaceAlreadyExists: 409,
53
- UserNotAuthorized: 403,
54
75
  AppNotAuthorized: 403,
55
- NotAuthorized: 403,
56
- NotSpaceOwner: 403,
57
- InvalidDelegationToken: 401,
76
+ AccountNotAuthorized: 403,
77
+ Forbidden: 403,
78
+ UpstreamFailure: 502,
58
79
  InvalidClientAttestation: 401,
59
- InvalidCredential: 401,
80
+ MissingJwt: 401,
81
+ BadJwt: 401,
82
+ BadJwtType: 401,
83
+ BadJwtIss: 401,
84
+ BadJwtSub: 401,
85
+ BadJwtAudience: 401,
86
+ BadJwtCnf: 401,
87
+ BadJwtSignature: 401,
88
+ JwtExpired: 401,
89
+ BadSpaceSignature: 401,
90
+ BadSpaceAudience: 401,
91
+ CredentialRevoked: 401,
92
+ KemKeyUnavailable: 503,
60
93
  SpacesSchemaOutdated: 503
61
94
  };
62
95
  var SpaceError = class extends Error {
@@ -102,6 +135,143 @@ function spaceErrorStatus(code) {
102
135
  return ERROR_STATUS[code] ?? 400;
103
136
  }
104
137
 
138
+ //#endregion
139
+ //#region src/types.ts
140
+ const PERSONALSPACE_POLICY = "com.atproto.personalspace.policy";
141
+ const MEMBERSPACE_POLICY = "com.atproto.memberspace.policy";
142
+ const MANAGEDSPACE_POLICY = "com.atproto.managedspace.policy";
143
+
144
+ //#endregion
145
+ //#region src/policy.ts
146
+ /**
147
+ * Space policies: the three baseline policies every PDS supports, as
148
+ * `com.atproto.space.createSpace` / `updateSpace` take them. A policy is an
149
+ * open union discriminated by `$type` that both selects the policy and
150
+ * carries its configuration.
151
+ *
152
+ * What is stored is exactly what is enforced: {@link normalizePolicy}
153
+ * refuses a policy this host doesn't implement and fills in every default.
154
+ * Unknown fields are dropped, as Lexicon evolution allows.
155
+ */
156
+ /** The collection a published policy record lives in (rkey `self`). */
157
+ const POLICY_COLLECTION = "com.atproto.space.policy";
158
+ const POLICY_RKEY = "self";
159
+ /** The collection published member records live in (rkey = member DID). */
160
+ const MEMBER_COLLECTION = "com.atproto.memberspace.member";
161
+ /** The collections the host publishes a space's configuration to. */
162
+ const PUBLISHED_COLLECTIONS = [POLICY_COLLECTION, MEMBER_COLLECTION];
163
+ const isBool = (value) => typeof value === "boolean";
164
+ function isUri(value) {
165
+ if (typeof value !== "string") return false;
166
+ try {
167
+ new URL(value);
168
+ return true;
169
+ } catch {
170
+ return false;
171
+ }
172
+ }
173
+ function optionalBool(input, key) {
174
+ const value = input[key];
175
+ if (value === void 0) return false;
176
+ if (!isBool(value)) throw new SpaceError("InvalidRequest", `Policy ${key} must be a boolean`);
177
+ return value;
178
+ }
179
+ /** Validate and normalise a policy from a request or an archive. */
180
+ function normalizePolicy(input) {
181
+ if (!input || typeof input !== "object" || Array.isArray(input)) throw new SpaceError("InvalidRequest", "policy must be an object");
182
+ const policy = input;
183
+ switch (policy.$type) {
184
+ case PERSONALSPACE_POLICY: return { $type: PERSONALSPACE_POLICY };
185
+ case MEMBERSPACE_POLICY: {
186
+ const allowedApps = policy.allowedApps;
187
+ if (allowedApps !== void 0 && (!Array.isArray(allowedApps) || allowedApps.some((app) => !isUri(app)))) throw new SpaceError("InvalidRequest", "allowedApps must be an array of OAuth client ID URIs");
188
+ return {
189
+ $type: MEMBERSPACE_POLICY,
190
+ publicRead: optionalBool(policy, "publicRead"),
191
+ publicWrite: optionalBool(policy, "publicWrite"),
192
+ ...allowedApps !== void 0 ? { allowedApps: [...allowedApps] } : {},
193
+ publishPolicy: optionalBool(policy, "publishPolicy"),
194
+ publishMembers: optionalBool(policy, "publishMembers")
195
+ };
196
+ }
197
+ case MANAGEDSPACE_POLICY: {
198
+ const managingApp = policy.managingApp;
199
+ const [did, fragment, extra] = typeof managingApp === "string" ? managingApp.split("#") : [];
200
+ if (!did?.startsWith("did:") || !fragment || extra !== void 0) throw new SpaceError("InvalidRequest", `managingApp must be a did#serviceId reference, got: ${String(managingApp)}`);
201
+ return {
202
+ $type: MANAGEDSPACE_POLICY,
203
+ managingApp,
204
+ publishPolicy: optionalBool(policy, "publishPolicy")
205
+ };
206
+ }
207
+ default: throw new SpaceError("UnsupportedPolicy", `Unsupported policy: ${String(policy.$type)}`);
208
+ }
209
+ }
210
+ /** The member list and its methods belong to the memberspace policy. */
211
+ function assertMemberspace(policy) {
212
+ if (policy.$type !== MEMBERSPACE_POLICY) throw new SpaceError("PolicyMismatch", "Space is not governed by the memberspace policy");
213
+ }
214
+ function isPolicyPublished(policy) {
215
+ return policy.$type !== PERSONALSPACE_POLICY && policy.publishPolicy;
216
+ }
217
+ function areMembersPublished(policy) {
218
+ return policy.$type === MEMBERSPACE_POLICY && policy.publishMembers;
219
+ }
220
+ /**
221
+ * Only memberspace restricts apps, against the attested client_id, so an
222
+ * app that presents no attestation is never one of the allowed apps.
223
+ */
224
+ function isAppAuthorized(policy, clientId) {
225
+ if (policy.$type !== MEMBERSPACE_POLICY || !policy.allowedApps) return true;
226
+ return clientId !== void 0 && policy.allowedApps.includes(clientId);
227
+ }
228
+ /**
229
+ * A DID as a record key, for published member records. A record key can't
230
+ * contain `%`, so the percent-encoded port of a localhost did:web is left
231
+ * unencoded, as the reference does. Unambiguous because the unencoded form
232
+ * would otherwise be a did:web path, which atproto doesn't support.
233
+ */
234
+ function didToRecordKey(did) {
235
+ return did.replace("%3A", ":");
236
+ }
237
+ function recordKeyToDid(rkey) {
238
+ return rkey.replace(/^(did:web:[^:]+):(\d+)$/, "$1%3A$2");
239
+ }
240
+ /** Records published from a space's configuration are the host's to write. */
241
+ function assertNotPublishedCollection(collection) {
242
+ if (PUBLISHED_COLLECTIONS.includes(collection)) throw new SpaceError("InvalidRequest", `${collection} records are published by the PDS from a space's configuration and cannot be written directly`);
243
+ }
244
+
245
+ //#endregion
246
+ //#region src/records.ts
247
+ /**
248
+ * Record preparation and serialization for the Worker side of the write
249
+ * and read paths. Records are stored as dag-cbor bytes with their CID,
250
+ * computed here — the same encoding path the reference uses.
251
+ */
252
+ /**
253
+ * Convert a client-supplied JSON record into its stored form: lex value →
254
+ * dag-cbor bytes → CID, with blob references enumerated for the space's
255
+ * blob tracking.
256
+ */
257
+ async function prepareRecord(record) {
258
+ const lex = jsonToLex(record);
259
+ const bytes = encode(lex);
260
+ const cid = await cidForLex(lex);
261
+ const blobCids = [];
262
+ for (const ref of enumBlobRefs(lex)) blobCids.push(getBlobCidString(ref));
263
+ return {
264
+ cid: cid.toString(),
265
+ bytes,
266
+ blobCids,
267
+ json: lexToJson(lex)
268
+ };
269
+ }
270
+ /** Decode stored record bytes back into response JSON. */
271
+ function recordBytesToJson(bytes) {
272
+ return lexToJson(decode(bytes));
273
+ }
274
+
105
275
  //#endregion
106
276
  //#region src/schema.ts
107
277
  /**
@@ -114,8 +284,19 @@ function spaceErrorStatus(code) {
114
284
  * {@link SPACE_SCHEMA_VERSION} puts existing DOs into a refusing state until
115
285
  * `pds spaces reset` wipes them. That is the alpha policy, applied honestly.
116
286
  */
117
- /** Bump on any breaking change to the tables below. */
118
- const SPACE_SCHEMA_VERSION = 1;
287
+ /**
288
+ * Bump on any breaking change to the tables below.
289
+ *
290
+ * 2: baseline policies replace simplespace config; members carry
291
+ * read/write access; writers carry space revisions; revoked
292
+ * credentials; coalescing notification queue.
293
+ * 3: webhook registrations (endpoint + token) replace registerNotify;
294
+ * writers keep a removal marker; queue rows carry their retry policy
295
+ * and authentication.
296
+ * 4: space URIs move to `at:space/{did}/{type}/{skey}`. Space DOs are
297
+ * named by URI, so spaces stored under the old form are unreachable.
298
+ */
299
+ const SPACE_SCHEMA_VERSION = 4;
119
300
  const SPACE_DO_SCHEMA = `
120
301
  -- One row. schema_version is checked on every open.
121
302
  CREATE TABLE IF NOT EXISTS meta (
@@ -165,38 +346,67 @@ const SPACE_DO_SCHEMA = `
165
346
  PRIMARY KEY (rev, idx)
166
347
  );
167
348
 
168
- -- Authority role only.
349
+ -- Authority role only. The policy is stored as its normalised lexicon
350
+ -- object (com.atproto.{personal,member,managed}space.policy).
169
351
  CREATE TABLE IF NOT EXISTS config (
170
352
  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
353
+ policy TEXT NOT NULL
175
354
  );
176
355
 
177
- CREATE TABLE IF NOT EXISTS member (did TEXT PRIMARY KEY);
356
+ -- memberspace member list.
357
+ CREATE TABLE IF NOT EXISTS member (
358
+ did TEXT PRIMARY KEY,
359
+ can_read INTEGER NOT NULL,
360
+ can_write INTEGER NOT NULL
361
+ );
178
362
 
363
+ -- The writer set, sequenced by space revision. A removed writer keeps
364
+ -- its row, marked removed at the revision of its removal, so listWriters
365
+ -- can report the removal until it writes again.
179
366
  CREATE TABLE IF NOT EXISTS writer (
180
367
  did TEXT PRIMARY KEY,
181
- rev TEXT NOT NULL,
182
- hash BLOB NOT NULL
368
+ repo_rev TEXT NOT NULL,
369
+ data BLOB NOT NULL,
370
+ space_rev TEXT NOT NULL,
371
+ removed_at INTEGER
183
372
  );
373
+ CREATE INDEX IF NOT EXISTS idx_writer_space_rev ON writer(space_rev);
184
374
 
375
+ -- Syncer webhook registrations, made through authorizeSpaceSync. Active
376
+ -- until the credential of their latest authorization expires
377
+ -- (expires_at, ms); expiry_notified marks a lapse already announced.
185
378
  CREATE TABLE IF NOT EXISTS notify_registration (
186
- service TEXT PRIMARY KEY,
187
379
  endpoint TEXT NOT NULL,
188
- expires_at TEXT NOT NULL
380
+ token TEXT NOT NULL,
381
+ expires_at INTEGER NOT NULL,
382
+ expiry_notified INTEGER NOT NULL DEFAULT 0,
383
+ PRIMARY KEY (endpoint, token)
189
384
  );
190
385
 
386
+ -- Outbound notifications, both roles. A row with a coalesce_key is
387
+ -- replaced by a newer one with the same key; deadline (ms) is when
388
+ -- retrying stops. policy picks the retry schedule ('fanout' | 'repo' |
389
+ -- 'syncer'); auth is 'service' (a service JWT from the operator) or
390
+ -- 'none' (a syncer webhook, authenticated by the token in its body).
191
391
  CREATE TABLE IF NOT EXISTS notify_queue (
192
392
  id INTEGER PRIMARY KEY AUTOINCREMENT,
193
393
  service TEXT NOT NULL,
194
394
  body TEXT NOT NULL,
195
395
  attempts INTEGER NOT NULL DEFAULT 0,
196
- next_at INTEGER NOT NULL
396
+ next_at INTEGER NOT NULL,
397
+ deadline INTEGER,
398
+ coalesce_key TEXT UNIQUE,
399
+ policy TEXT NOT NULL DEFAULT 'fanout',
400
+ auth TEXT NOT NULL DEFAULT 'service'
197
401
  );
198
402
  CREATE INDEX IF NOT EXISTS idx_notify_queue_next ON notify_queue(next_at);
199
403
 
404
+ -- Credentials for this space revoked by its authority (repo-host role).
405
+ CREATE TABLE IF NOT EXISTS revoked_credential (
406
+ jti TEXT PRIMARY KEY,
407
+ expires_at INTEGER NOT NULL
408
+ );
409
+
200
410
  -- Replay protection, both roles.
201
411
  CREATE TABLE IF NOT EXISTS replay (
202
412
  kind TEXT NOT NULL,
@@ -209,10 +419,35 @@ const SPACE_DO_SCHEMA = `
209
419
  const OPLOG_RETENTION_DAYS = 30;
210
420
  /** Retain at most this many oplog entries. */
211
421
  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. */
422
+ /**
423
+ * Give up delivering a notification without its own deadline after this
424
+ * many attempts: syncer fan-out is reasonable-effort, and a syncer that
425
+ * misses one recovers through listRepos.
426
+ */
215
427
  const NOTIFY_MAX_ATTEMPTS = 5;
428
+ /** A repo host retries its write notification to the authority this long. */
429
+ const NOTIFY_WRITE_RETRY_MS = 1440 * 60 * 1e3;
430
+ /**
431
+ * A syncer's deletion or expiry notice is retried after each of these
432
+ * delays in turn, repeating the last, for at least
433
+ * {@link SYNCER_NOTICE_RETRY_WINDOW_MS}.
434
+ */
435
+ const SYNCER_NOTICE_RETRY_DELAYS_MS = [
436
+ 6e4,
437
+ 10 * 6e4,
438
+ 60 * 6e4,
439
+ 360 * 6e4,
440
+ 720 * 6e4
441
+ ];
442
+ const SYNCER_NOTICE_RETRY_WINDOW_MS = 4320 * 60 * 1e3;
443
+ /** The largest notify token a syncer may register. */
444
+ const MAX_NOTIFY_TOKEN_LENGTH = 512;
445
+ /** Cap on the backoff between notification retries. */
446
+ const NOTIFY_BACKOFF_MAX_MS = 3600 * 1e3;
447
+ /** notifyWrite refuses repo revisions this far ahead of the clock. */
448
+ const MAX_REV_CLOCK_SKEW_MS = 300 * 1e3;
449
+ /** The largest record a space repo accepts, as its DRISL encoding. */
450
+ const MAX_SPACE_RECORD_BYTES = 1024 * 1024;
216
451
  /** Base delay for notification retry backoff, in milliseconds. */
217
452
  const NOTIFY_BACKOFF_BASE_MS = 3e4;
218
453
  const INDEX_DO_SCHEMA = `
@@ -228,10 +463,134 @@ const INDEX_DO_SCHEMA = `
228
463
  schema_version INTEGER NOT NULL
229
464
  );
230
465
  CREATE INDEX IF NOT EXISTS idx_space_state ON space(state);
466
+
467
+ -- Blobs referenced by an imported space repo that had not been uploaded
468
+ -- yet. uploadBlob claims them and promotes the staged copy into each
469
+ -- space's blob prefix.
470
+ CREATE TABLE IF NOT EXISTS pending_blob (
471
+ cid TEXT NOT NULL,
472
+ uri TEXT NOT NULL,
473
+ created_at INTEGER NOT NULL,
474
+ PRIMARY KEY (cid, uri)
475
+ );
231
476
  `;
477
+ /** Forget pending imported-space blobs that were never uploaded. */
478
+ const PENDING_BLOB_TTL_MS = 720 * 60 * 60 * 1e3;
232
479
  /** Remove `pending` index entries that never activated after this long. */
233
480
  const PENDING_ENTRY_TTL_MS = 1440 * 60 * 1e3;
234
481
 
482
+ //#endregion
483
+ //#region src/mac.ts
484
+ /**
485
+ * Commits and MACs.
486
+ *
487
+ * A space repo commit carries no signature. A syncer authenticates what a
488
+ * repo host serves with a MAC instead: an HTTP message signature (RFC 9421)
489
+ * using `hmac-sha256`, keyed by a per-request secret both sides derive with
490
+ * HPKE secret export against the account's `#atproto_kem` key. The syncer
491
+ * asks with `Accept-Signature`, naming its ephemeral key and a profile tag;
492
+ * the host answers with a header describing the commit or record
493
+ * (`Atproto-Space-Commit` / `Atproto-Space-Record`) and a MAC covering it.
494
+ * A leaked response proves nothing to a third party. The KEM key is the only
495
+ * secret here, and it lives with the Worker.
496
+ */
497
+ /** The request header a syncer asks for a MAC with. */
498
+ const MAC_REQUEST_HEADER = "accept-signature";
499
+ /** The response headers a browser syncer must read to check a MAC. */
500
+ function macExposedHeaders(profile) {
501
+ return [
502
+ MAC_COVERED_HEADER[profile],
503
+ "signature-input",
504
+ "signature"
505
+ ];
506
+ }
507
+ /** The commit over a repo's persisted state. */
508
+ function buildCommit(params) {
509
+ return RepoCommit.fromState(params.state.setHash).toCommit({
510
+ space: params.spaceUri,
511
+ repo: params.repo,
512
+ rev: params.state.rev
513
+ });
514
+ }
515
+ /**
516
+ * Lexicon JSON form of a commit (`com.atproto.space.defs#commit`): bytes
517
+ * fields encode as `{"$bytes": "<base64>"}`.
518
+ */
519
+ function commitToJson(commit) {
520
+ return {
521
+ ver: commit.ver,
522
+ repo: commit.repo,
523
+ space: commit.space,
524
+ rev: commit.rev,
525
+ data: bytesToJson(commit.data)
526
+ };
527
+ }
528
+ /** Lexicon JSON form of a bare bytes value. */
529
+ function bytesToJson(bytes) {
530
+ return { $bytes: toBase64(bytes) };
531
+ }
532
+ /** Import the account's `#atproto_kem` keypair from its hex private key. */
533
+ async function importKemKeypair(privateKeyHex) {
534
+ return P256Keypair.import(privateKeyHex);
535
+ }
536
+ /** Generate a fresh `#atproto_kem` keypair. */
537
+ async function generateKemKey() {
538
+ const keypair = await P256Keypair.create({ exportable: true });
539
+ const exported = await keypair.export();
540
+ const didKey = keypair.did();
541
+ return {
542
+ privateKeyHex: Array.from(exported, (b) => b.toString(16).padStart(2, "0")).join(""),
543
+ didKey,
544
+ publicKeyMultibase: didKey.slice(8)
545
+ };
546
+ }
547
+ /** The public half of a KEM private key, as a did:key. */
548
+ async function kemDidKey(privateKeyHex) {
549
+ return (await importKemKeypair(privateKeyHex)).did();
550
+ }
551
+ /**
552
+ * The MAC owed by a read that returns a commit or record. A space
553
+ * credential must ask for one with the profile's tag; an account reading its
554
+ * own data gets one only if it asks. Requests with other tags are ignored.
555
+ * Returns undefined when no MAC is owed.
556
+ */
557
+ async function macRequest(req) {
558
+ let request;
559
+ try {
560
+ request = parseMacRequest(req.acceptSignature, req.profile);
561
+ } catch (err) {
562
+ throw invalidMac(err);
563
+ }
564
+ if (!request) {
565
+ if (!req.credential) return void 0;
566
+ throw new SpaceError("InvalidSpaceMac", `A MAC must be requested with tag "${req.profile}"`);
567
+ }
568
+ const keypair = await req.getKemKeypair();
569
+ if (!keypair) throw new SpaceError("KemKeyUnavailable", "This host has no #atproto_kem key configured, so it cannot authenticate space data to syncers");
570
+ try {
571
+ return {
572
+ ...request,
573
+ sharedSecret: decapsulate(keypair, request.keyShare)
574
+ };
575
+ } catch (err) {
576
+ throw invalidMac(err);
577
+ }
578
+ }
579
+ function invalidMac(err) {
580
+ if (err instanceof SpaceMacError || err instanceof SpaceKemError) return new SpaceError("InvalidSpaceMac", err.message);
581
+ return new SpaceError("InvalidSpaceMac", "Invalid Accept-Signature header");
582
+ }
583
+ /** The MAC response headers for a commit, when one is owed. */
584
+ function commitMacHeaders(mac, commit) {
585
+ if (!mac) return {};
586
+ return createCommitMacHeaders(commit, mac).headers;
587
+ }
588
+ /** The MAC response headers for a record, when one is owed. */
589
+ function recordMacHeaders(mac, uri, cid) {
590
+ if (!mac) return {};
591
+ return createRecordMacHeaders(uri, parseCid(cid), mac).headers;
592
+ }
593
+
235
594
  //#endregion
236
595
  //#region src/tid.ts
237
596
  /**
@@ -271,6 +630,16 @@ function tidCutoff(msAgo) {
271
630
  }
272
631
  return out;
273
632
  }
633
+ /** The timestamp a TID encodes, in milliseconds since the epoch. */
634
+ function tidTimestampMs(tid) {
635
+ let value = 0n;
636
+ for (const char of tid) {
637
+ const idx = S32_CHAR.indexOf(char);
638
+ if (idx === -1) throw new Error(`Invalid TID: ${tid}`);
639
+ value = value << 5n | BigInt(idx);
640
+ }
641
+ return Number(value >> 10n) / 1e3;
642
+ }
274
643
 
275
644
  //#endregion
276
645
  //#region src/service-jwt.ts
@@ -306,16 +675,17 @@ async function createServiceJwt(params, keypair) {
306
675
  *
307
676
  * Holds everything Cirrus knows about that space: the operator's
308
677
  * 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.
678
+ * when the operator is the authority, the space's policy, member list,
679
+ * writer set (sequenced by space revision) and notification registrations.
680
+ * Both roles share the outbound notification queue, and the replay and
681
+ * revocation tables for tokens presented against the space.
313
682
  *
314
683
  * Constraints inherited from the Cirrus architecture:
315
684
  * - 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.
685
+ * - No key material in here except through
686
+ * {@link SpaceHostConfig.getKeypair}, used only for outbound notification
687
+ * service JWTs from the alarm. Commits are unsigned and MACs are the
688
+ * Worker's, so the KEM key never enters this class.
319
689
  * - The host supplies its identity via {@link getHostConfig}; this class
320
690
  * must not read `env.DID`. If it ever contains a branch on which host is
321
691
  * running it, the boundary has failed.
@@ -325,6 +695,19 @@ const DAY_MS = 1440 * 60 * 1e3;
325
695
  const MAINTENANCE_INTERVAL_MS = DAY_MS;
326
696
  /** How many queued notifications to attempt per alarm invocation. */
327
697
  const NOTIFY_BATCH = 20;
698
+ const NOTIFY_SPACE_UPDATE_LXM = "com.atproto.space.notifySpaceUpdate";
699
+ const REPO_WRITE = "com.atproto.space.defs#repoWrite";
700
+ const REPO_REMOVED = "com.atproto.space.defs#repoRemoved";
701
+ const SPACE_DELETED = "com.atproto.space.notifySpaceUpdate#spaceDeleted";
702
+ const REGISTRATION_EXPIRED = "com.atproto.space.notifySpaceUpdate#registrationExpired";
703
+ /** 50-100% of a delay, so retries from many spaces don't align. */
704
+ function jitter(delay) {
705
+ return Math.floor(delay * (.5 + Math.random() / 2));
706
+ }
707
+ /** HTTP statuses worth retrying; anything else is a permanent refusal. */
708
+ function isRetryableStatus(status) {
709
+ return status === 408 || status === 425 || status === 429 || status >= 500;
710
+ }
328
711
  var SpaceDurableObject = class extends DurableObject {
329
712
  sql;
330
713
  initialized = false;
@@ -377,88 +760,193 @@ var SpaceDurableObject = class extends DurableObject {
377
760
  if (meta.deletedAt) throw new SpaceError("SpaceNotFound", "Space has been deleted");
378
761
  return meta;
379
762
  }
763
+ /** The policy of a live space this host governs, or SpaceNotFound. */
764
+ requirePolicy() {
765
+ const meta = this.requireLiveMeta();
766
+ const policy = this.readPolicy();
767
+ if (!policy) throw new SpaceError("SpaceNotFound", "Space not found");
768
+ return {
769
+ meta,
770
+ policy
771
+ };
772
+ }
380
773
  async rpcGetMeta() {
381
774
  await this.ensureOpen();
382
775
  return this.readMeta();
383
776
  }
384
777
  /**
385
778
  * Initialise this DO as the operator's repo in a space (either role).
386
- * Idempotent for an existing live space with matching identity.
779
+ * For the authority role a policy creates the space: refused when a live
780
+ * space already has one. A deleted space may be created again; its
781
+ * tables were wiped at deletion, so reviving is a fresh start. Returns
782
+ * the commit when publishing the policy wrote to the repo.
387
783
  */
388
784
  async rpcInit(params) {
389
785
  await this.ensureOpen();
390
786
  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);
787
+ if (existing && existing.uri !== params.uri) throw new SpaceError("InvalidRequest", `Space DO already holds ${existing.uri}`);
788
+ if (existing && !existing.deletedAt && params.policy && this.readPolicy()) throw new SpaceError("SpaceAlreadyExists", `Space already exists: ${params.uri}`);
789
+ const publishWrites = params.policy ? await this.preparePolicyRecordWrites(params.policy) : [];
790
+ return this.ctx.storage.transactionSync(() => {
791
+ if (!existing) this.sql.exec(`INSERT INTO meta (uri, authority, type, skey, is_authority, created_at, deleted_at, schema_version)
792
+ VALUES (?, ?, ?, ?, ?, ?, NULL, ?)`, params.uri, params.authority, params.type, params.skey, params.isAuthority ? 1 : 0, (/* @__PURE__ */ new Date()).toISOString(), SPACE_SCHEMA_VERSION);
793
+ else if (existing.deletedAt) this.sql.exec("UPDATE meta SET deleted_at = NULL, created_at = ?, is_authority = ?", (/* @__PURE__ */ new Date()).toISOString(), params.isAuthority ? 1 : 0);
794
+ if (!params.policy) return null;
795
+ this.writePolicy(params.policy);
796
+ return this.applyWritesSync(publishWrites);
797
+ });
407
798
  }
408
799
  async rpcApplyWrites(writes) {
409
800
  await this.ensureOpen();
410
801
  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);
802
+ return this.ctx.storage.transactionSync(() => this.applyWritesSync(writes));
803
+ }
804
+ /**
805
+ * Apply a batch as one commit sharing a single rev. Must run in a
806
+ * transaction. Returns null for an empty batch. Each write lands before
807
+ * the next is read, so a batch can create and then update a record, and
808
+ * a repeated create is refused rather than counted twice.
809
+ */
810
+ applyWritesSync(writes) {
811
+ if (writes.length === 0) return null;
812
+ const state = this.readRepoState();
813
+ const commit = RepoCommit.fromState(state?.setHash ?? null);
814
+ const rev = nextRev(state?.rev ?? null);
815
+ const indexedAt = (/* @__PURE__ */ new Date()).toISOString();
816
+ const results = [];
817
+ let idx = 0;
818
+ for (const write of writes) {
819
+ const prevRow = this.sql.exec("SELECT cid FROM record WHERE collection = ? AND rkey = ?", write.collection, write.rkey).toArray()[0];
820
+ const prev = prevRow ? prevRow.cid : null;
821
+ if (write.action === "create" && prev) throw new SpaceError("RecordAlreadyExists", `Record already exists: ${write.collection}/${write.rkey}`);
822
+ if (write.action !== "create" && !prev) throw new SpaceError("RecordNotFound", `Record not found: ${write.collection}/${write.rkey}`);
823
+ if (write.action === "delete") {
824
+ this.deleteRecordRow(write.collection, write.rkey);
825
+ commit.setHash.remove(`${write.collection}/${write.rkey}/${prev}`);
826
+ this.appendOplog(rev, idx++, write.collection, write.rkey, null, prev);
444
827
  results.push({
445
- action: write.action,
828
+ action: "delete",
446
829
  collection: write.collection,
447
830
  rkey: write.rkey,
448
- cid: write.cid
831
+ cid: null
449
832
  });
833
+ continue;
450
834
  }
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);
835
+ this.sql.exec(`INSERT OR REPLACE INTO record (collection, rkey, cid, bytes, rev, indexed_at)
836
+ VALUES (?, ?, ?, ?, ?, ?)`, write.collection, write.rkey, write.cid, write.bytes, rev, indexedAt);
837
+ this.replaceRecordBlobs(write.collection, write.rkey, write.blobCids);
838
+ if (prev) commit.setHash.remove(`${write.collection}/${write.rkey}/${prev}`);
839
+ commit.setHash.add(`${write.collection}/${write.rkey}/${write.cid}`);
840
+ this.appendOplog(rev, idx++, write.collection, write.rkey, write.cid, prev);
841
+ results.push({
842
+ action: write.action,
843
+ collection: write.collection,
844
+ rkey: write.rkey,
845
+ cid: write.cid
846
+ });
847
+ }
848
+ this.writeRepoState(commit.setHash.state(), rev);
849
+ return {
850
+ rev,
851
+ data: commit.setHash.digest(),
852
+ results
853
+ };
854
+ }
855
+ deleteRecordRow(collection, rkey) {
856
+ this.sql.exec("DELETE FROM record WHERE collection = ? AND rkey = ?", collection, rkey);
857
+ this.sql.exec("DELETE FROM record_blob WHERE collection = ? AND rkey = ?", collection, rkey);
858
+ }
859
+ replaceRecordBlobs(collection, rkey, blobCids) {
860
+ this.sql.exec("DELETE FROM record_blob WHERE collection = ? AND rkey = ?", collection, rkey);
861
+ for (const blobCid of blobCids) this.sql.exec("INSERT OR IGNORE INTO record_blob (blob_cid, collection, rkey) VALUES (?, ?, ?)", blobCid, collection, rkey);
862
+ }
863
+ writeRepoState(setHash, rev) {
864
+ this.sql.exec(`INSERT INTO repo_state (id, set_hash, rev) VALUES (1, ?, ?)
865
+ ON CONFLICT (id) DO UPDATE SET set_hash = excluded.set_hash, rev = excluded.rev`, setHash, rev);
866
+ }
867
+ appendOplog(rev, idx, collection, rkey, cid, prev) {
868
+ this.sql.exec("INSERT INTO oplog (rev, idx, collection, rkey, cid, prev) VALUES (?, ?, ?, ?, ?, ?)", rev, idx, collection, rkey, cid, prev);
869
+ }
870
+ /** The collections the repo holds records in, for clearRecords' grants. */
871
+ async rpcListCollections() {
872
+ await this.ensureOpen();
873
+ this.requireLiveMeta();
874
+ return this.sql.exec("SELECT DISTINCT collection FROM record ORDER BY collection").toArray().map((row) => row.collection);
875
+ }
876
+ /**
877
+ * Delete every record outside `keep` and clear the oplog, leaving the
878
+ * repo at a new rev with the digest of what remains. Returns null when
879
+ * there was nothing to delete.
880
+ */
881
+ async rpcClearRecords(keep) {
882
+ await this.ensureOpen();
883
+ this.requireLiveMeta();
884
+ return this.ctx.storage.transactionSync(() => {
885
+ const state = this.readRepoState();
886
+ if (!state) return null;
887
+ const placeholders = keep.map(() => "?").join(", ");
888
+ const notKept = keep.length > 0 ? `collection NOT IN (${placeholders})` : "1=1";
889
+ if (!this.sql.exec(`SELECT COUNT(*) AS n FROM record WHERE ${notKept}`, ...keep).toArray()[0]?.n) return null;
890
+ this.sql.exec(`DELETE FROM record_blob WHERE ${notKept}`, ...keep);
891
+ this.sql.exec(`DELETE FROM record WHERE ${notKept}`, ...keep);
892
+ this.sql.exec("DELETE FROM oplog");
893
+ const commit = new RepoCommit();
894
+ for (const row of this.sql.exec("SELECT collection, rkey, cid FROM record").toArray()) commit.setHash.add(`${row.collection}/${row.rkey}/${row.cid}`);
895
+ const rev = nextRev(state.rev);
896
+ this.writeRepoState(commit.setHash.state(), rev);
453
897
  return {
454
898
  rev,
455
- hash: commit.setHash.digest(),
456
- results
899
+ data: commit.setHash.digest()
457
900
  };
458
901
  });
459
902
  }
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);
903
+ /**
904
+ * Replace the repo with records imported from its previous host. Takes a
905
+ * new rev here and none of its history, so the oplog starts empty.
906
+ *
907
+ * Policy and member records are only ever written by the host, so the
908
+ * archive's are left out. In the authority's own repo they are published
909
+ * again, in a commit of their own, from the configuration importSpaceMeta
910
+ * set, as the reference does.
911
+ */
912
+ async rpcImportRepo(records) {
913
+ await this.ensureOpen();
914
+ const meta = this.requireLiveMeta();
915
+ const imported = records.filter((record) => !PUBLISHED_COLLECTIONS.includes(record.collection));
916
+ const policy = meta.isAuthority ? this.readPolicy() : null;
917
+ const publishWrites = policy ? await this.preparePublishedRecordCreates(policy) : [];
918
+ return this.ctx.storage.transactionSync(() => {
919
+ const state = this.readRepoState();
920
+ this.sql.exec("DELETE FROM record_blob");
921
+ this.sql.exec("DELETE FROM record");
922
+ this.sql.exec("DELETE FROM oplog");
923
+ const rev = nextRev(state?.rev ?? null);
924
+ const indexedAt = (/* @__PURE__ */ new Date()).toISOString();
925
+ const commit = new RepoCommit();
926
+ for (const record of imported) {
927
+ this.sql.exec(`INSERT INTO record (collection, rkey, cid, bytes, rev, indexed_at)
928
+ VALUES (?, ?, ?, ?, ?, ?)`, record.collection, record.rkey, record.cid, record.bytes, rev, indexedAt);
929
+ this.replaceRecordBlobs(record.collection, record.rkey, record.blobCids);
930
+ commit.setHash.add(`${record.collection}/${record.rkey}/${record.cid}`);
931
+ }
932
+ this.writeRepoState(commit.setHash.state(), rev);
933
+ const published = this.applyWritesSync(publishWrites);
934
+ return published ? {
935
+ rev: published.rev,
936
+ data: published.data
937
+ } : {
938
+ rev,
939
+ data: commit.setHash.digest()
940
+ };
941
+ });
942
+ }
943
+ readRepoState() {
944
+ const row = this.sql.exec("SELECT set_hash, rev FROM repo_state WHERE id = 1").toArray()[0];
945
+ if (!row) return null;
946
+ return {
947
+ setHash: new Uint8Array(row.set_hash),
948
+ rev: row.rev
949
+ };
462
950
  }
463
951
  async rpcGetRecord(collection, rkey) {
464
952
  await this.ensureOpen();
@@ -474,16 +962,10 @@ var SpaceDurableObject = class extends DurableObject {
474
962
  * List records ordered by (collection, rkey) — equivalent to record-URI
475
963
  * order since every record shares the space and repo prefix. Descending
476
964
  * 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
965
  */
482
966
  async rpcListRecords(params) {
483
967
  await this.ensureOpen();
484
968
  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
969
  const asc = params.reverse === true;
488
970
  const op = asc ? ">" : "<";
489
971
  const order = asc ? "ASC" : "DESC";
@@ -509,27 +991,66 @@ var SpaceDurableObject = class extends DurableObject {
509
991
  cid: row.cid,
510
992
  ...params.excludeValues ? {} : { bytes: new Uint8Array(row.bytes) }
511
993
  })),
512
- hasMore,
513
- rev
994
+ hasMore
514
995
  };
515
996
  }
516
- async rpcGetRepoState() {
997
+ /**
998
+ * Records in strict byte order of their `{collection}/{rkey}` path, as a
999
+ * repo archive requires — not (collection, rkey) order, which differs
1000
+ * when one collection NSID prefixes another. `state` is the repo state
1001
+ * the page was read at: the page and the state are one snapshot
1002
+ * (synchronous reads, single-threaded DO), so a streaming export can
1003
+ * fence against concurrent writes.
1004
+ */
1005
+ async rpcListRecordsByPath(params) {
517
1006
  await this.ensureOpen();
518
1007
  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;
1008
+ const state = this.readRepoState();
1009
+ const rows = this.sql.exec(`SELECT collection, rkey, bytes FROM record
1010
+ ${params.afterPath !== void 0 ? "WHERE collection || '/' || rkey > ?" : ""}
1011
+ ORDER BY collection || '/' || rkey ASC
1012
+ LIMIT ?`, ...params.afterPath !== void 0 ? [params.afterPath] : [], params.limit + 1).toArray();
1013
+ const hasMore = rows.length > params.limit;
521
1014
  return {
522
- setHash: new Uint8Array(row.set_hash),
523
- rev: row.rev
1015
+ records: (hasMore ? rows.slice(0, params.limit) : rows).map((row) => ({
1016
+ collection: row.collection,
1017
+ rkey: row.rkey,
1018
+ bytes: new Uint8Array(row.bytes)
1019
+ })),
1020
+ hasMore,
1021
+ state
1022
+ };
1023
+ }
1024
+ /**
1025
+ * What listSpaces reports for this space: the operator's repo state in
1026
+ * it and, for a space the operator is the authority of, its revision.
1027
+ */
1028
+ async rpcGetSpaceView() {
1029
+ await this.ensureOpen();
1030
+ const meta = this.readMeta();
1031
+ if (!meta || meta.deletedAt) return null;
1032
+ const state = this.readRepoState();
1033
+ const spaceRev = meta.isAuthority ? this.currentSpaceRev() : null;
1034
+ return {
1035
+ ...state ? {
1036
+ repoRev: state.rev,
1037
+ data: RepoCommit.fromState(state.setHash).setHash.digest()
1038
+ } : {},
1039
+ ...spaceRev ? { spaceRev } : {}
524
1040
  };
525
1041
  }
1042
+ async rpcGetRepoState() {
1043
+ await this.ensureOpen();
1044
+ this.requireLiveMeta();
1045
+ return this.readRepoState();
1046
+ }
526
1047
  /**
527
1048
  * List oplog entries after `since` (a rev) or `after` (an exact cursor
528
1049
  * position). Creates and updates carry the record's current bytes when
529
1050
  * the oplog cid still matches the live record; superseded values are
530
1051
  * 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.
1052
+ * state read in the same transaction so the Worker can attach the
1053
+ * commit without a state race.
533
1054
  */
534
1055
  async rpcListRepoOps(params) {
535
1056
  await this.ensureOpen();
@@ -561,14 +1082,11 @@ var SpaceDurableObject = class extends DurableObject {
561
1082
  prev: row.prev ?? null,
562
1083
  ...row.live_bytes ? { bytes: new Uint8Array(row.live_bytes) } : {}
563
1084
  }));
564
- if (hasMore) return { ops };
565
- const stateRow = this.sql.exec("SELECT set_hash, rev FROM repo_state WHERE id = 1").toArray()[0];
1085
+ const head = this.readRepoState();
566
1086
  return {
567
1087
  ops,
568
- ...stateRow ? { head: {
569
- setHash: new Uint8Array(stateRow.set_hash),
570
- rev: stateRow.rev
571
- } } : {}
1088
+ hasMore,
1089
+ ...head ? { head } : {}
572
1090
  };
573
1091
  });
574
1092
  }
@@ -611,33 +1129,32 @@ var SpaceDurableObject = class extends DurableObject {
611
1129
  await this.ensureOpen();
612
1130
  return this.sql.exec("INSERT OR IGNORE INTO replay (kind, key, expires_at) VALUES (?, ?, ?)", kind, key, expiresAtSec).rowsWritten > 0;
613
1131
  }
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
- };
1132
+ /**
1133
+ * Record credentials the authority revoked (repo-host role). Held until
1134
+ * any credential with that jti must have expired anyway. Needs no live
1135
+ * repo: a revocation can precede the first write.
1136
+ */
1137
+ async rpcRevokeCredentials(jtis, expiresAtSec) {
1138
+ await this.ensureOpen();
1139
+ for (const jti of jtis) this.sql.exec(`INSERT INTO revoked_credential (jti, expires_at) VALUES (?, ?)
1140
+ ON CONFLICT (jti) DO UPDATE SET expires_at = excluded.expires_at`, jti, expiresAtSec);
1141
+ await this.scheduleNextAlarm();
1142
+ }
1143
+ async rpcIsCredentialRevoked(jti) {
1144
+ await this.ensureOpen();
1145
+ return this.sql.exec("SELECT 1 FROM revoked_credential WHERE jti = ? AND expires_at > ?", jti, Math.floor(Date.now() / 1e3)).toArray().length > 0;
1146
+ }
1147
+ writePolicy(policy) {
1148
+ this.sql.exec(`INSERT INTO config (id, policy) VALUES (1, ?)
1149
+ ON CONFLICT (id) DO UPDATE SET policy = excluded.policy`, JSON.stringify(policy));
1150
+ }
1151
+ readPolicy() {
1152
+ const row = this.sql.exec("SELECT policy FROM config WHERE id = 1").toArray()[0];
1153
+ return row ? JSON.parse(row.policy) : null;
637
1154
  }
638
1155
  /**
639
- * State needed to answer getSpaceCredential: meta (including the
640
- * deletion tombstone) and the simplespace config. Never throws on a
1156
+ * State needed to answer getSpaceCredential and notifyWrite: meta
1157
+ * (including the deletion tombstone) and the policy. Never throws on a
641
1158
  * deleted space — a late credential request must get SpaceDeleted, not
642
1159
  * SpaceNotFound, and that mapping is the caller's.
643
1160
  */
@@ -645,140 +1162,413 @@ var SpaceDurableObject = class extends DurableObject {
645
1162
  await this.ensureOpen();
646
1163
  return {
647
1164
  meta: this.readMeta(),
648
- config: this.readConfig()
1165
+ policy: this.readPolicy()
649
1166
  };
650
1167
  }
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
- });
1168
+ hasRecord(collection, rkey) {
1169
+ return this.sql.exec("SELECT 1 FROM record WHERE collection = ? AND rkey = ?", collection, rkey).toArray().length > 0;
660
1170
  }
661
- async rpcAddMember(did) {
662
- await this.ensureOpen();
663
- this.requireLiveMeta();
664
- this.sql.exec("INSERT OR IGNORE INTO member (did) VALUES (?)", did);
1171
+ async preparePut(collection, rkey, record) {
1172
+ const prepared = await prepareRecord(record);
1173
+ return {
1174
+ action: this.hasRecord(collection, rkey) ? "update" : "create",
1175
+ collection,
1176
+ rkey,
1177
+ cid: prepared.cid,
1178
+ bytes: prepared.bytes,
1179
+ blobCids: prepared.blobCids
1180
+ };
665
1181
  }
666
- async rpcRemoveMember(did) {
667
- await this.ensureOpen();
668
- this.requireLiveMeta();
669
- this.sql.exec("DELETE FROM member WHERE did = ?", did);
1182
+ prepareDeleteIfExists(collection, rkey) {
1183
+ return this.hasRecord(collection, rkey) ? [{
1184
+ action: "delete",
1185
+ collection,
1186
+ rkey
1187
+ }] : [];
1188
+ }
1189
+ /** Publish, update or withdraw the policy record to match the policy. */
1190
+ async preparePolicyRecordWrites(policy) {
1191
+ if (isPolicyPublished(policy)) return [await this.preparePut(POLICY_COLLECTION, POLICY_RKEY, {
1192
+ $type: POLICY_COLLECTION,
1193
+ policy
1194
+ })];
1195
+ return this.prepareDeleteIfExists(POLICY_COLLECTION, POLICY_RKEY);
670
1196
  }
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;
1197
+ /**
1198
+ * Publish, update or withdraw a member's record to match their entry.
1199
+ * `access` is omitted for a DID that is no longer a member.
1200
+ */
1201
+ async prepareMemberRecordWrites(policy, did, access) {
1202
+ const rkey = didToRecordKey(did);
1203
+ if (access && areMembersPublished(policy)) return [await this.preparePut(MEMBER_COLLECTION, rkey, {
1204
+ $type: MEMBER_COLLECTION,
1205
+ read: access.read,
1206
+ write: access.write
1207
+ })];
1208
+ return this.prepareDeleteIfExists(MEMBER_COLLECTION, rkey);
675
1209
  }
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
- };
1210
+ /**
1211
+ * The policy and member records the policy publishes, as creates into a
1212
+ * repo that holds none (an import has just cleared it).
1213
+ */
1214
+ async preparePublishedRecordCreates(policy) {
1215
+ const writes = await this.preparePolicyRecordWrites(policy);
1216
+ for (const member of this.readMembers()) writes.push(...await this.prepareMemberRecordWrites(policy, member.did, member));
1217
+ return writes.flatMap((write) => write.action === "delete" ? [] : [{
1218
+ ...write,
1219
+ action: "create"
1220
+ }]);
1221
+ }
1222
+ readMembers() {
1223
+ return this.sql.exec("SELECT did, can_read, can_write FROM member ORDER BY did").toArray().map((row) => ({
1224
+ did: row.did,
1225
+ read: row.can_read === 1,
1226
+ write: row.can_write === 1
1227
+ }));
691
1228
  }
692
1229
  /**
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.
1230
+ * Replace the policy wholesale. A different `$type` migrates the space:
1231
+ * state held by the previous policy (the member list) is discarded, and
1232
+ * a published member list is withdrawn with it.
697
1233
  */
698
- async rpcRecordWriter(did, rev, hash) {
1234
+ async rpcUpdatePolicy(next) {
699
1235
  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 };
1236
+ const { policy: current } = this.requirePolicy();
1237
+ const writes = await this.preparePolicyRecordWrites(next);
1238
+ if (areMembersPublished(current) !== areMembersPublished(next)) for (const member of this.readMembers()) writes.push(...await this.prepareMemberRecordWrites(next, member.did, member));
1239
+ return this.ctx.storage.transactionSync(() => {
1240
+ this.writePolicy(next);
1241
+ if (current.$type !== next.$type) this.sql.exec("DELETE FROM member");
1242
+ return this.applyWritesSync(writes);
1243
+ });
704
1244
  }
705
- async rpcListWriters(params) {
1245
+ /**
1246
+ * Add members or replace their access, in one commit. A DID listed twice
1247
+ * takes its last entry. Revoking write access removes the member from
1248
+ * the writer set, sequenced and announced like any removal.
1249
+ */
1250
+ async rpcPutMembers(members) {
706
1251
  await this.ensureOpen();
707
- this.requireLiveMeta();
1252
+ const { policy } = this.requirePolicy();
1253
+ assertMemberspace(policy);
1254
+ const byDid = new Map(members.map((m) => [m.did, m]));
1255
+ const writes = [];
1256
+ for (const member of byDid.values()) writes.push(...await this.prepareMemberRecordWrites(policy, member.did, member));
1257
+ const commit = this.ctx.storage.transactionSync(() => {
1258
+ for (const member of byDid.values()) {
1259
+ this.sql.exec(`INSERT INTO member (did, can_read, can_write) VALUES (?, ?, ?)
1260
+ ON CONFLICT (did) DO UPDATE SET can_read = excluded.can_read, can_write = excluded.can_write`, member.did, member.read ? 1 : 0, member.write ? 1 : 0);
1261
+ if (!member.write) this.removeWriterSync(member.did);
1262
+ }
1263
+ return this.applyWritesSync(writes);
1264
+ });
1265
+ await this.scheduleNextAlarm();
1266
+ return commit;
1267
+ }
1268
+ /**
1269
+ * Remove members, in one commit, and from the writer set. DIDs that are
1270
+ * not members are ignored, leaving any writer set entry alone.
1271
+ */
1272
+ async rpcRemoveMembers(dids) {
1273
+ await this.ensureOpen();
1274
+ const { policy } = this.requirePolicy();
1275
+ assertMemberspace(policy);
1276
+ const members = [...new Set(dids)].filter((did) => this.sql.exec("SELECT 1 FROM member WHERE did = ?", did).toArray().length > 0);
1277
+ const writes = [];
1278
+ for (const did of members) writes.push(...await this.prepareMemberRecordWrites(policy, did));
1279
+ const commit = this.ctx.storage.transactionSync(() => {
1280
+ for (const did of members) {
1281
+ this.sql.exec("DELETE FROM member WHERE did = ?", did);
1282
+ this.removeWriterSync(did);
1283
+ }
1284
+ return this.applyWritesSync(writes);
1285
+ });
1286
+ await this.scheduleNextAlarm();
1287
+ return commit;
1288
+ }
1289
+ async rpcGetMember(did) {
1290
+ await this.ensureOpen();
1291
+ this.requirePolicy();
1292
+ const row = this.sql.exec("SELECT did, can_read, can_write FROM member WHERE did = ?", did).toArray()[0];
1293
+ if (!row) return null;
1294
+ return {
1295
+ did: row.did,
1296
+ read: row.can_read === 1,
1297
+ write: row.can_write === 1
1298
+ };
1299
+ }
1300
+ async rpcListMembers(params) {
1301
+ await this.ensureOpen();
1302
+ const { policy } = this.requirePolicy();
1303
+ assertMemberspace(policy);
708
1304
  const args = [];
709
1305
  let where = "1=1";
710
1306
  if (params.afterDid) {
711
1307
  where += " AND did > ?";
712
1308
  args.push(params.afterDid);
713
1309
  }
714
- const rows = this.sql.exec(`SELECT did, rev, hash FROM writer WHERE ${where} ORDER BY did ASC LIMIT ?`, ...args, params.limit + 1).toArray();
1310
+ const rows = this.sql.exec(`SELECT did, can_read, can_write FROM member WHERE ${where} ORDER BY did ASC LIMIT ?`, ...args, params.limit + 1).toArray();
715
1311
  const hasMore = rows.length > params.limit;
716
1312
  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)
1313
+ members: (hasMore ? rows.slice(0, params.limit) : rows).map((row) => ({
1314
+ did: row.did,
1315
+ read: row.can_read === 1,
1316
+ write: row.can_write === 1
721
1317
  })),
722
1318
  hasMore
723
1319
  };
724
1320
  }
1321
+ /** The space's current revision: the latest in its writer set, removals included. */
1322
+ currentSpaceRev() {
1323
+ return this.sql.exec("SELECT MAX(space_rev) AS rev FROM writer").toArray()[0]?.rev ?? null;
1324
+ }
1325
+ async rpcGetSpaceRev() {
1326
+ await this.ensureOpen();
1327
+ this.requirePolicy();
1328
+ return this.currentSpaceRev();
1329
+ }
725
1330
  /**
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.
1331
+ * Record a writer's latest (repoRev, data), from notifyRepoUpdate or own
1332
+ * writes, advance the space sequence, and queue the update for the
1333
+ * registered syncers in the same transaction. Monotonic per writer: a
1334
+ * delayed or replayed notification with an older (or equal) rev changes
1335
+ * nothing and returns null. A newer write from a removed writer re-adds
1336
+ * it.
729
1337
  */
730
- async rpcRegisterNotify(service, endpoint) {
1338
+ async rpcRecordWriter(did, repoRev, data) {
731
1339
  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 };
1340
+ const { meta } = this.requirePolicy();
1341
+ const sequence = this.ctx.storage.transactionSync(() => {
1342
+ const existing = this.sql.exec("SELECT repo_rev FROM writer WHERE did = ?", did).toArray()[0];
1343
+ if (existing && existing.repo_rev >= repoRev) return null;
1344
+ const prevSpaceRev = this.currentSpaceRev();
1345
+ const spaceRev = nextRev(prevSpaceRev);
1346
+ this.sql.exec(`INSERT INTO writer (did, repo_rev, data, space_rev, removed_at) VALUES (?, ?, ?, ?, NULL)
1347
+ ON CONFLICT (did) DO UPDATE SET repo_rev = excluded.repo_rev, data = excluded.data,
1348
+ space_rev = excluded.space_rev, removed_at = NULL`, did, repoRev, data, spaceRev);
1349
+ const sequence$1 = {
1350
+ spaceRev,
1351
+ ...prevSpaceRev ? { prevSpaceRev } : {}
1352
+ };
1353
+ this.queueSpaceUpdate(meta.uri, {
1354
+ $type: REPO_WRITE,
1355
+ repo: did,
1356
+ repoRev,
1357
+ data: bytesToJson(data),
1358
+ ...sequence$1
1359
+ });
1360
+ return sequence$1;
1361
+ });
1362
+ if (sequence) await this.scheduleNextAlarm();
1363
+ return sequence;
1364
+ }
1365
+ /**
1366
+ * Remove a repo from the writer set at a new space revision, keeping its
1367
+ * row marked removed so listWriters reports the removal, and announce it.
1368
+ * Returns false when the repo is not in the writer set. Must run in a
1369
+ * transaction.
1370
+ */
1371
+ removeWriterSync(did) {
1372
+ const meta = this.readMeta();
1373
+ const row = this.sql.exec("SELECT removed_at FROM writer WHERE did = ?", did).toArray()[0];
1374
+ if (!meta || !row || row.removed_at !== null) return false;
1375
+ const prevSpaceRev = this.currentSpaceRev();
1376
+ const spaceRev = nextRev(prevSpaceRev);
1377
+ this.sql.exec("UPDATE writer SET space_rev = ?, removed_at = ? WHERE did = ?", spaceRev, Date.now(), did);
1378
+ this.queueSpaceUpdate(meta.uri, {
1379
+ $type: REPO_REMOVED,
1380
+ repo: did,
1381
+ spaceRev,
1382
+ ...prevSpaceRev ? { prevSpaceRev } : {}
1383
+ });
1384
+ return true;
737
1385
  }
738
- /** Idempotent: succeeds whether or not a registration existed. */
739
- async rpcUnregisterNotify(service) {
1386
+ /**
1387
+ * Drop an account from the writer set. It is tracked again if it later
1388
+ * writes while still authorised. Idempotent.
1389
+ */
1390
+ async rpcRemoveWriter(did) {
740
1391
  await this.ensureOpen();
741
- this.requireLiveMeta();
742
- this.sql.exec("DELETE FROM notify_registration WHERE service = ?", service);
1392
+ this.requirePolicy();
1393
+ this.ctx.storage.transactionSync(() => this.removeWriterSync(did));
1394
+ await this.scheduleNextAlarm();
743
1395
  }
744
- async rpcGetActiveRegistrations() {
1396
+ readWriter(row) {
1397
+ return {
1398
+ did: row.did,
1399
+ repoRev: row.repo_rev,
1400
+ data: new Uint8Array(row.data),
1401
+ spaceRev: row.space_rev,
1402
+ removed: row.removed_at !== null
1403
+ };
1404
+ }
1405
+ /** The writer set, removals included, in ascending space revision after `cursor`. */
1406
+ async rpcListWriters(params) {
745
1407
  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
- }));
1408
+ this.requirePolicy();
1409
+ return this.sql.exec(`SELECT did, repo_rev, data, space_rev, removed_at FROM writer
1410
+ ${params.cursor ? "WHERE space_rev > ?" : ""}
1411
+ ORDER BY space_rev ASC LIMIT ?`, ...params.cursor ? [params.cursor] : [], params.limit).toArray().map((row) => this.readWriter(row));
1412
+ }
1413
+ /** The space's host-side state, for migrating its authority's account. */
1414
+ async rpcExportMeta() {
1415
+ await this.ensureOpen();
1416
+ const { policy } = this.requirePolicy();
1417
+ const writers = this.sql.exec("SELECT did, repo_rev, data, space_rev, removed_at FROM writer WHERE removed_at IS NULL ORDER BY did").toArray().map((row) => this.readWriter(row));
1418
+ return {
1419
+ policy,
1420
+ members: this.readMembers(),
1421
+ writers
1422
+ };
1423
+ }
1424
+ /**
1425
+ * Import a space exported by its previous host, replacing whatever this
1426
+ * host held for it, so a migration step can be retried. Nothing is
1427
+ * published here: the authority's repo arrives afterwards with
1428
+ * importRepo, which publishes the policy and member records from what is
1429
+ * set here.
1430
+ * Registrations, revocations and tombstones are not carried over.
1431
+ */
1432
+ async rpcImportMeta(params) {
1433
+ await this.ensureOpen();
1434
+ const existing = this.readMeta();
1435
+ if (existing && existing.uri !== params.uri) throw new SpaceError("InvalidRequest", `Space DO already holds ${existing.uri}`);
1436
+ this.ctx.storage.transactionSync(() => {
1437
+ if (!existing) this.sql.exec(`INSERT INTO meta (uri, authority, type, skey, is_authority, created_at, deleted_at, schema_version)
1438
+ VALUES (?, ?, ?, ?, 1, ?, NULL, ?)`, params.uri, params.authority, params.type, params.skey, (/* @__PURE__ */ new Date()).toISOString(), SPACE_SCHEMA_VERSION);
1439
+ else this.sql.exec("UPDATE meta SET deleted_at = NULL, is_authority = 1");
1440
+ this.writePolicy(params.policy);
1441
+ this.sql.exec("DELETE FROM member");
1442
+ for (const member of params.members) this.sql.exec("INSERT INTO member (did, can_read, can_write) VALUES (?, ?, ?)", member.did, member.read ? 1 : 0, member.write ? 1 : 0);
1443
+ this.sql.exec("DELETE FROM writer");
1444
+ for (const writer of params.writers) this.sql.exec("INSERT INTO writer (did, repo_rev, data, space_rev, removed_at) VALUES (?, ?, ?, ?, NULL)", writer.did, writer.repoRev, writer.data, writer.spaceRev);
1445
+ });
1446
+ }
1447
+ async rpcGetNotifyRegistration(registration) {
1448
+ await this.ensureOpen();
1449
+ const row = this.sql.exec("SELECT expires_at FROM notify_registration WHERE endpoint = ? AND token = ?", registration.endpoint, registration.token).toArray()[0];
1450
+ return row ? { expiresAt: row.expires_at } : null;
1451
+ }
1452
+ /**
1453
+ * Register a syncer's webhook, or renew it, to the expiry of the
1454
+ * credential it was authorised with. Renewal clears a lapse already
1455
+ * announced, so the next lapse is announced too.
1456
+ */
1457
+ async rpcPutNotifyRegistration(registration, expiresAt) {
1458
+ await this.ensureOpen();
1459
+ const meta = this.readMeta();
1460
+ if (!meta) throw new SpaceError("SpaceNotFound", "Space not found");
1461
+ if (meta.deletedAt) throw new SpaceError("SpaceDeleted", "Space has been deleted");
1462
+ this.sql.exec(`INSERT INTO notify_registration (endpoint, token, expires_at, expiry_notified) VALUES (?, ?, ?, 0)
1463
+ ON CONFLICT (endpoint, token) DO UPDATE SET expires_at = excluded.expires_at, expiry_notified = 0`, registration.endpoint, registration.token, expiresAt);
1464
+ }
1465
+ /** Withdraw a registration, as when its syncer is denied access. */
1466
+ async rpcRemoveNotifyRegistration(registration) {
1467
+ await this.ensureOpen();
1468
+ this.sql.exec("DELETE FROM notify_registration WHERE endpoint = ? AND token = ?", registration.endpoint, registration.token);
1469
+ }
1470
+ /**
1471
+ * Queue a sequenced writer-set change for the registered syncers: best
1472
+ * effort to each active registration, and in place of the update an
1473
+ * expiry notice, delivered reliably, to each registration that has
1474
+ * lapsed since the last one. Each lapse is claimed once. Must run in a
1475
+ * transaction.
1476
+ */
1477
+ queueSpaceUpdate(space, update) {
1478
+ const now$1 = Date.now();
1479
+ const registrations = this.sql.exec("SELECT endpoint, token, expires_at, expiry_notified FROM notify_registration").toArray();
1480
+ for (const row of registrations) {
1481
+ const endpoint = row.endpoint;
1482
+ const token = row.token;
1483
+ if (row.expires_at > now$1) this.insertNotify({
1484
+ service: endpoint,
1485
+ endpoint,
1486
+ lxm: NOTIFY_SPACE_UPDATE_LXM,
1487
+ body: {
1488
+ space,
1489
+ token,
1490
+ update
1491
+ },
1492
+ policy: "fanout",
1493
+ auth: "none"
1494
+ });
1495
+ else if (row.expiry_notified === 0) {
1496
+ this.sql.exec("UPDATE notify_registration SET expiry_notified = 1 WHERE endpoint = ? AND token = ?", endpoint, token);
1497
+ this.queueSyncerNotice({
1498
+ endpoint,
1499
+ token
1500
+ }, space, {
1501
+ $type: REGISTRATION_EXPIRED,
1502
+ spaceRev: update.spaceRev
1503
+ });
1504
+ }
1505
+ }
1506
+ }
1507
+ /** A deletion or expiry notice, delivered reliably for 72 hours. */
1508
+ queueSyncerNotice(registration, space, notice) {
1509
+ this.insertNotify({
1510
+ service: registration.endpoint,
1511
+ endpoint: registration.endpoint,
1512
+ lxm: NOTIFY_SPACE_UPDATE_LXM,
1513
+ body: {
1514
+ space,
1515
+ token: registration.token,
1516
+ update: notice
1517
+ },
1518
+ policy: "syncer",
1519
+ auth: "none",
1520
+ coalesceKey: `syncer\n${registration.endpoint}\n${registration.token}`,
1521
+ keepPending: notice.$type !== SPACE_DELETED,
1522
+ deadline: Date.now() + SYNCER_NOTICE_RETRY_WINDOW_MS
1523
+ });
750
1524
  }
751
1525
  /**
752
1526
  * 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.
1527
+ * retries. An item with a coalesce key replaces any pending item with
1528
+ * the same key, resetting its backoff and deadline.
756
1529
  */
757
- async rpcEnqueueNotify(items) {
1530
+ async rpcEnqueueNotify(items, opts = {}) {
758
1531
  await this.ensureOpen();
759
1532
  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({
1533
+ const nextAt = Date.now() + (opts.delayMs ?? 0);
1534
+ for (const item of items) this.insertNotify(item, nextAt);
1535
+ await this.scheduleNextAlarm();
1536
+ }
1537
+ insertNotify(item, nextAt = Date.now()) {
1538
+ const body = JSON.stringify({
762
1539
  endpoint: item.endpoint,
763
1540
  lxm: item.lxm,
764
1541
  body: item.body
765
- }), now$1);
766
- await this.scheduleNextAlarm();
1542
+ });
1543
+ this.sql.exec(`INSERT INTO notify_queue (service, body, attempts, next_at, deadline, coalesce_key, policy, auth)
1544
+ VALUES (?, ?, 0, ?, ?, ?, ?, ?)
1545
+ ON CONFLICT (coalesce_key) DO ${item.keepPending ? "NOTHING" : `UPDATE SET
1546
+ service = excluded.service, body = excluded.body, attempts = 0,
1547
+ next_at = excluded.next_at, deadline = excluded.deadline,
1548
+ policy = excluded.policy, auth = excluded.auth`}`, item.service, body, nextAt, item.deadline ?? null, item.coalesceKey ?? null, item.policy ?? "fanout", item.auth ?? "service");
1549
+ }
1550
+ /** Drop a pending coalesced notification, e.g. once a newer one landed. */
1551
+ async rpcClearNotify(coalesceKey) {
1552
+ await this.ensureOpen();
1553
+ this.sql.exec("DELETE FROM notify_queue WHERE coalesce_key = ?", coalesceKey);
767
1554
  }
768
1555
  /**
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.
1556
+ * Tombstone the space (authority role), delete the authority's own repo
1557
+ * in it, and queue a deletion notice to every registered syncer, lapsed
1558
+ * registrations included. The meta row is retained so a late
1559
+ * authorizeSpaceSync can answer SpaceDeleted rather than SpaceNotFound.
1560
+ * Idempotent.
774
1561
  */
775
1562
  async rpcDeleteSpace() {
776
1563
  await this.ensureOpen();
777
1564
  const meta = this.readMeta();
778
1565
  if (!meta) throw new SpaceError("SpaceNotFound", "Space is not initialised");
779
- if (meta.deletedAt) return { registrations: [] };
780
- const registrations = await this.rpcGetActiveRegistrations();
1566
+ if (meta.deletedAt) return;
781
1567
  this.ctx.storage.transactionSync(() => {
1568
+ for (const row of this.sql.exec("SELECT endpoint, token FROM notify_registration").toArray()) this.queueSyncerNotice({
1569
+ endpoint: row.endpoint,
1570
+ token: row.token
1571
+ }, meta.uri, { $type: SPACE_DELETED });
782
1572
  this.sql.exec("UPDATE meta SET deleted_at = ?", (/* @__PURE__ */ new Date()).toISOString());
783
1573
  for (const table of [
784
1574
  "record",
@@ -792,7 +1582,7 @@ var SpaceDurableObject = class extends DurableObject {
792
1582
  "replay"
793
1583
  ]) this.sql.exec(`DELETE FROM ${table}`);
794
1584
  });
795
- return { registrations };
1585
+ await this.scheduleNextAlarm();
796
1586
  }
797
1587
  /** Wipe everything, including queued notifications and alarms. */
798
1588
  async rpcDestroy() {
@@ -806,6 +1596,7 @@ var SpaceDurableObject = class extends DurableObject {
806
1596
  if (this.outdated) return {
807
1597
  meta: null,
808
1598
  outdated: true,
1599
+ policyType: null,
809
1600
  recordCount: 0,
810
1601
  memberCount: 0,
811
1602
  writerCount: 0,
@@ -815,9 +1606,10 @@ var SpaceDurableObject = class extends DurableObject {
815
1606
  return {
816
1607
  meta: this.readMeta(),
817
1608
  outdated: false,
1609
+ policyType: this.readPolicy()?.$type ?? null,
818
1610
  recordCount: count("record"),
819
1611
  memberCount: count("member"),
820
- writerCount: count("writer"),
1612
+ writerCount: count("writer WHERE removed_at IS NULL"),
821
1613
  queuedNotifications: count("notify_queue")
822
1614
  };
823
1615
  }
@@ -829,39 +1621,78 @@ var SpaceDurableObject = class extends DurableObject {
829
1621
  await this.scheduleNextAlarm();
830
1622
  }
831
1623
  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();
1624
+ const now$1 = Date.now();
1625
+ this.sql.exec("DELETE FROM notify_queue WHERE deadline IS NOT NULL AND deadline <= ? AND policy != 'syncer'", now$1);
1626
+ const due = this.sql.exec("SELECT id, service, body, attempts, next_at, deadline, policy, auth FROM notify_queue WHERE next_at <= ? ORDER BY next_at ASC LIMIT ?", now$1, NOTIFY_BATCH).toArray();
833
1627
  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) {
1628
+ const host = await this.getHostConfig();
1629
+ const keypair = await host.getKeypair();
1630
+ await Promise.all(due.map(async (row) => {
1631
+ const parsed = JSON.parse(row.body);
1632
+ if (row.policy === "syncer" && !this.isSyncerNoticeOwed(parsed.endpoint, parsed.body)) {
1633
+ this.sql.exec("DELETE FROM notify_queue WHERE id = ?", row.id);
1634
+ return;
1635
+ }
841
1636
  let delivered = false;
1637
+ let retryable = true;
842
1638
  try {
843
- const parsed = JSON.parse(row.body);
844
- const token = await createServiceJwt({
845
- iss: meta.authority,
1639
+ const headers = { "Content-Type": "application/json" };
1640
+ if (row.auth === "service") headers.Authorization = `Bearer ${await createServiceJwt({
1641
+ iss: host.operatorDid,
846
1642
  aud: row.service,
847
1643
  lxm: parsed.lxm
848
- }, keypair);
1644
+ }, keypair)}`;
849
1645
  const res = await fetch(`${parsed.endpoint}/xrpc/${parsed.lxm}`, {
850
1646
  method: "POST",
851
- headers: {
852
- "Content-Type": "application/json",
853
- Authorization: `Bearer ${token}`
854
- },
855
- body: JSON.stringify(parsed.body)
1647
+ headers,
1648
+ body: JSON.stringify(parsed.body),
1649
+ redirect: row.auth === "none" ? "manual" : "follow",
1650
+ signal: AbortSignal.timeout(1e4)
856
1651
  });
857
1652
  delivered = res.ok;
858
- if (!res.ok) console.warn(`notify ${parsed.lxm} to ${row.service} failed: ${res.status}`);
1653
+ if (!res.ok) {
1654
+ retryable = isRetryableStatus(res.status);
1655
+ console.warn(`notify ${parsed.lxm} to ${row.service} failed: ${res.status}`);
1656
+ }
859
1657
  } catch (err) {
860
1658
  console.warn(`notify to ${row.service} errored:`, err);
861
1659
  }
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);
1660
+ this.settleNotify(row, parsed, delivered, retryable);
1661
+ }));
1662
+ }
1663
+ /** A deletion or expiry notice that no longer applies is dropped unsent. */
1664
+ isSyncerNoticeOwed(endpoint, body) {
1665
+ if (body.update?.$type === SPACE_DELETED) return Boolean(this.readMeta()?.deletedAt);
1666
+ const row = this.sql.exec("SELECT expires_at FROM notify_registration WHERE endpoint = ? AND token = ?", endpoint, body.token).toArray()[0];
1667
+ return Boolean(row && row.expires_at <= Date.now());
1668
+ }
1669
+ settleNotify(row, parsed, delivered, retryable) {
1670
+ const attempts = row.attempts + 1;
1671
+ const now$1 = Date.now();
1672
+ const remove = () => this.sql.exec("DELETE FROM notify_queue WHERE id = ?", row.id);
1673
+ if (delivered) return void remove();
1674
+ if (row.policy === "syncer") {
1675
+ if (!retryable || row.deadline !== null && row.deadline <= now$1) {
1676
+ remove();
1677
+ this.abandonSyncerNotice(parsed.endpoint, parsed.body);
1678
+ return;
1679
+ }
1680
+ const delays = SYNCER_NOTICE_RETRY_DELAYS_MS;
1681
+ const delay = delays[Math.min(attempts, delays.length) - 1];
1682
+ this.sql.exec("UPDATE notify_queue SET attempts = ?, next_at = ? WHERE id = ?", attempts, now$1 + jitter(delay), row.id);
1683
+ return;
864
1684
  }
1685
+ const exhausted = row.deadline === null ? attempts >= NOTIFY_MAX_ATTEMPTS : false;
1686
+ if (!retryable || exhausted) return void remove();
1687
+ this.sql.exec("UPDATE notify_queue SET attempts = ?, next_at = ? WHERE id = ?", attempts, now$1 + jitter(Math.min(NOTIFY_BACKOFF_BASE_MS * 2 ** row.attempts, NOTIFY_BACKOFF_MAX_MS)), row.id);
1688
+ }
1689
+ /**
1690
+ * Give up on a notice. A syncer that rejects its expiry notice, or can't
1691
+ * be reached, is unregistered, unless it has renewed since.
1692
+ */
1693
+ abandonSyncerNotice(endpoint, body) {
1694
+ if (body.update?.$type !== REGISTRATION_EXPIRED) return;
1695
+ this.sql.exec("DELETE FROM notify_registration WHERE endpoint = ? AND token = ? AND expires_at <= ?", endpoint, body.token, Date.now());
865
1696
  }
866
1697
  runMaintenanceIfDue() {
867
1698
  const now$1 = Date.now();
@@ -869,8 +1700,9 @@ var SpaceDurableObject = class extends DurableObject {
869
1700
  this.sql.exec("DELETE FROM oplog WHERE rev < ?", tidCutoff(OPLOG_RETENTION_DAYS * DAY_MS));
870
1701
  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
1702
  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());
1703
+ const nowSec = Math.floor(now$1 / 1e3);
1704
+ this.sql.exec("DELETE FROM replay WHERE kind != '__maintenance' AND expires_at < ?", nowSec);
1705
+ this.sql.exec("DELETE FROM revoked_credential WHERE expires_at <= ?", nowSec);
874
1706
  this.sql.exec(`INSERT INTO replay (kind, key, expires_at) VALUES ('__maintenance', 'last', ?)
875
1707
  ON CONFLICT (kind, key) DO UPDATE SET expires_at = excluded.expires_at`, now$1);
876
1708
  }
@@ -975,6 +1807,25 @@ var SpaceIndexDurableObject = class extends DurableObject {
975
1807
  hosted: count("is_authority = 1 AND state = 'active'")
976
1808
  };
977
1809
  }
1810
+ /**
1811
+ * Note blobs an imported space repo references but whose bytes have not
1812
+ * been uploaded yet, so uploadBlob can promote them when they arrive.
1813
+ */
1814
+ async rpcAddPendingBlobs(uri, cids) {
1815
+ await this.ensureInitialized();
1816
+ const now$1 = Date.now();
1817
+ for (const cid of cids) this.sql.exec("INSERT OR REPLACE INTO pending_blob (cid, uri, created_at) VALUES (?, ?, ?)", cid, uri, now$1);
1818
+ }
1819
+ /**
1820
+ * Claim a freshly uploaded blob: the spaces whose imported records
1821
+ * reference it. Claimed entries are removed.
1822
+ */
1823
+ async rpcClaimPendingBlob(cid) {
1824
+ await this.ensureInitialized();
1825
+ const uris = this.sql.exec("SELECT uri FROM pending_blob WHERE cid = ?", cid).toArray().map((row) => row.uri);
1826
+ if (uris.length > 0) this.sql.exec("DELETE FROM pending_blob WHERE cid = ?", cid);
1827
+ return uris;
1828
+ }
978
1829
  /** Wipe the registry (spaces reset). */
979
1830
  async rpcDestroy() {
980
1831
  await this.ctx.storage.deleteAlarm();
@@ -992,6 +1843,7 @@ var SpaceIndexDurableObject = class extends DurableObject {
992
1843
  await this.ensureInitialized();
993
1844
  const cutoff = new Date(Date.now() - PENDING_ENTRY_TTL_MS).toISOString();
994
1845
  this.sql.exec("UPDATE space SET state = 'deleted', updated_at = ? WHERE state = 'pending' AND updated_at < ?", (/* @__PURE__ */ new Date()).toISOString(), cutoff);
1846
+ this.sql.exec("DELETE FROM pending_blob WHERE created_at < ?", Date.now() - PENDING_BLOB_TTL_MS);
995
1847
  await this.ctx.storage.setAlarm(Date.now() + ALARM_INTERVAL_MS);
996
1848
  }
997
1849
  };
@@ -1013,21 +1865,25 @@ function toEntry(row) {
1013
1865
  /**
1014
1866
  * Space URI handling.
1015
1867
  *
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}`.
1868
+ * A space is addressed as `at:space/{authorityDid}/{typeNsid}/{skey}`, and a
1869
+ * record in a space appends `/{authorDid}/{collection}/{rkey}`. The
1870
+ * `at:space/` prefix tells it apart from a public `at://` URI.
1871
+ *
1872
+ * Params are parsed strictly: the alpha's earlier `at://{did}/space/...`
1873
+ * form is refused, as the reference refuses it. Only record values written
1874
+ * during the alpha may still carry it, and the engine never parses those.
1020
1875
  */
1876
+ /** The prefix of every space URI. */
1877
+ const SPACE_URI_PREFIX = "at:space/";
1021
1878
  /**
1022
1879
  * Parse a space URI. Returns null when the string is not a valid space
1023
1880
  * reference.
1024
1881
  */
1025
1882
  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;
1883
+ if (!uri.startsWith(SPACE_URI_PREFIX)) return null;
1884
+ const parts = uri.slice(9).split("/");
1885
+ if (parts.length !== 3) return null;
1886
+ const [authority, type, skey] = parts;
1031
1887
  if (!isDid(authority) || !isNsid(type) || !isRecordKey(skey)) return null;
1032
1888
  const ref = {
1033
1889
  uri: formatSpaceUri(authority, type, skey),
@@ -1038,14 +1894,17 @@ function parseSpaceUri(uri) {
1038
1894
  if (ref.uri !== uri) return null;
1039
1895
  return ref;
1040
1896
  }
1041
- /** Parse a space URI or throw an InvalidSpaceUri error. */
1897
+ /**
1898
+ * Parse a space URI or throw. The error is XRPC's generic InvalidRequest, as
1899
+ * the reference answers: no lexicon declares a more specific one.
1900
+ */
1042
1901
  function requireSpaceUri(uri) {
1043
1902
  const ref = uri ? parseSpaceUri(uri) : null;
1044
- if (!ref) throw new SpaceError("InvalidSpaceUri", `Invalid space URI: ${uri}`);
1903
+ if (!ref) throw new SpaceError("InvalidRequest", `Invalid space URI: ${uri}`);
1045
1904
  return ref;
1046
1905
  }
1047
1906
  function formatSpaceUri(authority, type, skey) {
1048
- return `at://${authority}/space/${type}/${skey}`;
1907
+ return `${SPACE_URI_PREFIX}${authority}/${type}/${skey}`;
1049
1908
  }
1050
1909
  /** URI of a record within a space: `{spaceUri}/{repoDid}/{collection}/{rkey}`. */
1051
1910
  function spaceRecordUri(spaceUri, repo, collection, rkey) {
@@ -1109,124 +1968,127 @@ function spaceBlobKey(did, id, cid) {
1109
1968
  async function spaceBlobKeyForUri(did, spaceUri, cid) {
1110
1969
  return spaceBlobKey(did, await spaceId(spaceUri), cid);
1111
1970
  }
1971
+ /**
1972
+ * Copy a staged upload into a space's blob prefix. Idempotent; returns
1973
+ * whether the blob is now at its destination (false when it was neither
1974
+ * there nor staged).
1975
+ */
1976
+ async function promoteStagedBlobToSpace(bucket, did, spaceUri, cid) {
1977
+ const destKey = await spaceBlobKeyForUri(did, spaceUri, cid);
1978
+ if (await bucket.head(destKey)) return true;
1979
+ const staged = await bucket.get(stagedBlobKey(did, cid));
1980
+ if (!staged) return false;
1981
+ await bucket.put(destKey, staged.body, { httpMetadata: staged.httpMetadata });
1982
+ return true;
1983
+ }
1984
+ /**
1985
+ * Promote a freshly uploaded blob into every space whose imported records
1986
+ * reference it (see `com.atproto.space.importRepo`). The host calls this
1987
+ * from `com.atproto.repo.uploadBlob`, mirroring how an imported public repo's
1988
+ * blobs are made permanent on upload.
1989
+ */
1990
+ async function promotePendingSpaceBlob(params) {
1991
+ const uris = await params.claimPendingBlob(params.cid);
1992
+ for (const uri of uris) await promoteStagedBlobToSpace(params.bucket, params.did, uri, params.cid);
1993
+ return uris.length;
1994
+ }
1112
1995
 
1113
1996
  //#endregion
1114
1997
  //#region src/auth.ts
1115
1998
  /**
1116
1999
  * Worker-side verification of space credentials and delegation tokens.
1117
2000
  *
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.
2001
+ * A space credential is presented as `Authorization: Atproto-Space-Credential
2002
+ * <jwt>` (scheme case-insensitive), with an `Atproto-Space-Audience` header
2003
+ * naming the service being called and an HTTP message signature over both,
2004
+ * by the P-256 key the credential is bound to (`cnf.kid`). A delegation
2005
+ * token arrives in the `getSpaceCredential` request body.
2006
+ *
2007
+ * Everything here is stateless except the revocation and replay checks,
2008
+ * which are one RPC each to the space DO. Key resolution goes through the
2009
+ * host's DID resolver with a forced refresh on signature failure (handled
2010
+ * inside `verifySpaceToken`) so key rotation doesn't strand callers.
1122
2011
  */
2012
+ const SPACE_CREDENTIAL_SCHEME = "Atproto-Space-Credential";
2013
+ const SPACE_AUDIENCE_HEADER = "atproto-space-audience";
1123
2014
  /**
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.
2015
+ * Split an Authorization header into scheme and token. The scheme is
2016
+ * case-insensitive, as for every HTTP authentication scheme.
1127
2017
  */
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
- }
2018
+ function splitAuthorization(authorization) {
2019
+ if (!authorization) return null;
2020
+ const parts = authorization.split(" ");
2021
+ if (parts.length !== 2 || !parts[0] || !parts[1]) return null;
2022
+ return {
2023
+ scheme: parts[0].toLowerCase(),
2024
+ token: parts[1]
2025
+ };
1137
2026
  }
1138
2027
  /** Whether an Authorization header carries a space credential. */
1139
2028
  function isSpaceCredentialAuth(authorization) {
1140
- if (!authorization?.startsWith("DPoP ")) return false;
1141
- return unverifiedJwtTyp(authorization.slice(5)) === SPACE_TOKEN_TYPES.credential.typ;
2029
+ return splitAuthorization(authorization)?.scheme === SPACE_CREDENTIAL_SCHEME.toLowerCase();
1142
2030
  }
1143
- function htuFor(opts) {
1144
- return `${opts.publicOrigin}${new URL(opts.url).pathname}`;
1145
- }
1146
- const nowSec = () => Math.floor(Date.now() / 1e3);
1147
2031
  /**
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.
2032
+ * Verify a space credential presented against `space`: the token itself
2033
+ * (type, signature against the issuer's `#atproto` key, expiry, lifetime),
2034
+ * its issuer being the space's authority and its subject the space, the
2035
+ * HTTP message signature by its bound key over the credential and the
2036
+ * audience, the audience naming this service, and revocation.
1154
2037
  */
1155
- async function verifySpaceCredentialAuth(credential, space, opts) {
2038
+ async function verifySpaceCredentialAuth(space, opts) {
2039
+ const authorization = splitAuthorization(opts.headers.authorization);
2040
+ if (!authorization || authorization.scheme !== SPACE_CREDENTIAL_SCHEME.toLowerCase()) throw new SpaceError("MissingJwt", "Missing space credential");
1156
2041
  let payload;
1157
2042
  try {
1158
- ({payload} = await verifySpaceToken("credential", credential, {
1159
- getSigningKey: opts.getSigningKey,
1160
- sub: space.uri
1161
- }));
2043
+ ({payload} = await verifySpaceToken("credential", authorization.token, { getSigningKey: opts.getSigningKey }));
1162
2044
  } catch (err) {
1163
- throw invalidCredential(err);
2045
+ throw tokenError(err, "BadJwt");
1164
2046
  }
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;
2047
+ const subject = parseSpaceUri(payload.sub);
2048
+ if (!subject) throw new SpaceError("BadJwtSub", `Space token subject is not a space URI: ${payload.sub}`);
2049
+ if (payload.iss !== subject.authority) throw new SpaceError("BadJwtIss", "Space credential issuer is not the space authority");
2050
+ const audience = opts.headers[SPACE_AUDIENCE_HEADER];
2051
+ if (!audience?.startsWith("did:")) throw new SpaceError("BadSpaceSignature", "Missing or invalid space audience DID");
1170
2052
  try {
1171
- proof = await verifyDpopProof(opts.dpopProof, {
1172
- htm: opts.htm,
1173
- htu: htuFor(opts),
1174
- credential,
1175
- jkt
1176
- });
2053
+ await verifyCredentialSig(opts.headers, payload.cnf.kid);
1177
2054
  } catch (err) {
1178
- throw invalidCredential(err);
2055
+ if (err instanceof SpaceSignatureError) throw new SpaceError("BadSpaceSignature", err.message);
2056
+ throw err;
1179
2057
  }
1180
- if (!await opts.checkReplay("dpop", proof.jti, nowSec() + 300)) throw new SpaceError("InvalidCredential", "DPoP proof replayed");
2058
+ if (audience !== opts.audience) throw new SpaceError("BadSpaceAudience", "Space audience does not match the request");
2059
+ if (payload.sub !== space.uri) throw new SpaceError("InvalidCredential", "Credential is not scoped to this space");
2060
+ if (await opts.checkRevoked(payload.jti)) throw new SpaceError("CredentialRevoked", "Space credential has been revoked");
1181
2061
  return {
1182
2062
  kind: "credential",
1183
- iss: payload.iss
2063
+ iss: payload.iss,
2064
+ jti: payload.jti
1184
2065
  };
1185
2066
  }
1186
2067
  /**
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)`.
2068
+ * Verify a delegation token from a `getSpaceCredential` body: signature
2069
+ * against the issuer's `#atproto` key, audience the space authority's
2070
+ * `#atproto_pds`, subject the requested space, single use by `(iss, jti)`.
2071
+ * Any failure is `InvalidDelegationToken`: the token arrives in the body
2072
+ * rather than as the request's authorization, so it is an invalid request,
2073
+ * not an authentication failure.
1190
2074
  */
1191
- async function verifyDelegationAuth(token, space, opts) {
2075
+ async function verifyDelegationToken(token, space, opts) {
1192
2076
  let payload;
1193
2077
  try {
1194
- ({payload} = await verifySpaceToken("delegation", token, {
1195
- getSigningKey: opts.getSigningKey,
1196
- aud: spaceHostAud(space.authority),
1197
- sub: space.uri
1198
- }));
2078
+ ({payload} = await verifySpaceToken("delegation", token, { getSigningKey: opts.getSigningKey }));
1199
2079
  } catch (err) {
1200
- throw invalidDelegation(err);
2080
+ throw tokenError(err, "InvalidDelegationToken", "InvalidDelegationToken");
1201
2081
  }
2082
+ if (payload.sub !== space.uri) throw new SpaceError("InvalidDelegationToken", "Delegation token subject does not match requested space");
2083
+ if (payload.aud !== spaceHostAud$1(space.authority)) throw new SpaceError("InvalidDelegationToken", "Delegation token audience does not match the space authority");
1202
2084
  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
2085
  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
- console.warn("space credential verification failed:", err);
1221
- return new SpaceError("InvalidCredential", authErrorMessage(err));
1222
- }
1223
- function invalidDelegation(err) {
1224
- console.warn("delegation token verification failed:", err);
1225
- return new SpaceError("InvalidDelegationToken", authErrorMessage(err));
2086
+ return { userDid: payload.iss };
1226
2087
  }
1227
- function authErrorMessage(err) {
1228
- if (err instanceof SpaceTokenError || err instanceof DpopProofError) return err.message;
1229
- return "Token verification failed";
2088
+ function tokenError(err, fallback, override) {
2089
+ console.warn("space token verification failed:", err);
2090
+ if (err instanceof SpaceTokenError) return new SpaceError(override ?? err.code, err.message);
2091
+ return new SpaceError(override ?? fallback, "Token verification failed");
1230
2092
  }
1231
2093
 
1232
2094
  //#endregion
@@ -1272,7 +2134,7 @@ async function verifyClientAttestation(attestation, opts) {
1272
2134
  const res = await doFetch(url, {
1273
2135
  headers: { Accept: "application/json" },
1274
2136
  signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
1275
- redirect: "error"
2137
+ redirect: "manual"
1276
2138
  });
1277
2139
  if (!res.ok) throw new Error(`fetch of ${url} returned ${res.status}`);
1278
2140
  return res.json();
@@ -1304,7 +2166,7 @@ async function verifyClientAttestation(attestation, opts) {
1304
2166
  issuer: clientId,
1305
2167
  subject: clientId,
1306
2168
  audience: opts.expectedAud,
1307
- typ: SPACE_TOKEN_TYPES.clientAttestation.typ,
2169
+ typ: CLIENT_ATTESTATION_TYP,
1308
2170
  requiredClaims: ["jti", "exp"],
1309
2171
  clockTolerance: 5
1310
2172
  });
@@ -1318,88 +2180,45 @@ function invalid(err) {
1318
2180
  return new SpaceError("InvalidClientAttestation", err instanceof Error ? err.message : "Invalid client attestation");
1319
2181
  }
1320
2182
 
1321
- //#endregion
1322
- //#region src/commit.ts
1323
- /**
1324
- * Commit signing.
1325
- *
1326
- * Signing happens in the Worker, never in the Durable Object. The proposal
1327
- * requires a fresh `ikm` per reader, so a signature is never stored — each
1328
- * response that carries a commit signs the persisted LtHash state anew with
1329
- * the account keypair the Worker already holds.
1330
- */
1331
- async function signCommit(params, keypair) {
1332
- return RepoCommit.fromState(params.state.setHash).sign({
1333
- space: params.spaceUri,
1334
- author: params.author,
1335
- rev: params.state.rev
1336
- }, keypair);
1337
- }
1338
- /**
1339
- * Lexicon JSON form of a signed commit (`com.atproto.space.defs#signedCommit`):
1340
- * bytes fields encode as `{"$bytes": "<base64>"}`.
1341
- */
1342
- function commitToJson(commit) {
1343
- return {
1344
- ver: commit.ver,
1345
- hash: { $bytes: toBase64(commit.hash) },
1346
- ikm: { $bytes: toBase64(commit.ikm) },
1347
- sig: { $bytes: toBase64(commit.sig) },
1348
- mac: { $bytes: toBase64(commit.mac) },
1349
- rev: commit.rev
1350
- };
1351
- }
1352
- /** Lexicon JSON form of a bare bytes value. */
1353
- function bytesToJson(bytes) {
1354
- return { $bytes: toBase64(bytes) };
1355
- }
1356
-
1357
- //#endregion
1358
- //#region src/records.ts
1359
- /**
1360
- * Record preparation and serialization for the Worker side of the write
1361
- * and read paths. Records are stored as dag-cbor bytes with their CID,
1362
- * computed here — the same encoding path the reference uses.
1363
- */
1364
- /**
1365
- * Convert a client-supplied JSON record into its stored form: lex value →
1366
- * dag-cbor bytes → CID, with blob references enumerated for the space's
1367
- * blob tracking.
1368
- */
1369
- async function prepareRecord(record) {
1370
- const lex = jsonToLex(record);
1371
- const bytes = encode(lex);
1372
- const cid = await cidForLex(lex);
1373
- const blobCids = [];
1374
- for (const ref of enumBlobRefs(lex)) blobCids.push(getBlobCidString(ref));
1375
- return {
1376
- cid: cid.toString(),
1377
- bytes,
1378
- blobCids,
1379
- json: lexToJson(lex)
1380
- };
1381
- }
1382
- /** Decode stored record bytes back into response JSON. */
1383
- function recordBytesToJson(bytes) {
1384
- return lexToJson(decode(bytes));
1385
- }
1386
-
1387
2183
  //#endregion
1388
2184
  //#region src/routes.ts
1389
2185
  /**
1390
2186
  * Hono route factory for `com.atproto.space.*` and
1391
- * `com.atproto.simplespace.*`.
2187
+ * `com.atproto.memberspace.*`.
1392
2188
  *
1393
2189
  * The factory is host-agnostic: everything account-specific — session
1394
2190
  * authentication, DID resolution, record validation, the operator identity
1395
- * — arrives through {@link SpaceRoutesHost}. The host mounts the returned
1396
- * app behind its feature flag.
2191
+ * and its keys — arrives through {@link SpaceRoutesHost}. The host mounts
2192
+ * the returned app behind its feature flag.
2193
+ */
2194
+ const NOTIFY_REPO_UPDATE_LXM = "com.atproto.space.notifyRepoUpdate";
2195
+ const CREDENTIALS_REVOKED_LXM = "com.atproto.space.notifyCredentialsRevoked";
2196
+ const CONFIRM_REGISTRATION_LXM = "com.atproto.space.confirmRegistration";
2197
+ const CHECK_ACCESS_LXM = "com.atproto.managedspace.checkAccess";
2198
+ /** A managing app or syncer endpoint that doesn't answer in this window fails. */
2199
+ const UPSTREAM_TIMEOUT_MS = 1e4;
2200
+ /** The queue key for this repo's pending update notification to a foreign authority. */
2201
+ const NOTIFY_REPO_UPDATE_COALESCE_KEY = "notifyRepoUpdate:authority";
2202
+ /** Upper bound on archives accepted by importRepo / importSpaceMeta. */
2203
+ const MAX_IMPORT_BYTES = 100 * 1024 * 1024;
2204
+ /** Revocations are held until any credential they name has expired. */
2205
+ const REVOCATION_TTL_SEC = 3610;
2206
+ /** The media type of STAR archives (repos and space meta). */
2207
+ const STAR_CONTENT_TYPE = "application/vnd.dasl.star";
2208
+ /** Batched member changes take at most this many entries. */
2209
+ const MAX_MEMBER_BATCH = 100;
2210
+ /**
2211
+ * The narrowest `space:` scope that covers an operation, written as
2212
+ * `@atproto/oauth-scopes` writes it (`SpacePermission.scopeNeededFor`), so a
2213
+ * refusal can tell the app what to ask for. A manage op adds the narrowest
2214
+ * action, `read_self`, since a scope with no action defaults to all of them.
1397
2215
  */
1398
- const NOTIFY_WRITE_LXM = "com.atproto.space.notifyWrite";
1399
- const SPACE_DELETED_LXM = "com.atproto.space.notifySpaceDeleted";
1400
- const CHECK_USER_ACCESS_LXM = "com.atproto.simplespace.checkUserAccess";
1401
- /** A managing app that doesn't answer within this window denies access. */
1402
- const CHECK_USER_ACCESS_TIMEOUT_MS = 5e3;
2216
+ function spaceScopeNeededFor(match) {
2217
+ const scope = `space:${match.type}?authority=${match.authority}&skey=${match.skey}`;
2218
+ if ("manage" in match) return `${scope}&action=read_self&manage=${match.manage}`;
2219
+ if ("collection" in match) return `${scope}&collection=${match.collection}&action=${match.action}`;
2220
+ return `${scope}&action=${match.action}`;
2221
+ }
1403
2222
  function errorResponse(c, err) {
1404
2223
  const parsed = parseSpaceErrorCode(err);
1405
2224
  if (parsed) return c.json({
@@ -1415,24 +2234,40 @@ function waitUntil(c, promise) {
1415
2234
  promise.catch((err) => console.warn("background task failed", err));
1416
2235
  }
1417
2236
  }
1418
- function replayChecker(stub) {
1419
- return (kind, key, expiresAtSec) => stub.rpcCheckReplay(kind, key, expiresAtSec);
2237
+ /** Request headers as a plain object with lower-cased names. */
2238
+ function headerRecord(c) {
2239
+ return Object.fromEntries(c.req.raw.headers);
2240
+ }
2241
+ /** Append to a comma-separated response header without clobbering it. */
2242
+ function appendHeader(c, name, value) {
2243
+ c.header(name, value, { append: true });
1420
2244
  }
1421
2245
  function createSpaceRoutes(host) {
1422
2246
  const app = new Hono();
1423
- const doFetch = host.outboundFetch ?? fetch;
2247
+ const doFetch = host.outboundFetch ?? ((input, init) => globalThis.fetch(input, init));
2248
+ let kemKeypair = null;
2249
+ function getKemKeypair() {
2250
+ kemKeypair ??= Promise.resolve(host.getKemPrivateKey()).then((hex) => hex ? importKemKeypair(hex) : null);
2251
+ return kemKeypair;
2252
+ }
1424
2253
  /** The `repo` param on every repo-host method must be the operator DID. */
1425
2254
  function requireRepoParam(repo) {
1426
2255
  if (repo !== host.operatorDid) throw new SpaceError("RepoNotFound", `Repository not found: ${String(repo)}`);
1427
2256
  }
1428
- const verifyOpts = (c, stub) => ({
1429
- htm: c.req.method,
1430
- url: c.req.url,
1431
- publicOrigin: host.publicOrigin,
1432
- dpopProof: c.req.header("DPoP"),
1433
- getSigningKey: host.getSigningKey,
1434
- checkReplay: replayChecker(stub)
1435
- });
2257
+ /**
2258
+ * Verify a space credential addressed to this host. Every audience is
2259
+ * the operator DID: Cirrus serves only the operator's repos, and hosts
2260
+ * only spaces under the operator's authority.
2261
+ */
2262
+ async function credentialAuth(c, ref) {
2263
+ const stub = host.getSpaceDO(ref.uri);
2264
+ await verifySpaceCredentialAuth(ref, {
2265
+ headers: headerRecord(c),
2266
+ audience: host.operatorDid,
2267
+ getSigningKey: host.getSigningKey,
2268
+ checkRevoked: (jti) => stub.rpcIsCredentialRevoked(jti)
2269
+ });
2270
+ }
1436
2271
  /**
1437
2272
  * Authenticate a read: a space credential for the requested space, or a
1438
2273
  * host session covering `read_self` on it. The `repo` param on every
@@ -1440,91 +2275,137 @@ function createSpaceRoutes(host) {
1440
2275
  * RepoNotFound, deliberately indistinguishable from an absent repo.
1441
2276
  */
1442
2277
  async function readAuth(c, ref, repo) {
1443
- if (repo !== host.operatorDid) throw new SpaceError("RepoNotFound", `Repository not found: ${repo}`);
1444
- const authHeader = c.req.header("Authorization");
1445
- if (isSpaceCredentialAuth(authHeader)) {
1446
- const stub = host.getSpaceDO(ref.uri);
1447
- await verifySpaceCredentialAuth(authHeader.slice(5), ref, verifyOpts(c, stub));
2278
+ requireRepoParam(repo);
2279
+ if (isSpaceCredentialAuth(c.req.header("Authorization"))) {
2280
+ await credentialAuth(c, ref);
1448
2281
  return { kind: "credential" };
1449
2282
  }
1450
2283
  const session = await host.authenticate(c);
1451
2284
  if (session instanceof Response) return session;
1452
- if (!session.fullTrust) {
1453
- if (!session.allowsSpace({
1454
- type: ref.type,
1455
- authority: ref.authority,
1456
- skey: ref.skey,
1457
- action: "read_self"
1458
- })) return c.json({
1459
- error: "InsufficientScope",
1460
- message: "Token does not cover reading this space"
1461
- }, 403);
1462
- }
2285
+ const scopeError = assertScope(c, session, {
2286
+ type: ref.type,
2287
+ authority: ref.authority,
2288
+ skey: ref.skey,
2289
+ action: "read_self"
2290
+ });
2291
+ if (scopeError) return scopeError;
1463
2292
  return { kind: "session" };
1464
2293
  }
1465
- /** Session-only auth for writes and management. */
1466
- async function sessionAuth(c) {
1467
- return host.authenticate(c);
2294
+ /**
2295
+ * The MAC owed by a read that returns a commit or record, with the
2296
+ * response headers a browser syncer needs to read the MAC.
2297
+ */
2298
+ async function readMac(c, auth, profile) {
2299
+ appendHeader(c, "Vary", "Accept-Signature");
2300
+ const mac = await macRequest({
2301
+ acceptSignature: c.req.header(MAC_REQUEST_HEADER),
2302
+ credential: auth.kind === "credential",
2303
+ profile,
2304
+ getKemKeypair
2305
+ });
2306
+ if (mac) for (const header of macExposedHeaders(profile)) appendHeader(c, "Access-Control-Expose-Headers", header);
2307
+ return mac;
1468
2308
  }
1469
2309
  function assertScope(c, session, match) {
1470
2310
  if (session.fullTrust) return null;
1471
2311
  if (session.allowsSpace(match)) return null;
1472
2312
  return c.json({
1473
2313
  error: "InsufficientScope",
1474
- message: "Token does not cover this space operation"
2314
+ message: `Missing required scope: ${spaceScopeNeededFor(match)}`
1475
2315
  }, 403);
1476
2316
  }
1477
2317
  /** The operator hosts this space, or SpaceNotFound. */
1478
2318
  function assertSpaceHost(ref) {
1479
2319
  if (ref.authority !== host.operatorDid) throw new SpaceError("SpaceNotFound", `Space not found: ${ref.uri}`);
1480
2320
  }
2321
+ /** As assertSpaceHost, and the authority's account must be active. */
2322
+ async function assertActiveSpaceHost(ref) {
2323
+ assertSpaceHost(ref);
2324
+ if (host.isAccountActive && !await host.isAccountActive()) throw new SpaceError("RepoDeactivated", `Repo has been deactivated: ${ref.authority}`);
2325
+ }
1481
2326
  /**
1482
- * The simplespace user-access policy, applied at credential mint and to
1483
- * inbound notifyWrite writers. The authority itself always passes; a
1484
- * managing app that errors or times out denies.
2327
+ * A space created here is anchored on its creator's DID, so ownership
2328
+ * is a comparison against the space URI, made before anything else.
1485
2329
  */
1486
- async function authorizeUser(config, ref, userDid, clientId, stub) {
1487
- if (userDid === ref.authority) return true;
1488
- switch (config.policy.kind) {
1489
- case "public": return true;
1490
- case "member-list": return stub.rpcIsMember(userDid);
1491
- case "managing-app": {
1492
- const managingApp = config.policy.managingApp;
1493
- try {
1494
- const endpoint = await host.resolveServiceEndpoint(managingApp);
1495
- if (!endpoint) return false;
1496
- const keypair = await host.getKeypair();
1497
- const token = await createServiceJwt({
1498
- iss: host.operatorDid,
1499
- aud: managingApp,
1500
- lxm: CHECK_USER_ACCESS_LXM
1501
- }, keypair);
1502
- const url = new URL(`${endpoint}/xrpc/${CHECK_USER_ACCESS_LXM}`);
1503
- url.searchParams.set("space", ref.uri);
1504
- url.searchParams.set("user", userDid);
1505
- if (clientId) url.searchParams.set("clientId", clientId);
1506
- const res = await doFetch(url.toString(), {
1507
- headers: { Authorization: `Bearer ${token}` },
1508
- signal: AbortSignal.timeout(CHECK_USER_ACCESS_TIMEOUT_MS)
1509
- });
1510
- if (!res.ok) return false;
1511
- return (await res.json()).authorized === true;
1512
- } catch {
1513
- return false;
1514
- }
2330
+ function assertOwner(ref, session) {
2331
+ if (session.did !== ref.authority) throw new SpaceError("NotAuthorized", "Not the space authority");
2332
+ assertSpaceHost(ref);
2333
+ }
2334
+ /** The policy of a live space this host governs. */
2335
+ async function requirePolicy(stub, ref) {
2336
+ const { meta, policy } = await stub.rpcGetAuthorityState();
2337
+ if (!meta || meta.deletedAt || !policy) throw new SpaceError("SpaceNotFound", `Space not found: ${ref.uri}`);
2338
+ return policy;
2339
+ }
2340
+ /**
2341
+ * Whether a policy authorises an account to read or write. `repo` is
2342
+ * absent for a read with no delegation token, which a policy authorises
2343
+ * only if it does not gate on the account. The authority always passes
2344
+ * under every policy: it alone can reconfigure the space, so it must not
2345
+ * be able to lock itself out.
2346
+ *
2347
+ * A managing app that can't be reached throws UpstreamFailure rather
2348
+ * than denying: denying would read as a loss of access, withdrawing a
2349
+ * syncer's registration and making a repo host drop its notification.
2350
+ */
2351
+ async function authorizeRepo(params) {
2352
+ const { policy, ref, repo, access, clientId, stub } = params;
2353
+ if (repo === ref.authority) return true;
2354
+ switch (policy.$type) {
2355
+ case PERSONALSPACE_POLICY: return false;
2356
+ case MEMBERSPACE_POLICY: {
2357
+ if (access === "read" && policy.publicRead) return true;
2358
+ if (!repo) return false;
2359
+ const member = await stub.rpcGetMember(repo);
2360
+ if (access === "read") return member?.read ?? false;
2361
+ if (member) return member.write;
2362
+ return policy.publicWrite;
1515
2363
  }
2364
+ case MANAGEDSPACE_POLICY: return (await checkAccess(policy.managingApp, ref, repo, clientId))[access];
2365
+ }
2366
+ }
2367
+ /** Ask a managed space's managing app for an account's access. */
2368
+ async function checkAccess(managingApp, ref, repo, clientId) {
2369
+ try {
2370
+ const endpoint = await host.resolveServiceEndpoint(managingApp);
2371
+ if (!endpoint) throw new Error("could not resolve the managing app");
2372
+ const token = await createServiceJwt({
2373
+ iss: host.operatorDid,
2374
+ aud: managingApp,
2375
+ lxm: CHECK_ACCESS_LXM
2376
+ }, await host.getKeypair());
2377
+ const url = new URL(`${endpoint}/xrpc/${CHECK_ACCESS_LXM}`);
2378
+ url.searchParams.set("space", ref.uri);
2379
+ if (repo) url.searchParams.set("repo", repo);
2380
+ if (clientId) url.searchParams.set("clientId", clientId);
2381
+ const res = await doFetch(url.toString(), {
2382
+ headers: { Authorization: `Bearer ${token}` },
2383
+ redirect: "manual",
2384
+ signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS)
2385
+ });
2386
+ if (!res.ok) throw new Error(`checkAccess answered ${res.status}`);
2387
+ const body = await res.json();
2388
+ if (typeof body.read !== "boolean" || typeof body.write !== "boolean") throw new Error("checkAccess answered without read and write");
2389
+ return {
2390
+ read: body.read,
2391
+ write: body.write
2392
+ };
2393
+ } catch (err) {
2394
+ console.warn(`managing app check for ${ref.uri} failed:`, err);
2395
+ throw new SpaceError("UpstreamFailure", "Managing app did not answer");
1516
2396
  }
1517
2397
  }
1518
2398
  /**
1519
- * Ensure the space DO exists for a write. First write into a foreign
1520
- * space registers it `pending` in the index, initialises the DO as
1521
- * repo-host, then activates the entry. Spaces under the operator's own
1522
- * authority must have been created via simplespace first.
2399
+ * Ensure the space DO exists for a write. The first write into a foreign
2400
+ * space registers it `pending` in the index, initialises the DO as repo
2401
+ * host, then activates the entry. The operator's own spaces must already
2402
+ * exist: a write must neither conjure an ungoverned space nor revive a
2403
+ * deleted one.
1523
2404
  */
1524
2405
  async function ensureSpaceForWrite(ref, stub) {
1525
2406
  const meta = await stub.rpcGetMeta();
1526
2407
  if (meta && !meta.deletedAt) return;
1527
- if (ref.authority === host.operatorDid) throw new SpaceError("SpaceNotFound", `Space not found: ${ref.uri}. Create it with com.atproto.simplespace.createSpace.`);
2408
+ if (ref.authority === host.operatorDid) throw new SpaceError("SpaceNotFound", `Space not found: ${ref.uri}. Create it with com.atproto.space.createSpace.`);
1528
2409
  const index = host.getIndexDO();
1529
2410
  await index.rpcRegister({
1530
2411
  uri: ref.uri,
@@ -1548,71 +2429,73 @@ function createSpaceRoutes(host) {
1548
2429
  * CID; CIDs that are neither staged nor at the destination are skipped.
1549
2430
  */
1550
2431
  async function promoteSpaceBlobs(ref, blobCids) {
1551
- if (!host.blobs || blobCids.length === 0) return;
1552
- const id = await spaceId(ref.uri);
2432
+ const missing = [];
2433
+ if (!host.blobs || blobCids.length === 0) return missing;
1553
2434
  await Promise.all(blobCids.map(async (cid) => {
1554
- const destKey = spaceBlobKey(host.operatorDid, id, cid);
1555
- if (await host.blobs.head(destKey)) return;
1556
- const staged = await host.blobs.get(stagedBlobKey(host.operatorDid, cid));
1557
- if (!staged) return;
1558
- await host.blobs.put(destKey, staged.body, { httpMetadata: staged.httpMetadata });
2435
+ if (!await promoteStagedBlobToSpace(host.blobs, host.operatorDid, ref.uri, cid)) missing.push(cid);
1559
2436
  }));
2437
+ return missing;
1560
2438
  }
1561
2439
  /**
1562
- * Step 8 of the write path: after the commit is applied, record the
1563
- * writer and fan out (own authority) or send one best-effort
1564
- * notifyWrite to the space's authority (foreign space).
2440
+ * After a commit: the authority sequences its own update into the writer
2441
+ * set, which queues it for registered syncers; a repo host in a foreign
2442
+ * space delivers its latest state to the authority, immediately,
2443
+ * persisting a retryable failure for the DO's alarm to retry for up to
2444
+ * 24 hours. Retries coalesce, so only the newest revision is pending.
1565
2445
  */
1566
- async function postWrite(ref, stub, rev, hash) {
2446
+ async function postWrite(ref, stub, commit) {
1567
2447
  if (ref.authority === host.operatorDid) {
1568
- const { advanced } = await stub.rpcRecordWriter(host.operatorDid, rev, hash);
1569
- if (!advanced) return;
1570
- const registrations = await stub.rpcGetActiveRegistrations();
1571
- if (registrations.length === 0) return;
1572
- const body = {
1573
- space: ref.uri,
1574
- repo: host.operatorDid,
1575
- rev,
1576
- hash: bytesToJson(hash)
1577
- };
1578
- const items = registrations.map((registration) => ({
1579
- service: registration.service,
1580
- endpoint: registration.endpoint,
1581
- lxm: NOTIFY_WRITE_LXM,
1582
- body
1583
- }));
1584
- await stub.rpcEnqueueNotify(items);
2448
+ await stub.rpcRecordWriter(host.operatorDid, commit.rev, commit.data);
1585
2449
  return;
1586
2450
  }
2451
+ const body = {
2452
+ space: ref.uri,
2453
+ repo: host.operatorDid,
2454
+ repoRev: commit.rev,
2455
+ data: bytesToJson(commit.data)
2456
+ };
2457
+ const aud = spaceHostAud$1(ref.authority);
2458
+ const endpoint = await host.resolveServiceEndpoint(aud).catch(() => null);
2459
+ if (!endpoint) {
2460
+ console.warn(`notifyRepoUpdate: no endpoint for ${ref.authority}`);
2461
+ return;
2462
+ }
2463
+ const retry = {
2464
+ service: aud,
2465
+ endpoint,
2466
+ lxm: NOTIFY_REPO_UPDATE_LXM,
2467
+ body,
2468
+ coalesceKey: NOTIFY_REPO_UPDATE_COALESCE_KEY,
2469
+ deadline: Date.now() + NOTIFY_WRITE_RETRY_MS,
2470
+ policy: "repo",
2471
+ auth: "service"
2472
+ };
1587
2473
  try {
1588
- const endpoint = await host.resolveAuthorityEndpoint(ref.authority);
1589
- if (!endpoint) {
1590
- console.warn(`notifyWrite: no endpoint for ${ref.authority}`);
1591
- return;
1592
- }
1593
- const keypair = await host.getKeypair();
1594
2474
  const token = await createServiceJwt({
1595
2475
  iss: host.operatorDid,
1596
- aud: ref.authority,
1597
- lxm: NOTIFY_WRITE_LXM
1598
- }, keypair);
1599
- const res = await doFetch(`${endpoint}/xrpc/${NOTIFY_WRITE_LXM}`, {
2476
+ aud,
2477
+ lxm: NOTIFY_REPO_UPDATE_LXM
2478
+ }, await host.getKeypair());
2479
+ const res = await doFetch(`${endpoint}/xrpc/${NOTIFY_REPO_UPDATE_LXM}`, {
1600
2480
  method: "POST",
1601
2481
  headers: {
1602
2482
  "Content-Type": "application/json",
1603
2483
  Authorization: `Bearer ${token}`
1604
2484
  },
1605
- body: JSON.stringify({
1606
- space: ref.uri,
1607
- repo: host.operatorDid,
1608
- rev,
1609
- hash: bytesToJson(hash)
1610
- })
2485
+ body: JSON.stringify(body),
2486
+ redirect: "manual",
2487
+ signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS)
1611
2488
  });
1612
- if (!res.ok) console.warn(`notifyWrite to ${ref.authority} failed: ${res.status}`);
2489
+ if (res.ok || !isRetryableStatus(res.status)) {
2490
+ if (!res.ok) console.warn(`notifyRepoUpdate to ${ref.authority} refused: ${res.status}; not retrying`);
2491
+ await stub.rpcClearNotify(NOTIFY_REPO_UPDATE_COALESCE_KEY);
2492
+ return;
2493
+ }
2494
+ console.warn(`notifyRepoUpdate to ${ref.authority} failed: ${res.status}`);
1613
2495
  } catch (err) {
1614
- console.warn(`notifyWrite to ${ref.authority} errored:`, err);
2496
+ console.warn(`notifyRepoUpdate to ${ref.authority} errored:`, err);
1615
2497
  }
2498
+ await stub.rpcEnqueueNotify([retry], { delayMs: NOTIFY_BACKOFF_BASE_MS });
1616
2499
  }
1617
2500
  /**
1618
2501
  * Common write pipeline for createRecord/putRecord/deleteRecord and
@@ -1632,6 +2515,7 @@ function createSpaceRoutes(host) {
1632
2515
  collection: write.collection
1633
2516
  });
1634
2517
  if (scopeError) return scopeError;
2518
+ assertNotPublishedCollection(write.collection);
1635
2519
  if (write.action === "delete") {
1636
2520
  prepared.push({
1637
2521
  action: "delete",
@@ -1657,6 +2541,7 @@ function createSpaceRoutes(host) {
1657
2541
  }, 400);
1658
2542
  }
1659
2543
  const preparedRecord = await prepareRecord(validated.record);
2544
+ if (preparedRecord.bytes.length > MAX_SPACE_RECORD_BYTES) throw new SpaceError("InvalidRequest", `Record exceeds the maximum space record size of ${MAX_SPACE_RECORD_BYTES} bytes`);
1660
2545
  for (const cid of preparedRecord.blobCids) blobCids.add(cid);
1661
2546
  prepared.push({
1662
2547
  action: write.action,
@@ -1672,7 +2557,7 @@ function createSpaceRoutes(host) {
1672
2557
  const stub = host.getSpaceDO(ref.uri);
1673
2558
  await ensureSpaceForWrite(ref, stub);
1674
2559
  const result = await stub.rpcApplyWrites(prepared);
1675
- waitUntil(c, postWrite(ref, stub, result.rev, result.hash));
2560
+ waitUntil(c, postWrite(ref, stub, result));
1676
2561
  return {
1677
2562
  rev: result.rev,
1678
2563
  results: result.results.map((r, i) => ({
@@ -1681,13 +2566,17 @@ function createSpaceRoutes(host) {
1681
2566
  }))
1682
2567
  };
1683
2568
  }
2569
+ /** Notify after a configuration change that published to the repo. */
2570
+ function afterConfigCommit(c, ref, stub, commit) {
2571
+ if (commit) waitUntil(c, postWrite(ref, stub, commit));
2572
+ }
1684
2573
  app.post("/xrpc/com.atproto.space.createRecord", async (c) => {
1685
2574
  try {
1686
2575
  const body = await c.req.json();
1687
2576
  const ref = requireSpaceUri(body.space);
1688
2577
  requireRepoParam(body.repo);
1689
2578
  requireString(body.collection, "collection");
1690
- const session = await sessionAuth(c);
2579
+ const session = await host.authenticate(c);
1691
2580
  if (session instanceof Response) return session;
1692
2581
  const result = await runWrites(c, ref, session, [{
1693
2582
  action: "create",
@@ -1713,7 +2602,7 @@ function createSpaceRoutes(host) {
1713
2602
  requireRepoParam(body.repo);
1714
2603
  requireString(body.collection, "collection");
1715
2604
  requireString(body.rkey, "rkey");
1716
- const session = await sessionAuth(c);
2605
+ const session = await host.authenticate(c);
1717
2606
  if (session instanceof Response) return session;
1718
2607
  const stub = host.getSpaceDO(ref.uri);
1719
2608
  const meta = await stub.rpcGetMeta();
@@ -1741,7 +2630,7 @@ function createSpaceRoutes(host) {
1741
2630
  requireRepoParam(body.repo);
1742
2631
  requireString(body.collection, "collection");
1743
2632
  requireString(body.rkey, "rkey");
1744
- const session = await sessionAuth(c);
2633
+ const session = await host.authenticate(c);
1745
2634
  if (session instanceof Response) return session;
1746
2635
  const result = await runWrites(c, ref, session, [{
1747
2636
  action: "delete",
@@ -1762,7 +2651,7 @@ function createSpaceRoutes(host) {
1762
2651
  requireRepoParam(body.repo);
1763
2652
  if (!Array.isArray(body.writes)) throw new SpaceError("InvalidRequest", "writes must be an array");
1764
2653
  if (body.writes.length > 200) throw new SpaceError("InvalidRequest", "Too many writes. Max: 200");
1765
- const session = await sessionAuth(c);
2654
+ const session = await host.authenticate(c);
1766
2655
  if (session instanceof Response) return session;
1767
2656
  const result = await runWrites(c, ref, session, body.writes.map((write, i) => {
1768
2657
  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;
@@ -1789,16 +2678,118 @@ function createSpaceRoutes(host) {
1789
2678
  return errorResponse(c, err);
1790
2679
  }
1791
2680
  });
1792
- app.get("/xrpc/com.atproto.space.getRecord", async (c) => {
2681
+ app.post("/xrpc/com.atproto.space.clearRecords", async (c) => {
1793
2682
  try {
1794
- const ref = requireSpaceUri(c.req.query("space"));
1795
- const auth = await readAuth(c, ref, c.req.query("repo"));
1796
- if (auth instanceof Response) return auth;
1797
- const collection = c.req.query("collection");
1798
- const rkey = c.req.query("rkey");
1799
- requireString(collection, "collection");
1800
- requireString(rkey, "rkey");
1801
- const stub = host.getSpaceDO(ref.uri);
2683
+ const body = await c.req.json();
2684
+ const ref = requireSpaceUri(body.space);
2685
+ requireString(body.repo, "repo");
2686
+ const session = await host.authenticate(c);
2687
+ if (session instanceof Response) return session;
2688
+ if (body.repo !== session.did) throw new SpaceError("Forbidden", "repo must match authenticated user");
2689
+ requireRepoParam(body.repo);
2690
+ const stub = host.getSpaceDO(ref.uri);
2691
+ const meta = await stub.rpcGetMeta();
2692
+ if (!meta || meta.deletedAt) return c.json({});
2693
+ const keep = ref.authority === host.operatorDid ? [...PUBLISHED_COLLECTIONS] : [];
2694
+ for (const collection of await stub.rpcListCollections()) {
2695
+ if (keep.includes(collection)) continue;
2696
+ const scopeError = assertScope(c, session, {
2697
+ type: ref.type,
2698
+ authority: ref.authority,
2699
+ skey: ref.skey,
2700
+ action: "delete",
2701
+ collection
2702
+ });
2703
+ if (scopeError) return scopeError;
2704
+ }
2705
+ const commit = await stub.rpcClearRecords(keep);
2706
+ if (commit) waitUntil(c, postWrite(ref, stub, commit));
2707
+ return c.json({});
2708
+ } catch (err) {
2709
+ return errorResponse(c, err);
2710
+ }
2711
+ });
2712
+ app.post("/xrpc/com.atproto.space.importRepo", async (c) => {
2713
+ try {
2714
+ const session = await host.authenticate(c);
2715
+ if (session instanceof Response) return session;
2716
+ const bytes = await readBody(c);
2717
+ let records;
2718
+ let space;
2719
+ let repo;
2720
+ try {
2721
+ const archive = await readRepoStar([bytes]);
2722
+ try {
2723
+ space = archive.commit.space;
2724
+ repo = archive.commit.repo;
2725
+ records = [];
2726
+ for await (const record of archive.records) {
2727
+ const encoded = encode(record.record);
2728
+ const cid = await cidForCbor(encoded);
2729
+ if (!cid.equals(record.cid)) throw new SpaceError("InvalidRequest", `Invalid STAR: record is not canonical DRISL at ${record.collection}/${record.rkey}`);
2730
+ const blobCids = [];
2731
+ for (const ref$1 of enumBlobRefs(record.record, { strict: false })) blobCids.push(getBlobCidString(ref$1));
2732
+ records.push({
2733
+ collection: record.collection,
2734
+ rkey: record.rkey,
2735
+ cid: cid.toString(),
2736
+ bytes: encoded,
2737
+ blobCids
2738
+ });
2739
+ }
2740
+ } finally {
2741
+ await archive[Symbol.asyncDispose]();
2742
+ }
2743
+ } catch (err) {
2744
+ throw invalidArchive(err, "InvalidRepoFile");
2745
+ }
2746
+ if (repo !== host.operatorDid || repo !== session.did) throw new SpaceError("RepoMismatch", "Repo does not match the authenticated account");
2747
+ const ref = requireSpaceUri(space);
2748
+ for (const match of [
2749
+ { action: "read" },
2750
+ {
2751
+ action: "create",
2752
+ collection: "*"
2753
+ },
2754
+ {
2755
+ action: "update",
2756
+ collection: "*"
2757
+ },
2758
+ {
2759
+ action: "delete",
2760
+ collection: "*"
2761
+ }
2762
+ ]) {
2763
+ const scopeError = assertScope(c, session, {
2764
+ type: ref.type,
2765
+ authority: ref.authority,
2766
+ skey: ref.skey,
2767
+ ...match
2768
+ });
2769
+ if (scopeError) return scopeError;
2770
+ }
2771
+ const stub = host.getSpaceDO(ref.uri);
2772
+ if (ref.authority === host.operatorDid) await requirePolicy(stub, ref);
2773
+ else await ensureSpaceForWrite(ref, stub);
2774
+ await stub.rpcImportRepo(records);
2775
+ const missing = await promoteSpaceBlobs(ref, Array.from(new Set(records.flatMap((r) => r.blobCids))));
2776
+ if (missing.length > 0) await host.getIndexDO().rpcAddPendingBlobs(ref.uri, missing);
2777
+ return c.json({});
2778
+ } catch (err) {
2779
+ return errorResponse(c, err);
2780
+ }
2781
+ });
2782
+ app.get("/xrpc/com.atproto.space.getRecord", async (c) => {
2783
+ try {
2784
+ const ref = requireSpaceUri(c.req.query("space"));
2785
+ const auth = await readAuth(c, ref, c.req.query("repo"));
2786
+ if (auth instanceof Response) return auth;
2787
+ const collection = c.req.query("collection");
2788
+ const rkey = c.req.query("rkey");
2789
+ requireString(collection, "collection");
2790
+ requireString(rkey, "rkey");
2791
+ const mac = await readMac(c, auth, RECORD_MAC_PROFILE);
2792
+ const stub = host.getSpaceDO(ref.uri);
1802
2793
  await requireRepoExists(stub, ref);
1803
2794
  const record = await stub.rpcGetRecord(collection, rkey);
1804
2795
  const uri = spaceRecordUri(ref.uri, host.operatorDid, collection, rkey);
@@ -1807,7 +2798,7 @@ function createSpaceRoutes(host) {
1807
2798
  uri,
1808
2799
  cid: record.cid,
1809
2800
  value: recordBytesToJson(record.bytes)
1810
- });
2801
+ }, 200, recordMacHeaders(mac, uri, record.cid));
1811
2802
  } catch (err) {
1812
2803
  return errorResponse(c, err);
1813
2804
  }
@@ -1819,7 +2810,6 @@ function createSpaceRoutes(host) {
1819
2810
  if (auth instanceof Response) return auth;
1820
2811
  const collection = c.req.query("collection");
1821
2812
  const limit = clampLimit(c.req.query("limit"), 50, 1e3);
1822
- const reverse = c.req.query("reverse") === "true";
1823
2813
  const excludeValues = c.req.query("excludeValues") === "true";
1824
2814
  const after = parseRecordCursor(c.req.query("cursor"));
1825
2815
  const stub = host.getSpaceDO(ref.uri);
@@ -1828,7 +2818,6 @@ function createSpaceRoutes(host) {
1828
2818
  collection,
1829
2819
  limit,
1830
2820
  after,
1831
- reverse,
1832
2821
  excludeValues
1833
2822
  });
1834
2823
  const records = page.records.map((record) => ({
@@ -1851,20 +2840,20 @@ function createSpaceRoutes(host) {
1851
2840
  const ref = requireSpaceUri(c.req.query("space"));
1852
2841
  const auth = await readAuth(c, ref, c.req.query("repo"));
1853
2842
  if (auth instanceof Response) return auth;
2843
+ const mac = await readMac(c, auth, COMMIT_MAC_PROFILE);
1854
2844
  const stub = host.getSpaceDO(ref.uri);
1855
2845
  await requireRepoExists(stub, ref);
1856
2846
  const state = await stub.rpcGetRepoState();
1857
2847
  if (!state) throw new SpaceError("RepoNotFound", `Could not find repo for space: ${ref.uri}`);
1858
- const keypair = await host.getKeypair();
1859
- const commit = await signCommit({
2848
+ const commit = buildCommit({
1860
2849
  spaceUri: ref.uri,
1861
- author: host.operatorDid,
2850
+ repo: host.operatorDid,
1862
2851
  state: {
1863
2852
  setHash: new Uint8Array(state.setHash),
1864
2853
  rev: state.rev
1865
2854
  }
1866
- }, keypair);
1867
- return c.json({ commit: commitToJson(commit) });
2855
+ });
2856
+ return c.json({ commit: commitToJson(commit) }, 200, commitMacHeaders(mac, commit));
1868
2857
  } catch (err) {
1869
2858
  return errorResponse(c, err);
1870
2859
  }
@@ -1878,6 +2867,7 @@ function createSpaceRoutes(host) {
1878
2867
  const since = c.req.query("since");
1879
2868
  const excludeValues = c.req.query("excludeValues") === "true";
1880
2869
  const after = parseOpsCursor(c.req.query("cursor"));
2870
+ const mac = await readMac(c, auth, COMMIT_MAC_PROFILE);
1881
2871
  const stub = host.getSpaceDO(ref.uri);
1882
2872
  await requireRepoExists(stub, ref);
1883
2873
  const page = await stub.rpcListRepoOps({
@@ -1894,26 +2884,22 @@ function createSpaceRoutes(host) {
1894
2884
  prev: op.prev,
1895
2885
  ...op.bytes ? { value: recordBytesToJson(new Uint8Array(op.bytes)) } : {}
1896
2886
  }));
1897
- if (!page.head) {
1898
- const last = page.ops[page.ops.length - 1];
1899
- return c.json({
1900
- ops,
1901
- ...last ? { cursor: `${last.rev}/${last.idx}` } : {}
1902
- });
1903
- }
1904
- const keypair = await host.getKeypair();
1905
- const commit = await signCommit({
2887
+ if (!page.head) throw new SpaceError("RepoNotFound", `Could not find repo for space: ${ref.uri}`);
2888
+ const last = page.ops[page.ops.length - 1];
2889
+ const cursor = last && page.ops.length === limit ? `${last.rev}/${last.idx}` : void 0;
2890
+ const commit = buildCommit({
1906
2891
  spaceUri: ref.uri,
1907
- author: host.operatorDid,
2892
+ repo: host.operatorDid,
1908
2893
  state: {
1909
2894
  setHash: new Uint8Array(page.head.setHash),
1910
2895
  rev: page.head.rev
1911
2896
  }
1912
- }, keypair);
2897
+ });
1913
2898
  return c.json({
1914
2899
  ops,
1915
- commit: commitToJson(commit)
1916
- });
2900
+ commit: commitToJson(commit),
2901
+ ...cursor ? { cursor } : {}
2902
+ }, 200, commitMacHeaders(mac, commit));
1917
2903
  } catch (err) {
1918
2904
  return errorResponse(c, err);
1919
2905
  }
@@ -1923,67 +2909,42 @@ function createSpaceRoutes(host) {
1923
2909
  const ref = requireSpaceUri(c.req.query("space"));
1924
2910
  const auth = await readAuth(c, ref, c.req.query("repo"));
1925
2911
  if (auth instanceof Response) return auth;
1926
- const excludeValues = c.req.query("excludeValues") === "true";
2912
+ const mac = await readMac(c, auth, COMMIT_MAC_PROFILE);
1927
2913
  const stub = host.getSpaceDO(ref.uri);
1928
2914
  await requireRepoExists(stub, ref);
1929
- let state = null;
1930
- let records = null;
1931
- for (let attempt = 0; attempt < 3 && !records; attempt++) {
1932
- state = await stub.rpcGetRepoState();
1933
- if (!state) throw new SpaceError("RepoNotFound", `Could not find repo for space: ${ref.uri}`);
1934
- const collected = [];
1935
- let after;
1936
- let fenced = true;
2915
+ const PAGE = 500;
2916
+ const first = await stub.rpcListRecordsByPath({ limit: PAGE });
2917
+ const state = first.state;
2918
+ if (!state) throw new SpaceError("RepoNotFound", `Could not find repo for space: ${ref.uri}`);
2919
+ const commit = buildCommit({
2920
+ spaceUri: ref.uri,
2921
+ repo: host.operatorDid,
2922
+ state: {
2923
+ setHash: new Uint8Array(state.setHash),
2924
+ rev: state.rev
2925
+ }
2926
+ });
2927
+ async function* records() {
2928
+ let page = first;
1937
2929
  for (;;) {
1938
- const page = await stub.rpcListRecords({
1939
- limit: 500,
1940
- after,
1941
- reverse: true,
1942
- excludeValues: false
1943
- });
1944
- if (page.rev !== state.rev) {
1945
- fenced = false;
1946
- break;
1947
- }
1948
- for (const record of page.records) collected.push({
2930
+ for (const record of page.records) yield {
1949
2931
  collection: record.collection,
1950
2932
  rkey: record.rkey,
1951
- cid: parseCid(record.cid),
1952
2933
  bytes: new Uint8Array(record.bytes)
1953
- });
1954
- const last = page.records[page.records.length - 1];
1955
- if (!page.hasMore || !last) break;
1956
- after = {
1957
- collection: last.collection,
1958
- rkey: last.rkey
1959
2934
  };
2935
+ const last = page.records[page.records.length - 1];
2936
+ if (!page.hasMore || !last) return;
2937
+ page = await stub.rpcListRecordsByPath({
2938
+ afterPath: `${last.collection}/${last.rkey}`,
2939
+ limit: PAGE
2940
+ });
2941
+ if (page.state?.rev !== state.rev) throw new Error("The repo changed during export; retry getRepo");
1960
2942
  }
1961
- if (fenced) records = collected;
1962
2943
  }
1963
- if (!records || !state) return c.json({
1964
- error: "ConcurrentModification",
1965
- message: "The repo changed repeatedly during export; retry getRepo"
1966
- }, 409);
1967
- const keypair = await host.getKeypair();
1968
- const car = serializeRepo(await signCommit({
1969
- spaceUri: ref.uri,
1970
- author: host.operatorDid,
1971
- state: {
1972
- setHash: new Uint8Array(state.setHash),
1973
- rev: state.rev
1974
- }
1975
- }, keypair), records, { excludeValues });
1976
- const stream = new ReadableStream({ async start(controller) {
1977
- try {
1978
- for await (const chunk of car) controller.enqueue(chunk);
1979
- controller.close();
1980
- } catch (err) {
1981
- controller.error(err);
1982
- }
1983
- } });
1984
- return new Response(stream, {
1985
- status: 200,
1986
- headers: { "Content-Type": "application/vnd.ipld.car" }
2944
+ const star = writeRepoStar(commit, records());
2945
+ return c.body(asyncIterableToStream(star), 200, {
2946
+ "Content-Type": STAR_CONTENT_TYPE,
2947
+ ...commitMacHeaders(mac, commit)
1987
2948
  });
1988
2949
  } catch (err) {
1989
2950
  return errorResponse(c, err);
@@ -1995,12 +2956,10 @@ function createSpaceRoutes(host) {
1995
2956
  const auth = await readAuth(c, ref, c.req.query("repo"));
1996
2957
  if (auth instanceof Response) return auth;
1997
2958
  const limit = clampLimit(c.req.query("limit"), 500, 1e3);
1998
- const since = c.req.query("since");
1999
2959
  const afterCid = c.req.query("cursor");
2000
2960
  const stub = host.getSpaceDO(ref.uri);
2001
2961
  await requireRepoExists(stub, ref);
2002
2962
  const page = await stub.rpcListBlobs({
2003
- since,
2004
2963
  limit,
2005
2964
  afterCid
2006
2965
  });
@@ -2020,15 +2979,18 @@ function createSpaceRoutes(host) {
2020
2979
  if (auth instanceof Response) return auth;
2021
2980
  const cid = c.req.query("cid");
2022
2981
  requireString(cid, "cid");
2982
+ const stub = host.getSpaceDO(ref.uri);
2983
+ await requireRepoExists(stub, ref);
2984
+ if (!await stub.rpcHasSpaceBlob(cid)) throw new SpaceError("BlobNotFound", `Blob not found: ${cid}`);
2023
2985
  if (!host.blobs) return c.json({
2024
2986
  error: "ServiceUnavailable",
2025
2987
  message: "Blob storage is not configured"
2026
2988
  }, 503);
2027
- const stub = host.getSpaceDO(ref.uri);
2028
- await requireRepoExists(stub, ref);
2029
- if (!await stub.rpcHasSpaceBlob(cid)) throw new SpaceError("BlobNotFound", `Blob not found: ${cid}`);
2030
2989
  const key = spaceBlobKey(host.operatorDid, await spaceId(ref.uri), cid);
2031
- const blob = await host.blobs.get(key);
2990
+ let blob = await host.blobs.get(key);
2991
+ if (!blob) {
2992
+ if (await promoteStagedBlobToSpace(host.blobs, host.operatorDid, ref.uri, cid)) blob = await host.blobs.get(key);
2993
+ }
2032
2994
  if (!blob) throw new SpaceError("BlobNotFound", `Blob not found: ${cid}`);
2033
2995
  return new Response(blob.body, {
2034
2996
  status: 200,
@@ -2036,7 +2998,7 @@ function createSpaceRoutes(host) {
2036
2998
  "Content-Type": blob.httpMetadata?.contentType ?? "application/octet-stream",
2037
2999
  "Content-Length": blob.size.toString(),
2038
3000
  "Cache-Control": "private, no-store",
2039
- Vary: "Authorization, DPoP",
3001
+ Vary: "Authorization",
2040
3002
  "X-Content-Type-Options": "nosniff",
2041
3003
  "Content-Disposition": `attachment; filename="${cid}"`,
2042
3004
  "Content-Security-Policy": "default-src 'none'; sandbox"
@@ -2046,204 +3008,161 @@ function createSpaceRoutes(host) {
2046
3008
  return errorResponse(c, err);
2047
3009
  }
2048
3010
  });
2049
- app.post("/xrpc/com.atproto.space.getSpaceCredential", async (c) => {
3011
+ app.post("/xrpc/com.atproto.space.authorizeSpaceSync", async (c) => {
2050
3012
  try {
2051
3013
  const body = await c.req.json();
2052
3014
  const ref = requireSpaceUri(body.space);
2053
- assertSpaceHost(ref);
2054
- const authHeader = c.req.header("Authorization");
2055
- if (!authHeader?.startsWith("Bearer ")) throw new SpaceError("InvalidDelegationToken", "Expected a Bearer delegation token");
3015
+ requireString(body.credentialKey, "credentialKey");
3016
+ if (!isP256DidKey(body.credentialKey)) throw new SpaceError("InvalidRequest", "credentialKey must be a P-256 did:key");
3017
+ const notify = body.notify === void 0 ? void 0 : parseNotify(body.notify);
3018
+ await assertActiveSpaceHost(ref);
2056
3019
  const stub = host.getSpaceDO(ref.uri);
2057
- const delegation = await verifyDelegationAuth(authHeader.slice(7), ref, verifyOpts(c, stub));
2058
- const { meta, config } = await stub.rpcGetAuthorityState();
3020
+ const { meta, policy } = await stub.rpcGetAuthorityState();
2059
3021
  if (meta?.deletedAt) throw new SpaceError("SpaceDeleted", `Space deleted: ${ref.uri}`);
2060
- if (!meta || !config) throw new SpaceError("SpaceNotFound", `Space not found: ${ref.uri}`);
3022
+ let repo;
3023
+ if (body.delegationToken) ({userDid: repo} = await verifyDelegationToken(body.delegationToken, ref, {
3024
+ getSigningKey: host.getSigningKey,
3025
+ checkReplay: (kind, key, exp) => stub.rpcCheckReplay(kind, key, exp)
3026
+ }));
2061
3027
  let clientId;
2062
- if (config.appAccess.kind === "allowList") {
2063
- if (!body.clientAttestation) throw new SpaceError("AppNotAuthorized", "This space requires a client attestation");
2064
- clientId = await verifyClientAttestation(body.clientAttestation, {
2065
- expectedAud: spaceHostAud(ref.authority),
2066
- allowedClientIds: config.appAccess.allowed,
2067
- checkReplay: replayChecker(stub),
2068
- fetch: host.outboundFetch
2069
- });
2070
- if (!config.appAccess.allowed.includes(clientId)) throw new SpaceError("AppNotAuthorized", "App is not authorized for this space");
3028
+ if (body.clientAttestation) clientId = await verifyClientAttestation(body.clientAttestation, {
3029
+ expectedAud: spaceHostAud$1(ref.authority),
3030
+ allowedClientIds: policy?.$type === MEMBERSPACE_POLICY ? policy.allowedApps : void 0,
3031
+ checkReplay: (kind, key, exp) => stub.rpcCheckReplay(kind, key, exp),
3032
+ fetch: host.outboundFetch
3033
+ });
3034
+ if (!meta || !policy) throw new SpaceError("SpaceNotFound", `Space not found: ${ref.uri}`);
3035
+ try {
3036
+ if (!await authorizeRepo({
3037
+ policy,
3038
+ ref,
3039
+ repo,
3040
+ access: "read",
3041
+ clientId,
3042
+ stub
3043
+ })) throw new SpaceError("SpaceNotFound", `Space not found: ${ref.uri}`);
3044
+ if (!isAppAuthorized(policy, clientId)) throw new SpaceError("AppNotAuthorized", "Application not authorized for this space");
3045
+ } catch (err) {
3046
+ if (notify && parseSpaceErrorCode(err)?.code !== "UpstreamFailure") await stub.rpcRemoveNotifyRegistration(notify);
3047
+ throw err;
2071
3048
  }
2072
- if (!await authorizeUser(config, ref, delegation.userDid, clientId, stub)) throw new SpaceError("UserNotAuthorized", "User is not authorized for this space");
2073
- const keypair = await host.getKeypair();
2074
- const credential = await createSpaceToken("credential", {
3049
+ if (notify && !await stub.rpcGetNotifyRegistration(notify)) await confirmRegistration(ref, notify);
3050
+ const credential = await createSpaceCredential({
2075
3051
  iss: host.operatorDid,
2076
3052
  sub: ref.uri,
2077
- dpopJkt: delegation.dpopJkt
2078
- }, keypair);
2079
- return c.json({ credential });
3053
+ keyId: body.credentialKey,
3054
+ keypair: await host.getKeypair()
3055
+ });
3056
+ if (notify) {
3057
+ const { exp } = parseSpaceToken("credential", credential).payload;
3058
+ await stub.rpcPutNotifyRegistration(notify, exp * 1e3);
3059
+ }
3060
+ const spaceRev = await stub.rpcGetSpaceRev();
3061
+ return c.json({
3062
+ credential,
3063
+ ...spaceRev ? { spaceRev } : {}
3064
+ });
2080
3065
  } catch (err) {
2081
3066
  return errorResponse(c, err);
2082
3067
  }
2083
3068
  });
2084
- app.get("/xrpc/com.atproto.space.listRepos", async (c) => {
3069
+ app.get("/xrpc/com.atproto.space.listWriters", async (c) => {
2085
3070
  try {
2086
3071
  const ref = requireSpaceUri(c.req.query("space"));
2087
- assertSpaceHost(ref);
2088
- const authHeader = c.req.header("Authorization");
2089
- if (!isSpaceCredentialAuth(authHeader)) throw new SpaceError("InvalidCredential", "listRepos requires a space credential");
3072
+ await credentialAuth(c, ref);
3073
+ await assertActiveSpaceHost(ref);
2090
3074
  const stub = host.getSpaceDO(ref.uri);
2091
- await verifySpaceCredentialAuth(authHeader.slice(5), ref, verifyOpts(c, stub));
2092
- const limit = clampLimit(c.req.query("limit"), 100, 1e3);
2093
- const page = await stub.rpcListWriters({
3075
+ await requirePolicy(stub, ref);
3076
+ const limit = clampLimit(c.req.query("limit"), 500, 1e3);
3077
+ const writers = await stub.rpcListWriters({
2094
3078
  limit,
2095
- afterDid: c.req.query("cursor")
3079
+ cursor: c.req.query("cursor") || void 0
2096
3080
  });
2097
- const last = page.repos[page.repos.length - 1];
3081
+ const last = writers[writers.length - 1];
2098
3082
  return c.json({
2099
- repos: page.repos.map((repo) => ({
2100
- did: repo.did,
2101
- rev: repo.rev,
2102
- hash: bytesToJson(new Uint8Array(repo.hash))
2103
- })),
2104
- ...page.hasMore && last ? { cursor: last.did } : {}
3083
+ repos: writers.map((writer) => writer.removed ? {
3084
+ $type: "com.atproto.space.defs#repoRemoved",
3085
+ repo: writer.did,
3086
+ spaceRev: writer.spaceRev
3087
+ } : {
3088
+ $type: "com.atproto.space.defs#repoWrite",
3089
+ repo: writer.did,
3090
+ repoRev: writer.repoRev,
3091
+ data: bytesToJson(new Uint8Array(writer.data)),
3092
+ spaceRev: writer.spaceRev
3093
+ }),
3094
+ ...last ? { cursor: last.spaceRev } : {}
2105
3095
  });
2106
3096
  } catch (err) {
2107
3097
  return errorResponse(c, err);
2108
3098
  }
2109
3099
  });
2110
- app.post("/xrpc/com.atproto.space.registerNotify", async (c) => {
2111
- try {
2112
- const body = await c.req.json();
2113
- const ref = requireSpaceUri(body.space);
2114
- assertSpaceHost(ref);
2115
- requireString(body.service, "service");
2116
- const authHeader = c.req.header("Authorization");
2117
- if (!isSpaceCredentialAuth(authHeader)) throw new SpaceError("InvalidCredential", "registerNotify requires a space credential");
2118
- const stub = host.getSpaceDO(ref.uri);
2119
- await verifySpaceCredentialAuth(authHeader.slice(5), ref, verifyOpts(c, stub));
2120
- const endpoint = await host.resolveServiceEndpoint(body.service);
2121
- if (!endpoint) throw new SpaceError("ServiceNotResolvable", `Could not resolve service: ${body.service}`);
2122
- const result = await stub.rpcRegisterNotify(body.service, endpoint);
2123
- return c.json({ expiresAt: result.expiresAt });
2124
- } catch (err) {
2125
- return errorResponse(c, err);
2126
- }
2127
- });
2128
- app.post("/xrpc/com.atproto.space.unregisterNotify", async (c) => {
3100
+ app.post("/xrpc/com.atproto.space.notifyRepoUpdate", async (c) => {
2129
3101
  try {
2130
3102
  const body = await c.req.json();
2131
3103
  const ref = requireSpaceUri(body.space);
3104
+ requireString(body.repo, "repo");
3105
+ requireString(body.repoRev, "repoRev");
3106
+ if (typeof body.data?.$bytes !== "string") throw new SpaceError("InvalidRequest", "Missing data bytes");
3107
+ const serviceAuth = await requireServiceAuth(c, NOTIFY_REPO_UPDATE_LXM);
3108
+ if (serviceAuth instanceof Response) return serviceAuth;
3109
+ if (serviceAuth.iss !== body.repo) throw new SpaceError("Forbidden", "notifyRepoUpdate iss does not match the repo");
3110
+ if (serviceAuth.aud !== ref.authority && serviceAuth.aud !== spaceHostAud$1(ref.authority)) throw new SpaceError("Forbidden", "notifyRepoUpdate aud does not match the space authority");
2132
3111
  assertSpaceHost(ref);
2133
- requireString(body.service, "service");
2134
- const authHeader = c.req.header("Authorization");
2135
- if (!isSpaceCredentialAuth(authHeader)) throw new SpaceError("InvalidCredential", "unregisterNotify requires a space credential");
3112
+ let revMs;
3113
+ try {
3114
+ revMs = tidTimestampMs(body.repoRev);
3115
+ } catch {
3116
+ throw new SpaceError("InvalidRequest", "repoRev must be a TID");
3117
+ }
3118
+ if (revMs > Date.now() + MAX_REV_CLOCK_SKEW_MS) throw new SpaceError("FutureRev", "Repo revision is in the future");
2136
3119
  const stub = host.getSpaceDO(ref.uri);
2137
- await verifySpaceCredentialAuth(authHeader.slice(5), ref, verifyOpts(c, stub));
2138
- await stub.rpcUnregisterNotify(body.service);
3120
+ if (!await authorizeRepo({
3121
+ policy: await requirePolicy(stub, ref),
3122
+ ref,
3123
+ repo: body.repo,
3124
+ access: "write",
3125
+ stub
3126
+ })) throw new SpaceError("Forbidden", "Repo is not authorized to write to the space");
3127
+ await stub.rpcRecordWriter(body.repo, body.repoRev, fromBase64(body.data.$bytes));
2139
3128
  return c.json({});
2140
3129
  } catch (err) {
2141
3130
  return errorResponse(c, err);
2142
3131
  }
2143
3132
  });
2144
- app.post("/xrpc/com.atproto.space.notifyWrite", async (c) => {
3133
+ app.post("/xrpc/com.atproto.space.notifyCredentialsRevoked", async (c) => {
2145
3134
  try {
2146
3135
  const body = await c.req.json();
2147
3136
  const ref = requireSpaceUri(body.space);
2148
- assertSpaceHost(ref);
2149
- requireString(body.repo, "repo");
2150
- requireString(body.rev, "rev");
2151
- if (typeof body.hash?.$bytes !== "string") throw new SpaceError("InvalidRequest", "Missing hash bytes");
2152
- const authHeader = c.req.header("Authorization");
2153
- if (!authHeader?.startsWith("Bearer ")) return c.json({
2154
- error: "AuthenticationRequired",
2155
- message: "Service auth required"
2156
- }, 401);
2157
- const serviceAuth = await host.verifyServiceJwt(authHeader.slice(7), NOTIFY_WRITE_LXM);
2158
- if (serviceAuth.iss !== body.repo) return c.json({
2159
- error: "Forbidden",
2160
- message: "notifyWrite iss does not match claimed writer"
2161
- }, 403);
2162
- if (serviceAuth.aud !== host.operatorDid) return c.json({
2163
- error: "Forbidden",
2164
- message: "notifyWrite aud does not match the space authority"
2165
- }, 403);
2166
- const stub = host.getSpaceDO(ref.uri);
2167
- const { meta, config } = await stub.rpcGetAuthorityState();
2168
- if (!meta || meta.deletedAt || !config) return c.json({});
2169
- if (!await authorizeUser(config, ref, body.repo, void 0, stub)) return c.json({
2170
- error: "Forbidden",
2171
- message: "notifyWrite writer is not authorized"
2172
- }, 403);
2173
- const hash = fromBase64(body.hash.$bytes);
2174
- const { advanced } = await stub.rpcRecordWriter(body.repo, body.rev, hash);
2175
- if (!advanced) return c.json({});
2176
- const registrations = await stub.rpcGetActiveRegistrations();
2177
- const senderDid = body.repo;
2178
- const targets = registrations.filter((registration) => registration.service.split("#")[0] !== senderDid);
2179
- if (targets.length > 0) {
2180
- const notifyBody = {
2181
- space: ref.uri,
2182
- repo: body.repo,
2183
- rev: body.rev,
2184
- hash: body.hash
2185
- };
2186
- await stub.rpcEnqueueNotify(targets.map((registration) => ({
2187
- service: registration.service,
2188
- endpoint: registration.endpoint,
2189
- lxm: NOTIFY_WRITE_LXM,
2190
- body: notifyBody
2191
- })));
2192
- }
3137
+ const credentials = body.credentials;
3138
+ if (!Array.isArray(credentials) || credentials.length < 1 || credentials.length > 100 || credentials.some((jti) => typeof jti !== "string" || jti.length === 0)) throw new SpaceError("InvalidRequest", "credentials must be 1 to 100 credential jti strings");
3139
+ const serviceAuth = await requireServiceAuth(c, CREDENTIALS_REVOKED_LXM);
3140
+ if (serviceAuth instanceof Response) return serviceAuth;
3141
+ if (serviceAuth.iss !== ref.authority) throw new SpaceError("Forbidden", "Revocation issuer is not the space authority");
3142
+ if (serviceAuth.aud !== host.operatorDid) throw new SpaceError("Forbidden", "Revocation audience does not match a repo hosted here");
3143
+ await host.getSpaceDO(ref.uri).rpcRevokeCredentials(credentials, Math.floor(Date.now() / 1e3) + REVOCATION_TTL_SEC);
2193
3144
  return c.json({});
2194
3145
  } catch (err) {
2195
3146
  return errorResponse(c, err);
2196
3147
  }
2197
3148
  });
2198
- app.post("/xrpc/com.atproto.space.notifySpaceDeleted", async (c) => {
2199
- try {
2200
- const ref = requireSpaceUri((await c.req.json()).space);
2201
- const authHeader = c.req.header("Authorization");
2202
- if (!authHeader?.startsWith("Bearer ")) return c.json({
2203
- error: "AuthenticationRequired",
2204
- message: "Service auth required"
2205
- }, 401);
2206
- const serviceAuth = await host.verifyServiceJwt(authHeader.slice(7), SPACE_DELETED_LXM);
2207
- if (serviceAuth.iss !== ref.authority) return c.json({
2208
- error: "Forbidden",
2209
- message: "notifySpaceDeleted iss is not the space authority"
2210
- }, 403);
2211
- if (serviceAuth.aud !== host.operatorDid && !serviceAuth.aud.startsWith(`${host.operatorDid}#`)) return c.json({
2212
- error: "Forbidden",
2213
- message: "notifySpaceDeleted aud does not match this service"
2214
- }, 403);
2215
- if (ref.authority === host.operatorDid) return c.json({});
2216
- const stub = host.getSpaceDO(ref.uri);
2217
- const meta = await stub.rpcGetMeta();
2218
- if (meta && !meta.deletedAt) {
2219
- await stub.rpcDeleteSpace();
2220
- await host.getIndexDO().rpcMarkDeleted(ref.uri);
2221
- if (host.blobs) waitUntil(c, deleteR2Prefix(host.blobs, spaceBlobPrefix(host.operatorDid, await spaceId(ref.uri))));
2222
- }
2223
- return c.json({});
2224
- } catch (err) {
2225
- return errorResponse(c, err);
2226
- }
2227
- });
2228
- app.post("/xrpc/com.atproto.simplespace.createSpace", async (c) => {
3149
+ app.post("/xrpc/com.atproto.space.createSpace", async (c) => {
2229
3150
  try {
2230
3151
  const body = await c.req.json();
2231
- requireString(body.type, "type");
3152
+ requireString(body.spaceType, "spaceType");
2232
3153
  const skey = body.skey ?? now();
2233
- const session = await sessionAuth(c);
3154
+ const ref = requireSpaceUri(formatSpaceUri(host.operatorDid, body.spaceType, skey));
3155
+ const session = await host.authenticate(c);
2234
3156
  if (session instanceof Response) return session;
2235
3157
  const scopeError = assertScope(c, session, {
2236
- type: body.type,
3158
+ type: ref.type,
2237
3159
  authority: host.operatorDid,
2238
- skey,
3160
+ skey: ref.skey,
2239
3161
  manage: "create"
2240
3162
  });
2241
3163
  if (scopeError) return scopeError;
2242
- const config = {
2243
- policy: parsePolicy(body.policy),
2244
- appAccess: parseAppAccess(body.appAccess)
2245
- };
2246
- const ref = requireSpaceUri(`at://${host.operatorDid}/space/${body.type}/${skey}`);
3164
+ await assertActiveSpaceHost(ref);
3165
+ const policy = normalizePolicy(body.policy);
2247
3166
  const index = host.getIndexDO();
2248
3167
  await index.rpcRegister({
2249
3168
  uri: ref.uri,
@@ -2252,27 +3171,28 @@ function createSpaceRoutes(host) {
2252
3171
  skey: ref.skey,
2253
3172
  isAuthority: true
2254
3173
  });
2255
- await host.getSpaceDO(ref.uri).rpcInit({
3174
+ const stub = host.getSpaceDO(ref.uri);
3175
+ const commit = await stub.rpcInit({
2256
3176
  uri: ref.uri,
2257
3177
  authority: ref.authority,
2258
3178
  type: ref.type,
2259
3179
  skey: ref.skey,
2260
3180
  isAuthority: true,
2261
- config
3181
+ policy
2262
3182
  });
2263
3183
  await index.rpcActivate(ref.uri);
2264
- return c.json({ uri: ref.uri });
3184
+ afterConfigCommit(c, ref, stub, commit);
3185
+ return c.json({ space: ref.uri });
2265
3186
  } catch (err) {
2266
3187
  return errorResponse(c, err);
2267
3188
  }
2268
3189
  });
2269
- app.post("/xrpc/com.atproto.simplespace.updateSpace", async (c) => {
3190
+ app.post("/xrpc/com.atproto.space.updateSpace", async (c) => {
2270
3191
  try {
2271
3192
  const body = await c.req.json();
2272
3193
  const ref = requireSpaceUri(body.space);
2273
- const session = await sessionAuth(c);
3194
+ const session = await host.authenticate(c);
2274
3195
  if (session instanceof Response) return session;
2275
- assertOwner(ref, session);
2276
3196
  const scopeError = assertScope(c, session, {
2277
3197
  type: ref.type,
2278
3198
  authority: ref.authority,
@@ -2280,21 +3200,21 @@ function createSpaceRoutes(host) {
2280
3200
  manage: "update"
2281
3201
  });
2282
3202
  if (scopeError) return scopeError;
2283
- await host.getSpaceDO(ref.uri).rpcUpdateConfig({
2284
- ...body.policy !== void 0 ? { policy: parsePolicy(body.policy) } : {},
2285
- ...body.appAccess !== void 0 ? { appAccess: parseAppAccess(body.appAccess) } : {}
2286
- });
3203
+ assertOwner(ref, session);
3204
+ await assertActiveSpaceHost(ref);
3205
+ const policy = normalizePolicy(body.policy);
3206
+ const stub = host.getSpaceDO(ref.uri);
3207
+ afterConfigCommit(c, ref, stub, await stub.rpcUpdatePolicy(policy));
2287
3208
  return c.json({});
2288
3209
  } catch (err) {
2289
3210
  return errorResponse(c, err);
2290
3211
  }
2291
3212
  });
2292
- app.post("/xrpc/com.atproto.simplespace.deleteSpace", async (c) => {
3213
+ app.post("/xrpc/com.atproto.space.deleteSpace", async (c) => {
2293
3214
  try {
2294
3215
  const ref = requireSpaceUri((await c.req.json()).space);
2295
- const session = await sessionAuth(c);
3216
+ const session = await host.authenticate(c);
2296
3217
  if (session instanceof Response) return session;
2297
- assertOwner(ref, session);
2298
3218
  const scopeError = assertScope(c, session, {
2299
3219
  type: ref.type,
2300
3220
  authority: ref.authority,
@@ -2302,35 +3222,45 @@ function createSpaceRoutes(host) {
2302
3222
  manage: "delete"
2303
3223
  });
2304
3224
  if (scopeError) return scopeError;
2305
- const stub = host.getSpaceDO(ref.uri);
2306
- const { registrations } = await stub.rpcDeleteSpace();
3225
+ assertOwner(ref, session);
3226
+ await assertActiveSpaceHost(ref);
3227
+ await host.getSpaceDO(ref.uri).rpcDeleteSpace();
2307
3228
  await host.getIndexDO().rpcMarkDeleted(ref.uri);
2308
- if (registrations.length > 0) await stub.rpcEnqueueNotify(registrations.map((registration) => ({
2309
- service: registration.service,
2310
- endpoint: registration.endpoint,
2311
- lxm: SPACE_DELETED_LXM,
2312
- body: { space: ref.uri }
2313
- })));
2314
3229
  if (host.blobs) waitUntil(c, deleteR2Prefix(host.blobs, spaceBlobPrefix(host.operatorDid, await spaceId(ref.uri))));
2315
3230
  return c.json({});
2316
3231
  } catch (err) {
2317
3232
  return errorResponse(c, err);
2318
3233
  }
2319
3234
  });
2320
- app.post("/xrpc/com.atproto.simplespace.addMember", async (c) => {
2321
- return memberChange(c, "add");
2322
- });
2323
- app.post("/xrpc/com.atproto.simplespace.removeMember", async (c) => {
2324
- return memberChange(c, "remove");
3235
+ app.get("/xrpc/com.atproto.space.getSpace", async (c) => {
3236
+ try {
3237
+ const ref = requireSpaceUri(c.req.query("space"));
3238
+ const session = await host.authenticate(c);
3239
+ if (session instanceof Response) return session;
3240
+ const scopeError = assertScope(c, session, {
3241
+ type: ref.type,
3242
+ authority: ref.authority,
3243
+ skey: ref.skey,
3244
+ action: "read_self"
3245
+ });
3246
+ if (scopeError) return scopeError;
3247
+ assertOwner(ref, session);
3248
+ const policy = await requirePolicy(host.getSpaceDO(ref.uri), ref);
3249
+ return c.json({
3250
+ space: ref.uri,
3251
+ policy
3252
+ });
3253
+ } catch (err) {
3254
+ return errorResponse(c, err);
3255
+ }
2325
3256
  });
2326
- async function memberChange(c, op) {
3257
+ app.post("/xrpc/com.atproto.space.removeWriter", async (c) => {
2327
3258
  try {
2328
3259
  const body = await c.req.json();
2329
3260
  const ref = requireSpaceUri(body.space);
2330
- requireString(body.did, "did");
2331
- const session = await sessionAuth(c);
3261
+ requireDid(body.repo, "repo");
3262
+ const session = await host.authenticate(c);
2332
3263
  if (session instanceof Response) return session;
2333
- assertOwner(ref, session);
2334
3264
  const scopeError = assertScope(c, session, {
2335
3265
  type: ref.type,
2336
3266
  authority: ref.authority,
@@ -2338,80 +3268,268 @@ function createSpaceRoutes(host) {
2338
3268
  manage: "update"
2339
3269
  });
2340
3270
  if (scopeError) return scopeError;
2341
- const stub = host.getSpaceDO(ref.uri);
2342
- await requireConfigured(stub, ref);
2343
- if (op === "add") await stub.rpcAddMember(body.did);
2344
- else await stub.rpcRemoveMember(body.did);
3271
+ assertOwner(ref, session);
3272
+ await assertActiveSpaceHost(ref);
3273
+ await host.getSpaceDO(ref.uri).rpcRemoveWriter(body.repo);
2345
3274
  return c.json({});
2346
3275
  } catch (err) {
2347
3276
  return errorResponse(c, err);
2348
3277
  }
2349
- }
2350
- app.get("/xrpc/com.atproto.simplespace.getSpace", async (c) => {
3278
+ });
3279
+ app.get("/xrpc/com.atproto.space.exportSpaceMeta", async (c) => {
2351
3280
  try {
2352
3281
  const ref = requireSpaceUri(c.req.query("space"));
2353
- assertSpaceHost(ref);
2354
- const stub = host.getSpaceDO(ref.uri);
2355
- const authHeader = c.req.header("Authorization");
2356
- if (isSpaceCredentialAuth(authHeader)) await verifySpaceCredentialAuth(authHeader.slice(5), ref, verifyOpts(c, stub));
2357
- else {
2358
- const session = await sessionAuth(c);
2359
- if (session instanceof Response) return session;
3282
+ const session = await host.authenticate(c);
3283
+ if (session instanceof Response) return session;
3284
+ const scopeError = assertScope(c, session, {
3285
+ type: ref.type,
3286
+ authority: ref.authority,
3287
+ skey: ref.skey,
3288
+ action: "read_self"
3289
+ });
3290
+ if (scopeError) return scopeError;
3291
+ assertOwner(ref, session);
3292
+ const exported = await host.getSpaceDO(ref.uri).rpcExportMeta();
3293
+ const star = writeSpaceMetaStar({
3294
+ space: ref.uri,
3295
+ policy: exported.policy,
3296
+ policyState: exported.members.map((member) => ({
3297
+ key: `${MEMBER_COLLECTION}/${didToRecordKey(member.did)}`,
3298
+ value: {
3299
+ $type: MEMBER_COLLECTION,
3300
+ read: member.read,
3301
+ write: member.write
3302
+ }
3303
+ })),
3304
+ writers: exported.writers.map((writer) => ({
3305
+ did: writer.did,
3306
+ repoRev: writer.repoRev,
3307
+ data: new Uint8Array(writer.data),
3308
+ spaceRev: writer.spaceRev
3309
+ }))
3310
+ });
3311
+ return c.body(asyncIterableToStream(star), 200, { "Content-Type": STAR_CONTENT_TYPE });
3312
+ } catch (err) {
3313
+ return errorResponse(c, err);
3314
+ }
3315
+ });
3316
+ app.post("/xrpc/com.atproto.space.importSpaceMeta", async (c) => {
3317
+ try {
3318
+ const session = await host.authenticate(c);
3319
+ if (session instanceof Response) return session;
3320
+ const bytes = await readBody(c);
3321
+ let archive;
3322
+ try {
3323
+ archive = await readSpaceMetaStar([bytes]);
3324
+ } catch (err) {
3325
+ throw invalidArchive(err, "InvalidSpaceMeta");
3326
+ }
3327
+ const ref = requireSpaceUri(archive.space);
3328
+ for (const manage of ["create", "update"]) {
2360
3329
  const scopeError = assertScope(c, session, {
2361
3330
  type: ref.type,
2362
3331
  authority: ref.authority,
2363
3332
  skey: ref.skey,
2364
- action: "read_self"
3333
+ manage
2365
3334
  });
2366
3335
  if (scopeError) return scopeError;
2367
3336
  }
2368
- const config = await requireConfigured(stub, ref);
2369
- return c.json({
3337
+ if (ref.authority !== session.did || ref.authority !== host.operatorDid) throw new SpaceError("NotAuthorized", "Not the space authority");
3338
+ const policy = normalizePolicy(archive.policy);
3339
+ const members = parsePolicyState(policy, archive.policyState);
3340
+ const index = host.getIndexDO();
3341
+ await index.rpcRegister({
3342
+ uri: ref.uri,
3343
+ authority: ref.authority,
3344
+ type: ref.type,
3345
+ skey: ref.skey,
3346
+ isAuthority: true
3347
+ });
3348
+ await host.getSpaceDO(ref.uri).rpcImportMeta({
2370
3349
  uri: ref.uri,
2371
- policy: policyToJson(config.policy),
2372
- appAccess: appAccessToJson(config.appAccess)
3350
+ authority: ref.authority,
3351
+ type: ref.type,
3352
+ skey: ref.skey,
3353
+ policy,
3354
+ members,
3355
+ writers: archive.writers.map((writer) => ({
3356
+ did: writer.did,
3357
+ repoRev: writer.repoRev,
3358
+ data: writer.data,
3359
+ spaceRev: writer.spaceRev,
3360
+ removed: false
3361
+ }))
2373
3362
  });
3363
+ await index.rpcActivate(ref.uri);
3364
+ return c.json({});
2374
3365
  } catch (err) {
2375
3366
  return errorResponse(c, err);
2376
3367
  }
2377
3368
  });
2378
- app.get("/xrpc/com.atproto.simplespace.listMembers", async (c) => {
3369
+ app.get("/xrpc/com.atproto.space.listSpaces", async (c) => {
2379
3370
  try {
2380
- const ref = requireSpaceUri(c.req.query("space"));
2381
- const session = await sessionAuth(c);
3371
+ const session = await host.authenticate(c);
3372
+ if (session instanceof Response) return session;
3373
+ const type = c.req.query("spaceType") || void 0;
3374
+ const authority = c.req.query("spaceDid") || void 0;
3375
+ const scopeError = assertScope(c, session, {
3376
+ type: type ?? "*",
3377
+ authority: authority ?? "*",
3378
+ skey: "*",
3379
+ action: "read_self"
3380
+ });
3381
+ if (scopeError) return scopeError;
3382
+ const limit = clampLimit(c.req.query("limit"), 50, 100);
3383
+ const cursor = c.req.query("cursor") || void 0;
3384
+ if (cursor && !parseSpaceUri(cursor)) throw new SpaceError("InvalidCursor", `Malformed cursor: ${cursor}`);
3385
+ const page = await host.getIndexDO().rpcList({
3386
+ type,
3387
+ authority,
3388
+ state: "active",
3389
+ limit,
3390
+ afterUri: cursor
3391
+ });
3392
+ const spaces = await Promise.all(page.spaces.map(async (space) => {
3393
+ const view = await host.getSpaceDO(space.uri).rpcGetSpaceView();
3394
+ return {
3395
+ space: space.uri,
3396
+ ...view?.repoRev ? { repoRev: view.repoRev } : {},
3397
+ ...view?.data ? { data: bytesToJson(new Uint8Array(view.data)) } : {},
3398
+ ...view?.spaceRev ? { spaceRev: view.spaceRev } : {}
3399
+ };
3400
+ }));
3401
+ const last = page.spaces[page.spaces.length - 1];
3402
+ return c.json({
3403
+ spaces,
3404
+ ...page.hasMore && last ? { cursor: last.uri } : {}
3405
+ });
3406
+ } catch (err) {
3407
+ return errorResponse(c, err);
3408
+ }
3409
+ });
3410
+ app.post("/xrpc/com.atproto.memberspace.putMembers", async (c) => {
3411
+ try {
3412
+ const body = await c.req.json();
3413
+ const ref = requireSpaceUri(body.space);
3414
+ const members = parseMemberBatch(body.members);
3415
+ const session = await host.authenticate(c);
2382
3416
  if (session instanceof Response) return session;
3417
+ const scopeError = assertScope(c, session, {
3418
+ type: ref.type,
3419
+ authority: ref.authority,
3420
+ skey: ref.skey,
3421
+ manage: "update"
3422
+ });
3423
+ if (scopeError) return scopeError;
2383
3424
  assertOwner(ref, session);
3425
+ await assertActiveSpaceHost(ref);
3426
+ const stub = host.getSpaceDO(ref.uri);
3427
+ afterConfigCommit(c, ref, stub, await stub.rpcPutMembers(members));
3428
+ return c.json({});
3429
+ } catch (err) {
3430
+ return errorResponse(c, err);
3431
+ }
3432
+ });
3433
+ app.post("/xrpc/com.atproto.memberspace.removeMembers", async (c) => {
3434
+ try {
3435
+ const body = await c.req.json();
3436
+ const ref = requireSpaceUri(body.space);
3437
+ const dids = body.dids;
3438
+ if (!Array.isArray(dids) || dids.length > MAX_MEMBER_BATCH || dids.some((did) => typeof did !== "string" || !did.startsWith("did:"))) throw new SpaceError("InvalidRequest", `dids must be an array of at most ${MAX_MEMBER_BATCH} DIDs`);
3439
+ const session = await host.authenticate(c);
3440
+ if (session instanceof Response) return session;
2384
3441
  const scopeError = assertScope(c, session, {
2385
3442
  type: ref.type,
2386
3443
  authority: ref.authority,
2387
3444
  skey: ref.skey,
2388
- action: "read_self"
3445
+ manage: "update"
2389
3446
  });
2390
3447
  if (scopeError) return scopeError;
3448
+ assertOwner(ref, session);
3449
+ await assertActiveSpaceHost(ref);
2391
3450
  const stub = host.getSpaceDO(ref.uri);
2392
- await requireConfigured(stub, ref);
3451
+ afterConfigCommit(c, ref, stub, await stub.rpcRemoveMembers(dids));
3452
+ return c.json({});
3453
+ } catch (err) {
3454
+ return errorResponse(c, err);
3455
+ }
3456
+ });
3457
+ app.get("/xrpc/com.atproto.memberspace.listMembers", async (c) => {
3458
+ try {
3459
+ const ref = requireSpaceUri(c.req.query("space"));
3460
+ const session = await host.authenticate(c);
3461
+ if (session instanceof Response) return session;
3462
+ const scopeError = assertScope(c, session, {
3463
+ type: ref.type,
3464
+ authority: ref.authority,
3465
+ skey: ref.skey,
3466
+ action: "read_self"
3467
+ });
3468
+ if (scopeError) return scopeError;
3469
+ assertOwner(ref, session);
2393
3470
  const limit = clampLimit(c.req.query("limit"), 100, 1e3);
2394
- const page = await stub.rpcListMembers({
3471
+ const cursor = c.req.query("cursor");
3472
+ if (cursor !== void 0 && !isDid(cursor)) throw new SpaceError("InvalidCursor", `Malformed cursor: ${cursor}`);
3473
+ const page = await host.getSpaceDO(ref.uri).rpcListMembers({
2395
3474
  limit,
2396
- afterDid: c.req.query("cursor")
3475
+ afterDid: cursor
2397
3476
  });
2398
- const last = page.dids[page.dids.length - 1];
3477
+ const last = page.members[page.members.length - 1];
2399
3478
  return c.json({
2400
- members: page.dids.map((did) => ({ did })),
2401
- ...page.hasMore && last ? { cursor: last } : {}
3479
+ members: page.members.map((member) => ({
3480
+ did: member.did,
3481
+ read: member.read,
3482
+ write: member.write
3483
+ })),
3484
+ ...page.hasMore && last ? { cursor: last.did } : {}
2402
3485
  });
2403
3486
  } catch (err) {
2404
3487
  return errorResponse(c, err);
2405
3488
  }
2406
3489
  });
2407
- function assertOwner(ref, session) {
2408
- assertSpaceHost(ref);
2409
- if (session.did !== ref.authority) throw new SpaceError("NotSpaceOwner", "Only the space owner may manage the space");
3490
+ /**
3491
+ * Before registering a webhook, check it asked to be: the endpoint must
3492
+ * recognise the token as one it issued for this space and echo back a
3493
+ * random challenge. The endpoint is the requester's choice, so it is
3494
+ * fetched as untrusted: https only, no redirects, bounded in time.
3495
+ */
3496
+ async function confirmRegistration(ref, notify) {
3497
+ const challenge = crypto.randomUUID();
3498
+ try {
3499
+ const res = await doFetch(`${notify.endpoint.replace(/\/$/, "")}/xrpc/${CONFIRM_REGISTRATION_LXM}`, {
3500
+ method: "POST",
3501
+ headers: { "Content-Type": "application/json" },
3502
+ body: JSON.stringify({
3503
+ space: ref.uri,
3504
+ token: notify.token,
3505
+ challenge
3506
+ }),
3507
+ redirect: "manual",
3508
+ signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS)
3509
+ });
3510
+ if (res.ok) {
3511
+ if ((await res.json()).challenge === challenge) return;
3512
+ }
3513
+ } catch (err) {
3514
+ console.warn(`registration for ${ref.uri} not confirmed:`, err);
3515
+ }
3516
+ throw new SpaceError("RegistrationNotConfirmed", "Notify endpoint did not confirm the registration");
2410
3517
  }
2411
- async function requireConfigured(stub, ref) {
2412
- const { meta, config } = await stub.rpcGetAuthorityState();
2413
- if (!meta || meta.deletedAt || !config) throw new SpaceError("SpaceNotFound", `Space not found: ${ref.uri}`);
2414
- return config;
3518
+ /** Service auth for inbound notifications; a Response on failure. */
3519
+ async function requireServiceAuth(c, lxm) {
3520
+ const authHeader = c.req.header("Authorization");
3521
+ if (!authHeader?.startsWith("Bearer ")) return c.json({
3522
+ error: "AuthenticationRequired",
3523
+ message: "Service auth required"
3524
+ }, 401);
3525
+ try {
3526
+ return await host.verifyServiceJwt(authHeader.slice(7), lxm);
3527
+ } catch (err) {
3528
+ return c.json({
3529
+ error: "AuthenticationRequired",
3530
+ message: err instanceof Error ? err.message : "Invalid service auth"
3531
+ }, 401);
3532
+ }
2415
3533
  }
2416
3534
  /**
2417
3535
  * A repo exists in a space once the operator has written into it (or
@@ -2428,6 +3546,32 @@ function createSpaceRoutes(host) {
2428
3546
  function requireString(value, name) {
2429
3547
  if (typeof value !== "string" || value.length === 0) throw new SpaceError("InvalidRequest", `Missing required parameter: ${name}`);
2430
3548
  }
3549
+ /**
3550
+ * An authorizeSpaceSync `notify`: an https base URL the space host calls
3551
+ * XRPC methods against, and the opaque token that authenticates them.
3552
+ */
3553
+ function parseNotify(input) {
3554
+ const notify = input;
3555
+ const endpoint = notify?.endpoint;
3556
+ const token = notify?.token;
3557
+ if (typeof endpoint !== "string" || typeof token !== "string") throw new SpaceError("InvalidRequest", "notify requires an endpoint and a token");
3558
+ let url;
3559
+ try {
3560
+ url = new URL(endpoint);
3561
+ } catch {
3562
+ throw new SpaceError("InvalidRequest", "notify endpoint must be a URL");
3563
+ }
3564
+ if (url.protocol !== "https:" || url.username || url.password) throw new SpaceError("InvalidRequest", "notify endpoint must be a plain https URL");
3565
+ if (token.length === 0 || token.length > MAX_NOTIFY_TOKEN_LENGTH) throw new SpaceError("InvalidRequest", `notify token must be 1 to ${MAX_NOTIFY_TOKEN_LENGTH} characters`);
3566
+ return {
3567
+ endpoint,
3568
+ token
3569
+ };
3570
+ }
3571
+ function requireDid(value, name) {
3572
+ requireString(value, name);
3573
+ if (!value.startsWith("did:")) throw new SpaceError("InvalidRequest", `${name} must be a DID`);
3574
+ }
2431
3575
  function clampLimit(raw, fallback, max) {
2432
3576
  const parsed = raw ? Number.parseInt(raw, 10) : fallback;
2433
3577
  if (Number.isNaN(parsed) || parsed < 1) return fallback;
@@ -2436,7 +3580,7 @@ function clampLimit(raw, fallback, max) {
2436
3580
  function parseRecordCursor(cursor) {
2437
3581
  if (!cursor) return void 0;
2438
3582
  const slash = cursor.lastIndexOf("/");
2439
- if (slash <= 0 || slash === cursor.length - 1) throw new SpaceError("MalformedCursor", `Malformed cursor: ${cursor}`);
3583
+ if (slash <= 0 || slash === cursor.length - 1) throw new SpaceError("InvalidCursor", `Malformed cursor: ${cursor}`);
2440
3584
  return {
2441
3585
  collection: cursor.slice(0, slash),
2442
3586
  rkey: cursor.slice(slash + 1)
@@ -2446,62 +3590,76 @@ function parseOpsCursor(cursor) {
2446
3590
  if (!cursor) return void 0;
2447
3591
  const slash = cursor.indexOf("/");
2448
3592
  const idx = slash === -1 ? NaN : Number.parseInt(cursor.slice(slash + 1), 10);
2449
- if (slash <= 0 || Number.isNaN(idx)) throw new SpaceError("MalformedCursor", `Malformed cursor: ${cursor}`);
3593
+ if (slash <= 0 || Number.isNaN(idx)) throw new SpaceError("InvalidCursor", `Malformed cursor: ${cursor}`);
2450
3594
  return {
2451
3595
  rev: cursor.slice(0, slash),
2452
3596
  idx
2453
3597
  };
2454
3598
  }
2455
- const POLICY_PREFIX = "com.atproto.simplespace.defs#";
2456
- function parsePolicy(input) {
2457
- const type = input?.$type;
2458
- switch (type) {
2459
- case `${POLICY_PREFIX}publicPolicy`: return { kind: "public" };
2460
- case `${POLICY_PREFIX}memberListPolicy`: return { kind: "member-list" };
2461
- case `${POLICY_PREFIX}managingAppPolicy`: {
2462
- const managingApp = input.managingApp;
2463
- if (typeof managingApp !== "string" || !managingApp.startsWith("did:")) throw new SpaceError("UnsupportedPolicy", "managingApp must be a DID service identifier");
2464
- return {
2465
- kind: "managing-app",
2466
- managingApp
2467
- };
2468
- }
2469
- default: throw new SpaceError("UnsupportedPolicy", `Unsupported policy: ${String(type)}`);
2470
- }
2471
- }
2472
- function policyToJson(policy) {
2473
- switch (policy.kind) {
2474
- case "public": return { $type: `${POLICY_PREFIX}publicPolicy` };
2475
- case "member-list": return { $type: `${POLICY_PREFIX}memberListPolicy` };
2476
- case "managing-app": return {
2477
- $type: `${POLICY_PREFIX}managingAppPolicy`,
2478
- managingApp: policy.managingApp
3599
+ /**
3600
+ * Read the members out of a space meta archive's policy state. A key the
3601
+ * policy doesn't define is refused rather than dropped, since dropping it
3602
+ * would quietly change who has access to the space.
3603
+ */
3604
+ function parsePolicyState(policy, entries) {
3605
+ const prefix = `${MEMBER_COLLECTION}/`;
3606
+ return entries.map(({ key, value }) => {
3607
+ const did = key.startsWith(prefix) ? recordKeyToDid(key.slice(prefix.length)) : void 0;
3608
+ if (policy.$type !== MEMBERSPACE_POLICY || !did?.startsWith("did:")) throw new SpaceError("InvalidRequest", `Unrecognized policy state: ${key}`);
3609
+ if (typeof value.read !== "boolean" || typeof value.write !== "boolean") throw new SpaceError("InvalidRequest", `Invalid member at ${key}`);
3610
+ return {
3611
+ did,
3612
+ read: value.read,
3613
+ write: value.write
2479
3614
  };
2480
- }
3615
+ });
3616
+ }
3617
+ /**
3618
+ * A malformed archive in a request body is the caller's error, reported
3619
+ * under the error name the method declares for it.
3620
+ */
3621
+ function invalidArchive(err, code) {
3622
+ if (parseSpaceErrorCode(err)) return err;
3623
+ return new SpaceError(code, `Invalid archive: ${err instanceof Error ? err.message : String(err)}`);
2481
3624
  }
2482
- function appAccessToJson(appAccess) {
2483
- switch (appAccess.kind) {
2484
- case "open": return { $type: `${POLICY_PREFIX}open` };
2485
- case "allowList": return {
2486
- $type: `${POLICY_PREFIX}allowList`,
2487
- allowed: appAccess.allowed
3625
+ /** A putMembers batch: at most 100 `{did, read, write}` entries. */
3626
+ function parseMemberBatch(input) {
3627
+ if (!Array.isArray(input) || input.length > MAX_MEMBER_BATCH) throw new SpaceError("InvalidRequest", `members must be an array of at most ${MAX_MEMBER_BATCH} entries`);
3628
+ return input.map((entry, i) => {
3629
+ const member = entry;
3630
+ if (typeof member?.did !== "string" || !member.did.startsWith("did:") || typeof member.read !== "boolean" || typeof member.write !== "boolean") throw new SpaceError("InvalidRequest", `members[${i}] must be {did, read, write}`);
3631
+ return {
3632
+ did: member.did,
3633
+ read: member.read,
3634
+ write: member.write
2488
3635
  };
2489
- }
3636
+ });
2490
3637
  }
2491
- function parseAppAccess(input) {
2492
- const type = input?.$type;
2493
- switch (type) {
2494
- case `${POLICY_PREFIX}open`: return { kind: "open" };
2495
- case `${POLICY_PREFIX}allowList`: {
2496
- const allowed = input.allowed;
2497
- if (!Array.isArray(allowed) || allowed.some((entry) => typeof entry !== "string")) throw new SpaceError("UnsupportedAppAccess", "allowList requires an array of client IDs");
2498
- return {
2499
- kind: "allowList",
2500
- allowed
2501
- };
3638
+ async function readBody(c) {
3639
+ if (c.req.header("Content-Type")?.split(";")[0]?.trim() !== STAR_CONTENT_TYPE) throw new SpaceError("InvalidRequest", `Content-Type must be ${STAR_CONTENT_TYPE}`);
3640
+ if (Number.parseInt(c.req.header("Content-Length") ?? "", 10) > MAX_IMPORT_BYTES) throw new SpaceError("InvalidRequest", "Archive is too large");
3641
+ const bytes = new Uint8Array(await c.req.arrayBuffer());
3642
+ if (bytes.length === 0) throw new SpaceError("InvalidRequest", "Empty archive");
3643
+ if (bytes.length > MAX_IMPORT_BYTES) throw new SpaceError("InvalidRequest", "Archive is too large");
3644
+ return bytes;
3645
+ }
3646
+ /** A pull-based stream over an async iterable, cancelling it on abort. */
3647
+ function asyncIterableToStream(iterable) {
3648
+ const iterator = iterable[Symbol.asyncIterator]();
3649
+ return new ReadableStream({
3650
+ async pull(controller) {
3651
+ try {
3652
+ const { value, done } = await iterator.next();
3653
+ if (done) controller.close();
3654
+ else controller.enqueue(value);
3655
+ } catch (err) {
3656
+ controller.error(err);
3657
+ }
3658
+ },
3659
+ async cancel() {
3660
+ await iterator.return?.();
2502
3661
  }
2503
- default: throw new SpaceError("UnsupportedAppAccess", `Unsupported appAccess: ${String(type)}`);
2504
- }
3662
+ });
2505
3663
  }
2506
3664
  async function deleteR2Prefix(bucket, prefix) {
2507
3665
  let cursor;
@@ -2517,5 +3675,33 @@ async function deleteR2Prefix(bucket, prefix) {
2517
3675
  }
2518
3676
 
2519
3677
  //#endregion
2520
- 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 };
3678
+ //#region src/tokens.ts
3679
+ /**
3680
+ * Delegation tokens, minted by the user's PDS for a space hosted anywhere.
3681
+ *
3682
+ * Thin wrappers over `@atproto/space`, so a host gets them without
3683
+ * depending on that package's types directly.
3684
+ */
3685
+ /**
3686
+ * How a space authority is addressed as the space host: its `#atproto_pds`
3687
+ * service entry, the audience of delegation tokens and client attestations.
3688
+ */
3689
+ function spaceHostAud(authority) {
3690
+ return spaceHostAud$1(authority);
3691
+ }
3692
+ /**
3693
+ * Mint a delegation token: the user's PDS vouching, for 60 seconds and one
3694
+ * use, that `iss` wants a credential for `space` from its authority.
3695
+ */
3696
+ function createDelegationToken(params, keypair) {
3697
+ return createDelegationToken$1({
3698
+ iss: params.iss,
3699
+ sub: params.space,
3700
+ aud: spaceHostAud(params.authority),
3701
+ keypair
3702
+ });
3703
+ }
3704
+
3705
+ //#endregion
3706
+ export { MAC_REQUEST_HEADER, MANAGEDSPACE_POLICY, MEMBERSPACE_POLICY, MEMBER_COLLECTION, OPLOG_RETENTION_DAYS, OPLOG_RETENTION_OPS, PERSONALSPACE_POLICY, POLICY_COLLECTION, PUBLISHED_COLLECTIONS, SPACE_AUDIENCE_HEADER, SPACE_CREDENTIAL_SCHEME, SPACE_ERROR_CODES, SPACE_SCHEMA_VERSION, SPACE_URI_PREFIX, SpaceDurableObject, SpaceError, SpaceIndexDurableObject, buildCommit, bytesToJson, commitToJson, createDelegationToken, createServiceJwt, createSpaceRoutes, formatSpaceUri, generateKemKey, isSpaceCredentialAuth, kemDidKey, macExposedHeaders, nextRev, normalizePolicy, parseSpaceErrorCode, parseSpaceUri, prepareRecord, promotePendingSpaceBlob, promoteStagedBlobToSpace, recordBytesToJson, requireSpaceUri, spaceBlobKey, spaceBlobKeyForUri, spaceBlobPrefix, spaceBlobRootPrefix, spaceErrorStatus, spaceHostAud, spaceId, spaceRecordUri, spaceScopeNeededFor, stagedBlobKey, tidCutoff, tidTimestampMs, verifyClientAttestation, verifyDelegationToken, verifySpaceCredentialAuth };
2521
3707
  //# sourceMappingURL=index.js.map