@getcirrus/pds 0.13.0 → 0.15.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,22 +1,23 @@
1
1
  import { DurableObject, env, waitUntil } from "cloudflare:workers";
2
2
  import { BlockMap, ReadableBlockstore, Repo, WriteOpAction, blocksToCarFile, getRecords, readCarWithRoot, writeCarStream } from "@atproto/repo";
3
3
  import { Secp256k1Keypair, randomStr, verifySignature } from "@atproto/crypto";
4
- import { CID, asCid, isBlobRef } from "@atproto/lex-data";
4
+ import { CID, asCid, isBlobRef, isLegacyBlobRef } from "@atproto/lex-data";
5
5
  import { now } from "@atcute/tid";
6
6
  import { decode, encode, fromBytes, isBytes, toBytes, toCidLink } from "@atcute/cbor";
7
7
  import { CODEC_RAW, create, fromString, toString } from "@atcute/cid";
8
+ import { ATProtoOAuthProvider, REFRESH_TOKEN_TTL, ScopeMissingError, createAtcutePermissionSetResolver, permissionsFor } from "@getcirrus/oauth-provider";
8
9
  import { jsonToLex } from "@atproto/lex-json";
10
+ import { ValidationError, parse, safeParse } from "@atcute/lexicons/validations";
11
+ import { isDid, isHandle, isNsid, isRecordKey } from "@atcute/lexicons/syntax";
12
+ import { AppBskyActorProfile, AppBskyActorStatus, AppBskyFeedGenerator, AppBskyFeedLike, AppBskyFeedPost, AppBskyFeedPostgate, AppBskyFeedRepost, AppBskyFeedThreadgate, AppBskyGraphBlock, AppBskyGraphFollow, AppBskyGraphList, AppBskyGraphListblock, AppBskyGraphListitem, AppBskyGraphStarterpack, AppBskyGraphVerification, AppBskyLabelerService, AppBskyNotificationDeclaration, ChatBskyActorDeclaration } from "@atcute/bluesky";
13
+ import { ComAtprotoLexiconSchema } from "@atcute/atproto";
9
14
  import { Hono } from "hono";
10
15
  import { cors } from "hono/cors";
11
- import { isDid, isHandle, isNsid, isRecordKey } from "@atcute/lexicons/syntax";
12
16
  import { SignJWT, base64url, errors, jwtVerify } from "jose";
13
17
  import { compare, compare as compare$1, hash } from "bcryptjs";
14
- import { ATProtoOAuthProvider } from "@getcirrus/oauth-provider";
15
- import { generateAuthenticationOptions, generateRegistrationOptions, verifyAuthenticationResponse, verifyRegistrationResponse } from "@simplewebauthn/server";
16
18
  import { CompositeDidDocumentResolver, PlcDidDocumentResolver, WebDidDocumentResolver } from "@atcute/identity-resolver";
19
+ import { generateAuthenticationOptions, generateRegistrationOptions, verifyAuthenticationResponse, verifyRegistrationResponse } from "@simplewebauthn/server";
17
20
  import { defs, getAtprotoServiceEndpoint } from "@atcute/identity";
18
- import { ValidationError, parse } from "@atcute/lexicons/validations";
19
- import { AppBskyActorProfile, AppBskyFeedGenerator, AppBskyFeedLike, AppBskyFeedPost, AppBskyFeedPostgate, AppBskyFeedRepost, AppBskyFeedThreadgate, AppBskyGraphBlock, AppBskyGraphFollow, AppBskyGraphList, AppBskyGraphListblock, AppBskyGraphListitem, AppBskyGraphStarterpack, AppBskyGraphVerification, AppBskyLabelerService } from "@atcute/bluesky";
20
21
 
21
22
  //#region src/cbor-compat.ts
22
23
  /**
@@ -568,7 +569,7 @@ var SqliteRepoStorage = class extends ReadableBlockstore {
568
569
  * Implements the OAuthStorage interface from @getcirrus/oauth-provider,
569
570
  * storing OAuth data in SQLite tables within a Durable Object.
570
571
  */
571
- var SqliteOAuthStorage = class {
572
+ var SqliteOAuthStorage = class SqliteOAuthStorage {
572
573
  constructor(sql) {
573
574
  this.sql = sql;
574
575
  }
@@ -598,13 +599,11 @@ var SqliteOAuthStorage = class {
598
599
  scope TEXT NOT NULL,
599
600
  dpop_jkt TEXT,
600
601
  issued_at INTEGER NOT NULL,
601
- expires_at INTEGER NOT NULL,
602
+ access_expires_at INTEGER NOT NULL,
603
+ refresh_expires_at INTEGER NOT NULL,
602
604
  revoked INTEGER NOT NULL DEFAULT 0
603
605
  );
604
606
 
605
- CREATE INDEX IF NOT EXISTS idx_tokens_refresh ON oauth_tokens(refresh_token);
606
- CREATE INDEX IF NOT EXISTS idx_tokens_sub ON oauth_tokens(sub);
607
- CREATE INDEX IF NOT EXISTS idx_tokens_expires ON oauth_tokens(expires_at);
608
607
 
609
608
  -- Cached client metadata
610
609
  CREATE TABLE IF NOT EXISTS oauth_clients (
@@ -641,8 +640,24 @@ var SqliteOAuthStorage = class {
641
640
  );
642
641
 
643
642
  CREATE INDEX IF NOT EXISTS idx_challenges_created ON oauth_webauthn_challenges(created_at);
643
+
644
+ -- Cached permission-set lexicons resolved via @atcute/lexicon-resolver.
645
+ -- Cache is per-account (lives inside this AccountDurableObject) and
646
+ -- uses the stale-while-revalidate semantics from the atproto
647
+ -- permission spec.
648
+ CREATE TABLE IF NOT EXISTS oauth_permission_sets (
649
+ nsid TEXT PRIMARY KEY,
650
+ lexicon TEXT NOT NULL,
651
+ fetched_at INTEGER NOT NULL,
652
+ stale_at INTEGER NOT NULL,
653
+ expires_at INTEGER NOT NULL
654
+ );
655
+
656
+ CREATE INDEX IF NOT EXISTS idx_permission_sets_expires ON oauth_permission_sets(expires_at);
644
657
  `);
645
658
  this.migrateClientTable();
659
+ this.migrateTokensTable();
660
+ this.ensureTokenIndexes();
646
661
  }
647
662
  migrateClientTable() {
648
663
  if (!this.sql.exec("PRAGMA table_info(oauth_clients)").toArray().map((r) => r.name).includes("token_endpoint_auth_method")) {
@@ -652,14 +667,51 @@ var SqliteOAuthStorage = class {
652
667
  this.sql.exec("DELETE FROM oauth_clients");
653
668
  }
654
669
  }
670
+ migrateTokensTable() {
671
+ const columns = this.sql.exec("PRAGMA table_info(oauth_tokens)").toArray().map((r) => r.name);
672
+ if (columns.length === 0) return;
673
+ if (columns.includes("access_expires_at") && columns.includes("refresh_expires_at")) return;
674
+ this.sql.exec(`
675
+ CREATE TABLE oauth_tokens_new (
676
+ access_token TEXT PRIMARY KEY,
677
+ refresh_token TEXT NOT NULL UNIQUE,
678
+ client_id TEXT NOT NULL,
679
+ sub TEXT NOT NULL,
680
+ scope TEXT NOT NULL,
681
+ dpop_jkt TEXT,
682
+ issued_at INTEGER NOT NULL,
683
+ access_expires_at INTEGER NOT NULL,
684
+ refresh_expires_at INTEGER NOT NULL,
685
+ revoked INTEGER NOT NULL DEFAULT 0
686
+ );
687
+ `);
688
+ this.sql.exec(`INSERT INTO oauth_tokens_new (
689
+ access_token, refresh_token, client_id, sub, scope, dpop_jkt, issued_at, access_expires_at, refresh_expires_at, revoked
690
+ )
691
+ SELECT
692
+ access_token, refresh_token, client_id, sub, scope, dpop_jkt, issued_at,
693
+ expires_at AS access_expires_at,
694
+ MAX(expires_at, issued_at + ?) AS refresh_expires_at,
695
+ revoked
696
+ FROM oauth_tokens`, REFRESH_TOKEN_TTL);
697
+ this.sql.exec("DROP TABLE oauth_tokens");
698
+ this.sql.exec("ALTER TABLE oauth_tokens_new RENAME TO oauth_tokens");
699
+ }
700
+ ensureTokenIndexes() {
701
+ this.sql.exec("CREATE INDEX IF NOT EXISTS idx_tokens_refresh ON oauth_tokens(refresh_token)");
702
+ this.sql.exec("CREATE INDEX IF NOT EXISTS idx_tokens_sub ON oauth_tokens(sub)");
703
+ this.sql.exec("CREATE INDEX IF NOT EXISTS idx_tokens_access_expires ON oauth_tokens(access_expires_at)");
704
+ this.sql.exec("CREATE INDEX IF NOT EXISTS idx_tokens_refresh_expires ON oauth_tokens(refresh_expires_at)");
705
+ }
655
706
  /**
656
707
  * Clean up expired entries. Should be called periodically.
657
708
  */
658
709
  cleanup() {
659
710
  const now$1 = Date.now();
660
711
  this.sql.exec("DELETE FROM oauth_auth_codes WHERE expires_at < ?", now$1);
661
- this.sql.exec("DELETE FROM oauth_tokens WHERE expires_at < ? AND revoked = 0", now$1);
712
+ this.sql.exec("DELETE FROM oauth_tokens WHERE refresh_expires_at < ?", now$1);
662
713
  this.sql.exec("DELETE FROM oauth_par_requests WHERE expires_at < ?", now$1);
714
+ this.sql.exec("DELETE FROM oauth_permission_sets WHERE expires_at < ?", now$1);
663
715
  const nonceExpiry = now$1 - 300 * 1e3;
664
716
  this.sql.exec("DELETE FROM oauth_nonces WHERE created_at < ?", nonceExpiry);
665
717
  const challengeExpiry = now$1 - 120 * 1e3;
@@ -695,17 +747,17 @@ var SqliteOAuthStorage = class {
695
747
  }
696
748
  async saveTokens(data) {
697
749
  this.sql.exec(`INSERT INTO oauth_tokens
698
- (access_token, refresh_token, client_id, sub, scope, dpop_jkt, issued_at, expires_at, revoked)
699
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, data.accessToken, data.refreshToken, data.clientId, data.sub, data.scope, data.dpopJkt ?? null, data.issuedAt, data.expiresAt, data.revoked ? 1 : 0);
750
+ (access_token, refresh_token, client_id, sub, scope, dpop_jkt, issued_at, access_expires_at, refresh_expires_at, revoked)
751
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, data.accessToken, data.refreshToken, data.clientId, data.sub, data.scope, data.dpopJkt ?? null, data.issuedAt, data.accessExpiresAt, data.refreshExpiresAt, data.revoked ? 1 : 0);
700
752
  }
701
753
  async getTokenByAccess(accessToken) {
702
- const rows = this.sql.exec(`SELECT access_token, refresh_token, client_id, sub, scope, dpop_jkt, issued_at, expires_at, revoked
754
+ const rows = this.sql.exec(`SELECT access_token, refresh_token, client_id, sub, scope, dpop_jkt, issued_at, access_expires_at, refresh_expires_at, revoked
703
755
  FROM oauth_tokens WHERE access_token = ?`, accessToken).toArray();
704
756
  if (rows.length === 0) return null;
705
757
  const row = rows[0];
706
758
  const revoked = Boolean(row.revoked);
707
- const expiresAt = row.expires_at;
708
- if (revoked || Date.now() > expiresAt) return null;
759
+ const accessExpiresAt = row.access_expires_at;
760
+ if (revoked || Date.now() > accessExpiresAt) return null;
709
761
  return {
710
762
  accessToken: row.access_token,
711
763
  refreshToken: row.refresh_token,
@@ -714,17 +766,19 @@ var SqliteOAuthStorage = class {
714
766
  scope: row.scope,
715
767
  dpopJkt: row.dpop_jkt ?? void 0,
716
768
  issuedAt: row.issued_at,
717
- expiresAt,
769
+ accessExpiresAt,
770
+ refreshExpiresAt: row.refresh_expires_at,
718
771
  revoked
719
772
  };
720
773
  }
721
774
  async getTokenByRefresh(refreshToken) {
722
- const rows = this.sql.exec(`SELECT access_token, refresh_token, client_id, sub, scope, dpop_jkt, issued_at, expires_at, revoked
775
+ const rows = this.sql.exec(`SELECT access_token, refresh_token, client_id, sub, scope, dpop_jkt, issued_at, access_expires_at, refresh_expires_at, revoked
723
776
  FROM oauth_tokens WHERE refresh_token = ?`, refreshToken).toArray();
724
777
  if (rows.length === 0) return null;
725
778
  const row = rows[0];
726
779
  const revoked = Boolean(row.revoked);
727
- if (revoked) return null;
780
+ const refreshExpiresAt = row.refresh_expires_at;
781
+ if (revoked || Date.now() > refreshExpiresAt) return null;
728
782
  return {
729
783
  accessToken: row.access_token,
730
784
  refreshToken: row.refresh_token,
@@ -733,7 +787,8 @@ var SqliteOAuthStorage = class {
733
787
  scope: row.scope,
734
788
  dpopJkt: row.dpop_jkt ?? void 0,
735
789
  issuedAt: row.issued_at,
736
- expiresAt: row.expires_at,
790
+ accessExpiresAt: row.access_expires_at,
791
+ refreshExpiresAt,
737
792
  revoked
738
793
  };
739
794
  }
@@ -802,6 +857,31 @@ var SqliteOAuthStorage = class {
802
857
  this.sql.exec("DELETE FROM oauth_par_requests");
803
858
  this.sql.exec("DELETE FROM oauth_nonces");
804
859
  this.sql.exec("DELETE FROM oauth_webauthn_challenges");
860
+ this.sql.exec("DELETE FROM oauth_permission_sets");
861
+ }
862
+ /** Soft-expiry: serve stale, but try to refresh. */
863
+ static PERMISSION_SET_STALE_MS = 1440 * 60 * 1e3;
864
+ /** Hard-expiry: drop entirely. */
865
+ static PERMISSION_SET_EXPIRY_MS = 2160 * 60 * 60 * 1e3;
866
+ savePermissionSet(nsid, set, now$1 = Date.now()) {
867
+ this.sql.exec(`INSERT OR REPLACE INTO oauth_permission_sets
868
+ (nsid, lexicon, fetched_at, stale_at, expires_at)
869
+ VALUES (?, ?, ?, ?, ?)`, nsid, JSON.stringify(set), now$1, now$1 + SqliteOAuthStorage.PERMISSION_SET_STALE_MS, now$1 + SqliteOAuthStorage.PERMISSION_SET_EXPIRY_MS);
870
+ }
871
+ getPermissionSet(nsid) {
872
+ const rows = this.sql.exec("SELECT lexicon, fetched_at, stale_at, expires_at FROM oauth_permission_sets WHERE nsid = ?", nsid).toArray();
873
+ if (rows.length === 0) return null;
874
+ const row = rows[0];
875
+ const now$1 = Date.now();
876
+ if (now$1 > row.expires_at) {
877
+ this.sql.exec("DELETE FROM oauth_permission_sets WHERE nsid = ?", nsid);
878
+ return null;
879
+ }
880
+ return {
881
+ set: JSON.parse(row.lexicon),
882
+ fetchedAt: row.fetched_at,
883
+ stale: now$1 > row.stale_at
884
+ };
805
885
  }
806
886
  /**
807
887
  * Save a WebAuthn challenge for later verification
@@ -974,6 +1054,110 @@ var BlobStore = class {
974
1054
  }
975
1055
  };
976
1056
 
1057
+ //#endregion
1058
+ //#region src/validation.ts
1059
+ const recordSchemas = {
1060
+ "app.bsky.actor.profile": AppBskyActorProfile.mainSchema,
1061
+ "app.bsky.actor.status": AppBskyActorStatus.mainSchema,
1062
+ "app.bsky.feed.generator": AppBskyFeedGenerator.mainSchema,
1063
+ "app.bsky.feed.like": AppBskyFeedLike.mainSchema,
1064
+ "app.bsky.feed.post": AppBskyFeedPost.mainSchema,
1065
+ "app.bsky.feed.postgate": AppBskyFeedPostgate.mainSchema,
1066
+ "app.bsky.feed.repost": AppBskyFeedRepost.mainSchema,
1067
+ "app.bsky.feed.threadgate": AppBskyFeedThreadgate.mainSchema,
1068
+ "app.bsky.graph.block": AppBskyGraphBlock.mainSchema,
1069
+ "app.bsky.graph.follow": AppBskyGraphFollow.mainSchema,
1070
+ "app.bsky.graph.list": AppBskyGraphList.mainSchema,
1071
+ "app.bsky.graph.listblock": AppBskyGraphListblock.mainSchema,
1072
+ "app.bsky.graph.listitem": AppBskyGraphListitem.mainSchema,
1073
+ "app.bsky.graph.starterpack": AppBskyGraphStarterpack.mainSchema,
1074
+ "app.bsky.graph.verification": AppBskyGraphVerification.mainSchema,
1075
+ "app.bsky.labeler.service": AppBskyLabelerService.mainSchema,
1076
+ "app.bsky.notification.declaration": AppBskyNotificationDeclaration.mainSchema,
1077
+ "chat.bsky.actor.declaration": ChatBskyActorDeclaration.mainSchema,
1078
+ "com.atproto.lexicon.schema": ComAtprotoLexiconSchema.mainSchema
1079
+ };
1080
+ var InvalidRecordError = class extends Error {
1081
+ name = "InvalidRecordError";
1082
+ };
1083
+ /**
1084
+ * Thrown when a write targets an rkey that already exists in the repo.
1085
+ * Uses a `name` field rather than relying on class identity, so the error
1086
+ * survives a Cloudflare DO RPC boundary (RPC preserves message + name + stack
1087
+ * but not the prototype chain).
1088
+ */
1089
+ var RecordAlreadyExistsError = class extends Error {
1090
+ name = "RecordAlreadyExistsError";
1091
+ };
1092
+ function isRecordAlreadyExistsError(err) {
1093
+ if (!(err instanceof Error)) return false;
1094
+ return err.name === "RecordAlreadyExistsError" || err.message.startsWith("RecordAlreadyExistsError:");
1095
+ }
1096
+ var RecordValidator = class {
1097
+ validate(opts) {
1098
+ const reconciled = reconcileType(opts.record, opts.collection);
1099
+ rejectLegacyBlobRefs(reconciled);
1100
+ if (opts.rkey !== void 0 && !isRecordKey(opts.rkey)) throw new InvalidRecordError(`Invalid record key: ${opts.rkey}`);
1101
+ if (opts.validate === false) return { record: reconciled };
1102
+ const schema = recordSchemas[opts.collection];
1103
+ if (!schema) {
1104
+ if (opts.validate === true) throw new InvalidRecordError(`Unknown lexicon type: ${opts.collection}`);
1105
+ return {
1106
+ record: reconciled,
1107
+ status: "unknown"
1108
+ };
1109
+ }
1110
+ if (opts.rkey !== void 0) {
1111
+ const keyResult = safeParse(schema.key, opts.rkey);
1112
+ if (!keyResult.ok) throw new InvalidRecordError(`Invalid record key for ${opts.collection}: ${keyResult.message}`);
1113
+ }
1114
+ try {
1115
+ parse(schema, reconciled);
1116
+ } catch (err) {
1117
+ if (err instanceof ValidationError) throw new InvalidRecordError(`Invalid ${opts.collection} record: ${err.message}`);
1118
+ throw err;
1119
+ }
1120
+ return {
1121
+ record: reconciled,
1122
+ status: "valid"
1123
+ };
1124
+ }
1125
+ hasSchema(collection) {
1126
+ return collection in recordSchemas;
1127
+ }
1128
+ getLoadedSchemas() {
1129
+ return Object.keys(recordSchemas);
1130
+ }
1131
+ };
1132
+ const validator = new RecordValidator();
1133
+ function reconcileType(record, collection) {
1134
+ if (record === null || typeof record !== "object" || Array.isArray(record)) throw new InvalidRecordError("Record must be an object");
1135
+ const obj = record;
1136
+ const declared = obj.$type;
1137
+ if (declared === void 0) return {
1138
+ ...obj,
1139
+ $type: collection
1140
+ };
1141
+ if (declared !== collection) throw new InvalidRecordError(`Invalid $type: expected ${collection}, got ${String(declared)}`);
1142
+ return obj;
1143
+ }
1144
+ function rejectLegacyBlobRefs(value) {
1145
+ const stack = [value];
1146
+ const visited = /* @__PURE__ */ new WeakSet();
1147
+ while (stack.length > 0) {
1148
+ const current = stack.pop();
1149
+ if (current === null || typeof current !== "object") continue;
1150
+ if (visited.has(current)) continue;
1151
+ visited.add(current);
1152
+ if (Array.isArray(current)) {
1153
+ for (const item of current) stack.push(item);
1154
+ continue;
1155
+ }
1156
+ if (isLegacyBlobRef(current)) throw new InvalidRecordError(`Legacy blobs are not allowed (${current.cid})`);
1157
+ for (const v of Object.values(current)) if (v !== null && typeof v === "object") stack.push(v);
1158
+ }
1159
+ }
1160
+
977
1161
  //#endregion
978
1162
  //#region src/account-do.ts
979
1163
  /**
@@ -1088,6 +1272,17 @@ var AccountDurableObject = class extends DurableObject {
1088
1272
  this.repo = repo;
1089
1273
  }
1090
1274
  /**
1275
+ * Drop the in-memory repo so the next access reloads from storage.
1276
+ * Used after a write fails post-applyWrites: Cloudflare rolls back the
1277
+ * SQLite writes, but JS state isn't rolled back, so the cached Repo can
1278
+ * end up ahead of storage. That mismatch produces firehose events whose
1279
+ * `since` rev the relay never saw, causing it to mark us desynced.
1280
+ */
1281
+ invalidateRepoCache() {
1282
+ this.repo = null;
1283
+ this.repoInitialized = false;
1284
+ }
1285
+ /**
1091
1286
  * RPC method: Get repo metadata for describeRepo
1092
1287
  */
1093
1288
  async rpcDescribeRepo() {
@@ -1151,11 +1346,18 @@ var AccountDurableObject = class extends DurableObject {
1151
1346
  /**
1152
1347
  * RPC method: Create a record
1153
1348
  */
1154
- async rpcCreateRecord(collection, rkey, record) {
1349
+ async rpcCreateRecord(collection, rkey, record, validationStatus) {
1155
1350
  await this.ensureActive();
1156
1351
  const repo = await this.getRepo();
1157
1352
  const keypair = await this.getKeypair();
1158
- const actualRkey = rkey || now();
1353
+ const autoGenerated = rkey === void 0;
1354
+ let actualRkey = rkey ?? now();
1355
+ for (let attempt = 0; attempt < 5; attempt++) {
1356
+ if (!await repo.data.get(`${collection}/${actualRkey}`)) break;
1357
+ if (!autoGenerated) throw new RecordAlreadyExistsError(`${collection}/${actualRkey}`);
1358
+ if (attempt === 4) throw new Error(`Failed to allocate unique rkey for ${collection} after 5 attempts`);
1359
+ actualRkey = now();
1360
+ }
1159
1361
  const createOp = {
1160
1362
  action: WriteOpAction.Create,
1161
1363
  collection,
@@ -1163,42 +1365,49 @@ var AccountDurableObject = class extends DurableObject {
1163
1365
  record: jsonToLex(record)
1164
1366
  };
1165
1367
  const prevRev = repo.commit.rev;
1166
- this.repo = await repo.applyWrites([createOp], keypair);
1167
- const dataKey = `${collection}/${actualRkey}`;
1168
- const recordCid = await this.repo.data.get(dataKey);
1169
- if (!recordCid) throw new Error(`Failed to create record: ${collection}/${actualRkey}`);
1170
- this.storage.addCollection(collection);
1171
- if (this.sequencer) {
1172
- const newBlocks = new BlockMap();
1173
- const rows = this.ctx.storage.sql.exec("SELECT cid, bytes FROM blocks WHERE rev = ?", this.repo.commit.rev).toArray();
1174
- for (const row of rows) {
1175
- const cid = CID.parse(row.cid);
1176
- const bytes = new Uint8Array(row.bytes);
1177
- newBlocks.set(cid, bytes);
1368
+ const updatedRepo = await repo.applyWrites([createOp], keypair);
1369
+ try {
1370
+ const dataKey = `${collection}/${actualRkey}`;
1371
+ const recordCid = await updatedRepo.data.get(dataKey);
1372
+ if (!recordCid) throw new Error(`Failed to create record: ${collection}/${actualRkey}`);
1373
+ this.storage.addCollection(collection);
1374
+ if (this.sequencer) {
1375
+ const newBlocks = new BlockMap();
1376
+ const rows = this.ctx.storage.sql.exec("SELECT cid, bytes FROM blocks WHERE rev = ?", updatedRepo.commit.rev).toArray();
1377
+ for (const row of rows) {
1378
+ const cid = CID.parse(row.cid);
1379
+ const bytes = new Uint8Array(row.bytes);
1380
+ newBlocks.set(cid, bytes);
1381
+ }
1382
+ const opWithCid = {
1383
+ ...createOp,
1384
+ cid: recordCid
1385
+ };
1386
+ const commitData = {
1387
+ did: updatedRepo.did,
1388
+ commit: updatedRepo.cid,
1389
+ rev: updatedRepo.commit.rev,
1390
+ since: prevRev,
1391
+ newBlocks,
1392
+ ops: [opWithCid]
1393
+ };
1394
+ const event = await this.sequencer.sequenceCommit(commitData);
1395
+ await this.broadcastCommit(event);
1178
1396
  }
1179
- const opWithCid = {
1180
- ...createOp,
1181
- cid: recordCid
1182
- };
1183
- const commitData = {
1184
- did: this.repo.did,
1185
- commit: this.repo.cid,
1186
- rev: this.repo.commit.rev,
1187
- since: prevRev,
1188
- newBlocks,
1189
- ops: [opWithCid]
1397
+ this.repo = updatedRepo;
1398
+ return {
1399
+ uri: `at://${updatedRepo.did}/${collection}/${actualRkey}`,
1400
+ cid: recordCid.toString(),
1401
+ commit: {
1402
+ cid: updatedRepo.cid.toString(),
1403
+ rev: updatedRepo.commit.rev
1404
+ },
1405
+ ...validationStatus !== void 0 ? { validationStatus } : {}
1190
1406
  };
1191
- const event = await this.sequencer.sequenceCommit(commitData);
1192
- await this.broadcastCommit(event);
1407
+ } catch (err) {
1408
+ this.invalidateRepoCache();
1409
+ throw err;
1193
1410
  }
1194
- return {
1195
- uri: `at://${this.repo.did}/${collection}/${actualRkey}`,
1196
- cid: recordCid.toString(),
1197
- commit: {
1198
- cid: this.repo.cid.toString(),
1199
- rev: this.repo.commit.rev
1200
- }
1201
- };
1202
1411
  }
1203
1412
  /**
1204
1413
  * RPC method: Delete a record
@@ -1215,35 +1424,40 @@ var AccountDurableObject = class extends DurableObject {
1215
1424
  };
1216
1425
  const prevRev = repo.commit.rev;
1217
1426
  const updatedRepo = await repo.applyWrites([deleteOp], keypair);
1218
- this.repo = updatedRepo;
1219
- if (this.sequencer) {
1220
- const newBlocks = new BlockMap();
1221
- const rows = this.ctx.storage.sql.exec("SELECT cid, bytes FROM blocks WHERE rev = ?", this.repo.commit.rev).toArray();
1222
- for (const row of rows) {
1223
- const cid = CID.parse(row.cid);
1224
- const bytes = new Uint8Array(row.bytes);
1225
- newBlocks.set(cid, bytes);
1427
+ try {
1428
+ if (this.sequencer) {
1429
+ const newBlocks = new BlockMap();
1430
+ const rows = this.ctx.storage.sql.exec("SELECT cid, bytes FROM blocks WHERE rev = ?", updatedRepo.commit.rev).toArray();
1431
+ for (const row of rows) {
1432
+ const cid = CID.parse(row.cid);
1433
+ const bytes = new Uint8Array(row.bytes);
1434
+ newBlocks.set(cid, bytes);
1435
+ }
1436
+ const commitData = {
1437
+ did: updatedRepo.did,
1438
+ commit: updatedRepo.cid,
1439
+ rev: updatedRepo.commit.rev,
1440
+ since: prevRev,
1441
+ newBlocks,
1442
+ ops: [deleteOp]
1443
+ };
1444
+ const event = await this.sequencer.sequenceCommit(commitData);
1445
+ await this.broadcastCommit(event);
1226
1446
  }
1227
- const commitData = {
1228
- did: this.repo.did,
1229
- commit: this.repo.cid,
1230
- rev: this.repo.commit.rev,
1231
- since: prevRev,
1232
- newBlocks,
1233
- ops: [deleteOp]
1234
- };
1235
- const event = await this.sequencer.sequenceCommit(commitData);
1236
- await this.broadcastCommit(event);
1447
+ this.repo = updatedRepo;
1448
+ return { commit: {
1449
+ cid: updatedRepo.cid.toString(),
1450
+ rev: updatedRepo.commit.rev
1451
+ } };
1452
+ } catch (err) {
1453
+ this.invalidateRepoCache();
1454
+ throw err;
1237
1455
  }
1238
- return { commit: {
1239
- cid: updatedRepo.cid.toString(),
1240
- rev: updatedRepo.commit.rev
1241
- } };
1242
1456
  }
1243
1457
  /**
1244
1458
  * RPC method: Put a record (create or update)
1245
1459
  */
1246
- async rpcPutRecord(collection, rkey, record) {
1460
+ async rpcPutRecord(collection, rkey, record, validationStatus) {
1247
1461
  await this.ensureActive();
1248
1462
  const repo = await this.getRepo();
1249
1463
  const keypair = await this.getKeypair();
@@ -1261,43 +1475,49 @@ var AccountDurableObject = class extends DurableObject {
1261
1475
  record: normalizedRecord
1262
1476
  };
1263
1477
  const prevRev = repo.commit.rev;
1264
- this.repo = await repo.applyWrites([op], keypair);
1265
- const dataKey = `${collection}/${rkey}`;
1266
- const recordCid = await this.repo.data.get(dataKey);
1267
- if (!recordCid) throw new Error(`Failed to put record: ${collection}/${rkey}`);
1268
- this.storage.addCollection(collection);
1269
- if (this.sequencer) {
1270
- const newBlocks = new BlockMap();
1271
- const rows = this.ctx.storage.sql.exec("SELECT cid, bytes FROM blocks WHERE rev = ?", this.repo.commit.rev).toArray();
1272
- for (const row of rows) {
1273
- const cid = CID.parse(row.cid);
1274
- const bytes = new Uint8Array(row.bytes);
1275
- newBlocks.set(cid, bytes);
1478
+ const updatedRepo = await repo.applyWrites([op], keypair);
1479
+ try {
1480
+ const dataKey = `${collection}/${rkey}`;
1481
+ const recordCid = await updatedRepo.data.get(dataKey);
1482
+ if (!recordCid) throw new Error(`Failed to put record: ${collection}/${rkey}`);
1483
+ this.storage.addCollection(collection);
1484
+ if (this.sequencer) {
1485
+ const newBlocks = new BlockMap();
1486
+ const rows = this.ctx.storage.sql.exec("SELECT cid, bytes FROM blocks WHERE rev = ?", updatedRepo.commit.rev).toArray();
1487
+ for (const row of rows) {
1488
+ const cid = CID.parse(row.cid);
1489
+ const bytes = new Uint8Array(row.bytes);
1490
+ newBlocks.set(cid, bytes);
1491
+ }
1492
+ const opWithCid = {
1493
+ ...op,
1494
+ cid: recordCid
1495
+ };
1496
+ const commitData = {
1497
+ did: updatedRepo.did,
1498
+ commit: updatedRepo.cid,
1499
+ rev: updatedRepo.commit.rev,
1500
+ since: prevRev,
1501
+ newBlocks,
1502
+ ops: [opWithCid]
1503
+ };
1504
+ const event = await this.sequencer.sequenceCommit(commitData);
1505
+ await this.broadcastCommit(event);
1276
1506
  }
1277
- const opWithCid = {
1278
- ...op,
1279
- cid: recordCid
1280
- };
1281
- const commitData = {
1282
- did: this.repo.did,
1283
- commit: this.repo.cid,
1284
- rev: this.repo.commit.rev,
1285
- since: prevRev,
1286
- newBlocks,
1287
- ops: [opWithCid]
1507
+ this.repo = updatedRepo;
1508
+ return {
1509
+ uri: `at://${updatedRepo.did}/${collection}/${rkey}`,
1510
+ cid: recordCid.toString(),
1511
+ commit: {
1512
+ cid: updatedRepo.cid.toString(),
1513
+ rev: updatedRepo.commit.rev
1514
+ },
1515
+ ...validationStatus !== void 0 ? { validationStatus } : {}
1288
1516
  };
1289
- const event = await this.sequencer.sequenceCommit(commitData);
1290
- await this.broadcastCommit(event);
1517
+ } catch (err) {
1518
+ this.invalidateRepoCache();
1519
+ throw err;
1291
1520
  }
1292
- return {
1293
- uri: `at://${this.repo.did}/${collection}/${rkey}`,
1294
- cid: recordCid.toString(),
1295
- commit: {
1296
- cid: this.repo.cid.toString(),
1297
- rev: this.repo.commit.rev
1298
- },
1299
- validationStatus: "valid"
1300
- };
1301
1521
  }
1302
1522
  /**
1303
1523
  * RPC method: Apply multiple writes (batch create/update/delete)
@@ -1308,8 +1528,20 @@ var AccountDurableObject = class extends DurableObject {
1308
1528
  const keypair = await this.getKeypair();
1309
1529
  const ops = [];
1310
1530
  const results = [];
1531
+ const reservedRkeys = /* @__PURE__ */ new Set();
1311
1532
  for (const write of writes) if (write.$type === "com.atproto.repo.applyWrites#create") {
1312
- const rkey = write.rkey || now();
1533
+ const autoGenerated = write.rkey === void 0;
1534
+ let rkey = write.rkey ?? now();
1535
+ for (let attempt = 0; attempt < 5; attempt++) {
1536
+ const composite = `${write.collection}/${rkey}`;
1537
+ const collidesInBatch = reservedRkeys.has(composite);
1538
+ const collidesInRepo = !collidesInBatch && await repo.data.get(composite) !== null;
1539
+ if (!collidesInBatch && !collidesInRepo) break;
1540
+ if (!autoGenerated) throw new RecordAlreadyExistsError(composite);
1541
+ if (attempt === 4) throw new Error(`Failed to allocate unique rkey for ${write.collection} after 5 attempts`);
1542
+ rkey = now();
1543
+ }
1544
+ reservedRkeys.add(`${write.collection}/${rkey}`);
1313
1545
  const op = {
1314
1546
  action: WriteOpAction.Create,
1315
1547
  collection: write.collection,
@@ -1321,7 +1553,8 @@ var AccountDurableObject = class extends DurableObject {
1321
1553
  $type: "com.atproto.repo.applyWrites#createResult",
1322
1554
  collection: write.collection,
1323
1555
  rkey,
1324
- action: WriteOpAction.Create
1556
+ action: WriteOpAction.Create,
1557
+ validationStatus: write.validationStatus
1325
1558
  });
1326
1559
  } else if (write.$type === "com.atproto.repo.applyWrites#update") {
1327
1560
  if (!write.rkey) throw new Error("Update requires rkey");
@@ -1336,7 +1569,8 @@ var AccountDurableObject = class extends DurableObject {
1336
1569
  $type: "com.atproto.repo.applyWrites#updateResult",
1337
1570
  collection: write.collection,
1338
1571
  rkey: write.rkey,
1339
- action: WriteOpAction.Update
1572
+ action: WriteOpAction.Update,
1573
+ validationStatus: write.validationStatus
1340
1574
  });
1341
1575
  } else if (write.$type === "com.atproto.repo.applyWrites#delete") {
1342
1576
  if (!write.rkey) throw new Error("Delete requires rkey");
@@ -1354,57 +1588,63 @@ var AccountDurableObject = class extends DurableObject {
1354
1588
  });
1355
1589
  } else throw new Error(`Unknown write type: ${write.$type}`);
1356
1590
  const prevRev = repo.commit.rev;
1357
- this.repo = await repo.applyWrites(ops, keypair);
1358
- for (const op of ops) if (op.action !== WriteOpAction.Delete) this.storage.addCollection(op.collection);
1359
- const finalResults = [];
1360
- const opsWithCids = [];
1361
- for (let i = 0; i < results.length; i++) {
1362
- const result = results[i];
1363
- const op = ops[i];
1364
- if (result.action === WriteOpAction.Delete) {
1365
- finalResults.push({ $type: result.$type });
1366
- opsWithCids.push(op);
1367
- } else {
1368
- const dataKey = `${result.collection}/${result.rkey}`;
1369
- const recordCid = await this.repo.data.get(dataKey);
1370
- finalResults.push({
1371
- $type: result.$type,
1372
- uri: `at://${this.repo.did}/${result.collection}/${result.rkey}`,
1373
- cid: recordCid?.toString(),
1374
- validationStatus: "valid"
1375
- });
1376
- opsWithCids.push({
1377
- ...op,
1378
- cid: recordCid
1379
- });
1591
+ const updatedRepo = await repo.applyWrites(ops, keypair);
1592
+ try {
1593
+ for (const op of ops) if (op.action !== WriteOpAction.Delete) this.storage.addCollection(op.collection);
1594
+ const finalResults = [];
1595
+ const opsWithCids = [];
1596
+ for (let i = 0; i < results.length; i++) {
1597
+ const result = results[i];
1598
+ const op = ops[i];
1599
+ if (result.action === WriteOpAction.Delete) {
1600
+ finalResults.push({ $type: result.$type });
1601
+ opsWithCids.push(op);
1602
+ } else {
1603
+ const dataKey = `${result.collection}/${result.rkey}`;
1604
+ const recordCid = await updatedRepo.data.get(dataKey);
1605
+ finalResults.push({
1606
+ $type: result.$type,
1607
+ uri: `at://${updatedRepo.did}/${result.collection}/${result.rkey}`,
1608
+ cid: recordCid?.toString(),
1609
+ ...result.validationStatus !== void 0 ? { validationStatus: result.validationStatus } : {}
1610
+ });
1611
+ opsWithCids.push({
1612
+ ...op,
1613
+ cid: recordCid
1614
+ });
1615
+ }
1380
1616
  }
1381
- }
1382
- if (this.sequencer) {
1383
- const newBlocks = new BlockMap();
1384
- const rows = this.ctx.storage.sql.exec("SELECT cid, bytes FROM blocks WHERE rev = ?", this.repo.commit.rev).toArray();
1385
- for (const row of rows) {
1386
- const cid = CID.parse(row.cid);
1387
- const bytes = new Uint8Array(row.bytes);
1388
- newBlocks.set(cid, bytes);
1617
+ if (this.sequencer) {
1618
+ const newBlocks = new BlockMap();
1619
+ const rows = this.ctx.storage.sql.exec("SELECT cid, bytes FROM blocks WHERE rev = ?", updatedRepo.commit.rev).toArray();
1620
+ for (const row of rows) {
1621
+ const cid = CID.parse(row.cid);
1622
+ const bytes = new Uint8Array(row.bytes);
1623
+ newBlocks.set(cid, bytes);
1624
+ }
1625
+ const commitData = {
1626
+ did: updatedRepo.did,
1627
+ commit: updatedRepo.cid,
1628
+ rev: updatedRepo.commit.rev,
1629
+ since: prevRev,
1630
+ newBlocks,
1631
+ ops: opsWithCids
1632
+ };
1633
+ const event = await this.sequencer.sequenceCommit(commitData);
1634
+ await this.broadcastCommit(event);
1389
1635
  }
1390
- const commitData = {
1391
- did: this.repo.did,
1392
- commit: this.repo.cid,
1393
- rev: this.repo.commit.rev,
1394
- since: prevRev,
1395
- newBlocks,
1396
- ops: opsWithCids
1636
+ this.repo = updatedRepo;
1637
+ return {
1638
+ commit: {
1639
+ cid: updatedRepo.cid.toString(),
1640
+ rev: updatedRepo.commit.rev
1641
+ },
1642
+ results: finalResults
1397
1643
  };
1398
- const event = await this.sequencer.sequenceCommit(commitData);
1399
- await this.broadcastCommit(event);
1644
+ } catch (err) {
1645
+ this.invalidateRepoCache();
1646
+ throw err;
1400
1647
  }
1401
- return {
1402
- commit: {
1403
- cid: this.repo.cid.toString(),
1404
- rev: this.repo.commit.rev
1405
- },
1406
- results: finalResults
1407
- };
1408
1648
  }
1409
1649
  /**
1410
1650
  * RPC method: Get repo status
@@ -1872,6 +2112,18 @@ var AccountDurableObject = class extends DurableObject {
1872
2112
  async rpcCheckAndSaveNonce(nonce) {
1873
2113
  return (await this.getOAuthStorage()).checkAndSaveNonce(nonce);
1874
2114
  }
2115
+ /**
2116
+ * Look up a cached permission-set lexicon by NSID. Returns the cached
2117
+ * value (with `stale: true` when past its 24h soft-expiry) or null when
2118
+ * not cached or hard-expired.
2119
+ */
2120
+ async rpcGetPermissionSet(nsid) {
2121
+ return (await this.getOAuthStorage()).getPermissionSet(nsid);
2122
+ }
2123
+ /** Cache a fetched permission-set lexicon. */
2124
+ async rpcSavePermissionSet(nsid, set) {
2125
+ (await this.getOAuthStorage()).savePermissionSet(nsid, set);
2126
+ }
1875
2127
  /** Save a passkey credential */
1876
2128
  async rpcSavePasskey(credentialId, publicKey, counter, name) {
1877
2129
  (await this.getStorage()).savePasskey(credentialId, publicKey, counter, name);
@@ -2395,6 +2647,65 @@ var DOProxyOAuthStorage = class {
2395
2647
  }
2396
2648
  };
2397
2649
  /**
2650
+ * Build a network-backed permission-set resolver. Constructed once per
2651
+ * isolate; `@atcute/lexicon-resolver` is stateless beyond the cache it
2652
+ * doesn't have, so it's safe to share.
2653
+ */
2654
+ let networkPermissionSetResolver;
2655
+ function getNetworkPermissionSetResolver() {
2656
+ if (!networkPermissionSetResolver) networkPermissionSetResolver = createAtcutePermissionSetResolver({
2657
+ dohUrl: "https://mozilla.cloudflare-dns.com/dns-query",
2658
+ didDocumentResolver: new CompositeDidDocumentResolver({ methods: {
2659
+ plc: new PlcDidDocumentResolver({ apiUrl: "https://plc.directory" }),
2660
+ web: new WebDidDocumentResolver({})
2661
+ } })
2662
+ });
2663
+ return networkPermissionSetResolver;
2664
+ }
2665
+ /**
2666
+ * Wrap the network-backed resolver in a DO-SQLite cache implementing
2667
+ * stale-while-revalidate semantics from the atproto permission spec
2668
+ * (24h soft / 90d hard). Stale-entry refreshes use the Workers global
2669
+ * `waitUntil` so they outlive the request that triggered them, and an
2670
+ * in-memory in-flight map ensures concurrent stale hits coalesce into a
2671
+ * single network fetch.
2672
+ *
2673
+ * Note: cirrus PDS is single-tenant per Worker isolate (one account DID
2674
+ * per deployment), so an NSID-keyed inflight map is correct — every
2675
+ * resolver call within an isolate targets the same `accountDO` and the
2676
+ * subsequent `rpcSavePermissionSet` writes to the right cache. If cirrus
2677
+ * ever becomes multi-tenant, this map needs to be keyed by `${did}:${nsid}`
2678
+ * or each observer needs to fan out their own save.
2679
+ */
2680
+ const inflightRefresh = /* @__PURE__ */ new Map();
2681
+ function createCachedPermissionSetResolver(accountDO) {
2682
+ const network = getNetworkPermissionSetResolver();
2683
+ const fetchAndStore = (nsid) => {
2684
+ const existing = inflightRefresh.get(nsid);
2685
+ if (existing) return existing;
2686
+ const p = (async () => {
2687
+ try {
2688
+ const fresh = await network.resolve(nsid);
2689
+ if (fresh) await accountDO.rpcSavePermissionSet(nsid, fresh);
2690
+ return fresh;
2691
+ } finally {
2692
+ inflightRefresh.delete(nsid);
2693
+ }
2694
+ })();
2695
+ inflightRefresh.set(nsid, p);
2696
+ return p;
2697
+ };
2698
+ return { async resolve(nsid) {
2699
+ const cached = await accountDO.rpcGetPermissionSet(nsid);
2700
+ if (cached && !cached.stale) return cached.set;
2701
+ if (cached?.stale) {
2702
+ waitUntil(fetchAndStore(nsid).catch(() => {}));
2703
+ return cached.set;
2704
+ }
2705
+ return fetchAndStore(nsid);
2706
+ } };
2707
+ }
2708
+ /**
2398
2709
  * Get the OAuth provider for the given environment
2399
2710
  * Exported for use in auth middleware for token verification
2400
2711
  */
@@ -2421,7 +2732,8 @@ function getProvider(env$2) {
2421
2732
  sub: env$2.DID,
2422
2733
  handle: env$2.HANDLE
2423
2734
  };
2424
- }
2735
+ },
2736
+ permissionSetResolver: createCachedPermissionSetResolver(accountDO)
2425
2737
  });
2426
2738
  }
2427
2739
  let getAccountDO$1;
@@ -2527,6 +2839,61 @@ function createOAuthApp(accountDOGetter) {
2527
2839
 
2528
2840
  //#endregion
2529
2841
  //#region src/middleware/auth.ts
2842
+ /**
2843
+ * Legacy scope value produced by non-OAuth auth paths — session JWTs from
2844
+ * `createSession` (app-password flow), service JWTs from external services,
2845
+ * and the static `AUTH_TOKEN`. These predate the granular permission spec
2846
+ * and represent fully-trusted callers, so scope checks short-circuit to
2847
+ * allow.
2848
+ *
2849
+ * `com.atproto.refresh` is intentionally NOT in this set: refresh tokens
2850
+ * should never reach a resource handler (only `/oauth/token` and
2851
+ * `/com.atproto.server.refreshSession` accept them, both with their own
2852
+ * verifiers). If one ever leaks here, fail closed.
2853
+ */
2854
+ const LEGACY_FULL_TRUST_SCOPES = new Set(["com.atproto.access"]);
2855
+ /**
2856
+ * Build a scope checker pre-bound to the request's auth context. Returns a
2857
+ * function that accepts a `(perms) => void` callback (typically calling
2858
+ * `assertRepo` / `assertRpc` etc.) and returns a 403 Response on failure
2859
+ * or null on success. The underlying ScopePermissionsTransition is built
2860
+ * once and reused, so loops (e.g. applyWrites) don't pay re-parse cost.
2861
+ *
2862
+ * Returns null when the request was authenticated by a legacy fully-trusted
2863
+ * path (session JWT, static AUTH_TOKEN, service JWT) so callers can skip
2864
+ * scope checks entirely.
2865
+ */
2866
+ function buildScopeChecker(c) {
2867
+ const auth = c.get("auth");
2868
+ if (!auth?.scope) return null;
2869
+ if (LEGACY_FULL_TRUST_SCOPES.has(auth.scope)) return null;
2870
+ const perms = permissionsFor(auth.scope);
2871
+ return (check) => {
2872
+ try {
2873
+ check(perms);
2874
+ return null;
2875
+ } catch (err) {
2876
+ if (err instanceof ScopeMissingError) return c.json({
2877
+ error: "InsufficientScope",
2878
+ message: `Missing required scope: ${err.scope}`
2879
+ }, 403);
2880
+ throw err;
2881
+ }
2882
+ };
2883
+ }
2884
+ /**
2885
+ * Run a scope check against the authenticated request's token. Returns a 403
2886
+ * Response when the scope is missing, or null when the check passes.
2887
+ *
2888
+ * Use inside an XRPC handler after data-driven values (collection name, MIME
2889
+ * type, etc.) become available from the request body. For loops, prefer
2890
+ * {@link buildScopeChecker} which hoists the parse out of the hot path.
2891
+ */
2892
+ function requireScope(c, check) {
2893
+ const checker = buildScopeChecker(c);
2894
+ if (!checker) return null;
2895
+ return checker(check);
2896
+ }
2530
2897
  async function requireAuth(c, next) {
2531
2898
  const auth = c.req.header("Authorization");
2532
2899
  if (!auth) return c.json({
@@ -2538,7 +2905,7 @@ async function requireAuth(c, next) {
2538
2905
  if (!tokenData) return c.json({
2539
2906
  error: "AuthenticationRequired",
2540
2907
  message: "Invalid OAuth access token"
2541
- }, 401);
2908
+ }, 401, { "WWW-Authenticate": "DPoP error=\"invalid_token\", error_description=\"Invalid access token\"" });
2542
2909
  c.set("auth", {
2543
2910
  did: tokenData.sub,
2544
2911
  scope: tokenData.scope
@@ -2577,9 +2944,23 @@ async function requireAuth(c, next) {
2577
2944
  }
2578
2945
  try {
2579
2946
  const payload = await verifyServiceJwt(token, c.env.SIGNING_KEY, serviceDid, c.env.DID);
2947
+ if (payload.lxm) {
2948
+ const xrpcPrefix = "/xrpc/";
2949
+ const path = new URL(c.req.url).pathname;
2950
+ if (!path.startsWith(xrpcPrefix)) return c.json({
2951
+ error: "AuthenticationRequired",
2952
+ message: "Service JWT used outside an XRPC method call"
2953
+ }, 401);
2954
+ const rest = path.slice(6);
2955
+ const requestedLxm = rest.endsWith("/") ? rest.slice(0, -1) : rest;
2956
+ if (!requestedLxm || requestedLxm.includes("/") || requestedLxm !== payload.lxm) return c.json({
2957
+ error: "AuthenticationRequired",
2958
+ message: `Service JWT bound to ${payload.lxm}, not ${requestedLxm}`
2959
+ }, 401);
2960
+ }
2580
2961
  c.set("auth", {
2581
2962
  did: payload.iss,
2582
- scope: payload.lxm || "atproto"
2963
+ scope: "com.atproto.access"
2583
2964
  });
2584
2965
  return next();
2585
2966
  } catch {}
@@ -2776,7 +3157,19 @@ async function handleXrpcProxy(c, didResolver$1, getKeypair$1) {
2776
3157
  let userDid;
2777
3158
  if (auth?.startsWith("DPoP ")) try {
2778
3159
  const tokenData = await getProvider(c.env).verifyAccessToken(c.req.raw);
2779
- if (tokenData) userDid = tokenData.sub;
3160
+ if (tokenData) try {
3161
+ permissionsFor(tokenData.scope).assertRpc({
3162
+ lxm,
3163
+ aud: audienceDid
3164
+ });
3165
+ userDid = tokenData.sub;
3166
+ } catch (err) {
3167
+ if (err instanceof ScopeMissingError) return c.json({
3168
+ error: "InsufficientScope",
3169
+ message: `Token does not grant rpc:${lxm}?aud=${audienceDid}`
3170
+ }, 403);
3171
+ throw err;
3172
+ }
2780
3173
  } catch {}
2781
3174
  else if (auth?.startsWith("Bearer ")) {
2782
3175
  const token = auth.slice(7);
@@ -2880,13 +3273,17 @@ async function getRepoStatus(c, accountDO) {
2880
3273
  error: "RepoNotFound",
2881
3274
  message: `Repository not found for DID: ${did}`
2882
3275
  }, 404);
2883
- const data = await accountDO.rpcGetRepoStatus();
2884
- return c.json({
3276
+ const [data, active] = await Promise.all([accountDO.rpcGetRepoStatus(), accountDO.rpcGetActive()]);
3277
+ if (active) return c.json({
2885
3278
  did: data.did,
2886
3279
  active: true,
2887
- status: "active",
2888
3280
  rev: data.rev
2889
3281
  });
3282
+ return c.json({
3283
+ did: data.did,
3284
+ active: false,
3285
+ status: "deactivated"
3286
+ });
2890
3287
  }
2891
3288
  async function listRepos(c, accountDO) {
2892
3289
  const data = await accountDO.rpcGetRepoStatus();
@@ -3051,91 +3448,24 @@ async function getRecord$1(c, accountDO) {
3051
3448
  }
3052
3449
  }
3053
3450
 
3054
- //#endregion
3055
- //#region src/validation.ts
3056
- /**
3057
- * Map of collection NSID to validation schema.
3058
- * Only includes record types that can be created in repositories.
3059
- */
3060
- const recordSchemas = {
3061
- "app.bsky.actor.profile": AppBskyActorProfile.mainSchema,
3062
- "app.bsky.feed.generator": AppBskyFeedGenerator.mainSchema,
3063
- "app.bsky.feed.like": AppBskyFeedLike.mainSchema,
3064
- "app.bsky.feed.post": AppBskyFeedPost.mainSchema,
3065
- "app.bsky.feed.postgate": AppBskyFeedPostgate.mainSchema,
3066
- "app.bsky.feed.repost": AppBskyFeedRepost.mainSchema,
3067
- "app.bsky.feed.threadgate": AppBskyFeedThreadgate.mainSchema,
3068
- "app.bsky.graph.block": AppBskyGraphBlock.mainSchema,
3069
- "app.bsky.graph.follow": AppBskyGraphFollow.mainSchema,
3070
- "app.bsky.graph.list": AppBskyGraphList.mainSchema,
3071
- "app.bsky.graph.listblock": AppBskyGraphListblock.mainSchema,
3072
- "app.bsky.graph.listitem": AppBskyGraphListitem.mainSchema,
3073
- "app.bsky.graph.starterpack": AppBskyGraphStarterpack.mainSchema,
3074
- "app.bsky.graph.verification": AppBskyGraphVerification.mainSchema,
3075
- "app.bsky.labeler.service": AppBskyLabelerService.mainSchema
3076
- };
3077
- /**
3078
- * Record validator for AT Protocol records.
3079
- *
3080
- * Validates records against official Bluesky lexicon schemas from @atcute/bluesky.
3081
- * Uses optimistic validation strategy:
3082
- * - If a schema is loaded for the collection, validate the record
3083
- * - If no schema is loaded, allow the record (fail-open)
3084
- *
3085
- * This allows the PDS to accept records for new or unknown collection types
3086
- * while still validating known types.
3087
- */
3088
- var RecordValidator = class {
3089
- strictMode;
3090
- constructor(options = {}) {
3091
- this.strictMode = options.strict ?? false;
3092
- }
3093
- /**
3094
- * Validate a record against its lexicon schema.
3095
- *
3096
- * @param collection - The NSID of the record type (e.g., "app.bsky.feed.post")
3097
- * @param record - The record object to validate
3098
- * @throws {Error} If validation fails and schema is loaded
3099
- */
3100
- validateRecord(collection, record) {
3101
- const schema = recordSchemas[collection];
3102
- if (!schema) {
3103
- if (this.strictMode) throw new Error(`No lexicon schema loaded for collection: ${collection}. Enable optimistic validation or add the schema.`);
3104
- return;
3105
- }
3106
- try {
3107
- parse(schema, record);
3108
- } catch (error) {
3109
- if (error instanceof ValidationError) throw new Error(`Lexicon validation failed for ${collection}: ${error.message}`);
3110
- throw error;
3111
- }
3112
- }
3113
- /**
3114
- * Check if a schema is loaded for a collection.
3115
- */
3116
- hasSchema(collection) {
3117
- return collection in recordSchemas;
3118
- }
3119
- /**
3120
- * Get list of all loaded schema NSIDs.
3121
- */
3122
- getLoadedSchemas() {
3123
- return Object.keys(recordSchemas);
3124
- }
3125
- };
3126
- /**
3127
- * Shared validator instance (singleton pattern).
3128
- * Uses optimistic validation by default (strict: false).
3129
- */
3130
- const validator = new RecordValidator({ strict: false });
3131
-
3132
3451
  //#endregion
3133
3452
  //#region src/xrpc/repo.ts
3134
3453
  function invalidRecordError(c, err, prefix) {
3135
- const message = err instanceof Error ? err.message : String(err);
3136
3454
  return c.json({
3137
3455
  error: "InvalidRecord",
3138
- message: prefix ? `${prefix}: ${message}` : message
3456
+ message: prefix ? `${prefix}: ${err.message}` : err.message
3457
+ }, 400);
3458
+ }
3459
+ /**
3460
+ * Validate the optional `validate` field from a write request body.
3461
+ * Lexicon defines it as `boolean?`; reject anything else so clients can't
3462
+ * silently fall through to optimistic mode by sending `"true"` or `1`.
3463
+ */
3464
+ function checkValidateFlag(c, value) {
3465
+ if (value === void 0 || typeof value === "boolean") return value;
3466
+ return c.json({
3467
+ error: "InvalidRequest",
3468
+ message: "Parameter 'validate' must be a boolean if provided"
3139
3469
  }, 400);
3140
3470
  }
3141
3471
  /**
@@ -3151,6 +3481,14 @@ function checkAccountDeactivatedError(c, err) {
3151
3481
  }, 403);
3152
3482
  return null;
3153
3483
  }
3484
+ function checkRecordAlreadyExistsError(c, err) {
3485
+ if (!isRecordAlreadyExistsError(err)) return null;
3486
+ const message = err.message.startsWith("RecordAlreadyExistsError:") ? err.message.slice(25).trimStart() : err.message;
3487
+ return c.json({
3488
+ error: "RecordAlreadyExists",
3489
+ message
3490
+ }, 409);
3491
+ }
3154
3492
  async function describeRepo(c, accountDO) {
3155
3493
  const repo = c.req.query("repo");
3156
3494
  if (!repo) return c.json({
@@ -3239,7 +3577,7 @@ async function listRecords(c, accountDO) {
3239
3577
  return c.json(result);
3240
3578
  }
3241
3579
  async function createRecord(c, accountDO) {
3242
- const { repo, collection, rkey, record } = await c.req.json();
3580
+ const { repo, collection, rkey, record, validate } = await c.req.json();
3243
3581
  if (!repo || !collection || !record) return c.json({
3244
3582
  error: "InvalidRequest",
3245
3583
  message: "Missing required parameters: repo, collection, record"
@@ -3248,17 +3586,38 @@ async function createRecord(c, accountDO) {
3248
3586
  error: "InvalidRepo",
3249
3587
  message: `Invalid repository: ${repo}`
3250
3588
  }, 400);
3589
+ const scopeError = requireScope(c, (perms) => perms.assertRepo({
3590
+ collection,
3591
+ action: "create"
3592
+ }));
3593
+ if (scopeError) return scopeError;
3594
+ const validateChecked = checkValidateFlag(c, validate);
3595
+ if (validateChecked instanceof Response) return validateChecked;
3596
+ if (rkey !== void 0 && typeof rkey !== "string") return c.json({
3597
+ error: "InvalidRequest",
3598
+ message: "rkey must be a string"
3599
+ }, 400);
3600
+ const candidateRkey = rkey ?? now();
3601
+ let validated;
3251
3602
  try {
3252
- validator.validateRecord(collection, record);
3603
+ validated = validator.validate({
3604
+ collection,
3605
+ record,
3606
+ rkey: candidateRkey,
3607
+ validate: validateChecked
3608
+ });
3253
3609
  } catch (err) {
3254
- return invalidRecordError(c, err);
3610
+ if (err instanceof InvalidRecordError) return invalidRecordError(c, err);
3611
+ throw err;
3255
3612
  }
3256
3613
  try {
3257
- const result = await accountDO.rpcCreateRecord(collection, rkey, record);
3614
+ const result = await accountDO.rpcCreateRecord(collection, rkey, validated.record, validated.status);
3258
3615
  return c.json(result);
3259
3616
  } catch (err) {
3260
3617
  const deactivatedError = checkAccountDeactivatedError(c, err);
3261
3618
  if (deactivatedError) return deactivatedError;
3619
+ const conflictError = checkRecordAlreadyExistsError(c, err);
3620
+ if (conflictError) return conflictError;
3262
3621
  throw err;
3263
3622
  }
3264
3623
  }
@@ -3272,6 +3631,11 @@ async function deleteRecord(c, accountDO) {
3272
3631
  error: "InvalidRepo",
3273
3632
  message: `Invalid repository: ${repo}`
3274
3633
  }, 400);
3634
+ const scopeError = requireScope(c, (perms) => perms.assertRepo({
3635
+ collection,
3636
+ action: "delete"
3637
+ }));
3638
+ if (scopeError) return scopeError;
3275
3639
  try {
3276
3640
  const result = await accountDO.rpcDeleteRecord(collection, rkey);
3277
3641
  if (!result) return c.json({
@@ -3286,7 +3650,7 @@ async function deleteRecord(c, accountDO) {
3286
3650
  }
3287
3651
  }
3288
3652
  async function putRecord(c, accountDO) {
3289
- const { repo, collection, rkey, record } = await c.req.json();
3653
+ const { repo, collection, rkey, record, validate } = await c.req.json();
3290
3654
  if (!repo || !collection || !rkey || !record) return c.json({
3291
3655
  error: "InvalidRequest",
3292
3656
  message: "Missing required parameters: repo, collection, rkey, record"
@@ -3295,25 +3659,38 @@ async function putRecord(c, accountDO) {
3295
3659
  error: "InvalidRepo",
3296
3660
  message: `Invalid repository: ${repo}`
3297
3661
  }, 400);
3662
+ const scopeError = requireScope(c, (perms) => perms.assertRepo({
3663
+ collection,
3664
+ action: "update"
3665
+ }));
3666
+ if (scopeError) return scopeError;
3667
+ const validateChecked = checkValidateFlag(c, validate);
3668
+ if (validateChecked instanceof Response) return validateChecked;
3669
+ let validated;
3298
3670
  try {
3299
- validator.validateRecord(collection, record);
3671
+ validated = validator.validate({
3672
+ collection,
3673
+ record,
3674
+ rkey,
3675
+ validate: validateChecked
3676
+ });
3300
3677
  } catch (err) {
3301
- return invalidRecordError(c, err);
3678
+ if (err instanceof InvalidRecordError) return invalidRecordError(c, err);
3679
+ throw err;
3302
3680
  }
3303
3681
  try {
3304
- const result = await accountDO.rpcPutRecord(collection, rkey, record);
3682
+ const result = await accountDO.rpcPutRecord(collection, rkey, validated.record, validated.status);
3305
3683
  return c.json(result);
3306
3684
  } catch (err) {
3307
3685
  const deactivatedError = checkAccountDeactivatedError(c, err);
3308
3686
  if (deactivatedError) return deactivatedError;
3309
- return c.json({
3310
- error: "InvalidRequest",
3311
- message: err instanceof Error ? err.message : String(err)
3312
- }, 400);
3687
+ const conflictError = checkRecordAlreadyExistsError(c, err);
3688
+ if (conflictError) return conflictError;
3689
+ throw err;
3313
3690
  }
3314
3691
  }
3315
3692
  async function applyWrites(c, accountDO) {
3316
- const { repo, writes } = await c.req.json();
3693
+ const { repo, writes, validate } = await c.req.json();
3317
3694
  if (!repo || !writes || !Array.isArray(writes)) return c.json({
3318
3695
  error: "InvalidRequest",
3319
3696
  message: "Missing required parameters: repo, writes"
@@ -3326,30 +3703,96 @@ async function applyWrites(c, accountDO) {
3326
3703
  error: "InvalidRequest",
3327
3704
  message: "Too many writes. Max: 200"
3328
3705
  }, 400);
3706
+ const validateChecked = checkValidateFlag(c, validate);
3707
+ if (validateChecked instanceof Response) return validateChecked;
3708
+ const checkScope = buildScopeChecker(c);
3709
+ const preparedWrites = [];
3710
+ const seenRkeys = /* @__PURE__ */ new Set();
3329
3711
  for (let i = 0; i < writes.length; i++) {
3330
3712
  const write = writes[i];
3331
- if (write.$type === "com.atproto.repo.applyWrites#create" || write.$type === "com.atproto.repo.applyWrites#update") try {
3332
- validator.validateRecord(write.collection, write.value);
3713
+ const action = write.$type === "com.atproto.repo.applyWrites#create" ? "create" : write.$type === "com.atproto.repo.applyWrites#update" ? "update" : write.$type === "com.atproto.repo.applyWrites#delete" ? "delete" : null;
3714
+ if (!action || !write.collection) return c.json({
3715
+ error: "InvalidRequest",
3716
+ message: `Write ${i}: unknown $type or missing collection`
3717
+ }, 400);
3718
+ if (checkScope) {
3719
+ const scopeError = checkScope((perms) => perms.assertRepo({
3720
+ collection: write.collection,
3721
+ action
3722
+ }));
3723
+ if (scopeError) return scopeError;
3724
+ }
3725
+ if (action === "delete" || action === "update") {
3726
+ if (typeof write.rkey !== "string" || write.rkey.length === 0) return c.json({
3727
+ error: "InvalidRequest",
3728
+ message: `Write ${i}: ${action} requires rkey`
3729
+ }, 400);
3730
+ } else if (write.rkey !== void 0) {
3731
+ if (typeof write.rkey !== "string" || write.rkey.length === 0) return c.json({
3732
+ error: "InvalidRequest",
3733
+ message: `Write ${i}: rkey must be a non-empty string`
3734
+ }, 400);
3735
+ }
3736
+ if (typeof write.rkey === "string") {
3737
+ const composite = `${write.collection}/${write.rkey}`;
3738
+ if (seenRkeys.has(composite)) return c.json({
3739
+ error: "InvalidRequest",
3740
+ message: `Write ${i}: duplicate rkey in batch (${composite})`
3741
+ }, 400);
3742
+ seenRkeys.add(composite);
3743
+ }
3744
+ if (action === "delete") {
3745
+ preparedWrites.push({
3746
+ $type: write.$type,
3747
+ collection: write.collection,
3748
+ rkey: write.rkey
3749
+ });
3750
+ continue;
3751
+ }
3752
+ const candidateRkey = write.rkey ?? now();
3753
+ try {
3754
+ const validated = validator.validate({
3755
+ collection: write.collection,
3756
+ record: write.value,
3757
+ rkey: candidateRkey,
3758
+ validate: validateChecked
3759
+ });
3760
+ preparedWrites.push({
3761
+ $type: write.$type,
3762
+ collection: write.collection,
3763
+ rkey: write.rkey,
3764
+ value: validated.record,
3765
+ validationStatus: validated.status
3766
+ });
3333
3767
  } catch (err) {
3334
- return invalidRecordError(c, err, `Write ${i}`);
3768
+ if (err instanceof InvalidRecordError) return invalidRecordError(c, err, `Write ${i}`);
3769
+ throw err;
3335
3770
  }
3336
3771
  }
3337
3772
  try {
3338
- const result = await accountDO.rpcApplyWrites(writes);
3773
+ const result = await accountDO.rpcApplyWrites(preparedWrites);
3339
3774
  return c.json(result);
3340
3775
  } catch (err) {
3341
3776
  const deactivatedError = checkAccountDeactivatedError(c, err);
3342
3777
  if (deactivatedError) return deactivatedError;
3343
- return c.json({
3344
- error: "InvalidRequest",
3345
- message: err instanceof Error ? err.message : String(err)
3346
- }, 400);
3778
+ const conflictError = checkRecordAlreadyExistsError(c, err);
3779
+ if (conflictError) return conflictError;
3780
+ throw err;
3347
3781
  }
3348
3782
  }
3349
3783
  async function uploadBlob(c, accountDO) {
3350
3784
  let contentType = c.req.header("Content-Type");
3785
+ const mimeOf = (ct) => ct.split(";")[0].trim().toLowerCase();
3786
+ if (contentType && contentType !== "*/*") {
3787
+ const declared = mimeOf(contentType);
3788
+ const preCheck = requireScope(c, (perms) => perms.assertBlob({ mime: declared }));
3789
+ if (preCheck) return preCheck;
3790
+ }
3351
3791
  const bytes = new Uint8Array(await c.req.arrayBuffer());
3352
- if (!contentType || contentType === "*/*") contentType = detectContentType(bytes) || "application/octet-stream";
3792
+ const effective = detectContentType(bytes) ?? (contentType && contentType !== "*/*" ? mimeOf(contentType) : "application/octet-stream");
3793
+ const postCheck = requireScope(c, (perms) => perms.assertBlob({ mime: effective }));
3794
+ if (postCheck) return postCheck;
3795
+ contentType = effective;
3353
3796
  const MAX_BLOB_SIZE = 60 * 1024 * 1024;
3354
3797
  if (bytes.length > MAX_BLOB_SIZE) return c.json({
3355
3798
  error: "BlobTooLarge",
@@ -3602,7 +4045,7 @@ async function checkAccountStatus(c, accountDO) {
3602
4045
  repoRev: status.rev,
3603
4046
  repoBlocks,
3604
4047
  indexedRecords,
3605
- privateStateValues: null,
4048
+ privateStateValues: 0,
3606
4049
  expectedBlobs,
3607
4050
  importedBlobs
3608
4051
  });
@@ -3615,7 +4058,7 @@ async function checkAccountStatus(c, accountDO) {
3615
4058
  repoRev: null,
3616
4059
  repoBlocks: 0,
3617
4060
  indexedRecords: 0,
3618
- privateStateValues: null,
4061
+ privateStateValues: 0,
3619
4062
  expectedBlobs: 0,
3620
4063
  importedBlobs: 0
3621
4064
  });
@@ -4369,7 +4812,7 @@ function renderDashboard(config) {
4369
4812
 
4370
4813
  //#endregion
4371
4814
  //#region package.json
4372
- var version = "0.13.0";
4815
+ var version = "0.15.0";
4373
4816
 
4374
4817
  //#endregion
4375
4818
  //#region src/index.ts
@@ -4444,7 +4887,6 @@ app.get("/.well-known/did.json", (c) => {
4444
4887
  return c.json(didDocument);
4445
4888
  });
4446
4889
  app.get("/.well-known/atproto-did", (c) => {
4447
- if (c.env.HANDLE !== c.env.PDS_HOSTNAME) return c.notFound();
4448
4890
  return new Response(c.env.DID, { headers: { "Content-Type": "text/plain" } });
4449
4891
  });
4450
4892
  app.get("/xrpc/_health", async (c) => {