@getcirrus/pds 0.18.0 → 0.19.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
@@ -12,11 +12,13 @@ import { isDid, isHandle, isNsid, isRecordKey, parseResourceUri } from "@atcute/
12
12
  import { AppBskyActorProfile, AppBskyActorStatus, AppBskyFeedGenerator, AppBskyFeedLike, AppBskyFeedPost, AppBskyFeedPostgate, AppBskyFeedRepost, AppBskyFeedThreadgate, AppBskyGraphBlock, AppBskyGraphFollow, AppBskyGraphList, AppBskyGraphListblock, AppBskyGraphListitem, AppBskyGraphStarterpack, AppBskyGraphVerification, AppBskyLabelerService, AppBskyNotificationDeclaration, ChatBskyActorDeclaration } from "@atcute/bluesky";
13
13
  import { ComAtprotoLexiconSchema } from "@atcute/atproto";
14
14
  import { Hono } from "hono";
15
- import { cors } from "hono/cors";
16
- import { SignJWT, base64url, errors, jwtVerify } from "jose";
17
- import { compare, compare as compare$1, hash } from "bcryptjs";
15
+ import { createSpaceToken, spaceHostAud } from "@atproto/space";
16
+ import { SPACE_SCHEMA_VERSION, SpaceDurableObject as SpaceDurableObject$1, SpaceIndexDurableObject as SpaceIndexDurableObject$1, createSpaceRoutes, parseSpaceErrorCode, requireSpaceUri, spaceBlobRootPrefix, spaceErrorStatus } from "@getcirrus/spaces";
18
17
  import { CompositeDidDocumentResolver, PlcDidDocumentResolver, WebDidDocumentResolver } from "@atcute/identity-resolver";
18
+ import { compare, compare as compare$1, hash } from "bcryptjs";
19
19
  import { generateAuthenticationOptions, generateRegistrationOptions, verifyAuthenticationResponse, verifyRegistrationResponse } from "@simplewebauthn/server";
20
+ import { SignJWT, base64url, errors, jwtVerify } from "jose";
21
+ import { cors } from "hono/cors";
20
22
  import { defs, getAtprotoServiceEndpoint } from "@atcute/identity";
21
23
 
22
24
  //#region src/cbor-compat.ts
@@ -410,6 +412,12 @@ var SqliteRepoStorage = class extends ReadableBlockstore {
410
412
  this.sql.exec("INSERT OR REPLACE INTO imported_blobs (cid, size, mimeType) VALUES (?, ?, ?)", cid, size, mimeType);
411
413
  }
412
414
  /**
415
+ * Check if any record references a blob CID.
416
+ */
417
+ isBlobReferenced(cid) {
418
+ return this.sql.exec("SELECT 1 FROM record_blob WHERE blobCid = ? LIMIT 1", cid).toArray().length > 0;
419
+ }
420
+ /**
413
421
  * Check if a blob has been imported.
414
422
  */
415
423
  isBlobImported(cid) {
@@ -1152,6 +1160,54 @@ var Sequencer = class {
1152
1160
  //#endregion
1153
1161
  //#region src/blobs.ts
1154
1162
  /**
1163
+ * R2 key layout for blobs:
1164
+ *
1165
+ * `${did}/staged/${cid}` – uploaded, not yet referenced by any record.
1166
+ * Served by nothing; expired by an R2 lifecycle rule after seven days.
1167
+ * `${did}/${cid}` – referenced by at least one public record.
1168
+ * Served by com.atproto.sync.getBlob.
1169
+ *
1170
+ * Uploads land in `staged/` and are promoted (copied) to their destination
1171
+ * key when a record write first references them. The copy completes before
1172
+ * the commit is applied, so anything reacting to the commit never sees a
1173
+ * 404. Keys never move back: promotion is idempotent and `staged/` copies
1174
+ * are left for the lifecycle rule to reap.
1175
+ */
1176
+ function stagedBlobKey(did, cid) {
1177
+ return `${did}/staged/${cid}`;
1178
+ }
1179
+ function publicBlobKey(did, cid) {
1180
+ return `${did}/${cid}`;
1181
+ }
1182
+ /**
1183
+ * Extract blob CIDs from a record in JSON form (as received from clients),
1184
+ * recursively searching for blob references. Handles both the current
1185
+ * `{ $type: "blob", ref: { $link }, mimeType, size }` shape and the legacy
1186
+ * untyped `{ cid, mimeType }` shape.
1187
+ */
1188
+ function extractJsonBlobCids(value) {
1189
+ const cids = /* @__PURE__ */ new Set();
1190
+ walkForBlobRefs(value, cids);
1191
+ return Array.from(cids);
1192
+ }
1193
+ function walkForBlobRefs(value, out) {
1194
+ if (Array.isArray(value)) {
1195
+ for (const item of value) walkForBlobRefs(item, out);
1196
+ return;
1197
+ }
1198
+ if (value === null || typeof value !== "object") return;
1199
+ const obj = value;
1200
+ if (obj.$type === "blob" && typeof obj.ref === "object" && obj.ref !== null && typeof obj.ref.$link === "string") {
1201
+ out.add(obj.ref.$link);
1202
+ return;
1203
+ }
1204
+ if (obj.$type === void 0 && typeof obj.cid === "string" && typeof obj.mimeType === "string") {
1205
+ out.add(obj.cid);
1206
+ return;
1207
+ }
1208
+ for (const key of Object.keys(obj)) walkForBlobRefs(obj[key], out);
1209
+ }
1210
+ /**
1155
1211
  * BlobStore manages blob storage in R2.
1156
1212
  * Blobs are stored with CID-based keys prefixed by the account's DID.
1157
1213
  */
@@ -1161,12 +1217,14 @@ var BlobStore = class {
1161
1217
  this.did = did;
1162
1218
  }
1163
1219
  /**
1164
- * Upload a blob to R2 and return a BlobRef.
1220
+ * Upload a blob to R2 staging and return a BlobRef.
1221
+ *
1222
+ * The blob is not fetchable until a record write references it, which
1223
+ * promotes it to its serving key.
1165
1224
  */
1166
1225
  async putBlob(bytes, mimeType) {
1167
1226
  const cidStr = toString(await create(CODEC_RAW, bytes));
1168
- const key = `${this.did}/${cidStr}`;
1169
- await this.r2.put(key, bytes, { httpMetadata: { contentType: mimeType } });
1227
+ await this.r2.put(stagedBlobKey(this.did, cidStr), bytes, { httpMetadata: { contentType: mimeType } });
1170
1228
  return {
1171
1229
  $type: "blob",
1172
1230
  ref: { $link: cidStr },
@@ -1175,18 +1233,43 @@ var BlobStore = class {
1175
1233
  };
1176
1234
  }
1177
1235
  /**
1178
- * Retrieve a blob from R2 by CID string.
1236
+ * Promote a staged blob to a destination key with a streaming copy.
1237
+ *
1238
+ * Idempotent: returns early when the destination already exists, so
1239
+ * concurrent writes referencing the same staged blob are safe. A CID
1240
+ * that is neither staged nor at the destination is skipped — records
1241
+ * may reference blobs from before this layout existed, and reference
1242
+ * checking is not this method's job.
1243
+ */
1244
+ async promoteTo(cid, destKey) {
1245
+ if (await this.r2.head(destKey)) return;
1246
+ const staged = await this.r2.get(stagedBlobKey(this.did, cid));
1247
+ if (!staged) return;
1248
+ await this.r2.put(destKey, staged.body, { httpMetadata: staged.httpMetadata });
1249
+ }
1250
+ /**
1251
+ * Promote a staged blob to the public serving key.
1252
+ */
1253
+ async promoteBlob(cid) {
1254
+ await this.promoteTo(cid, publicBlobKey(this.did, cid));
1255
+ }
1256
+ /**
1257
+ * Promote several staged blobs to the public serving key.
1258
+ */
1259
+ async promoteBlobs(cids) {
1260
+ await Promise.all(cids.map((cid) => this.promoteBlob(cid)));
1261
+ }
1262
+ /**
1263
+ * Retrieve a public blob from R2 by CID string.
1179
1264
  */
1180
1265
  async getBlob(cid) {
1181
- const key = `${this.did}/${cid}`;
1182
- return this.r2.get(key);
1266
+ return this.r2.get(publicBlobKey(this.did, cid));
1183
1267
  }
1184
1268
  /**
1185
- * Check if a blob exists in R2.
1269
+ * Check if a blob exists at the public serving key.
1186
1270
  */
1187
1271
  async hasBlob(cid) {
1188
- const key = `${this.did}/${cid}`;
1189
- return await this.r2.head(key) !== null;
1272
+ return await this.r2.head(publicBlobKey(this.did, cid)) !== null;
1190
1273
  }
1191
1274
  };
1192
1275
 
@@ -1947,7 +2030,9 @@ var AccountDurableObject = class extends DurableObject {
1947
2030
  * row needs the DO's SQLite.
1948
2031
  */
1949
2032
  async rpcTrackBlob(cid, size, mimeType) {
1950
- (await this.getStorage()).trackImportedBlob(cid, size, mimeType);
2033
+ const storage = await this.getStorage();
2034
+ storage.trackImportedBlob(cid, size, mimeType);
2035
+ return { referenced: storage.isBlobReferenced(cid) };
1951
2036
  }
1952
2037
  /**
1953
2038
  * RPC method: Get a blob from R2
@@ -2433,166 +2518,6 @@ function extractBlobCids(obj) {
2433
2518
  return cids;
2434
2519
  }
2435
2520
 
2436
- //#endregion
2437
- //#region src/service-auth.ts
2438
- const SERVICE_JWT_EXPIRY_SECONDS = 300;
2439
- /**
2440
- * Shared keypair cache for signing and verification.
2441
- */
2442
- let cachedKeypair = null;
2443
- let cachedSigningKey = null;
2444
- /**
2445
- * Get the signing keypair, with caching.
2446
- * Used for creating service JWTs and verifying them.
2447
- */
2448
- async function getSigningKeypair(signingKey) {
2449
- if (cachedKeypair && cachedSigningKey === signingKey) return cachedKeypair;
2450
- cachedKeypair = await Secp256k1Keypair.import(signingKey);
2451
- cachedSigningKey = signingKey;
2452
- return cachedKeypair;
2453
- }
2454
- function jsonToB64Url(json) {
2455
- return Buffer.from(JSON.stringify(json)).toString("base64url");
2456
- }
2457
- function noUndefinedVals(obj) {
2458
- const result = {};
2459
- for (const [key, val] of Object.entries(obj)) if (val !== void 0) result[key] = val;
2460
- return result;
2461
- }
2462
- /**
2463
- * Create a service JWT for proxied requests to AppView.
2464
- * The JWT asserts that the PDS vouches for the user identified by `iss`.
2465
- */
2466
- async function createServiceJwt(params) {
2467
- const { iss, aud, keypair } = params;
2468
- const iat = Math.floor(Date.now() / 1e3);
2469
- const exp = iat + SERVICE_JWT_EXPIRY_SECONDS;
2470
- const lxm = params.lxm ?? void 0;
2471
- const jti = randomStr(16, "hex");
2472
- const header = {
2473
- typ: "JWT",
2474
- alg: keypair.jwtAlg
2475
- };
2476
- const payload = noUndefinedVals({
2477
- iat,
2478
- iss,
2479
- aud,
2480
- exp,
2481
- lxm,
2482
- jti
2483
- });
2484
- const toSignStr = `${jsonToB64Url(header)}.${jsonToB64Url(payload)}`;
2485
- const toSign = Buffer.from(toSignStr, "utf8");
2486
- return `${toSignStr}.${Buffer.from(await keypair.sign(toSign)).toString("base64url")}`;
2487
- }
2488
- /**
2489
- * Verify a service JWT signed with our signing key.
2490
- * These are issued by getServiceAuth and used by external services
2491
- * (like video.bsky.app) to call back to our PDS.
2492
- */
2493
- async function verifyServiceJwt(token, signingKey, expectedAudience, expectedIssuer) {
2494
- const parts = token.split(".");
2495
- if (parts.length !== 3) throw new Error("Invalid JWT format");
2496
- const headerB64 = parts[0];
2497
- const payloadB64 = parts[1];
2498
- const signatureB64 = parts[2];
2499
- const header = JSON.parse(Buffer.from(headerB64, "base64url").toString());
2500
- if (header.alg !== "ES256K") throw new Error(`Unsupported algorithm: ${header.alg}`);
2501
- const payload = JSON.parse(Buffer.from(payloadB64, "base64url").toString());
2502
- const now$1 = Math.floor(Date.now() / 1e3);
2503
- if (payload.exp && payload.exp < now$1) throw new Error("Token expired");
2504
- if (payload.aud !== expectedAudience) throw new Error(`Invalid audience: expected ${expectedAudience}`);
2505
- if (payload.iss !== expectedIssuer) throw new Error(`Invalid issuer: expected ${expectedIssuer}`);
2506
- const keypair = await getSigningKeypair(signingKey);
2507
- const msgBytes = new Uint8Array(Buffer.from(`${headerB64}.${payloadB64}`, "utf8"));
2508
- const sigBytes = new Uint8Array(Buffer.from(signatureB64, "base64url"));
2509
- if (!await verifySignature(keypair.did(), msgBytes, sigBytes, { allowMalleableSig: true })) throw new Error("Invalid signature");
2510
- return payload;
2511
- }
2512
-
2513
- //#endregion
2514
- //#region src/session.ts
2515
- /**
2516
- * Error thrown when a JWT has expired.
2517
- * Callers should return HTTP 400 with error code 'ExpiredToken'.
2518
- */
2519
- var TokenExpiredError = class extends Error {
2520
- constructor(message = "Token has expired") {
2521
- super(message);
2522
- this.name = "TokenExpiredError";
2523
- }
2524
- };
2525
- const ACCESS_TOKEN_LIFETIME = "120m";
2526
- const REFRESH_TOKEN_LIFETIME = "90d";
2527
- /**
2528
- * Create a secret key from string for HS256 signing
2529
- */
2530
- function createSecretKey(secret) {
2531
- return new TextEncoder().encode(secret);
2532
- }
2533
- /**
2534
- * Create an access token (short-lived, 2 hours)
2535
- */
2536
- async function createAccessToken(jwtSecret, userDid, serviceDid) {
2537
- const secret = createSecretKey(jwtSecret);
2538
- return new SignJWT({ scope: "com.atproto.access" }).setProtectedHeader({
2539
- alg: "HS256",
2540
- typ: "at+jwt"
2541
- }).setIssuedAt().setAudience(serviceDid).setSubject(userDid).setExpirationTime(ACCESS_TOKEN_LIFETIME).sign(secret);
2542
- }
2543
- /**
2544
- * Create a refresh token (long-lived, 90 days)
2545
- */
2546
- async function createRefreshToken(jwtSecret, userDid, serviceDid) {
2547
- const secret = createSecretKey(jwtSecret);
2548
- const jti = crypto.randomUUID();
2549
- return new SignJWT({ scope: "com.atproto.refresh" }).setProtectedHeader({
2550
- alg: "HS256",
2551
- typ: "refresh+jwt"
2552
- }).setIssuedAt().setAudience(serviceDid).setSubject(userDid).setJti(jti).setExpirationTime(REFRESH_TOKEN_LIFETIME).sign(secret);
2553
- }
2554
- /**
2555
- * Verify an access token and return the payload.
2556
- * Throws TokenExpiredError if the token has expired.
2557
- */
2558
- async function verifyAccessToken(token, jwtSecret, serviceDid) {
2559
- const secret = createSecretKey(jwtSecret);
2560
- let payload;
2561
- let protectedHeader;
2562
- try {
2563
- const result = await jwtVerify(token, secret, { audience: serviceDid });
2564
- payload = result.payload;
2565
- protectedHeader = result.protectedHeader;
2566
- } catch (err) {
2567
- if (err instanceof errors.JWTExpired) throw new TokenExpiredError();
2568
- throw err;
2569
- }
2570
- if (protectedHeader.typ !== "at+jwt") throw new Error("Invalid token type");
2571
- if (payload.scope !== "com.atproto.access") throw new Error("Invalid scope");
2572
- return payload;
2573
- }
2574
- /**
2575
- * Verify a refresh token and return the payload.
2576
- * Throws TokenExpiredError if the token has expired.
2577
- */
2578
- async function verifyRefreshToken(token, jwtSecret, serviceDid) {
2579
- const secret = createSecretKey(jwtSecret);
2580
- let payload;
2581
- let protectedHeader;
2582
- try {
2583
- const result = await jwtVerify(token, secret, { audience: serviceDid });
2584
- payload = result.payload;
2585
- protectedHeader = result.protectedHeader;
2586
- } catch (err) {
2587
- if (err instanceof errors.JWTExpired) throw new TokenExpiredError();
2588
- throw err;
2589
- }
2590
- if (protectedHeader.typ !== "refresh+jwt") throw new Error("Invalid token type");
2591
- if (payload.scope !== "com.atproto.refresh") throw new Error("Invalid scope");
2592
- if (!payload.jti) throw new Error("Missing token ID");
2593
- return payload;
2594
- }
2595
-
2596
2521
  //#endregion
2597
2522
  //#region src/passkey.ts
2598
2523
  /**
@@ -2896,15 +2821,18 @@ function createCachedPermissionSetResolver(accountDO) {
2896
2821
  inflightRefresh.set(nsid, p);
2897
2822
  return p;
2898
2823
  };
2899
- return { async resolve(nsid) {
2900
- const cached = await accountDO.rpcGetPermissionSet(nsid);
2901
- if (cached && !cached.stale) return cached.set;
2902
- if (cached?.stale) {
2903
- waitUntil(fetchAndStore(nsid).catch(() => {}));
2904
- return cached.set;
2905
- }
2906
- return fetchAndStore(nsid);
2907
- } };
2824
+ return {
2825
+ async resolve(nsid) {
2826
+ const cached = await accountDO.rpcGetPermissionSet(nsid);
2827
+ if (cached && !cached.stale) return cached.set;
2828
+ if (cached?.stale) {
2829
+ waitUntil(fetchAndStore(nsid).catch(() => {}));
2830
+ return cached.set;
2831
+ }
2832
+ return fetchAndStore(nsid);
2833
+ },
2834
+ resolveSpaceDeclaration: network.resolveSpaceDeclaration ? (nsid) => network.resolveSpaceDeclaration(nsid) : void 0
2835
+ };
2908
2836
  }
2909
2837
  /**
2910
2838
  * Get the OAuth provider for the given environment
@@ -2934,7 +2862,8 @@ function getProvider(env$2) {
2934
2862
  handle: env$2.HANDLE
2935
2863
  };
2936
2864
  },
2937
- permissionSetResolver: createCachedPermissionSetResolver(accountDO)
2865
+ permissionSetResolver: createCachedPermissionSetResolver(accountDO),
2866
+ spacesEnabled: env$2.SPACES_ENABLED === "true"
2938
2867
  });
2939
2868
  }
2940
2869
  let getAccountDO$1;
@@ -3041,6 +2970,566 @@ function createOAuthApp(accountDOGetter) {
3041
2970
  return oauth;
3042
2971
  }
3043
2972
 
2973
+ //#endregion
2974
+ //#region src/session.ts
2975
+ /**
2976
+ * Error thrown when a JWT has expired.
2977
+ * Callers should return HTTP 400 with error code 'ExpiredToken'.
2978
+ */
2979
+ var TokenExpiredError = class extends Error {
2980
+ constructor(message = "Token has expired") {
2981
+ super(message);
2982
+ this.name = "TokenExpiredError";
2983
+ }
2984
+ };
2985
+ const ACCESS_TOKEN_LIFETIME = "120m";
2986
+ const REFRESH_TOKEN_LIFETIME = "90d";
2987
+ /**
2988
+ * Create a secret key from string for HS256 signing
2989
+ */
2990
+ function createSecretKey(secret) {
2991
+ return new TextEncoder().encode(secret);
2992
+ }
2993
+ /**
2994
+ * Create an access token (short-lived, 2 hours)
2995
+ */
2996
+ async function createAccessToken(jwtSecret, userDid, serviceDid, options = {}) {
2997
+ const secret = createSecretKey(jwtSecret);
2998
+ return new SignJWT({
2999
+ scope: "com.atproto.access",
3000
+ ...options.appPassword ? { apf: true } : {}
3001
+ }).setProtectedHeader({
3002
+ alg: "HS256",
3003
+ typ: "at+jwt"
3004
+ }).setIssuedAt().setAudience(serviceDid).setSubject(userDid).setExpirationTime(ACCESS_TOKEN_LIFETIME).sign(secret);
3005
+ }
3006
+ /**
3007
+ * Create a refresh token (long-lived, 90 days)
3008
+ */
3009
+ async function createRefreshToken(jwtSecret, userDid, serviceDid, options = {}) {
3010
+ const secret = createSecretKey(jwtSecret);
3011
+ const jti = crypto.randomUUID();
3012
+ return new SignJWT({
3013
+ scope: "com.atproto.refresh",
3014
+ ...options.appPassword ? { apf: true } : {}
3015
+ }).setProtectedHeader({
3016
+ alg: "HS256",
3017
+ typ: "refresh+jwt"
3018
+ }).setIssuedAt().setAudience(serviceDid).setSubject(userDid).setJti(jti).setExpirationTime(REFRESH_TOKEN_LIFETIME).sign(secret);
3019
+ }
3020
+ /**
3021
+ * Verify an access token and return the payload.
3022
+ * Throws TokenExpiredError if the token has expired.
3023
+ */
3024
+ async function verifyAccessToken(token, jwtSecret, serviceDid) {
3025
+ const secret = createSecretKey(jwtSecret);
3026
+ let payload;
3027
+ let protectedHeader;
3028
+ try {
3029
+ const result = await jwtVerify(token, secret, { audience: serviceDid });
3030
+ payload = result.payload;
3031
+ protectedHeader = result.protectedHeader;
3032
+ } catch (err) {
3033
+ if (err instanceof errors.JWTExpired) throw new TokenExpiredError();
3034
+ throw err;
3035
+ }
3036
+ if (protectedHeader.typ !== "at+jwt") throw new Error("Invalid token type");
3037
+ if (payload.scope !== "com.atproto.access") throw new Error("Invalid scope");
3038
+ return payload;
3039
+ }
3040
+ /**
3041
+ * Verify a refresh token and return the payload.
3042
+ * Throws TokenExpiredError if the token has expired.
3043
+ */
3044
+ async function verifyRefreshToken(token, jwtSecret, serviceDid) {
3045
+ const secret = createSecretKey(jwtSecret);
3046
+ let payload;
3047
+ let protectedHeader;
3048
+ try {
3049
+ const result = await jwtVerify(token, secret, { audience: serviceDid });
3050
+ payload = result.payload;
3051
+ protectedHeader = result.protectedHeader;
3052
+ } catch (err) {
3053
+ if (err instanceof errors.JWTExpired) throw new TokenExpiredError();
3054
+ throw err;
3055
+ }
3056
+ if (protectedHeader.typ !== "refresh+jwt") throw new Error("Invalid token type");
3057
+ if (payload.scope !== "com.atproto.refresh") throw new Error("Invalid scope");
3058
+ if (!payload.jti) throw new Error("Missing token ID");
3059
+ return payload;
3060
+ }
3061
+
3062
+ //#endregion
3063
+ //#region src/spaces.ts
3064
+ /**
3065
+ * Atproto spaces (alpha) — PDS integration.
3066
+ *
3067
+ * The engine lives in @getcirrus/spaces; this module supplies the
3068
+ * account-specific pieces: the concrete Durable Object classes, the host
3069
+ * adapter (operator identity, DID resolution, session auth, record
3070
+ * validation), and the user's-PDS role endpoints (getDelegationToken,
3071
+ * listSpaces). Everything mounts behind the SPACES_ENABLED flag.
3072
+ */
3073
+ /**
3074
+ * The account's space DO: host identity comes from the PDS environment.
3075
+ * This is the only place `env.DID` crosses into the engine.
3076
+ */
3077
+ var SpaceDurableObject = class extends SpaceDurableObject$1 {
3078
+ keypairPromise = null;
3079
+ getHostConfig() {
3080
+ return {
3081
+ operatorDid: this.env.DID,
3082
+ getKeypair: () => {
3083
+ this.keypairPromise ??= Secp256k1Keypair.import(this.env.SIGNING_KEY);
3084
+ return this.keypairPromise;
3085
+ }
3086
+ };
3087
+ }
3088
+ };
3089
+ var SpaceIndexDurableObject = class extends SpaceIndexDurableObject$1 {};
3090
+ /** Data-location-aware stub creation, matching getAccountDO's handling. */
3091
+ function getSpaceDO(env$2, uri) {
3092
+ return locatedStub(env$2, env$2.SPACES, uri);
3093
+ }
3094
+ function getSpaceIndexDO(env$2) {
3095
+ return locatedStub(env$2, env$2.SPACES_INDEX, "spaces");
3096
+ }
3097
+ function locatedStub(env$2, namespace, name) {
3098
+ const location = env$2.DATA_LOCATION;
3099
+ if (location === "eu") {
3100
+ const jurisdiction = namespace.jurisdiction("eu");
3101
+ return jurisdiction.get(jurisdiction.idFromName(name));
3102
+ }
3103
+ const id = namespace.idFromName(name);
3104
+ if (location && location !== "auto") return namespace.get(id, { locationHint: location });
3105
+ return namespace.get(id);
3106
+ }
3107
+ const SESSION_KID_ALLOWED = new Set(["#atproto", "#atproto_space"]);
3108
+ /**
3109
+ * Fallback app mounted when SPACES_ENABLED is set but the SPACES /
3110
+ * SPACES_INDEX Durable Object bindings are absent: every space and
3111
+ * simplespace method answers 503 with a pointer at the fix, and
3112
+ * everything else falls through.
3113
+ *
3114
+ * Nothing in this module may throw for a missing binding at module scope:
3115
+ * Cloudflare's deploy-time startup validation evaluates the Worker with
3116
+ * vars visible but Durable Object bindings not yet materialized, so a
3117
+ * startup throw fails every deploy with the flag set — and a genuine
3118
+ * misconfiguration should degrade the spaces surface, never take the
3119
+ * public repo path down with it.
3120
+ */
3121
+ function createSpacesUnavailableApp() {
3122
+ const app$1 = new Hono();
3123
+ app$1.all("/xrpc/:method", async (c, next) => {
3124
+ const method = c.req.param("method");
3125
+ if (!method.startsWith("com.atproto.space.") && !method.startsWith("com.atproto.simplespace.")) return next();
3126
+ return c.json({
3127
+ error: "ServiceUnavailable",
3128
+ message: "SPACES_ENABLED is set but the SPACES / SPACES_INDEX Durable Object bindings are missing. Add them to wrangler.jsonc (migration v2)."
3129
+ }, 503);
3130
+ });
3131
+ return app$1;
3132
+ }
3133
+ /**
3134
+ * Build the host adapter and the complete spaces Hono app: the engine's
3135
+ * space/simplespace routes plus the PDS-level getDelegationToken and
3136
+ * listSpaces.
3137
+ */
3138
+ function createSpacesApp(deps) {
3139
+ const { env: env$2, didResolver: didResolver$1, getKeypair: getKeypair$1 } = deps;
3140
+ /**
3141
+ * Resolve a DID's signing key to a did:key string, honouring the
3142
+ * requested kid with the proposal's #atproto_space → #atproto fallback.
3143
+ */
3144
+ async function getSigningKey(iss, kid, forceRefresh) {
3145
+ if (kid && !SESSION_KID_ALLOWED.has(kid)) throw new Error(`Unsupported signing key id: ${kid}`);
3146
+ if (iss === env$2.DID) return `did:key:${env$2.SIGNING_KEY_PUBLIC}`;
3147
+ const doc = await didResolver$1.resolve(iss, { forceRefresh });
3148
+ if (!doc) throw new Error(`Could not resolve DID: ${iss}`);
3149
+ const methods = doc.verificationMethod ?? [];
3150
+ const find = (fragment) => methods.find((m) => m.id === fragment || m.id.endsWith(fragment));
3151
+ const method = (kid ? find(kid) : void 0) ?? find("#atproto");
3152
+ if (!method?.publicKeyMultibase) throw new Error(`No signing key in DID document for ${iss}`);
3153
+ return `did:key:${method.publicKeyMultibase}`;
3154
+ }
3155
+ /** Resolve a `did[#fragment]` service identifier to its endpoint. */
3156
+ async function resolveServiceEndpoint(service) {
3157
+ const [did, fragment] = service.split("#");
3158
+ const doc = await didResolver$1.resolve(did);
3159
+ if (!doc) return null;
3160
+ const services = doc.service ?? [];
3161
+ const entry = fragment ? services.find((s) => s.id === `#${fragment}` || s.id.endsWith(`#${fragment}`)) : services.find((s) => s.id === "#atproto_pds" || s.id.endsWith("#atproto_pds"));
3162
+ return typeof entry?.serviceEndpoint === "string" ? entry.serviceEndpoint : null;
3163
+ }
3164
+ /**
3165
+ * A space authority's host endpoint: the dedicated #atproto_space_host
3166
+ * entry when published, falling back to #atproto_pds.
3167
+ */
3168
+ async function resolveAuthorityEndpoint(did) {
3169
+ return await resolveServiceEndpoint(`${did}#atproto_space_host`) ?? await resolveServiceEndpoint(did);
3170
+ }
3171
+ /**
3172
+ * Verify an inbound service-auth JWT from a foreign issuer (notifyWrite
3173
+ * and notifySpaceDeleted): ES256K signature against the issuer's
3174
+ * #atproto key, expiry, and the lxm method binding. Resolution failures
3175
+ * surface as auth errors, never 500s.
3176
+ */
3177
+ async function verifyForeignServiceJwt(token, lxm) {
3178
+ const parts = token.split(".");
3179
+ if (parts.length !== 3) throw new Error("Malformed service JWT");
3180
+ const decode$2 = (part) => JSON.parse(atob(part.replace(/-/g, "+").replace(/_/g, "/")));
3181
+ const payload = decode$2(parts[1]);
3182
+ const iss = payload.iss;
3183
+ const aud = payload.aud;
3184
+ if (typeof iss !== "string" || typeof aud !== "string") throw new Error("Service JWT missing iss or aud");
3185
+ if (payload.lxm !== lxm) throw new Error(`Service JWT not bound to ${lxm}`);
3186
+ if (typeof payload.exp !== "number" || payload.exp < Math.floor(Date.now() / 1e3) - 5) throw new Error("Service JWT expired");
3187
+ const signingInput = new TextEncoder().encode(`${parts[0]}.${parts[1]}`);
3188
+ const sigB64 = parts[2].replace(/-/g, "+").replace(/_/g, "/");
3189
+ const sig = Uint8Array.from(atob(sigB64), (ch) => ch.charCodeAt(0));
3190
+ const verifyWith = async (forceRefresh) => verifySignature(await getSigningKey(iss, void 0, forceRefresh), signingInput, sig);
3191
+ if (!await verifyWith(false) && !await verifyWith(true)) throw new Error("Invalid service JWT signature");
3192
+ return {
3193
+ iss,
3194
+ aud
3195
+ };
3196
+ }
3197
+ /**
3198
+ * Session authentication for space routes. Accepts OAuth tokens
3199
+ * carrying space: grants and the operator's own full-access sessions
3200
+ * (AUTH_TOKEN, password and passkey sessions). App passwords are
3201
+ * excluded in the alpha; service JWTs never reach spaces.
3202
+ */
3203
+ async function authenticate(c) {
3204
+ const auth = c.req.header("Authorization");
3205
+ if (!auth) return c.json({
3206
+ error: "AuthMissing",
3207
+ message: "Authorization header required"
3208
+ }, 401);
3209
+ if (auth.startsWith("DPoP ")) {
3210
+ const tokenData = await getProvider(env$2).verifyAccessToken(c.req.raw);
3211
+ if (!tokenData) return c.json({
3212
+ error: "AuthenticationRequired",
3213
+ message: "Invalid OAuth access token"
3214
+ }, 401);
3215
+ const perms = permissionsFor(tokenData.scope);
3216
+ return {
3217
+ did: tokenData.sub,
3218
+ fullTrust: false,
3219
+ allowsSpace: (match) => perms.allowsSpace(match)
3220
+ };
3221
+ }
3222
+ if (!auth.startsWith("Bearer ")) return c.json({
3223
+ error: "AuthMissing",
3224
+ message: "Invalid authorization scheme"
3225
+ }, 401);
3226
+ const token = auth.slice(7);
3227
+ if (token === env$2.AUTH_TOKEN) return {
3228
+ did: env$2.DID,
3229
+ fullTrust: true,
3230
+ allowsSpace: () => true
3231
+ };
3232
+ try {
3233
+ const payload = await verifyAccessToken(token, env$2.JWT_SECRET, `did:web:${env$2.PDS_HOSTNAME}`);
3234
+ if (payload.sub !== env$2.DID) return c.json({
3235
+ error: "AuthenticationRequired",
3236
+ message: "Invalid access token"
3237
+ }, 401);
3238
+ if (payload.apf === true) return c.json({
3239
+ error: "AuthenticationRequired",
3240
+ message: "App passwords cannot access atproto spaces"
3241
+ }, 403);
3242
+ return {
3243
+ did: env$2.DID,
3244
+ fullTrust: true,
3245
+ allowsSpace: () => true
3246
+ };
3247
+ } catch (err) {
3248
+ if (err instanceof TokenExpiredError) return c.json({
3249
+ error: "ExpiredToken",
3250
+ message: err.message
3251
+ }, 400);
3252
+ }
3253
+ return c.json({
3254
+ error: "AuthenticationRequired",
3255
+ message: "Invalid authentication token"
3256
+ }, 401);
3257
+ }
3258
+ const app$1 = createSpaceRoutes({
3259
+ operatorDid: env$2.DID,
3260
+ publicOrigin: `https://${env$2.PDS_HOSTNAME}`,
3261
+ blobs: env$2.BLOBS,
3262
+ getKeypair: getKeypair$1,
3263
+ getSigningKey,
3264
+ resolveServiceEndpoint,
3265
+ resolveAuthorityEndpoint,
3266
+ verifyServiceJwt: verifyForeignServiceJwt,
3267
+ authenticate,
3268
+ validateRecord: ({ collection, record, rkey, validate }) => {
3269
+ const result = validator.validate({
3270
+ collection,
3271
+ record,
3272
+ rkey,
3273
+ validate
3274
+ });
3275
+ return {
3276
+ record: result.record,
3277
+ status: result.status
3278
+ };
3279
+ },
3280
+ getSpaceDO: (uri) => getSpaceDO(env$2, uri),
3281
+ getIndexDO: () => getSpaceIndexDO(env$2)
3282
+ });
3283
+ app$1.get("/xrpc/com.atproto.space.getDelegationToken", async (c) => {
3284
+ try {
3285
+ const ref = requireSpaceUri(c.req.query("space"));
3286
+ const session = await authenticate(c);
3287
+ if (session instanceof Response) return session;
3288
+ if (!session.fullTrust) {
3289
+ if (!session.allowsSpace({
3290
+ type: ref.type,
3291
+ authority: ref.authority,
3292
+ skey: ref.skey,
3293
+ action: "read"
3294
+ })) return c.json({
3295
+ error: "InsufficientScope",
3296
+ message: "Token does not cover reading this space"
3297
+ }, 403);
3298
+ }
3299
+ const keypair = await getKeypair$1();
3300
+ const token = await createSpaceToken("delegation", {
3301
+ iss: env$2.DID,
3302
+ sub: ref.uri,
3303
+ aud: spaceHostAud(ref.authority)
3304
+ }, keypair);
3305
+ return c.json({ token });
3306
+ } catch (err) {
3307
+ return spacesErrorResponse(c, err);
3308
+ }
3309
+ });
3310
+ app$1.get("/xrpc/com.atproto.space.listSpaces", async (c) => {
3311
+ try {
3312
+ const session = await authenticate(c);
3313
+ if (session instanceof Response) return session;
3314
+ const type = c.req.query("type");
3315
+ const authority = c.req.query("did");
3316
+ if (!session.fullTrust) {
3317
+ if (!session.allowsSpace({
3318
+ type: type ?? "*",
3319
+ authority: authority ?? "*",
3320
+ skey: "*",
3321
+ action: "read_self"
3322
+ })) return c.json({
3323
+ error: "InsufficientScope",
3324
+ message: "Token does not cover listing these spaces"
3325
+ }, 403);
3326
+ }
3327
+ const limitRaw = c.req.query("limit");
3328
+ const limit = Math.min(Math.max(limitRaw ? Number.parseInt(limitRaw, 10) || 50 : 50, 1), 100);
3329
+ const page = await getSpaceIndexDO(env$2).rpcList({
3330
+ type,
3331
+ authority,
3332
+ state: "active",
3333
+ limit,
3334
+ afterUri: c.req.query("cursor")
3335
+ });
3336
+ const last = page.spaces[page.spaces.length - 1];
3337
+ return c.json({
3338
+ spaces: page.spaces.map((space) => ({ uri: space.uri })),
3339
+ ...page.hasMore && last ? { cursor: last.uri } : {}
3340
+ });
3341
+ } catch (err) {
3342
+ return spacesErrorResponse(c, err);
3343
+ }
3344
+ });
3345
+ return app$1;
3346
+ }
3347
+ /**
3348
+ * Operator-only admin surface for spaces, mounted whenever the bindings
3349
+ * exist — deliberately independent of SPACES_ENABLED so `pds spaces reset`
3350
+ * and `pds spaces status` still work after the flag is turned off or an
3351
+ * alpha schema bump puts the space DOs into their refusing state.
3352
+ */
3353
+ function createSpacesAdminApp(deps) {
3354
+ const { env: env$2 } = deps;
3355
+ const app$1 = new Hono();
3356
+ /** Full-trust operator auth only: AUTH_TOKEN or a non-app-password session. */
3357
+ async function requireOperator(c) {
3358
+ const auth = c.req.header("Authorization");
3359
+ if (!auth?.startsWith("Bearer ")) return c.json({
3360
+ error: "AuthMissing",
3361
+ message: "Authorization header required"
3362
+ }, 401);
3363
+ const token = auth.slice(7);
3364
+ if (token === env$2.AUTH_TOKEN) return null;
3365
+ try {
3366
+ const payload = await verifyAccessToken(token, env$2.JWT_SECRET, `did:web:${env$2.PDS_HOSTNAME}`);
3367
+ if (payload.sub === env$2.DID && payload.apf !== true) return null;
3368
+ } catch {}
3369
+ return c.json({
3370
+ error: "AuthenticationRequired",
3371
+ message: "Operator session required"
3372
+ }, 401);
3373
+ }
3374
+ async function listAllIndexEntries() {
3375
+ const index = getSpaceIndexDO(env$2);
3376
+ const entries = [];
3377
+ let afterUri;
3378
+ for (;;) {
3379
+ const page = await index.rpcList({
3380
+ limit: 500,
3381
+ afterUri
3382
+ });
3383
+ entries.push(...page.spaces);
3384
+ if (!page.hasMore || page.spaces.length === 0) break;
3385
+ afterUri = page.spaces[page.spaces.length - 1].uri;
3386
+ }
3387
+ return entries;
3388
+ }
3389
+ app$1.get("/xrpc/gg.mk.experimental.getSpacesStatus", async (c) => {
3390
+ const denied = await requireOperator(c);
3391
+ if (denied) return denied;
3392
+ const stats = await getSpaceIndexDO(env$2).rpcStats();
3393
+ const entries = await listAllIndexEntries();
3394
+ const spaces = await Promise.all(entries.map(async (entry) => {
3395
+ const status = await getSpaceDO(env$2, entry.uri).rpcStatus();
3396
+ return {
3397
+ uri: entry.uri,
3398
+ role: entry.isAuthority ? "authority" : "writer",
3399
+ state: entry.state,
3400
+ outdated: status.outdated,
3401
+ recordCount: status.recordCount,
3402
+ memberCount: status.memberCount,
3403
+ writerCount: status.writerCount
3404
+ };
3405
+ }));
3406
+ return c.json({
3407
+ enabled: env$2.SPACES_ENABLED === "true",
3408
+ schemaVersion: SPACE_SCHEMA_VERSION,
3409
+ stats,
3410
+ spaces
3411
+ });
3412
+ });
3413
+ app$1.post("/xrpc/gg.mk.experimental.spacesReset", async (c) => {
3414
+ const denied = await requireOperator(c);
3415
+ if (denied) return denied;
3416
+ const entries = await listAllIndexEntries();
3417
+ for (const entry of entries) await getSpaceDO(env$2, entry.uri).rpcDestroy();
3418
+ await getSpaceIndexDO(env$2).rpcDestroy();
3419
+ let blobsDeleted = 0;
3420
+ if (env$2.BLOBS) {
3421
+ const prefix = spaceBlobRootPrefix(env$2.DID);
3422
+ let cursor;
3423
+ do {
3424
+ const listed = await env$2.BLOBS.list({
3425
+ prefix,
3426
+ cursor,
3427
+ limit: 500
3428
+ });
3429
+ if (listed.objects.length > 0) {
3430
+ await env$2.BLOBS.delete(listed.objects.map((o) => o.key));
3431
+ blobsDeleted += listed.objects.length;
3432
+ }
3433
+ cursor = listed.truncated ? listed.cursor : void 0;
3434
+ } while (cursor);
3435
+ }
3436
+ return c.json({
3437
+ spacesDeleted: entries.length,
3438
+ blobsDeleted
3439
+ });
3440
+ });
3441
+ return app$1;
3442
+ }
3443
+ function spacesErrorResponse(c, err) {
3444
+ if (err instanceof InvalidRecordError) return c.json({
3445
+ error: "InvalidRecord",
3446
+ message: err.message
3447
+ }, 400);
3448
+ const parsed = parseSpaceErrorCode(err);
3449
+ if (parsed) return c.json({
3450
+ error: parsed.code,
3451
+ message: parsed.message
3452
+ }, spaceErrorStatus(parsed.code));
3453
+ throw err;
3454
+ }
3455
+
3456
+ //#endregion
3457
+ //#region src/service-auth.ts
3458
+ const SERVICE_JWT_EXPIRY_SECONDS = 300;
3459
+ /**
3460
+ * Shared keypair cache for signing and verification.
3461
+ */
3462
+ let cachedKeypair = null;
3463
+ let cachedSigningKey = null;
3464
+ /**
3465
+ * Get the signing keypair, with caching.
3466
+ * Used for creating service JWTs and verifying them.
3467
+ */
3468
+ async function getSigningKeypair(signingKey) {
3469
+ if (cachedKeypair && cachedSigningKey === signingKey) return cachedKeypair;
3470
+ cachedKeypair = await Secp256k1Keypair.import(signingKey);
3471
+ cachedSigningKey = signingKey;
3472
+ return cachedKeypair;
3473
+ }
3474
+ function jsonToB64Url(json) {
3475
+ return Buffer.from(JSON.stringify(json)).toString("base64url");
3476
+ }
3477
+ function noUndefinedVals(obj) {
3478
+ const result = {};
3479
+ for (const [key, val] of Object.entries(obj)) if (val !== void 0) result[key] = val;
3480
+ return result;
3481
+ }
3482
+ /**
3483
+ * Create a service JWT for proxied requests to AppView.
3484
+ * The JWT asserts that the PDS vouches for the user identified by `iss`.
3485
+ */
3486
+ async function createServiceJwt(params) {
3487
+ const { iss, aud, keypair } = params;
3488
+ const iat = Math.floor(Date.now() / 1e3);
3489
+ const exp = iat + SERVICE_JWT_EXPIRY_SECONDS;
3490
+ const lxm = params.lxm ?? void 0;
3491
+ const jti = randomStr(16, "hex");
3492
+ const header = {
3493
+ typ: "JWT",
3494
+ alg: keypair.jwtAlg
3495
+ };
3496
+ const payload = noUndefinedVals({
3497
+ iat,
3498
+ iss,
3499
+ aud,
3500
+ exp,
3501
+ lxm,
3502
+ jti
3503
+ });
3504
+ const toSignStr = `${jsonToB64Url(header)}.${jsonToB64Url(payload)}`;
3505
+ const toSign = Buffer.from(toSignStr, "utf8");
3506
+ return `${toSignStr}.${Buffer.from(await keypair.sign(toSign)).toString("base64url")}`;
3507
+ }
3508
+ /**
3509
+ * Verify a service JWT signed with our signing key.
3510
+ * These are issued by getServiceAuth and used by external services
3511
+ * (like video.bsky.app) to call back to our PDS.
3512
+ */
3513
+ async function verifyServiceJwt(token, signingKey, expectedAudience, expectedIssuer) {
3514
+ const parts = token.split(".");
3515
+ if (parts.length !== 3) throw new Error("Invalid JWT format");
3516
+ const headerB64 = parts[0];
3517
+ const payloadB64 = parts[1];
3518
+ const signatureB64 = parts[2];
3519
+ const header = JSON.parse(Buffer.from(headerB64, "base64url").toString());
3520
+ if (header.alg !== "ES256K") throw new Error(`Unsupported algorithm: ${header.alg}`);
3521
+ const payload = JSON.parse(Buffer.from(payloadB64, "base64url").toString());
3522
+ const now$1 = Math.floor(Date.now() / 1e3);
3523
+ if (payload.exp && payload.exp < now$1) throw new Error("Token expired");
3524
+ if (payload.aud !== expectedAudience) throw new Error(`Invalid audience: expected ${expectedAudience}`);
3525
+ if (payload.iss !== expectedIssuer) throw new Error(`Invalid issuer: expected ${expectedIssuer}`);
3526
+ const keypair = await getSigningKeypair(signingKey);
3527
+ const msgBytes = new Uint8Array(Buffer.from(`${headerB64}.${payloadB64}`, "utf8"));
3528
+ const sigBytes = new Uint8Array(Buffer.from(signatureB64, "base64url"));
3529
+ if (!await verifySignature(keypair.did(), msgBytes, sigBytes, { allowMalleableSig: true })) throw new Error("Invalid signature");
3530
+ return payload;
3531
+ }
3532
+
3044
3533
  //#endregion
3045
3534
  //#region src/middleware/auth.ts
3046
3535
  /**
@@ -3205,8 +3694,8 @@ var DidResolver = class {
3205
3694
  web: new WebDidDocumentResolver({ fetch: stubbableFetch })
3206
3695
  } });
3207
3696
  }
3208
- async resolve(did) {
3209
- if (this.cache) {
3697
+ async resolve(did, opts = {}) {
3698
+ if (this.cache && !opts.forceRefresh) {
3210
3699
  const cached = await this.cache.checkCache(did);
3211
3700
  if (cached && !cached.expired) {
3212
3701
  if (cached.stale) this.cache.refreshCache(did, () => this.resolveNoCache(did), cached);
@@ -3627,6 +4116,7 @@ async function listBlobs(c, _accountDO) {
3627
4116
  const limit = Math.min(Number(c.req.query("limit")) || 500, 1e3);
3628
4117
  const listed = await c.env.BLOBS.list({
3629
4118
  prefix,
4119
+ delimiter: "/",
3630
4120
  limit,
3631
4121
  cursor: cursor || void 0
3632
4122
  });
@@ -3763,6 +4253,19 @@ async function getRecord$1(c, accountDO) {
3763
4253
 
3764
4254
  //#endregion
3765
4255
  //#region src/xrpc/repo.ts
4256
+ /**
4257
+ * Promote any staged blobs referenced by the given records to their public
4258
+ * serving key. Runs in the Worker before the DO applies the commit, so a
4259
+ * relay or AppView reacting to the commit never sees a 404 for a
4260
+ * just-referenced blob. Idempotent per CID; unknown CIDs are skipped.
4261
+ */
4262
+ async function promoteRecordBlobs(c, records) {
4263
+ if (!c.env.BLOBS) return;
4264
+ const cids = /* @__PURE__ */ new Set();
4265
+ for (const record of records) for (const cid of extractJsonBlobCids(record)) cids.add(cid);
4266
+ if (cids.size === 0) return;
4267
+ await new BlobStore(c.env.BLOBS, c.env.DID).promoteBlobs(Array.from(cids));
4268
+ }
3766
4269
  function invalidRecordError(c, err, prefix) {
3767
4270
  return c.json({
3768
4271
  error: "InvalidRecord",
@@ -3923,6 +4426,7 @@ async function createRecord(c, accountDO) {
3923
4426
  if (err instanceof InvalidRecordError) return invalidRecordError(c, err);
3924
4427
  throw err;
3925
4428
  }
4429
+ await promoteRecordBlobs(c, [validated.record]);
3926
4430
  try {
3927
4431
  const result = await accountDO.rpcCreateRecord(collection, rkey, validated.record, validated.status);
3928
4432
  return c.json(result);
@@ -3987,6 +4491,7 @@ async function putRecord(c, accountDO) {
3987
4491
  if (err instanceof InvalidRecordError) return invalidRecordError(c, err);
3988
4492
  throw err;
3989
4493
  }
4494
+ await promoteRecordBlobs(c, [validated.record]);
3990
4495
  try {
3991
4496
  const result = await accountDO.rpcPutRecord(collection, rkey, validated.record, validated.status);
3992
4497
  return c.json(result);
@@ -4069,6 +4574,7 @@ async function applyWrites(c, accountDO) {
4069
4574
  throw err;
4070
4575
  }
4071
4576
  }
4577
+ await promoteRecordBlobs(c, preparedWrites.filter((w) => w.value !== void 0).map((w) => w.value));
4072
4578
  try {
4073
4579
  const result = await accountDO.rpcApplyWrites(preparedWrites);
4074
4580
  return c.json(result);
@@ -4102,8 +4608,10 @@ async function uploadBlob(c, accountDO) {
4102
4608
  error: "ServiceUnavailable",
4103
4609
  message: "Blob storage is not configured"
4104
4610
  }, 503);
4105
- const blobRef = await new BlobStore(c.env.BLOBS, c.env.DID).putBlob(bytes, contentType);
4106
- await accountDO.rpcTrackBlob(blobRef.ref.$link, blobRef.size, blobRef.mimeType);
4611
+ const blobStore = new BlobStore(c.env.BLOBS, c.env.DID);
4612
+ const blobRef = await blobStore.putBlob(bytes, contentType);
4613
+ const { referenced } = await accountDO.rpcTrackBlob(blobRef.ref.$link, blobRef.size, blobRef.mimeType);
4614
+ if (referenced) await blobStore.promoteBlob(blobRef.ref.$link);
4107
4615
  return c.json({ blob: blobRef });
4108
4616
  }
4109
4617
  async function importRepo(c, accountDO) {
@@ -4197,6 +4705,7 @@ async function createSession(c, accountDO) {
4197
4705
  error: "AuthenticationRequired",
4198
4706
  message: "Invalid identifier or password"
4199
4707
  }, 401);
4708
+ let usedAppPassword = false;
4200
4709
  if (isAppPassword(password)) {
4201
4710
  const appPasswords = await accountDO.rpcGetAppPasswordHashes();
4202
4711
  let matched = false;
@@ -4208,13 +4717,15 @@ async function createSession(c, accountDO) {
4208
4717
  error: "AuthenticationRequired",
4209
4718
  message: "Invalid identifier or password"
4210
4719
  }, 401);
4720
+ usedAppPassword = true;
4211
4721
  } else if (!await compare$1(password, c.env.PASSWORD_HASH)) return c.json({
4212
4722
  error: "AuthenticationRequired",
4213
4723
  message: "Invalid identifier or password"
4214
4724
  }, 401);
4215
4725
  const serviceDid = `did:web:${c.env.PDS_HOSTNAME}`;
4216
- const accessJwt = await createAccessToken(c.env.JWT_SECRET, c.env.DID, serviceDid);
4217
- const refreshJwt = await createRefreshToken(c.env.JWT_SECRET, c.env.DID, serviceDid);
4726
+ const tokenOptions = { appPassword: usedAppPassword };
4727
+ const accessJwt = await createAccessToken(c.env.JWT_SECRET, c.env.DID, serviceDid, tokenOptions);
4728
+ const refreshJwt = await createRefreshToken(c.env.JWT_SECRET, c.env.DID, serviceDid, tokenOptions);
4218
4729
  const { email: storedEmail } = await accountDO.rpcGetEmail();
4219
4730
  const email = storedEmail || c.env.EMAIL;
4220
4731
  return c.json({
@@ -4239,12 +4750,14 @@ async function refreshSession(c, accountDO) {
4239
4750
  const token = authHeader.slice(7);
4240
4751
  const serviceDid = `did:web:${c.env.PDS_HOSTNAME}`;
4241
4752
  try {
4242
- if ((await verifyRefreshToken(token, c.env.JWT_SECRET, serviceDid)).sub !== c.env.DID) return c.json({
4753
+ const payload = await verifyRefreshToken(token, c.env.JWT_SECRET, serviceDid);
4754
+ if (payload.sub !== c.env.DID) return c.json({
4243
4755
  error: "AuthenticationRequired",
4244
4756
  message: "Invalid refresh token"
4245
4757
  }, 401);
4246
- const accessJwt = await createAccessToken(c.env.JWT_SECRET, c.env.DID, serviceDid);
4247
- const refreshJwt = await createRefreshToken(c.env.JWT_SECRET, c.env.DID, serviceDid);
4758
+ const tokenOptions = { appPassword: payload.apf === true };
4759
+ const accessJwt = await createAccessToken(c.env.JWT_SECRET, c.env.DID, serviceDid, tokenOptions);
4760
+ const refreshJwt = await createRefreshToken(c.env.JWT_SECRET, c.env.DID, serviceDid, tokenOptions);
4248
4761
  const { email: storedEmail } = await accountDO.rpcGetEmail();
4249
4762
  const email = storedEmail || c.env.EMAIL;
4250
4763
  return c.json({
@@ -4628,7 +5141,11 @@ function buildDidDocument(env$2) {
4628
5141
  id: "#atproto_pds",
4629
5142
  type: "AtprotoPersonalDataServer",
4630
5143
  serviceEndpoint: `https://${env$2.PDS_HOSTNAME}`
4631
- }]
5144
+ }, ...env$2.SPACES_ENABLED === "true" ? [{
5145
+ id: "#atproto_space_host",
5146
+ type: "AtprotoSpaceHost",
5147
+ serviceEndpoint: `https://${env$2.PDS_HOSTNAME}`
5148
+ }] : []]
4632
5149
  };
4633
5150
  }
4634
5151
  /**
@@ -5192,7 +5709,7 @@ function renderPasskeyErrorPage(error, description) {
5192
5709
 
5193
5710
  //#endregion
5194
5711
  //#region src/dashboard.html
5195
- var dashboard_default = "<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <title>CIRRUS</title>\n <style>\n * {\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n }\n :root {\n --bg: #08090d;\n --panel: #0f1117;\n --border: #1a1d2e;\n --text: #b4bcd0;\n --text-bright: #e8ecf4;\n --accent: #7dd3fc;\n --green: #4ade80;\n --amber: #fbbf24;\n --red: #f87171;\n --dim: #3f4558;\n }\n html,\n body {\n height: 100%;\n background: var(--bg);\n color: var(--text);\n font-family:\n ui-monospace, \"Cascadia Code\", \"Source Code Pro\", Menlo, Consolas,\n \"DejaVu Sans Mono\", monospace;\n overflow: hidden;\n }\n body {\n display: flex;\n flex-direction: column;\n padding: clamp(1rem, 2vw, 2rem);\n gap: clamp(0.75rem, 1.5vw, 1.5rem);\n }\n\n /* Header */\n header {\n display: flex;\n align-items: baseline;\n gap: 1.5rem;\n flex-wrap: wrap;\n }\n .brand {\n font-size: clamp(1.5rem, 3vw, 2.5rem);\n font-weight: 700;\n color: var(--text-bright);\n letter-spacing: 0.15em;\n }\n .server-info {\n display: flex;\n gap: 1.5rem;\n align-items: baseline;\n font-size: clamp(0.9rem, 1.5vw, 1.2rem);\n }\n .hostname {\n color: var(--accent);\n }\n .ver {\n color: var(--dim);\n }\n .identity {\n font-size: clamp(0.8rem, 1.2vw, 1rem);\n color: var(--dim);\n width: 100%;\n }\n .identity .handle {\n color: var(--text);\n }\n\n /* Panels */\n .panels {\n display: grid;\n grid-template-columns: 1fr 1fr;\n gap: clamp(0.75rem, 1.5vw, 1.5rem);\n }\n .panel {\n background: var(--panel);\n border: 1px solid var(--border);\n border-radius: 8px;\n padding: clamp(1rem, 2vw, 1.5rem);\n }\n .panel h2 {\n font-size: clamp(0.7rem, 1vw, 0.85rem);\n letter-spacing: 0.2em;\n color: var(--dim);\n margin-bottom: clamp(0.75rem, 1.5vw, 1.25rem);\n font-weight: 500;\n }\n\n /* Repository panel */\n .record-row {\n display: flex;\n justify-content: space-between;\n padding: 0.3em 0;\n font-size: clamp(0.9rem, 1.5vw, 1.2rem);\n }\n .record-name {\n color: var(--text);\n }\n .record-count {\n color: var(--text-bright);\n font-weight: 600;\n font-variant-numeric: tabular-nums;\n }\n .empty-state {\n color: var(--dim);\n font-style: italic;\n font-size: clamp(0.85rem, 1.3vw, 1.1rem);\n }\n\n /* Federation panel */\n .relay-name {\n font-size: clamp(0.85rem, 1.3vw, 1.1rem);\n color: var(--text);\n margin-bottom: clamp(0.5rem, 1vw, 1rem);\n }\n .sync-status {\n display: flex;\n align-items: center;\n gap: 0.75rem;\n transition: all 0.5s ease;\n }\n .sync-status .status-text {\n font-size: clamp(1.5rem, 3vw, 2.5rem);\n font-weight: 700;\n letter-spacing: 0.1em;\n transition:\n color 0.5s ease,\n text-shadow 0.8s ease;\n }\n .dot {\n width: clamp(10px, 1.2vw, 16px);\n height: clamp(10px, 1.2vw, 16px);\n border-radius: 50%;\n display: inline-block;\n flex-shrink: 0;\n transition:\n background 0.5s ease,\n box-shadow 0.8s ease;\n }\n .sync-status.checking .dot {\n background: var(--dim);\n }\n .sync-status.checking .status-text {\n color: var(--dim);\n }\n .sync-status.unknown .dot {\n background: var(--dim);\n animation: pulse-dim 3s ease-in-out infinite;\n }\n .sync-status.unknown .status-text {\n color: var(--dim);\n }\n .sync-status.behind .dot {\n background: var(--amber);\n animation: pulse 1.5s ease-in-out infinite;\n }\n .sync-status.behind .status-text {\n color: var(--amber);\n }\n .sync-status.synced .dot {\n background: var(--green);\n box-shadow: 0 0 12px var(--green);\n }\n .sync-status.synced .status-text {\n color: var(--green);\n }\n .sync-status.error .dot {\n background: var(--red);\n }\n .sync-status.error .status-text {\n color: var(--red);\n }\n .sync-status.flash .status-text {\n text-shadow:\n 0 0 30px currentColor,\n 0 0 60px currentColor;\n }\n .sync-status.flash .dot {\n box-shadow:\n 0 0 20px currentColor,\n 0 0 40px currentColor;\n }\n .relay-rev {\n font-size: clamp(0.7rem, 1vw, 0.85rem);\n color: var(--dim);\n margin-top: 0.5rem;\n font-variant-numeric: tabular-nums;\n }\n\n /* Events */\n .events-container {\n flex: 1;\n display: flex;\n flex-direction: column;\n background: var(--panel);\n border: 1px solid var(--border);\n border-radius: 8px;\n overflow: hidden;\n min-height: 0;\n }\n .events-header {\n display: flex;\n justify-content: space-between;\n align-items: center;\n padding: clamp(0.75rem, 1.5vw, 1rem) clamp(1rem, 2vw, 1.5rem);\n border-bottom: 1px solid var(--border);\n flex-shrink: 0;\n }\n .events-header h2 {\n font-size: clamp(0.7rem, 1vw, 0.85rem);\n letter-spacing: 0.2em;\n color: var(--dim);\n font-weight: 500;\n }\n .ws-status {\n display: flex;\n align-items: center;\n gap: 0.5rem;\n font-size: clamp(0.7rem, 1vw, 0.85rem);\n color: var(--dim);\n }\n .ws-status.connected .dot {\n background: var(--green);\n animation: pulse 2s ease-in-out infinite;\n }\n .ws-status.connected .ws-label {\n color: var(--green);\n }\n .ws-status.disconnected .dot {\n background: var(--dim);\n }\n .ws-status.error .dot {\n background: var(--red);\n }\n .events-list {\n flex: 1;\n overflow-y: auto;\n padding: 0 clamp(1rem, 2vw, 1.5rem);\n }\n .events-list .empty-state {\n padding: 1rem 0;\n }\n .event {\n display: flex;\n gap: clamp(0.75rem, 1.5vw, 1.5rem);\n padding: 0.4em 0;\n font-size: clamp(0.85rem, 1.3vw, 1.1rem);\n border-bottom: 1px solid rgba(26, 29, 46, 0.5);\n animation: slide-in 0.3s ease-out;\n }\n .event.new {\n background: rgba(125, 211, 252, 0.06);\n transition: background 1.5s ease-out;\n }\n .event-time {\n color: var(--dim);\n font-variant-numeric: tabular-nums;\n flex-shrink: 0;\n }\n .event-seq {\n color: var(--dim);\n font-variant-numeric: tabular-nums;\n flex-shrink: 0;\n min-width: 3em;\n text-align: right;\n }\n .event-action {\n flex-shrink: 0;\n font-weight: 600;\n min-width: 5em;\n }\n .event-action.create {\n color: var(--green);\n }\n .event-action.update {\n color: var(--amber);\n }\n .event-action.delete {\n color: var(--red);\n }\n .event-path {\n color: var(--text);\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n flex: 1;\n }\n /* Animations */\n @keyframes pulse {\n 0%,\n 100% {\n opacity: 0.5;\n }\n 50% {\n opacity: 1;\n }\n }\n @keyframes pulse-dim {\n 0%,\n 100% {\n opacity: 0.3;\n }\n 50% {\n opacity: 0.6;\n }\n }\n @keyframes slide-in {\n from {\n opacity: 0;\n transform: translateX(20px);\n }\n to {\n opacity: 1;\n transform: translateX(0);\n }\n }\n\n /* Scrollbar */\n .events-list::-webkit-scrollbar {\n width: 4px;\n }\n .events-list::-webkit-scrollbar-track {\n background: transparent;\n }\n .events-list::-webkit-scrollbar-thumb {\n background: var(--border);\n border-radius: 2px;\n }\n </style>\n </head>\n <body>\n <header>\n <div class=\"brand\">&#9729;&#65039; CIRRUS</div>\n <div class=\"server-info\">\n <span class=\"hostname\" id=\"cfg-hostname\"></span>\n <span class=\"ver\" id=\"cfg-version\"></span>\n </div>\n <div class=\"identity\">\n <span class=\"handle\" id=\"cfg-handle\"></span>\n <span>&middot;</span>\n <span id=\"cfg-did\"></span>\n </div>\n </header>\n\n <section class=\"panels\">\n <div class=\"panel\">\n <h2>REPOSITORY</h2>\n <div id=\"records\"><span class=\"empty-state\">Loading&hellip;</span></div>\n </div>\n <div class=\"panel\">\n <h2>FEDERATION</h2>\n <div class=\"relay-name\">bsky.network</div>\n <div class=\"sync-status checking\" id=\"sync-status\">\n <span class=\"dot\"></span>\n <span class=\"status-text\">CHECKING</span>\n </div>\n <div class=\"relay-rev\" id=\"relay-rev\"></div>\n </div>\n </section>\n\n <section class=\"events-container\">\n <div class=\"events-header\">\n <h2>EVENTS</h2>\n <div class=\"ws-status disconnected\" id=\"ws-status\">\n <span class=\"dot\"></span>\n <span class=\"ws-label\">disconnected</span>\n </div>\n </div>\n <div class=\"events-list\" id=\"events\">\n <div class=\"empty-state\">Waiting for events&hellip;</div>\n </div>\n </section>\n\n <script>\n {\n const CONFIG = window.__CIRRUS_CONFIG || {};\n const BASE = window.location.origin;\n const RELAY = \"https://bsky.network\";\n const DID = CONFIG.did || \"\";\n const MAX_EVENTS = 100;\n let pdsRev = null;\n let currentSyncStatus = null;\n let reconnectTimer = null;\n\n const $ = (id) => document.getElementById(id);\n\n // -- Populate config into DOM --\n const applyConfig = () => {\n document.title = `CIRRUS \\u00b7 ${CONFIG.hostname || \"\"}`;\n $(\"cfg-hostname\").textContent = CONFIG.hostname || \"\";\n $(\"cfg-version\").textContent = CONFIG.version\n ? `v${CONFIG.version}`\n : \"\";\n $(\"cfg-handle\").textContent = CONFIG.handle\n ? `@${CONFIG.handle}`\n : \"\";\n $(\"cfg-did\").textContent = CONFIG.did || \"\";\n };\n\n // -- Minimal CBOR decoder for firehose frames --\n const decodeCBOR = (d, o) => {\n const view = new DataView(d.buffer, d.byteOffset, d.byteLength);\n const major = d[o] >> 5;\n const additional = d[o] & 0x1f;\n\n const readLen = (off, add) => {\n if (add < 24) return [add, off + 1];\n if (add === 24) return [d[off + 1], off + 2];\n if (add === 25) return [view.getUint16(off + 1), off + 3];\n if (add === 26) return [view.getUint32(off + 1), off + 5];\n if (add === 27)\n return [\n view.getUint32(off + 1) * 0x100000000 + view.getUint32(off + 5),\n off + 9,\n ];\n return [0, off + 1];\n };\n\n switch (major) {\n case 0:\n return readLen(o, additional);\n case 1: {\n const [n, p] = readLen(o, additional);\n return [-1 - n, p];\n }\n case 2: {\n const [n, p] = readLen(o, additional);\n return [d.slice(p, p + n), p + n];\n }\n case 3: {\n const [n, p] = readLen(o, additional);\n return [new TextDecoder().decode(d.subarray(p, p + n)), p + n];\n }\n case 4: {\n let [count, pos] = readLen(o, additional);\n const arr = [];\n for (let i = 0; i < count; i++) {\n const [val, next] = decodeCBOR(d, pos);\n arr.push(val);\n pos = next;\n }\n return [arr, pos];\n }\n case 5: {\n let [count, pos] = readLen(o, additional);\n const obj = {};\n for (let i = 0; i < count; i++) {\n const [key, kNext] = decodeCBOR(d, pos);\n const [val, vNext] = decodeCBOR(d, kNext);\n obj[key] = val;\n pos = vNext;\n }\n return [obj, pos];\n }\n case 6: {\n const [, p] = readLen(o, additional);\n return decodeCBOR(d, p);\n }\n case 7: {\n if (additional === 20) return [false, o + 1];\n if (additional === 21) return [true, o + 1];\n if (additional === 22) return [null, o + 1];\n if (additional === 23) return [undefined, o + 1];\n if (additional === 25) return [null, o + 3];\n if (additional === 26) return [view.getFloat32(o + 1), o + 5];\n if (additional === 27) return [view.getFloat64(o + 1), o + 9];\n return [null, o + 1];\n }\n }\n return [null, o + 1];\n };\n\n const parseFirehoseMessage = (buffer) => {\n try {\n const d = new Uint8Array(buffer);\n const [header, bodyOff] = decodeCBOR(d, 0);\n if (!header || header.op !== 1 || header.t !== \"#commit\")\n return null;\n const [body] = decodeCBOR(d, bodyOff);\n if (!body) return null;\n return {\n seq: body.seq,\n repo: body.repo,\n rev: body.rev,\n ops: (body.ops || []).map((op) => ({\n action: op.action,\n path: op.path,\n })),\n };\n } catch {\n return null;\n }\n };\n\n // -- Friendly collection names --\n const COLLECTION_NAMES = {\n \"app.bsky.feed.post\": \"posts\",\n \"app.bsky.feed.like\": \"likes\",\n \"app.bsky.graph.follow\": \"follows\",\n \"app.bsky.feed.repost\": \"reposts\",\n \"app.bsky.actor.profile\": \"profile\",\n \"app.bsky.graph.block\": \"blocks\",\n \"app.bsky.graph.list\": \"lists\",\n \"app.bsky.graph.listitem\": \"list items\",\n \"app.bsky.feed.generator\": \"feeds\",\n \"app.bsky.feed.threadgate\": \"threadgates\",\n \"app.bsky.graph.starterpack\": \"starter packs\",\n };\n\n const friendlyName = (collection) =>\n COLLECTION_NAMES[collection] || collection.split(\".\").pop();\n\n const animateNumber = (el, target) => {\n let current = parseInt(el.textContent) || 0;\n if (current === target) return;\n const diff = target - current;\n const steps = Math.min(Math.abs(diff), 20);\n const stepSize = diff / steps;\n let step = 0;\n const tick = () => {\n step++;\n if (step >= steps) {\n el.textContent = target;\n return;\n }\n el.textContent = Math.round(current + stepSize * step);\n requestAnimationFrame(tick);\n };\n requestAnimationFrame(tick);\n };\n\n // -- Data fetching --\n const fetchRepoData = async () => {\n try {\n const reposRes = await fetch(\n `${BASE}/xrpc/com.atproto.sync.listRepos`,\n );\n const reposData = await reposRes.json();\n const repo = reposData.repos?.[0];\n if (repo) pdsRev = repo.rev;\n\n const descRes = await fetch(\n `${BASE}/xrpc/com.atproto.repo.describeRepo?repo=${encodeURIComponent(DID)}`,\n );\n const desc = await descRes.json();\n const collections = desc.collections || [];\n\n if (collections.length === 0) {\n $(\"records\").innerHTML =\n '<span class=\"empty-state\">No records yet</span>';\n return;\n }\n\n const results = await Promise.all(\n collections.map(async (col) => {\n const res = await fetch(\n `${BASE}/xrpc/com.atproto.repo.listRecords?repo=${encodeURIComponent(DID)}&collection=${encodeURIComponent(col)}&limit=100`,\n );\n const data = await res.json();\n return {\n collection: col,\n count: data.records?.length || 0,\n hasMore: !!data.cursor,\n };\n }),\n );\n\n const container = $(\"records\");\n for (const r of results) {\n const id = `rec-${r.collection.replaceAll(\".\", \"-\")}`;\n const existing = $(id);\n if (existing) {\n const countEl = existing.querySelector(\".record-count\");\n animateNumber(countEl, r.count);\n if (r.hasMore) countEl.textContent = `${r.count}+`;\n } else {\n if (container.querySelector(\".empty-state\"))\n container.innerHTML = \"\";\n const row = document.createElement(\"div\");\n row.className = \"record-row\";\n row.id = id;\n row.innerHTML = `<span class=\"record-name\">${friendlyName(r.collection)}</span><span class=\"record-count\">${r.count}${r.hasMore ? \"+\" : \"\"}</span>`;\n container.appendChild(row);\n }\n }\n } catch (e) {\n console.error(\"Failed to fetch repo data:\", e);\n }\n };\n\n const fetchRelaySync = async () => {\n if (!pdsRev) return;\n try {\n const res = await fetch(\n `${RELAY}/xrpc/com.atproto.sync.getLatestCommit?did=${encodeURIComponent(DID)}`,\n );\n if (res.status === 404) {\n setSyncStatus(\"unknown\");\n return;\n }\n const data = await res.json();\n setSyncStatus(data.rev === pdsRev ? \"synced\" : \"behind\", data.rev);\n } catch {\n setSyncStatus(\"error\");\n }\n };\n\n // -- Sync status display --\n const setSyncStatus = (status, rev) => {\n if (status === currentSyncStatus) return;\n const el = $(\"sync-status\");\n const prevStatus = currentSyncStatus;\n\n el.className = `sync-status ${status}`;\n el.querySelector(\".status-text\").textContent = status.toUpperCase();\n $(\"relay-rev\").textContent = rev ? `rev: ${rev.slice(0, 12)}` : \"\";\n\n if (prevStatus && prevStatus !== status) {\n el.classList.add(\"flash\");\n setTimeout(() => el.classList.remove(\"flash\"), 1200);\n }\n currentSyncStatus = status;\n };\n\n // -- Event stream --\n const addEvent = (seq, action, path) => {\n const container = $(\"events\");\n container.querySelector(\".empty-state\")?.remove();\n\n const el = document.createElement(\"div\");\n el.className = \"event new\";\n const time = new Date().toLocaleTimeString(\"en-GB\", {\n hour12: false,\n });\n el.innerHTML =\n `<span class=\"event-time\">${time}</span>` +\n `<span class=\"event-seq\">#${seq}</span>` +\n `<span class=\"event-action ${action}\">${action.toUpperCase()}</span>` +\n `<span class=\"event-path\">${path}</span>`;\n container.prepend(el);\n setTimeout(() => el.classList.remove(\"new\"), 1500);\n while (container.children.length > MAX_EVENTS) {\n container.lastChild.remove();\n }\n };\n\n // -- WebSocket --\n const setWsStatus = (status) => {\n const el = $(\"ws-status\");\n el.className = `ws-status ${status}`;\n el.querySelector(\".ws-label\").textContent = status;\n };\n\n const connectFirehose = () => {\n if (reconnectTimer) {\n clearTimeout(reconnectTimer);\n reconnectTimer = null;\n }\n const proto = location.protocol === \"https:\" ? \"wss:\" : \"ws:\";\n const ws = new WebSocket(\n `${proto}//${location.host}/xrpc/com.atproto.sync.subscribeRepos`,\n );\n ws.binaryType = \"arraybuffer\";\n\n ws.onopen = () => setWsStatus(\"connected\");\n ws.onmessage = (e) => {\n const commit = parseFirehoseMessage(e.data);\n if (!commit) return;\n for (const op of commit.ops) {\n addEvent(commit.seq, op.action, op.path);\n }\n };\n ws.onclose = () => {\n setWsStatus(\"disconnected\");\n reconnectTimer = setTimeout(connectFirehose, 3000);\n };\n ws.onerror = () => setWsStatus(\"error\");\n };\n\n // -- Init --\n const init = () => {\n applyConfig();\n fetchRepoData();\n fetchRelaySync();\n connectFirehose();\n\n setInterval(fetchRelaySync, 5000);\n setInterval(fetchRepoData, 30000);\n };\n\n if (document.readyState === \"loading\") {\n document.addEventListener(\"DOMContentLoaded\", init);\n } else {\n init();\n }\n }\n <\/script>\n </body>\n</html>\n";
5712
+ var dashboard_default = "<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <title>CIRRUS</title>\n <style>\n * {\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n }\n :root {\n --bg: #08090d;\n --panel: #0f1117;\n --border: #1a1d2e;\n --text: #b4bcd0;\n --text-bright: #e8ecf4;\n --accent: #7dd3fc;\n --green: #4ade80;\n --amber: #fbbf24;\n --red: #f87171;\n --dim: #3f4558;\n }\n html,\n body {\n height: 100%;\n background: var(--bg);\n color: var(--text);\n font-family:\n ui-monospace, \"Cascadia Code\", \"Source Code Pro\", Menlo, Consolas,\n \"DejaVu Sans Mono\", monospace;\n overflow: hidden;\n }\n body {\n display: flex;\n flex-direction: column;\n padding: clamp(1rem, 2vw, 2rem);\n gap: clamp(0.75rem, 1.5vw, 1.5rem);\n }\n\n /* Header */\n header {\n display: flex;\n align-items: baseline;\n gap: 1.5rem;\n flex-wrap: wrap;\n }\n .brand {\n font-size: clamp(1.5rem, 3vw, 2.5rem);\n font-weight: 700;\n color: var(--text-bright);\n letter-spacing: 0.15em;\n }\n .server-info {\n display: flex;\n gap: 1.5rem;\n align-items: baseline;\n font-size: clamp(0.9rem, 1.5vw, 1.2rem);\n }\n .hostname {\n color: var(--accent);\n }\n .ver {\n color: var(--dim);\n }\n .identity {\n font-size: clamp(0.8rem, 1.2vw, 1rem);\n color: var(--dim);\n width: 100%;\n }\n .identity .handle {\n color: var(--text);\n }\n\n /* Panels */\n .panels {\n display: grid;\n grid-template-columns: 1fr 1fr;\n gap: clamp(0.75rem, 1.5vw, 1.5rem);\n }\n .panel {\n background: var(--panel);\n border: 1px solid var(--border);\n border-radius: 8px;\n padding: clamp(1rem, 2vw, 1.5rem);\n }\n .panel h2 {\n font-size: clamp(0.7rem, 1vw, 0.85rem);\n letter-spacing: 0.2em;\n color: var(--dim);\n margin-bottom: clamp(0.75rem, 1.5vw, 1.25rem);\n font-weight: 500;\n }\n\n /* Repository panel */\n .record-row {\n display: flex;\n justify-content: space-between;\n padding: 0.3em 0;\n font-size: clamp(0.9rem, 1.5vw, 1.2rem);\n }\n .record-name {\n color: var(--text);\n }\n .record-count {\n color: var(--text-bright);\n font-weight: 600;\n font-variant-numeric: tabular-nums;\n }\n .empty-state {\n color: var(--dim);\n font-style: italic;\n font-size: clamp(0.85rem, 1.3vw, 1.1rem);\n }\n\n /* Federation panel */\n .relay-name {\n font-size: clamp(0.85rem, 1.3vw, 1.1rem);\n color: var(--text);\n margin-bottom: clamp(0.5rem, 1vw, 1rem);\n }\n .sync-status {\n display: flex;\n align-items: center;\n gap: 0.75rem;\n transition: all 0.5s ease;\n }\n .sync-status .status-text {\n font-size: clamp(1.5rem, 3vw, 2.5rem);\n font-weight: 700;\n letter-spacing: 0.1em;\n transition:\n color 0.5s ease,\n text-shadow 0.8s ease;\n }\n .dot {\n width: clamp(10px, 1.2vw, 16px);\n height: clamp(10px, 1.2vw, 16px);\n border-radius: 50%;\n display: inline-block;\n flex-shrink: 0;\n transition:\n background 0.5s ease,\n box-shadow 0.8s ease;\n }\n .sync-status.checking .dot {\n background: var(--dim);\n }\n .sync-status.checking .status-text {\n color: var(--dim);\n }\n .sync-status.unknown .dot {\n background: var(--dim);\n animation: pulse-dim 3s ease-in-out infinite;\n }\n .sync-status.unknown .status-text {\n color: var(--dim);\n }\n .sync-status.behind .dot {\n background: var(--amber);\n animation: pulse 1.5s ease-in-out infinite;\n }\n .sync-status.behind .status-text {\n color: var(--amber);\n }\n .sync-status.synced .dot {\n background: var(--green);\n box-shadow: 0 0 12px var(--green);\n }\n .sync-status.synced .status-text {\n color: var(--green);\n }\n .sync-status.error .dot {\n background: var(--red);\n }\n .sync-status.error .status-text {\n color: var(--red);\n }\n .sync-status.flash .status-text {\n text-shadow:\n 0 0 30px currentColor,\n 0 0 60px currentColor;\n }\n .sync-status.flash .dot {\n box-shadow:\n 0 0 20px currentColor,\n 0 0 40px currentColor;\n }\n .relay-rev {\n font-size: clamp(0.7rem, 1vw, 0.85rem);\n color: var(--dim);\n margin-top: 0.5rem;\n font-variant-numeric: tabular-nums;\n }\n\n /* Events */\n .events-container {\n flex: 1;\n display: flex;\n flex-direction: column;\n background: var(--panel);\n border: 1px solid var(--border);\n border-radius: 8px;\n overflow: hidden;\n min-height: 0;\n }\n .events-header {\n display: flex;\n justify-content: space-between;\n align-items: center;\n padding: clamp(0.75rem, 1.5vw, 1rem) clamp(1rem, 2vw, 1.5rem);\n border-bottom: 1px solid var(--border);\n flex-shrink: 0;\n }\n .events-header h2 {\n font-size: clamp(0.7rem, 1vw, 0.85rem);\n letter-spacing: 0.2em;\n color: var(--dim);\n font-weight: 500;\n }\n .ws-status {\n display: flex;\n align-items: center;\n gap: 0.5rem;\n font-size: clamp(0.7rem, 1vw, 0.85rem);\n color: var(--dim);\n }\n .ws-status.connected .dot {\n background: var(--green);\n animation: pulse 2s ease-in-out infinite;\n }\n .ws-status.connected .ws-label {\n color: var(--green);\n }\n .ws-status.disconnected .dot {\n background: var(--dim);\n }\n .ws-status.error .dot {\n background: var(--red);\n }\n .events-list {\n flex: 1;\n overflow-y: auto;\n padding: 0 clamp(1rem, 2vw, 1.5rem);\n }\n .events-list .empty-state {\n padding: 1rem 0;\n }\n .event {\n display: flex;\n gap: clamp(0.75rem, 1.5vw, 1.5rem);\n padding: 0.4em 0;\n font-size: clamp(0.85rem, 1.3vw, 1.1rem);\n border-bottom: 1px solid rgba(26, 29, 46, 0.5);\n animation: slide-in 0.3s ease-out;\n }\n .event.new {\n background: rgba(125, 211, 252, 0.06);\n transition: background 1.5s ease-out;\n }\n .event-time {\n color: var(--dim);\n font-variant-numeric: tabular-nums;\n flex-shrink: 0;\n }\n .event-seq {\n color: var(--dim);\n font-variant-numeric: tabular-nums;\n flex-shrink: 0;\n min-width: 3em;\n text-align: right;\n }\n .event-action {\n flex-shrink: 0;\n font-weight: 600;\n min-width: 5em;\n }\n .event-action.create {\n color: var(--green);\n }\n .event-action.update {\n color: var(--amber);\n }\n .event-action.delete {\n color: var(--red);\n }\n .event-path {\n color: var(--text);\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n flex: 1;\n }\n /* Animations */\n @keyframes pulse {\n 0%,\n 100% {\n opacity: 0.5;\n }\n 50% {\n opacity: 1;\n }\n }\n @keyframes pulse-dim {\n 0%,\n 100% {\n opacity: 0.3;\n }\n 50% {\n opacity: 0.6;\n }\n }\n @keyframes slide-in {\n from {\n opacity: 0;\n transform: translateX(20px);\n }\n to {\n opacity: 1;\n transform: translateX(0);\n }\n }\n\n /* Spaces panel */\n .spaces-alpha {\n font-size: 0.6rem;\n color: var(--amber);\n border: 1px solid var(--amber);\n padding: 0 0.3em;\n border-radius: 3px;\n vertical-align: middle;\n }\n .space-row {\n display: flex;\n flex-wrap: wrap;\n align-items: baseline;\n gap: 0.5em;\n padding: 0.35em 0;\n border-bottom: 1px solid var(--border);\n font-size: 0.8rem;\n }\n .space-row:last-child {\n border-bottom: none;\n }\n .space-uri {\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n max-width: 100%;\n }\n .space-meta {\n color: var(--text-dim, #888);\n font-size: 0.72rem;\n }\n .space-actions button,\n .spaces-token button,\n .space-members button {\n background: transparent;\n color: inherit;\n border: 1px solid var(--border);\n border-radius: 3px;\n padding: 0.1em 0.5em;\n font: inherit;\n font-size: 0.72rem;\n cursor: pointer;\n }\n .space-actions button:hover,\n .space-members button:hover {\n border-color: var(--red);\n color: var(--red);\n }\n .space-members {\n width: 100%;\n display: flex;\n gap: 0.4em;\n align-items: center;\n }\n .space-members input {\n background: transparent;\n border: 1px solid var(--border);\n border-radius: 3px;\n color: inherit;\n font: inherit;\n font-size: 0.72rem;\n padding: 0.1em 0.4em;\n flex: 1;\n min-width: 8em;\n }\n\n /* Scrollbar */\n .events-list::-webkit-scrollbar {\n width: 4px;\n }\n .events-list::-webkit-scrollbar-track {\n background: transparent;\n }\n .events-list::-webkit-scrollbar-thumb {\n background: var(--border);\n border-radius: 2px;\n }\n </style>\n </head>\n <body>\n <header>\n <div class=\"brand\">&#9729;&#65039; CIRRUS</div>\n <div class=\"server-info\">\n <span class=\"hostname\" id=\"cfg-hostname\"></span>\n <span class=\"ver\" id=\"cfg-version\"></span>\n </div>\n <div class=\"identity\">\n <span class=\"handle\" id=\"cfg-handle\"></span>\n <span>&middot;</span>\n <span id=\"cfg-did\"></span>\n </div>\n </header>\n\n <section class=\"panels\">\n <div class=\"panel\">\n <h2>REPOSITORY</h2>\n <div id=\"records\"><span class=\"empty-state\">Loading&hellip;</span></div>\n </div>\n <div class=\"panel\">\n <h2>FEDERATION</h2>\n <div class=\"relay-name\">bsky.network</div>\n <div class=\"sync-status checking\" id=\"sync-status\">\n <span class=\"dot\"></span>\n <span class=\"status-text\">CHECKING</span>\n </div>\n <div class=\"relay-rev\" id=\"relay-rev\"></div>\n </div>\n </section>\n\n <section class=\"panels\" id=\"spaces-section\" style=\"display: none\">\n <div class=\"panel\" style=\"grid-column: 1 / -1\">\n <h2>SPACES <span class=\"spaces-alpha\">ALPHA</span></h2>\n <div id=\"spaces-body\">\n <span class=\"empty-state\">Loading&hellip;</span>\n </div>\n </div>\n </section>\n\n <section class=\"events-container\">\n <div class=\"events-header\">\n <h2>EVENTS</h2>\n <div class=\"ws-status disconnected\" id=\"ws-status\">\n <span class=\"dot\"></span>\n <span class=\"ws-label\">disconnected</span>\n </div>\n </div>\n <div class=\"events-list\" id=\"events\">\n <div class=\"empty-state\">Waiting for events&hellip;</div>\n </div>\n </section>\n\n <script>\n {\n const CONFIG = window.__CIRRUS_CONFIG || {};\n const BASE = window.location.origin;\n const RELAY = \"https://bsky.network\";\n const DID = CONFIG.did || \"\";\n const MAX_EVENTS = 100;\n let pdsRev = null;\n let currentSyncStatus = null;\n let reconnectTimer = null;\n\n const $ = (id) => document.getElementById(id);\n\n // -- Populate config into DOM --\n const applyConfig = () => {\n document.title = `CIRRUS \\u00b7 ${CONFIG.hostname || \"\"}`;\n $(\"cfg-hostname\").textContent = CONFIG.hostname || \"\";\n $(\"cfg-version\").textContent = CONFIG.version\n ? `v${CONFIG.version}`\n : \"\";\n $(\"cfg-handle\").textContent = CONFIG.handle\n ? `@${CONFIG.handle}`\n : \"\";\n $(\"cfg-did\").textContent = CONFIG.did || \"\";\n };\n\n // -- Minimal CBOR decoder for firehose frames --\n const decodeCBOR = (d, o) => {\n const view = new DataView(d.buffer, d.byteOffset, d.byteLength);\n const major = d[o] >> 5;\n const additional = d[o] & 0x1f;\n\n const readLen = (off, add) => {\n if (add < 24) return [add, off + 1];\n if (add === 24) return [d[off + 1], off + 2];\n if (add === 25) return [view.getUint16(off + 1), off + 3];\n if (add === 26) return [view.getUint32(off + 1), off + 5];\n if (add === 27)\n return [\n view.getUint32(off + 1) * 0x100000000 + view.getUint32(off + 5),\n off + 9,\n ];\n return [0, off + 1];\n };\n\n switch (major) {\n case 0:\n return readLen(o, additional);\n case 1: {\n const [n, p] = readLen(o, additional);\n return [-1 - n, p];\n }\n case 2: {\n const [n, p] = readLen(o, additional);\n return [d.slice(p, p + n), p + n];\n }\n case 3: {\n const [n, p] = readLen(o, additional);\n return [new TextDecoder().decode(d.subarray(p, p + n)), p + n];\n }\n case 4: {\n let [count, pos] = readLen(o, additional);\n const arr = [];\n for (let i = 0; i < count; i++) {\n const [val, next] = decodeCBOR(d, pos);\n arr.push(val);\n pos = next;\n }\n return [arr, pos];\n }\n case 5: {\n let [count, pos] = readLen(o, additional);\n const obj = {};\n for (let i = 0; i < count; i++) {\n const [key, kNext] = decodeCBOR(d, pos);\n const [val, vNext] = decodeCBOR(d, kNext);\n obj[key] = val;\n pos = vNext;\n }\n return [obj, pos];\n }\n case 6: {\n const [, p] = readLen(o, additional);\n return decodeCBOR(d, p);\n }\n case 7: {\n if (additional === 20) return [false, o + 1];\n if (additional === 21) return [true, o + 1];\n if (additional === 22) return [null, o + 1];\n if (additional === 23) return [undefined, o + 1];\n if (additional === 25) return [null, o + 3];\n if (additional === 26) return [view.getFloat32(o + 1), o + 5];\n if (additional === 27) return [view.getFloat64(o + 1), o + 9];\n return [null, o + 1];\n }\n }\n return [null, o + 1];\n };\n\n const parseFirehoseMessage = (buffer) => {\n try {\n const d = new Uint8Array(buffer);\n const [header, bodyOff] = decodeCBOR(d, 0);\n if (!header || header.op !== 1 || header.t !== \"#commit\")\n return null;\n const [body] = decodeCBOR(d, bodyOff);\n if (!body) return null;\n return {\n seq: body.seq,\n repo: body.repo,\n rev: body.rev,\n ops: (body.ops || []).map((op) => ({\n action: op.action,\n path: op.path,\n })),\n };\n } catch {\n return null;\n }\n };\n\n // -- Friendly collection names --\n const COLLECTION_NAMES = {\n \"app.bsky.feed.post\": \"posts\",\n \"app.bsky.feed.like\": \"likes\",\n \"app.bsky.graph.follow\": \"follows\",\n \"app.bsky.feed.repost\": \"reposts\",\n \"app.bsky.actor.profile\": \"profile\",\n \"app.bsky.graph.block\": \"blocks\",\n \"app.bsky.graph.list\": \"lists\",\n \"app.bsky.graph.listitem\": \"list items\",\n \"app.bsky.feed.generator\": \"feeds\",\n \"app.bsky.feed.threadgate\": \"threadgates\",\n \"app.bsky.graph.starterpack\": \"starter packs\",\n };\n\n const friendlyName = (collection) =>\n COLLECTION_NAMES[collection] || collection.split(\".\").pop();\n\n const animateNumber = (el, target) => {\n let current = parseInt(el.textContent) || 0;\n if (current === target) return;\n const diff = target - current;\n const steps = Math.min(Math.abs(diff), 20);\n const stepSize = diff / steps;\n let step = 0;\n const tick = () => {\n step++;\n if (step >= steps) {\n el.textContent = target;\n return;\n }\n el.textContent = Math.round(current + stepSize * step);\n requestAnimationFrame(tick);\n };\n requestAnimationFrame(tick);\n };\n\n // -- Data fetching --\n const fetchRepoData = async () => {\n try {\n const reposRes = await fetch(\n `${BASE}/xrpc/com.atproto.sync.listRepos`,\n );\n const reposData = await reposRes.json();\n const repo = reposData.repos?.[0];\n if (repo) pdsRev = repo.rev;\n\n const descRes = await fetch(\n `${BASE}/xrpc/com.atproto.repo.describeRepo?repo=${encodeURIComponent(DID)}`,\n );\n const desc = await descRes.json();\n const collections = desc.collections || [];\n\n if (collections.length === 0) {\n $(\"records\").innerHTML =\n '<span class=\"empty-state\">No records yet</span>';\n return;\n }\n\n const results = await Promise.all(\n collections.map(async (col) => {\n const res = await fetch(\n `${BASE}/xrpc/com.atproto.repo.listRecords?repo=${encodeURIComponent(DID)}&collection=${encodeURIComponent(col)}&limit=100`,\n );\n const data = await res.json();\n return {\n collection: col,\n count: data.records?.length || 0,\n hasMore: !!data.cursor,\n };\n }),\n );\n\n const container = $(\"records\");\n for (const r of results) {\n const id = `rec-${r.collection.replaceAll(\".\", \"-\")}`;\n const existing = $(id);\n if (existing) {\n const countEl = existing.querySelector(\".record-count\");\n animateNumber(countEl, r.count);\n if (r.hasMore) countEl.textContent = `${r.count}+`;\n } else {\n if (container.querySelector(\".empty-state\"))\n container.innerHTML = \"\";\n const row = document.createElement(\"div\");\n row.className = \"record-row\";\n row.id = id;\n row.innerHTML = `<span class=\"record-name\">${friendlyName(r.collection)}</span><span class=\"record-count\">${r.count}${r.hasMore ? \"+\" : \"\"}</span>`;\n container.appendChild(row);\n }\n }\n } catch (e) {\n console.error(\"Failed to fetch repo data:\", e);\n }\n };\n\n const fetchRelaySync = async () => {\n if (!pdsRev) return;\n try {\n const res = await fetch(\n `${RELAY}/xrpc/com.atproto.sync.getLatestCommit?did=${encodeURIComponent(DID)}`,\n );\n if (res.status === 404) {\n setSyncStatus(\"unknown\");\n return;\n }\n const data = await res.json();\n setSyncStatus(data.rev === pdsRev ? \"synced\" : \"behind\", data.rev);\n } catch {\n setSyncStatus(\"error\");\n }\n };\n\n // -- Sync status display --\n const setSyncStatus = (status, rev) => {\n if (status === currentSyncStatus) return;\n const el = $(\"sync-status\");\n const prevStatus = currentSyncStatus;\n\n el.className = `sync-status ${status}`;\n el.querySelector(\".status-text\").textContent = status.toUpperCase();\n $(\"relay-rev\").textContent = rev ? `rev: ${rev.slice(0, 12)}` : \"\";\n\n if (prevStatus && prevStatus !== status) {\n el.classList.add(\"flash\");\n setTimeout(() => el.classList.remove(\"flash\"), 1200);\n }\n currentSyncStatus = status;\n };\n\n // -- Event stream --\n const addEvent = (seq, action, path) => {\n const container = $(\"events\");\n container.querySelector(\".empty-state\")?.remove();\n\n const el = document.createElement(\"div\");\n el.className = \"event new\";\n const time = new Date().toLocaleTimeString(\"en-GB\", {\n hour12: false,\n });\n el.innerHTML =\n `<span class=\"event-time\">${time}</span>` +\n `<span class=\"event-seq\">#${seq}</span>` +\n `<span class=\"event-action ${action}\">${action.toUpperCase()}</span>` +\n `<span class=\"event-path\">${path}</span>`;\n container.prepend(el);\n setTimeout(() => el.classList.remove(\"new\"), 1500);\n while (container.children.length > MAX_EVENTS) {\n container.lastChild.remove();\n }\n };\n\n // -- WebSocket --\n const setWsStatus = (status) => {\n const el = $(\"ws-status\");\n el.className = `ws-status ${status}`;\n el.querySelector(\".ws-label\").textContent = status;\n };\n\n const connectFirehose = () => {\n if (reconnectTimer) {\n clearTimeout(reconnectTimer);\n reconnectTimer = null;\n }\n const proto = location.protocol === \"https:\" ? \"wss:\" : \"ws:\";\n const ws = new WebSocket(\n `${proto}//${location.host}/xrpc/com.atproto.sync.subscribeRepos`,\n );\n ws.binaryType = \"arraybuffer\";\n\n ws.onopen = () => setWsStatus(\"connected\");\n ws.onmessage = (e) => {\n const commit = parseFirehoseMessage(e.data);\n if (!commit) return;\n for (const op of commit.ops) {\n addEvent(commit.seq, op.action, op.path);\n }\n };\n ws.onclose = () => {\n setWsStatus(\"disconnected\");\n reconnectTimer = setTimeout(connectFirehose, 3000);\n };\n ws.onerror = () => setWsStatus(\"error\");\n };\n\n // -- Init --\n const init = () => {\n applyConfig();\n fetchRepoData();\n fetchRelaySync();\n connectFirehose();\n\n setInterval(fetchRelaySync, 5000);\n setInterval(fetchRepoData, 30000);\n };\n\n if (document.readyState === \"loading\") {\n document.addEventListener(\"DOMContentLoaded\", init);\n } else {\n init();\n }\n }\n <\/script>\n <script>\n // -- Spaces (alpha) panel --\n {\n const CONFIG = window.__CIRRUS_CONFIG || {};\n const BASE = window.location.origin;\n const section = document.getElementById(\"spaces-section\");\n const body = document.getElementById(\"spaces-body\");\n\n const tokenKey = \"cirrus_spaces_token\";\n const getToken = (force) => {\n let token = sessionStorage.getItem(tokenKey);\n if (!token || force) {\n token = window.prompt(\n \"Admin token (AUTH_TOKEN) for space management:\",\n );\n if (token) sessionStorage.setItem(tokenKey, token);\n }\n return token;\n };\n\n const xrpc = async (method, nsid, opts = {}) => {\n const token = getToken();\n if (!token) throw new Error(\"No admin token\");\n const url = new URL(`${BASE}/xrpc/${nsid}`);\n for (const [k, v] of Object.entries(opts.params || {})) {\n url.searchParams.set(k, v);\n }\n const res = await fetch(url, {\n method,\n headers: {\n Authorization: `Bearer ${token}`,\n ...(opts.body ? { \"Content-Type\": \"application/json\" } : {}),\n },\n ...(opts.body ? { body: JSON.stringify(opts.body) } : {}),\n });\n if (res.status === 401) {\n sessionStorage.removeItem(tokenKey);\n throw new Error(\"Invalid admin token\");\n }\n if (!res.ok) {\n const err = await res.json().catch(() => ({}));\n throw new Error(err.message || `${nsid} failed (${res.status})`);\n }\n return res.json();\n };\n\n const el = (tag, cls, text) => {\n const node = document.createElement(tag);\n if (cls) node.className = cls;\n if (text !== undefined) node.textContent = text;\n return node;\n };\n\n const render = (status) => {\n body.replaceChildren();\n if (!status.spaces.length) {\n body.append(el(\"span\", \"empty-state\", \"No spaces yet.\"));\n return;\n }\n for (const space of status.spaces) {\n const row = el(\"div\", \"space-row\");\n row.append(el(\"span\", \"space-uri\", space.uri));\n const flags = [space.role, space.state]\n .concat(space.outdated ? [\"OUTDATED\"] : [])\n .join(\" · \");\n row.append(\n el(\n \"span\",\n \"space-meta\",\n `${flags} · ${space.recordCount} records · ${space.memberCount} members`,\n ),\n );\n if (space.role === \"authority\" && space.state === \"active\") {\n const actions = el(\"span\", \"space-actions\");\n const del = el(\"button\", null, \"delete\");\n del.addEventListener(\"click\", async () => {\n if (!window.confirm(`Delete ${space.uri}?`)) return;\n try {\n await xrpc(\n \"POST\",\n \"com.atproto.simplespace.deleteSpace\",\n { body: { space: space.uri } },\n );\n load();\n } catch (err) {\n window.alert(err.message);\n }\n });\n actions.append(del);\n row.append(actions);\n\n const members = el(\"div\", \"space-members\");\n const input = el(\"input\");\n input.placeholder = \"did:… to add/remove\";\n const mkBtn = (label, nsid) => {\n const btn = el(\"button\", null, label);\n btn.addEventListener(\"click\", async () => {\n const did = input.value.trim();\n if (!did) return;\n try {\n await xrpc(\"POST\", nsid, {\n body: { space: space.uri, did },\n });\n input.value = \"\";\n load();\n } catch (err) {\n window.alert(err.message);\n }\n });\n return btn;\n };\n members.append(\n input,\n mkBtn(\"add member\", \"com.atproto.simplespace.addMember\"),\n mkBtn(\n \"remove member\",\n \"com.atproto.simplespace.removeMember\",\n ),\n );\n row.append(members);\n }\n body.append(row);\n }\n };\n\n const load = async () => {\n try {\n const status = await xrpc(\n \"GET\",\n \"gg.mk.experimental.getSpacesStatus\",\n );\n render(status);\n } catch (err) {\n body.replaceChildren(\n el(\"span\", \"empty-state\", `Spaces: ${err.message}`),\n );\n }\n };\n\n if (CONFIG.spacesEnabled) {\n section.style.display = \"\";\n load();\n }\n }\n <\/script>\n </body>\n</html>\n";
5196
5713
 
5197
5714
  //#endregion
5198
5715
  //#region src/dashboard.ts
@@ -5203,7 +5720,7 @@ function renderDashboard(config) {
5203
5720
 
5204
5721
  //#endregion
5205
5722
  //#region package.json
5206
- var version = "0.18.0";
5723
+ var version = "0.19.0";
5207
5724
 
5208
5725
  //#endregion
5209
5726
  //#region src/index.ts
@@ -5318,7 +5835,8 @@ app.get("/status", (c) => {
5318
5835
  hostname: c.env.PDS_HOSTNAME,
5319
5836
  handle: c.env.HANDLE,
5320
5837
  did: c.env.DID,
5321
- version
5838
+ version,
5839
+ spacesEnabled: c.env.SPACES_ENABLED === "true"
5322
5840
  }));
5323
5841
  });
5324
5842
  app.get("/xrpc/com.atproto.sync.getRepo", (c) => getRepo(c, getAccountDO(c.env)));
@@ -5470,11 +5988,25 @@ app.post("/passkey/delete", requireAuth, async (c) => {
5470
5988
  });
5471
5989
  const oauthApp = createOAuthApp(getAccountDO);
5472
5990
  app.route("/", oauthApp);
5991
+ if (env$1.SPACES_ENABLED === "true") if (env$1.SPACES && env$1.SPACES_INDEX) app.route("/", createSpacesApp({
5992
+ env: env$1,
5993
+ didResolver,
5994
+ getKeypair
5995
+ }));
5996
+ else {
5997
+ console.error("SPACES_ENABLED is set but the SPACES / SPACES_INDEX Durable Object bindings are missing. Space endpoints will return 503.");
5998
+ app.route("/", createSpacesUnavailableApp());
5999
+ }
6000
+ if (env$1.SPACES && env$1.SPACES_INDEX) app.route("/", createSpacesAdminApp({
6001
+ env: env$1,
6002
+ didResolver,
6003
+ getKeypair
6004
+ }));
5473
6005
  app.get("/xrpc/app.bsky.feed.getFeed", (c) => handleGetFeedProxy(c, didResolver, getKeypair));
5474
6006
  app.post("/xrpc/com.atproto.moderation.createReport", (c) => handleCreateReportProxy(c, didResolver, getKeypair));
5475
6007
  app.all("/xrpc/*", (c) => handleXrpcProxy(c, didResolver, getKeypair));
5476
6008
  var src_default = app;
5477
6009
 
5478
6010
  //#endregion
5479
- export { AccountDurableObject, src_default as default };
6011
+ export { AccountDurableObject, SpaceDurableObject, SpaceIndexDurableObject, src_default as default };
5480
6012
  //# sourceMappingURL=index.js.map