@getcirrus/pds 0.14.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
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
  /**
@@ -1053,6 +1054,110 @@ var BlobStore = class {
1053
1054
  }
1054
1055
  };
1055
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
+
1056
1161
  //#endregion
1057
1162
  //#region src/account-do.ts
1058
1163
  /**
@@ -1167,6 +1272,17 @@ var AccountDurableObject = class extends DurableObject {
1167
1272
  this.repo = repo;
1168
1273
  }
1169
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
+ /**
1170
1286
  * RPC method: Get repo metadata for describeRepo
1171
1287
  */
1172
1288
  async rpcDescribeRepo() {
@@ -1230,11 +1346,18 @@ var AccountDurableObject = class extends DurableObject {
1230
1346
  /**
1231
1347
  * RPC method: Create a record
1232
1348
  */
1233
- async rpcCreateRecord(collection, rkey, record) {
1349
+ async rpcCreateRecord(collection, rkey, record, validationStatus) {
1234
1350
  await this.ensureActive();
1235
1351
  const repo = await this.getRepo();
1236
1352
  const keypair = await this.getKeypair();
1237
- 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
+ }
1238
1361
  const createOp = {
1239
1362
  action: WriteOpAction.Create,
1240
1363
  collection,
@@ -1242,42 +1365,49 @@ var AccountDurableObject = class extends DurableObject {
1242
1365
  record: jsonToLex(record)
1243
1366
  };
1244
1367
  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);
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);
1257
1396
  }
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]
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 } : {}
1269
1406
  };
1270
- const event = await this.sequencer.sequenceCommit(commitData);
1271
- await this.broadcastCommit(event);
1407
+ } catch (err) {
1408
+ this.invalidateRepoCache();
1409
+ throw err;
1272
1410
  }
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
1411
  }
1282
1412
  /**
1283
1413
  * RPC method: Delete a record
@@ -1294,35 +1424,40 @@ var AccountDurableObject = class extends DurableObject {
1294
1424
  };
1295
1425
  const prevRev = repo.commit.rev;
1296
1426
  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);
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);
1305
1446
  }
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);
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;
1316
1455
  }
1317
- return { commit: {
1318
- cid: updatedRepo.cid.toString(),
1319
- rev: updatedRepo.commit.rev
1320
- } };
1321
1456
  }
1322
1457
  /**
1323
1458
  * RPC method: Put a record (create or update)
1324
1459
  */
1325
- async rpcPutRecord(collection, rkey, record) {
1460
+ async rpcPutRecord(collection, rkey, record, validationStatus) {
1326
1461
  await this.ensureActive();
1327
1462
  const repo = await this.getRepo();
1328
1463
  const keypair = await this.getKeypair();
@@ -1340,43 +1475,49 @@ var AccountDurableObject = class extends DurableObject {
1340
1475
  record: normalizedRecord
1341
1476
  };
1342
1477
  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);
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);
1355
1506
  }
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]
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 } : {}
1367
1516
  };
1368
- const event = await this.sequencer.sequenceCommit(commitData);
1369
- await this.broadcastCommit(event);
1517
+ } catch (err) {
1518
+ this.invalidateRepoCache();
1519
+ throw err;
1370
1520
  }
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
1521
  }
1381
1522
  /**
1382
1523
  * RPC method: Apply multiple writes (batch create/update/delete)
@@ -1387,8 +1528,20 @@ var AccountDurableObject = class extends DurableObject {
1387
1528
  const keypair = await this.getKeypair();
1388
1529
  const ops = [];
1389
1530
  const results = [];
1531
+ const reservedRkeys = /* @__PURE__ */ new Set();
1390
1532
  for (const write of writes) if (write.$type === "com.atproto.repo.applyWrites#create") {
1391
- 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}`);
1392
1545
  const op = {
1393
1546
  action: WriteOpAction.Create,
1394
1547
  collection: write.collection,
@@ -1400,7 +1553,8 @@ var AccountDurableObject = class extends DurableObject {
1400
1553
  $type: "com.atproto.repo.applyWrites#createResult",
1401
1554
  collection: write.collection,
1402
1555
  rkey,
1403
- action: WriteOpAction.Create
1556
+ action: WriteOpAction.Create,
1557
+ validationStatus: write.validationStatus
1404
1558
  });
1405
1559
  } else if (write.$type === "com.atproto.repo.applyWrites#update") {
1406
1560
  if (!write.rkey) throw new Error("Update requires rkey");
@@ -1415,7 +1569,8 @@ var AccountDurableObject = class extends DurableObject {
1415
1569
  $type: "com.atproto.repo.applyWrites#updateResult",
1416
1570
  collection: write.collection,
1417
1571
  rkey: write.rkey,
1418
- action: WriteOpAction.Update
1572
+ action: WriteOpAction.Update,
1573
+ validationStatus: write.validationStatus
1419
1574
  });
1420
1575
  } else if (write.$type === "com.atproto.repo.applyWrites#delete") {
1421
1576
  if (!write.rkey) throw new Error("Delete requires rkey");
@@ -1433,57 +1588,63 @@ var AccountDurableObject = class extends DurableObject {
1433
1588
  });
1434
1589
  } else throw new Error(`Unknown write type: ${write.$type}`);
1435
1590
  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
- });
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
+ }
1459
1616
  }
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);
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);
1468
1635
  }
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
1636
+ this.repo = updatedRepo;
1637
+ return {
1638
+ commit: {
1639
+ cid: updatedRepo.cid.toString(),
1640
+ rev: updatedRepo.commit.rev
1641
+ },
1642
+ results: finalResults
1476
1643
  };
1477
- const event = await this.sequencer.sequenceCommit(commitData);
1478
- await this.broadcastCommit(event);
1644
+ } catch (err) {
1645
+ this.invalidateRepoCache();
1646
+ throw err;
1479
1647
  }
1480
- return {
1481
- commit: {
1482
- cid: this.repo.cid.toString(),
1483
- rev: this.repo.commit.rev
1484
- },
1485
- results: finalResults
1486
- };
1487
1648
  }
1488
1649
  /**
1489
1650
  * RPC method: Get repo status
@@ -3287,91 +3448,24 @@ async function getRecord$1(c, accountDO) {
3287
3448
  }
3288
3449
  }
3289
3450
 
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
3451
  //#endregion
3369
3452
  //#region src/xrpc/repo.ts
3370
3453
  function invalidRecordError(c, err, prefix) {
3371
- const message = err instanceof Error ? err.message : String(err);
3372
3454
  return c.json({
3373
3455
  error: "InvalidRecord",
3374
- 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"
3375
3469
  }, 400);
3376
3470
  }
3377
3471
  /**
@@ -3387,6 +3481,14 @@ function checkAccountDeactivatedError(c, err) {
3387
3481
  }, 403);
3388
3482
  return null;
3389
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
+ }
3390
3492
  async function describeRepo(c, accountDO) {
3391
3493
  const repo = c.req.query("repo");
3392
3494
  if (!repo) return c.json({
@@ -3475,7 +3577,7 @@ async function listRecords(c, accountDO) {
3475
3577
  return c.json(result);
3476
3578
  }
3477
3579
  async function createRecord(c, accountDO) {
3478
- const { repo, collection, rkey, record } = await c.req.json();
3580
+ const { repo, collection, rkey, record, validate } = await c.req.json();
3479
3581
  if (!repo || !collection || !record) return c.json({
3480
3582
  error: "InvalidRequest",
3481
3583
  message: "Missing required parameters: repo, collection, record"
@@ -3489,17 +3591,33 @@ async function createRecord(c, accountDO) {
3489
3591
  action: "create"
3490
3592
  }));
3491
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;
3492
3602
  try {
3493
- validator.validateRecord(collection, record);
3603
+ validated = validator.validate({
3604
+ collection,
3605
+ record,
3606
+ rkey: candidateRkey,
3607
+ validate: validateChecked
3608
+ });
3494
3609
  } catch (err) {
3495
- return invalidRecordError(c, err);
3610
+ if (err instanceof InvalidRecordError) return invalidRecordError(c, err);
3611
+ throw err;
3496
3612
  }
3497
3613
  try {
3498
- const result = await accountDO.rpcCreateRecord(collection, rkey, record);
3614
+ const result = await accountDO.rpcCreateRecord(collection, rkey, validated.record, validated.status);
3499
3615
  return c.json(result);
3500
3616
  } catch (err) {
3501
3617
  const deactivatedError = checkAccountDeactivatedError(c, err);
3502
3618
  if (deactivatedError) return deactivatedError;
3619
+ const conflictError = checkRecordAlreadyExistsError(c, err);
3620
+ if (conflictError) return conflictError;
3503
3621
  throw err;
3504
3622
  }
3505
3623
  }
@@ -3532,7 +3650,7 @@ async function deleteRecord(c, accountDO) {
3532
3650
  }
3533
3651
  }
3534
3652
  async function putRecord(c, accountDO) {
3535
- const { repo, collection, rkey, record } = await c.req.json();
3653
+ const { repo, collection, rkey, record, validate } = await c.req.json();
3536
3654
  if (!repo || !collection || !rkey || !record) return c.json({
3537
3655
  error: "InvalidRequest",
3538
3656
  message: "Missing required parameters: repo, collection, rkey, record"
@@ -3546,25 +3664,33 @@ async function putRecord(c, accountDO) {
3546
3664
  action: "update"
3547
3665
  }));
3548
3666
  if (scopeError) return scopeError;
3667
+ const validateChecked = checkValidateFlag(c, validate);
3668
+ if (validateChecked instanceof Response) return validateChecked;
3669
+ let validated;
3549
3670
  try {
3550
- validator.validateRecord(collection, record);
3671
+ validated = validator.validate({
3672
+ collection,
3673
+ record,
3674
+ rkey,
3675
+ validate: validateChecked
3676
+ });
3551
3677
  } catch (err) {
3552
- return invalidRecordError(c, err);
3678
+ if (err instanceof InvalidRecordError) return invalidRecordError(c, err);
3679
+ throw err;
3553
3680
  }
3554
3681
  try {
3555
- const result = await accountDO.rpcPutRecord(collection, rkey, record);
3682
+ const result = await accountDO.rpcPutRecord(collection, rkey, validated.record, validated.status);
3556
3683
  return c.json(result);
3557
3684
  } catch (err) {
3558
3685
  const deactivatedError = checkAccountDeactivatedError(c, err);
3559
3686
  if (deactivatedError) return deactivatedError;
3560
- return c.json({
3561
- error: "InvalidRequest",
3562
- message: err instanceof Error ? err.message : String(err)
3563
- }, 400);
3687
+ const conflictError = checkRecordAlreadyExistsError(c, err);
3688
+ if (conflictError) return conflictError;
3689
+ throw err;
3564
3690
  }
3565
3691
  }
3566
3692
  async function applyWrites(c, accountDO) {
3567
- const { repo, writes } = await c.req.json();
3693
+ const { repo, writes, validate } = await c.req.json();
3568
3694
  if (!repo || !writes || !Array.isArray(writes)) return c.json({
3569
3695
  error: "InvalidRequest",
3570
3696
  message: "Missing required parameters: repo, writes"
@@ -3577,7 +3703,11 @@ async function applyWrites(c, accountDO) {
3577
3703
  error: "InvalidRequest",
3578
3704
  message: "Too many writes. Max: 200"
3579
3705
  }, 400);
3706
+ const validateChecked = checkValidateFlag(c, validate);
3707
+ if (validateChecked instanceof Response) return validateChecked;
3580
3708
  const checkScope = buildScopeChecker(c);
3709
+ const preparedWrites = [];
3710
+ const seenRkeys = /* @__PURE__ */ new Set();
3581
3711
  for (let i = 0; i < writes.length; i++) {
3582
3712
  const write = writes[i];
3583
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;
@@ -3592,22 +3722,62 @@ async function applyWrites(c, accountDO) {
3592
3722
  }));
3593
3723
  if (scopeError) return scopeError;
3594
3724
  }
3595
- if (action !== "delete") try {
3596
- validator.validateRecord(write.collection, write.value);
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
+ });
3597
3767
  } catch (err) {
3598
- return invalidRecordError(c, err, `Write ${i}`);
3768
+ if (err instanceof InvalidRecordError) return invalidRecordError(c, err, `Write ${i}`);
3769
+ throw err;
3599
3770
  }
3600
3771
  }
3601
3772
  try {
3602
- const result = await accountDO.rpcApplyWrites(writes);
3773
+ const result = await accountDO.rpcApplyWrites(preparedWrites);
3603
3774
  return c.json(result);
3604
3775
  } catch (err) {
3605
3776
  const deactivatedError = checkAccountDeactivatedError(c, err);
3606
3777
  if (deactivatedError) return deactivatedError;
3607
- return c.json({
3608
- error: "InvalidRequest",
3609
- message: err instanceof Error ? err.message : String(err)
3610
- }, 400);
3778
+ const conflictError = checkRecordAlreadyExistsError(c, err);
3779
+ if (conflictError) return conflictError;
3780
+ throw err;
3611
3781
  }
3612
3782
  }
3613
3783
  async function uploadBlob(c, accountDO) {
@@ -4642,7 +4812,7 @@ function renderDashboard(config) {
4642
4812
 
4643
4813
  //#endregion
4644
4814
  //#region package.json
4645
- var version = "0.14.0";
4815
+ var version = "0.15.0";
4646
4816
 
4647
4817
  //#endregion
4648
4818
  //#region src/index.ts