@getcirrus/pds 0.14.0 → 0.15.1

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
8
  import { ATProtoOAuthProvider, REFRESH_TOKEN_TTL, ScopeMissingError, createAtcutePermissionSetResolver, permissionsFor } from "@getcirrus/oauth-provider";
9
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";
10
14
  import { Hono } from "hono";
11
15
  import { cors } from "hono/cors";
12
- import { isDid, isHandle, isNsid, isRecordKey } from "@atcute/lexicons/syntax";
13
16
  import { SignJWT, base64url, errors, jwtVerify } from "jose";
14
17
  import { compare, compare as compare$1, hash } from "bcryptjs";
15
18
  import { CompositeDidDocumentResolver, PlcDidDocumentResolver, WebDidDocumentResolver } from "@atcute/identity-resolver";
16
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
  /**
@@ -360,6 +361,12 @@ var SqliteRepoStorage = class extends ReadableBlockstore {
360
361
  this.sql.exec("INSERT OR IGNORE INTO collections (collection) VALUES (?)", collection);
361
362
  }
362
363
  /**
364
+ * Remove a collection name from the cache (no-op if not present).
365
+ */
366
+ removeCollection(collection) {
367
+ this.sql.exec("DELETE FROM collections WHERE collection = ?", collection);
368
+ }
369
+ /**
363
370
  * Check if the collections cache has been populated.
364
371
  */
365
372
  hasCollections() {
@@ -1053,6 +1060,110 @@ var BlobStore = class {
1053
1060
  }
1054
1061
  };
1055
1062
 
1063
+ //#endregion
1064
+ //#region src/validation.ts
1065
+ const recordSchemas = {
1066
+ "app.bsky.actor.profile": AppBskyActorProfile.mainSchema,
1067
+ "app.bsky.actor.status": AppBskyActorStatus.mainSchema,
1068
+ "app.bsky.feed.generator": AppBskyFeedGenerator.mainSchema,
1069
+ "app.bsky.feed.like": AppBskyFeedLike.mainSchema,
1070
+ "app.bsky.feed.post": AppBskyFeedPost.mainSchema,
1071
+ "app.bsky.feed.postgate": AppBskyFeedPostgate.mainSchema,
1072
+ "app.bsky.feed.repost": AppBskyFeedRepost.mainSchema,
1073
+ "app.bsky.feed.threadgate": AppBskyFeedThreadgate.mainSchema,
1074
+ "app.bsky.graph.block": AppBskyGraphBlock.mainSchema,
1075
+ "app.bsky.graph.follow": AppBskyGraphFollow.mainSchema,
1076
+ "app.bsky.graph.list": AppBskyGraphList.mainSchema,
1077
+ "app.bsky.graph.listblock": AppBskyGraphListblock.mainSchema,
1078
+ "app.bsky.graph.listitem": AppBskyGraphListitem.mainSchema,
1079
+ "app.bsky.graph.starterpack": AppBskyGraphStarterpack.mainSchema,
1080
+ "app.bsky.graph.verification": AppBskyGraphVerification.mainSchema,
1081
+ "app.bsky.labeler.service": AppBskyLabelerService.mainSchema,
1082
+ "app.bsky.notification.declaration": AppBskyNotificationDeclaration.mainSchema,
1083
+ "chat.bsky.actor.declaration": ChatBskyActorDeclaration.mainSchema,
1084
+ "com.atproto.lexicon.schema": ComAtprotoLexiconSchema.mainSchema
1085
+ };
1086
+ var InvalidRecordError = class extends Error {
1087
+ name = "InvalidRecordError";
1088
+ };
1089
+ /**
1090
+ * Thrown when a write targets an rkey that already exists in the repo.
1091
+ * Uses a `name` field rather than relying on class identity, so the error
1092
+ * survives a Cloudflare DO RPC boundary (RPC preserves message + name + stack
1093
+ * but not the prototype chain).
1094
+ */
1095
+ var RecordAlreadyExistsError = class extends Error {
1096
+ name = "RecordAlreadyExistsError";
1097
+ };
1098
+ function isRecordAlreadyExistsError(err) {
1099
+ if (!(err instanceof Error)) return false;
1100
+ return err.name === "RecordAlreadyExistsError" || err.message.startsWith("RecordAlreadyExistsError:");
1101
+ }
1102
+ var RecordValidator = class {
1103
+ validate(opts) {
1104
+ const reconciled = reconcileType(opts.record, opts.collection);
1105
+ rejectLegacyBlobRefs(reconciled);
1106
+ if (opts.rkey !== void 0 && !isRecordKey(opts.rkey)) throw new InvalidRecordError(`Invalid record key: ${opts.rkey}`);
1107
+ if (opts.validate === false) return { record: reconciled };
1108
+ const schema = recordSchemas[opts.collection];
1109
+ if (!schema) {
1110
+ if (opts.validate === true) throw new InvalidRecordError(`Unknown lexicon type: ${opts.collection}`);
1111
+ return {
1112
+ record: reconciled,
1113
+ status: "unknown"
1114
+ };
1115
+ }
1116
+ if (opts.rkey !== void 0) {
1117
+ const keyResult = safeParse(schema.key, opts.rkey);
1118
+ if (!keyResult.ok) throw new InvalidRecordError(`Invalid record key for ${opts.collection}: ${keyResult.message}`);
1119
+ }
1120
+ try {
1121
+ parse(schema, reconciled);
1122
+ } catch (err) {
1123
+ if (err instanceof ValidationError) throw new InvalidRecordError(`Invalid ${opts.collection} record: ${err.message}`);
1124
+ throw err;
1125
+ }
1126
+ return {
1127
+ record: reconciled,
1128
+ status: "valid"
1129
+ };
1130
+ }
1131
+ hasSchema(collection) {
1132
+ return collection in recordSchemas;
1133
+ }
1134
+ getLoadedSchemas() {
1135
+ return Object.keys(recordSchemas);
1136
+ }
1137
+ };
1138
+ const validator = new RecordValidator();
1139
+ function reconcileType(record, collection) {
1140
+ if (record === null || typeof record !== "object" || Array.isArray(record)) throw new InvalidRecordError("Record must be an object");
1141
+ const obj = record;
1142
+ const declared = obj.$type;
1143
+ if (declared === void 0) return {
1144
+ ...obj,
1145
+ $type: collection
1146
+ };
1147
+ if (declared !== collection) throw new InvalidRecordError(`Invalid $type: expected ${collection}, got ${String(declared)}`);
1148
+ return obj;
1149
+ }
1150
+ function rejectLegacyBlobRefs(value) {
1151
+ const stack = [value];
1152
+ const visited = /* @__PURE__ */ new WeakSet();
1153
+ while (stack.length > 0) {
1154
+ const current = stack.pop();
1155
+ if (current === null || typeof current !== "object") continue;
1156
+ if (visited.has(current)) continue;
1157
+ visited.add(current);
1158
+ if (Array.isArray(current)) {
1159
+ for (const item of current) stack.push(item);
1160
+ continue;
1161
+ }
1162
+ if (isLegacyBlobRef(current)) throw new InvalidRecordError(`Legacy blobs are not allowed (${current.cid})`);
1163
+ for (const v of Object.values(current)) if (v !== null && typeof v === "object") stack.push(v);
1164
+ }
1165
+ }
1166
+
1056
1167
  //#endregion
1057
1168
  //#region src/account-do.ts
1058
1169
  /**
@@ -1167,6 +1278,17 @@ var AccountDurableObject = class extends DurableObject {
1167
1278
  this.repo = repo;
1168
1279
  }
1169
1280
  /**
1281
+ * Drop the in-memory repo so the next access reloads from storage.
1282
+ * Used after a write fails post-applyWrites: Cloudflare rolls back the
1283
+ * SQLite writes, but JS state isn't rolled back, so the cached Repo can
1284
+ * end up ahead of storage. That mismatch produces firehose events whose
1285
+ * `since` rev the relay never saw, causing it to mark us desynced.
1286
+ */
1287
+ invalidateRepoCache() {
1288
+ this.repo = null;
1289
+ this.repoInitialized = false;
1290
+ }
1291
+ /**
1170
1292
  * RPC method: Get repo metadata for describeRepo
1171
1293
  */
1172
1294
  async rpcDescribeRepo() {
@@ -1230,11 +1352,18 @@ var AccountDurableObject = class extends DurableObject {
1230
1352
  /**
1231
1353
  * RPC method: Create a record
1232
1354
  */
1233
- async rpcCreateRecord(collection, rkey, record) {
1355
+ async rpcCreateRecord(collection, rkey, record, validationStatus) {
1234
1356
  await this.ensureActive();
1235
1357
  const repo = await this.getRepo();
1236
1358
  const keypair = await this.getKeypair();
1237
- const actualRkey = rkey || now();
1359
+ const autoGenerated = rkey === void 0;
1360
+ let actualRkey = rkey ?? now();
1361
+ for (let attempt = 0; attempt < 5; attempt++) {
1362
+ if (!await repo.data.get(`${collection}/${actualRkey}`)) break;
1363
+ if (!autoGenerated) throw new RecordAlreadyExistsError(`${collection}/${actualRkey}`);
1364
+ if (attempt === 4) throw new Error(`Failed to allocate unique rkey for ${collection} after 5 attempts`);
1365
+ actualRkey = now();
1366
+ }
1238
1367
  const createOp = {
1239
1368
  action: WriteOpAction.Create,
1240
1369
  collection,
@@ -1242,42 +1371,49 @@ var AccountDurableObject = class extends DurableObject {
1242
1371
  record: jsonToLex(record)
1243
1372
  };
1244
1373
  const prevRev = repo.commit.rev;
1245
- this.repo = await repo.applyWrites([createOp], keypair);
1246
- const dataKey = `${collection}/${actualRkey}`;
1247
- const recordCid = await this.repo.data.get(dataKey);
1248
- if (!recordCid) throw new Error(`Failed to create record: ${collection}/${actualRkey}`);
1249
- this.storage.addCollection(collection);
1250
- if (this.sequencer) {
1251
- const newBlocks = new BlockMap();
1252
- const rows = this.ctx.storage.sql.exec("SELECT cid, bytes FROM blocks WHERE rev = ?", this.repo.commit.rev).toArray();
1253
- for (const row of rows) {
1254
- const cid = CID.parse(row.cid);
1255
- const bytes = new Uint8Array(row.bytes);
1256
- newBlocks.set(cid, bytes);
1374
+ const updatedRepo = await repo.applyWrites([createOp], keypair);
1375
+ try {
1376
+ const dataKey = `${collection}/${actualRkey}`;
1377
+ const recordCid = await updatedRepo.data.get(dataKey);
1378
+ if (!recordCid) throw new Error(`Failed to create record: ${collection}/${actualRkey}`);
1379
+ this.storage.addCollection(collection);
1380
+ if (this.sequencer) {
1381
+ const newBlocks = new BlockMap();
1382
+ const rows = this.ctx.storage.sql.exec("SELECT cid, bytes FROM blocks WHERE rev = ?", updatedRepo.commit.rev).toArray();
1383
+ for (const row of rows) {
1384
+ const cid = CID.parse(row.cid);
1385
+ const bytes = new Uint8Array(row.bytes);
1386
+ newBlocks.set(cid, bytes);
1387
+ }
1388
+ const opWithCid = {
1389
+ ...createOp,
1390
+ cid: recordCid
1391
+ };
1392
+ const commitData = {
1393
+ did: updatedRepo.did,
1394
+ commit: updatedRepo.cid,
1395
+ rev: updatedRepo.commit.rev,
1396
+ since: prevRev,
1397
+ newBlocks,
1398
+ ops: [opWithCid]
1399
+ };
1400
+ const event = await this.sequencer.sequenceCommit(commitData);
1401
+ await this.broadcastCommit(event);
1257
1402
  }
1258
- const opWithCid = {
1259
- ...createOp,
1260
- cid: recordCid
1261
- };
1262
- const commitData = {
1263
- did: this.repo.did,
1264
- commit: this.repo.cid,
1265
- rev: this.repo.commit.rev,
1266
- since: prevRev,
1267
- newBlocks,
1268
- ops: [opWithCid]
1403
+ this.repo = updatedRepo;
1404
+ return {
1405
+ uri: `at://${updatedRepo.did}/${collection}/${actualRkey}`,
1406
+ cid: recordCid.toString(),
1407
+ commit: {
1408
+ cid: updatedRepo.cid.toString(),
1409
+ rev: updatedRepo.commit.rev
1410
+ },
1411
+ ...validationStatus !== void 0 ? { validationStatus } : {}
1269
1412
  };
1270
- const event = await this.sequencer.sequenceCommit(commitData);
1271
- await this.broadcastCommit(event);
1413
+ } catch (err) {
1414
+ this.invalidateRepoCache();
1415
+ throw err;
1272
1416
  }
1273
- return {
1274
- uri: `at://${this.repo.did}/${collection}/${actualRkey}`,
1275
- cid: recordCid.toString(),
1276
- commit: {
1277
- cid: this.repo.cid.toString(),
1278
- rev: this.repo.commit.rev
1279
- }
1280
- };
1281
1417
  }
1282
1418
  /**
1283
1419
  * RPC method: Delete a record
@@ -1294,35 +1430,47 @@ var AccountDurableObject = class extends DurableObject {
1294
1430
  };
1295
1431
  const prevRev = repo.commit.rev;
1296
1432
  const updatedRepo = await repo.applyWrites([deleteOp], keypair);
1297
- this.repo = updatedRepo;
1298
- if (this.sequencer) {
1299
- const newBlocks = new BlockMap();
1300
- const rows = this.ctx.storage.sql.exec("SELECT cid, bytes FROM blocks WHERE rev = ?", this.repo.commit.rev).toArray();
1301
- for (const row of rows) {
1302
- const cid = CID.parse(row.cid);
1303
- const bytes = new Uint8Array(row.bytes);
1304
- newBlocks.set(cid, bytes);
1433
+ try {
1434
+ if (this.sequencer) {
1435
+ const newBlocks = new BlockMap();
1436
+ const rows = this.ctx.storage.sql.exec("SELECT cid, bytes FROM blocks WHERE rev = ?", updatedRepo.commit.rev).toArray();
1437
+ for (const row of rows) {
1438
+ const cid = CID.parse(row.cid);
1439
+ const bytes = new Uint8Array(row.bytes);
1440
+ newBlocks.set(cid, bytes);
1441
+ }
1442
+ const commitData = {
1443
+ did: updatedRepo.did,
1444
+ commit: updatedRepo.cid,
1445
+ rev: updatedRepo.commit.rev,
1446
+ since: prevRev,
1447
+ newBlocks,
1448
+ ops: [deleteOp]
1449
+ };
1450
+ const event = await this.sequencer.sequenceCommit(commitData);
1451
+ await this.broadcastCommit(event);
1305
1452
  }
1306
- const commitData = {
1307
- did: this.repo.did,
1308
- commit: this.repo.cid,
1309
- rev: this.repo.commit.rev,
1310
- since: prevRev,
1311
- newBlocks,
1312
- ops: [deleteOp]
1313
- };
1314
- const event = await this.sequencer.sequenceCommit(commitData);
1315
- await this.broadcastCommit(event);
1453
+ this.repo = updatedRepo;
1454
+ let collectionStillHasRecords = false;
1455
+ for await (const remaining of updatedRepo.walkRecords(`${collection}/`)) {
1456
+ if (remaining.collection !== collection) break;
1457
+ collectionStillHasRecords = true;
1458
+ break;
1459
+ }
1460
+ if (!collectionStillHasRecords) this.storage.removeCollection(collection);
1461
+ return { commit: {
1462
+ cid: updatedRepo.cid.toString(),
1463
+ rev: updatedRepo.commit.rev
1464
+ } };
1465
+ } catch (err) {
1466
+ this.invalidateRepoCache();
1467
+ throw err;
1316
1468
  }
1317
- return { commit: {
1318
- cid: updatedRepo.cid.toString(),
1319
- rev: updatedRepo.commit.rev
1320
- } };
1321
1469
  }
1322
1470
  /**
1323
1471
  * RPC method: Put a record (create or update)
1324
1472
  */
1325
- async rpcPutRecord(collection, rkey, record) {
1473
+ async rpcPutRecord(collection, rkey, record, validationStatus) {
1326
1474
  await this.ensureActive();
1327
1475
  const repo = await this.getRepo();
1328
1476
  const keypair = await this.getKeypair();
@@ -1340,43 +1488,49 @@ var AccountDurableObject = class extends DurableObject {
1340
1488
  record: normalizedRecord
1341
1489
  };
1342
1490
  const prevRev = repo.commit.rev;
1343
- this.repo = await repo.applyWrites([op], keypair);
1344
- const dataKey = `${collection}/${rkey}`;
1345
- const recordCid = await this.repo.data.get(dataKey);
1346
- if (!recordCid) throw new Error(`Failed to put record: ${collection}/${rkey}`);
1347
- this.storage.addCollection(collection);
1348
- if (this.sequencer) {
1349
- const newBlocks = new BlockMap();
1350
- const rows = this.ctx.storage.sql.exec("SELECT cid, bytes FROM blocks WHERE rev = ?", this.repo.commit.rev).toArray();
1351
- for (const row of rows) {
1352
- const cid = CID.parse(row.cid);
1353
- const bytes = new Uint8Array(row.bytes);
1354
- newBlocks.set(cid, bytes);
1491
+ const updatedRepo = await repo.applyWrites([op], keypair);
1492
+ try {
1493
+ const dataKey = `${collection}/${rkey}`;
1494
+ const recordCid = await updatedRepo.data.get(dataKey);
1495
+ if (!recordCid) throw new Error(`Failed to put record: ${collection}/${rkey}`);
1496
+ this.storage.addCollection(collection);
1497
+ if (this.sequencer) {
1498
+ const newBlocks = new BlockMap();
1499
+ const rows = this.ctx.storage.sql.exec("SELECT cid, bytes FROM blocks WHERE rev = ?", updatedRepo.commit.rev).toArray();
1500
+ for (const row of rows) {
1501
+ const cid = CID.parse(row.cid);
1502
+ const bytes = new Uint8Array(row.bytes);
1503
+ newBlocks.set(cid, bytes);
1504
+ }
1505
+ const opWithCid = {
1506
+ ...op,
1507
+ cid: recordCid
1508
+ };
1509
+ const commitData = {
1510
+ did: updatedRepo.did,
1511
+ commit: updatedRepo.cid,
1512
+ rev: updatedRepo.commit.rev,
1513
+ since: prevRev,
1514
+ newBlocks,
1515
+ ops: [opWithCid]
1516
+ };
1517
+ const event = await this.sequencer.sequenceCommit(commitData);
1518
+ await this.broadcastCommit(event);
1355
1519
  }
1356
- const opWithCid = {
1357
- ...op,
1358
- cid: recordCid
1359
- };
1360
- const commitData = {
1361
- did: this.repo.did,
1362
- commit: this.repo.cid,
1363
- rev: this.repo.commit.rev,
1364
- since: prevRev,
1365
- newBlocks,
1366
- ops: [opWithCid]
1520
+ this.repo = updatedRepo;
1521
+ return {
1522
+ uri: `at://${updatedRepo.did}/${collection}/${rkey}`,
1523
+ cid: recordCid.toString(),
1524
+ commit: {
1525
+ cid: updatedRepo.cid.toString(),
1526
+ rev: updatedRepo.commit.rev
1527
+ },
1528
+ ...validationStatus !== void 0 ? { validationStatus } : {}
1367
1529
  };
1368
- const event = await this.sequencer.sequenceCommit(commitData);
1369
- await this.broadcastCommit(event);
1530
+ } catch (err) {
1531
+ this.invalidateRepoCache();
1532
+ throw err;
1370
1533
  }
1371
- return {
1372
- uri: `at://${this.repo.did}/${collection}/${rkey}`,
1373
- cid: recordCid.toString(),
1374
- commit: {
1375
- cid: this.repo.cid.toString(),
1376
- rev: this.repo.commit.rev
1377
- },
1378
- validationStatus: "valid"
1379
- };
1380
1534
  }
1381
1535
  /**
1382
1536
  * RPC method: Apply multiple writes (batch create/update/delete)
@@ -1387,8 +1541,20 @@ var AccountDurableObject = class extends DurableObject {
1387
1541
  const keypair = await this.getKeypair();
1388
1542
  const ops = [];
1389
1543
  const results = [];
1544
+ const reservedRkeys = /* @__PURE__ */ new Set();
1390
1545
  for (const write of writes) if (write.$type === "com.atproto.repo.applyWrites#create") {
1391
- const rkey = write.rkey || now();
1546
+ const autoGenerated = write.rkey === void 0;
1547
+ let rkey = write.rkey ?? now();
1548
+ for (let attempt = 0; attempt < 5; attempt++) {
1549
+ const composite = `${write.collection}/${rkey}`;
1550
+ const collidesInBatch = reservedRkeys.has(composite);
1551
+ const collidesInRepo = !collidesInBatch && await repo.data.get(composite) !== null;
1552
+ if (!collidesInBatch && !collidesInRepo) break;
1553
+ if (!autoGenerated) throw new RecordAlreadyExistsError(composite);
1554
+ if (attempt === 4) throw new Error(`Failed to allocate unique rkey for ${write.collection} after 5 attempts`);
1555
+ rkey = now();
1556
+ }
1557
+ reservedRkeys.add(`${write.collection}/${rkey}`);
1392
1558
  const op = {
1393
1559
  action: WriteOpAction.Create,
1394
1560
  collection: write.collection,
@@ -1400,7 +1566,8 @@ var AccountDurableObject = class extends DurableObject {
1400
1566
  $type: "com.atproto.repo.applyWrites#createResult",
1401
1567
  collection: write.collection,
1402
1568
  rkey,
1403
- action: WriteOpAction.Create
1569
+ action: WriteOpAction.Create,
1570
+ validationStatus: write.validationStatus
1404
1571
  });
1405
1572
  } else if (write.$type === "com.atproto.repo.applyWrites#update") {
1406
1573
  if (!write.rkey) throw new Error("Update requires rkey");
@@ -1415,7 +1582,8 @@ var AccountDurableObject = class extends DurableObject {
1415
1582
  $type: "com.atproto.repo.applyWrites#updateResult",
1416
1583
  collection: write.collection,
1417
1584
  rkey: write.rkey,
1418
- action: WriteOpAction.Update
1585
+ action: WriteOpAction.Update,
1586
+ validationStatus: write.validationStatus
1419
1587
  });
1420
1588
  } else if (write.$type === "com.atproto.repo.applyWrites#delete") {
1421
1589
  if (!write.rkey) throw new Error("Delete requires rkey");
@@ -1433,57 +1601,74 @@ var AccountDurableObject = class extends DurableObject {
1433
1601
  });
1434
1602
  } else throw new Error(`Unknown write type: ${write.$type}`);
1435
1603
  const prevRev = repo.commit.rev;
1436
- this.repo = await repo.applyWrites(ops, keypair);
1437
- for (const op of ops) if (op.action !== WriteOpAction.Delete) this.storage.addCollection(op.collection);
1438
- const finalResults = [];
1439
- const opsWithCids = [];
1440
- for (let i = 0; i < results.length; i++) {
1441
- const result = results[i];
1442
- const op = ops[i];
1443
- if (result.action === WriteOpAction.Delete) {
1444
- finalResults.push({ $type: result.$type });
1445
- opsWithCids.push(op);
1446
- } else {
1447
- const dataKey = `${result.collection}/${result.rkey}`;
1448
- const recordCid = await this.repo.data.get(dataKey);
1449
- finalResults.push({
1450
- $type: result.$type,
1451
- uri: `at://${this.repo.did}/${result.collection}/${result.rkey}`,
1452
- cid: recordCid?.toString(),
1453
- validationStatus: "valid"
1454
- });
1455
- opsWithCids.push({
1456
- ...op,
1457
- cid: recordCid
1458
- });
1604
+ const updatedRepo = await repo.applyWrites(ops, keypair);
1605
+ try {
1606
+ for (const op of ops) if (op.action !== WriteOpAction.Delete) this.storage.addCollection(op.collection);
1607
+ const finalResults = [];
1608
+ const opsWithCids = [];
1609
+ for (let i = 0; i < results.length; i++) {
1610
+ const result = results[i];
1611
+ const op = ops[i];
1612
+ if (result.action === WriteOpAction.Delete) {
1613
+ finalResults.push({ $type: result.$type });
1614
+ opsWithCids.push(op);
1615
+ } else {
1616
+ const dataKey = `${result.collection}/${result.rkey}`;
1617
+ const recordCid = await updatedRepo.data.get(dataKey);
1618
+ finalResults.push({
1619
+ $type: result.$type,
1620
+ uri: `at://${updatedRepo.did}/${result.collection}/${result.rkey}`,
1621
+ cid: recordCid?.toString(),
1622
+ ...result.validationStatus !== void 0 ? { validationStatus: result.validationStatus } : {}
1623
+ });
1624
+ opsWithCids.push({
1625
+ ...op,
1626
+ cid: recordCid
1627
+ });
1628
+ }
1459
1629
  }
1460
- }
1461
- if (this.sequencer) {
1462
- const newBlocks = new BlockMap();
1463
- const rows = this.ctx.storage.sql.exec("SELECT cid, bytes FROM blocks WHERE rev = ?", this.repo.commit.rev).toArray();
1464
- for (const row of rows) {
1465
- const cid = CID.parse(row.cid);
1466
- const bytes = new Uint8Array(row.bytes);
1467
- newBlocks.set(cid, bytes);
1630
+ if (this.sequencer) {
1631
+ const newBlocks = new BlockMap();
1632
+ const rows = this.ctx.storage.sql.exec("SELECT cid, bytes FROM blocks WHERE rev = ?", updatedRepo.commit.rev).toArray();
1633
+ for (const row of rows) {
1634
+ const cid = CID.parse(row.cid);
1635
+ const bytes = new Uint8Array(row.bytes);
1636
+ newBlocks.set(cid, bytes);
1637
+ }
1638
+ const commitData = {
1639
+ did: updatedRepo.did,
1640
+ commit: updatedRepo.cid,
1641
+ rev: updatedRepo.commit.rev,
1642
+ since: prevRev,
1643
+ newBlocks,
1644
+ ops: opsWithCids
1645
+ };
1646
+ const event = await this.sequencer.sequenceCommit(commitData);
1647
+ await this.broadcastCommit(event);
1468
1648
  }
1469
- const commitData = {
1470
- did: this.repo.did,
1471
- commit: this.repo.cid,
1472
- rev: this.repo.commit.rev,
1473
- since: prevRev,
1474
- newBlocks,
1475
- ops: opsWithCids
1649
+ this.repo = updatedRepo;
1650
+ const deletedCollections = /* @__PURE__ */ new Set();
1651
+ for (const op of ops) if (op.action === WriteOpAction.Delete) deletedCollections.add(op.collection);
1652
+ for (const collection of deletedCollections) {
1653
+ let collectionStillHasRecords = false;
1654
+ for await (const remaining of updatedRepo.walkRecords(`${collection}/`)) {
1655
+ if (remaining.collection !== collection) break;
1656
+ collectionStillHasRecords = true;
1657
+ break;
1658
+ }
1659
+ if (!collectionStillHasRecords) this.storage.removeCollection(collection);
1660
+ }
1661
+ return {
1662
+ commit: {
1663
+ cid: updatedRepo.cid.toString(),
1664
+ rev: updatedRepo.commit.rev
1665
+ },
1666
+ results: finalResults
1476
1667
  };
1477
- const event = await this.sequencer.sequenceCommit(commitData);
1478
- await this.broadcastCommit(event);
1668
+ } catch (err) {
1669
+ this.invalidateRepoCache();
1670
+ throw err;
1479
1671
  }
1480
- return {
1481
- commit: {
1482
- cid: this.repo.cid.toString(),
1483
- rev: this.repo.commit.rev
1484
- },
1485
- results: finalResults
1486
- };
1487
1672
  }
1488
1673
  /**
1489
1674
  * RPC method: Get repo status
@@ -3287,91 +3472,24 @@ async function getRecord$1(c, accountDO) {
3287
3472
  }
3288
3473
  }
3289
3474
 
3290
- //#endregion
3291
- //#region src/validation.ts
3292
- /**
3293
- * Map of collection NSID to validation schema.
3294
- * Only includes record types that can be created in repositories.
3295
- */
3296
- const recordSchemas = {
3297
- "app.bsky.actor.profile": AppBskyActorProfile.mainSchema,
3298
- "app.bsky.feed.generator": AppBskyFeedGenerator.mainSchema,
3299
- "app.bsky.feed.like": AppBskyFeedLike.mainSchema,
3300
- "app.bsky.feed.post": AppBskyFeedPost.mainSchema,
3301
- "app.bsky.feed.postgate": AppBskyFeedPostgate.mainSchema,
3302
- "app.bsky.feed.repost": AppBskyFeedRepost.mainSchema,
3303
- "app.bsky.feed.threadgate": AppBskyFeedThreadgate.mainSchema,
3304
- "app.bsky.graph.block": AppBskyGraphBlock.mainSchema,
3305
- "app.bsky.graph.follow": AppBskyGraphFollow.mainSchema,
3306
- "app.bsky.graph.list": AppBskyGraphList.mainSchema,
3307
- "app.bsky.graph.listblock": AppBskyGraphListblock.mainSchema,
3308
- "app.bsky.graph.listitem": AppBskyGraphListitem.mainSchema,
3309
- "app.bsky.graph.starterpack": AppBskyGraphStarterpack.mainSchema,
3310
- "app.bsky.graph.verification": AppBskyGraphVerification.mainSchema,
3311
- "app.bsky.labeler.service": AppBskyLabelerService.mainSchema
3312
- };
3313
- /**
3314
- * Record validator for AT Protocol records.
3315
- *
3316
- * Validates records against official Bluesky lexicon schemas from @atcute/bluesky.
3317
- * Uses optimistic validation strategy:
3318
- * - If a schema is loaded for the collection, validate the record
3319
- * - If no schema is loaded, allow the record (fail-open)
3320
- *
3321
- * This allows the PDS to accept records for new or unknown collection types
3322
- * while still validating known types.
3323
- */
3324
- var RecordValidator = class {
3325
- strictMode;
3326
- constructor(options = {}) {
3327
- this.strictMode = options.strict ?? false;
3328
- }
3329
- /**
3330
- * Validate a record against its lexicon schema.
3331
- *
3332
- * @param collection - The NSID of the record type (e.g., "app.bsky.feed.post")
3333
- * @param record - The record object to validate
3334
- * @throws {Error} If validation fails and schema is loaded
3335
- */
3336
- validateRecord(collection, record) {
3337
- const schema = recordSchemas[collection];
3338
- if (!schema) {
3339
- if (this.strictMode) throw new Error(`No lexicon schema loaded for collection: ${collection}. Enable optimistic validation or add the schema.`);
3340
- return;
3341
- }
3342
- try {
3343
- parse(schema, record);
3344
- } catch (error) {
3345
- if (error instanceof ValidationError) throw new Error(`Lexicon validation failed for ${collection}: ${error.message}`);
3346
- throw error;
3347
- }
3348
- }
3349
- /**
3350
- * Check if a schema is loaded for a collection.
3351
- */
3352
- hasSchema(collection) {
3353
- return collection in recordSchemas;
3354
- }
3355
- /**
3356
- * Get list of all loaded schema NSIDs.
3357
- */
3358
- getLoadedSchemas() {
3359
- return Object.keys(recordSchemas);
3360
- }
3361
- };
3362
- /**
3363
- * Shared validator instance (singleton pattern).
3364
- * Uses optimistic validation by default (strict: false).
3365
- */
3366
- const validator = new RecordValidator({ strict: false });
3367
-
3368
3475
  //#endregion
3369
3476
  //#region src/xrpc/repo.ts
3370
3477
  function invalidRecordError(c, err, prefix) {
3371
- const message = err instanceof Error ? err.message : String(err);
3372
3478
  return c.json({
3373
3479
  error: "InvalidRecord",
3374
- message: prefix ? `${prefix}: ${message}` : message
3480
+ message: prefix ? `${prefix}: ${err.message}` : err.message
3481
+ }, 400);
3482
+ }
3483
+ /**
3484
+ * Validate the optional `validate` field from a write request body.
3485
+ * Lexicon defines it as `boolean?`; reject anything else so clients can't
3486
+ * silently fall through to optimistic mode by sending `"true"` or `1`.
3487
+ */
3488
+ function checkValidateFlag(c, value) {
3489
+ if (value === void 0 || typeof value === "boolean") return value;
3490
+ return c.json({
3491
+ error: "InvalidRequest",
3492
+ message: "Parameter 'validate' must be a boolean if provided"
3375
3493
  }, 400);
3376
3494
  }
3377
3495
  /**
@@ -3387,6 +3505,14 @@ function checkAccountDeactivatedError(c, err) {
3387
3505
  }, 403);
3388
3506
  return null;
3389
3507
  }
3508
+ function checkRecordAlreadyExistsError(c, err) {
3509
+ if (!isRecordAlreadyExistsError(err)) return null;
3510
+ const message = err.message.startsWith("RecordAlreadyExistsError:") ? err.message.slice(25).trimStart() : err.message;
3511
+ return c.json({
3512
+ error: "RecordAlreadyExists",
3513
+ message
3514
+ }, 409);
3515
+ }
3390
3516
  async function describeRepo(c, accountDO) {
3391
3517
  const repo = c.req.query("repo");
3392
3518
  if (!repo) return c.json({
@@ -3475,7 +3601,7 @@ async function listRecords(c, accountDO) {
3475
3601
  return c.json(result);
3476
3602
  }
3477
3603
  async function createRecord(c, accountDO) {
3478
- const { repo, collection, rkey, record } = await c.req.json();
3604
+ const { repo, collection, rkey, record, validate } = await c.req.json();
3479
3605
  if (!repo || !collection || !record) return c.json({
3480
3606
  error: "InvalidRequest",
3481
3607
  message: "Missing required parameters: repo, collection, record"
@@ -3489,17 +3615,33 @@ async function createRecord(c, accountDO) {
3489
3615
  action: "create"
3490
3616
  }));
3491
3617
  if (scopeError) return scopeError;
3618
+ const validateChecked = checkValidateFlag(c, validate);
3619
+ if (validateChecked instanceof Response) return validateChecked;
3620
+ if (rkey !== void 0 && typeof rkey !== "string") return c.json({
3621
+ error: "InvalidRequest",
3622
+ message: "rkey must be a string"
3623
+ }, 400);
3624
+ const candidateRkey = rkey ?? now();
3625
+ let validated;
3492
3626
  try {
3493
- validator.validateRecord(collection, record);
3627
+ validated = validator.validate({
3628
+ collection,
3629
+ record,
3630
+ rkey: candidateRkey,
3631
+ validate: validateChecked
3632
+ });
3494
3633
  } catch (err) {
3495
- return invalidRecordError(c, err);
3634
+ if (err instanceof InvalidRecordError) return invalidRecordError(c, err);
3635
+ throw err;
3496
3636
  }
3497
3637
  try {
3498
- const result = await accountDO.rpcCreateRecord(collection, rkey, record);
3638
+ const result = await accountDO.rpcCreateRecord(collection, rkey, validated.record, validated.status);
3499
3639
  return c.json(result);
3500
3640
  } catch (err) {
3501
3641
  const deactivatedError = checkAccountDeactivatedError(c, err);
3502
3642
  if (deactivatedError) return deactivatedError;
3643
+ const conflictError = checkRecordAlreadyExistsError(c, err);
3644
+ if (conflictError) return conflictError;
3503
3645
  throw err;
3504
3646
  }
3505
3647
  }
@@ -3532,7 +3674,7 @@ async function deleteRecord(c, accountDO) {
3532
3674
  }
3533
3675
  }
3534
3676
  async function putRecord(c, accountDO) {
3535
- const { repo, collection, rkey, record } = await c.req.json();
3677
+ const { repo, collection, rkey, record, validate } = await c.req.json();
3536
3678
  if (!repo || !collection || !rkey || !record) return c.json({
3537
3679
  error: "InvalidRequest",
3538
3680
  message: "Missing required parameters: repo, collection, rkey, record"
@@ -3546,25 +3688,33 @@ async function putRecord(c, accountDO) {
3546
3688
  action: "update"
3547
3689
  }));
3548
3690
  if (scopeError) return scopeError;
3691
+ const validateChecked = checkValidateFlag(c, validate);
3692
+ if (validateChecked instanceof Response) return validateChecked;
3693
+ let validated;
3549
3694
  try {
3550
- validator.validateRecord(collection, record);
3695
+ validated = validator.validate({
3696
+ collection,
3697
+ record,
3698
+ rkey,
3699
+ validate: validateChecked
3700
+ });
3551
3701
  } catch (err) {
3552
- return invalidRecordError(c, err);
3702
+ if (err instanceof InvalidRecordError) return invalidRecordError(c, err);
3703
+ throw err;
3553
3704
  }
3554
3705
  try {
3555
- const result = await accountDO.rpcPutRecord(collection, rkey, record);
3706
+ const result = await accountDO.rpcPutRecord(collection, rkey, validated.record, validated.status);
3556
3707
  return c.json(result);
3557
3708
  } catch (err) {
3558
3709
  const deactivatedError = checkAccountDeactivatedError(c, err);
3559
3710
  if (deactivatedError) return deactivatedError;
3560
- return c.json({
3561
- error: "InvalidRequest",
3562
- message: err instanceof Error ? err.message : String(err)
3563
- }, 400);
3711
+ const conflictError = checkRecordAlreadyExistsError(c, err);
3712
+ if (conflictError) return conflictError;
3713
+ throw err;
3564
3714
  }
3565
3715
  }
3566
3716
  async function applyWrites(c, accountDO) {
3567
- const { repo, writes } = await c.req.json();
3717
+ const { repo, writes, validate } = await c.req.json();
3568
3718
  if (!repo || !writes || !Array.isArray(writes)) return c.json({
3569
3719
  error: "InvalidRequest",
3570
3720
  message: "Missing required parameters: repo, writes"
@@ -3577,7 +3727,11 @@ async function applyWrites(c, accountDO) {
3577
3727
  error: "InvalidRequest",
3578
3728
  message: "Too many writes. Max: 200"
3579
3729
  }, 400);
3730
+ const validateChecked = checkValidateFlag(c, validate);
3731
+ if (validateChecked instanceof Response) return validateChecked;
3580
3732
  const checkScope = buildScopeChecker(c);
3733
+ const preparedWrites = [];
3734
+ const seenRkeys = /* @__PURE__ */ new Set();
3581
3735
  for (let i = 0; i < writes.length; i++) {
3582
3736
  const write = writes[i];
3583
3737
  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;
@@ -3592,22 +3746,62 @@ async function applyWrites(c, accountDO) {
3592
3746
  }));
3593
3747
  if (scopeError) return scopeError;
3594
3748
  }
3595
- if (action !== "delete") try {
3596
- validator.validateRecord(write.collection, write.value);
3749
+ if (action === "delete" || action === "update") {
3750
+ if (typeof write.rkey !== "string" || write.rkey.length === 0) return c.json({
3751
+ error: "InvalidRequest",
3752
+ message: `Write ${i}: ${action} requires rkey`
3753
+ }, 400);
3754
+ } else if (write.rkey !== void 0) {
3755
+ if (typeof write.rkey !== "string" || write.rkey.length === 0) return c.json({
3756
+ error: "InvalidRequest",
3757
+ message: `Write ${i}: rkey must be a non-empty string`
3758
+ }, 400);
3759
+ }
3760
+ if (typeof write.rkey === "string") {
3761
+ const composite = `${write.collection}/${write.rkey}`;
3762
+ if (seenRkeys.has(composite)) return c.json({
3763
+ error: "InvalidRequest",
3764
+ message: `Write ${i}: duplicate rkey in batch (${composite})`
3765
+ }, 400);
3766
+ seenRkeys.add(composite);
3767
+ }
3768
+ if (action === "delete") {
3769
+ preparedWrites.push({
3770
+ $type: write.$type,
3771
+ collection: write.collection,
3772
+ rkey: write.rkey
3773
+ });
3774
+ continue;
3775
+ }
3776
+ const candidateRkey = write.rkey ?? now();
3777
+ try {
3778
+ const validated = validator.validate({
3779
+ collection: write.collection,
3780
+ record: write.value,
3781
+ rkey: candidateRkey,
3782
+ validate: validateChecked
3783
+ });
3784
+ preparedWrites.push({
3785
+ $type: write.$type,
3786
+ collection: write.collection,
3787
+ rkey: write.rkey,
3788
+ value: validated.record,
3789
+ validationStatus: validated.status
3790
+ });
3597
3791
  } catch (err) {
3598
- return invalidRecordError(c, err, `Write ${i}`);
3792
+ if (err instanceof InvalidRecordError) return invalidRecordError(c, err, `Write ${i}`);
3793
+ throw err;
3599
3794
  }
3600
3795
  }
3601
3796
  try {
3602
- const result = await accountDO.rpcApplyWrites(writes);
3797
+ const result = await accountDO.rpcApplyWrites(preparedWrites);
3603
3798
  return c.json(result);
3604
3799
  } catch (err) {
3605
3800
  const deactivatedError = checkAccountDeactivatedError(c, err);
3606
3801
  if (deactivatedError) return deactivatedError;
3607
- return c.json({
3608
- error: "InvalidRequest",
3609
- message: err instanceof Error ? err.message : String(err)
3610
- }, 400);
3802
+ const conflictError = checkRecordAlreadyExistsError(c, err);
3803
+ if (conflictError) return conflictError;
3804
+ throw err;
3611
3805
  }
3612
3806
  }
3613
3807
  async function uploadBlob(c, accountDO) {
@@ -4642,7 +4836,7 @@ function renderDashboard(config) {
4642
4836
 
4643
4837
  //#endregion
4644
4838
  //#region package.json
4645
- var version = "0.14.0";
4839
+ var version = "0.15.1";
4646
4840
 
4647
4841
  //#endregion
4648
4842
  //#region src/index.ts