@getcirrus/pds 0.15.2 → 0.16.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,5 +1,5 @@
1
1
  import { DurableObject, env, waitUntil } from "cloudflare:workers";
2
- import { BlockMap, ReadableBlockstore, Repo, WriteOpAction, blocksToCarFile, getRecords, readCarWithRoot, writeCarStream } from "@atproto/repo";
2
+ import { BlockMap, ReadableBlockstore, Repo, WriteOpAction, blocksToCarFile, cidForRecord, getRecords, readCarWithRoot, writeCarStream } from "@atproto/repo";
3
3
  import { Secp256k1Keypair, randomStr, verifySignature } from "@atproto/crypto";
4
4
  import { CID, asCid, isBlobRef, isLegacyBlobRef } from "@atproto/lex-data";
5
5
  import { now } from "@atcute/tid";
@@ -98,6 +98,19 @@ function decode$1(bytes) {
98
98
  //#endregion
99
99
  //#region src/storage.ts
100
100
  /**
101
+ * Convert SQLite's `datetime('now')` output ("YYYY-MM-DD HH:MM:SS" in UTC) to
102
+ * an RFC 3339 / ISO 8601 string for lexicon-compliant API responses. Returns
103
+ * the input unchanged when it already parses as a date (e.g. ISO strings
104
+ * written by application code).
105
+ */
106
+ function sqliteDatetimeToIso(value) {
107
+ if (value.includes("T")) return value;
108
+ const iso = value.replace(" ", "T") + "Z";
109
+ const date = new Date(iso);
110
+ if (Number.isNaN(date.getTime())) return value;
111
+ return date.toISOString();
112
+ }
113
+ /**
101
114
  * SQLite-backed repository storage for Cloudflare Durable Objects.
102
115
  *
103
116
  * Implements the RepoStorage interface from @atproto/repo, storing blocks
@@ -544,7 +557,7 @@ var SqliteRepoStorage = class extends ReadableBlockstore {
544
557
  listAppPasswords() {
545
558
  return this.sql.exec(`SELECT name, created_at FROM app_passwords ORDER BY created_at DESC`).toArray().map((row) => ({
546
559
  name: row.name,
547
- createdAt: row.created_at
560
+ createdAt: sqliteDatetimeToIso(row.created_at)
548
561
  }));
549
562
  }
550
563
  /**
@@ -913,7 +926,7 @@ var SqliteOAuthStorage = class SqliteOAuthStorage {
913
926
  * Sequencer manages the firehose event log.
914
927
  *
915
928
  * Stores commit events in SQLite and provides methods for:
916
- * - Sequencing new commits
929
+ * - Sequencing new commits, identity, sync, and account events
917
930
  * - Backfilling events from a cursor
918
931
  * - Getting the latest sequence number
919
932
  */
@@ -926,21 +939,29 @@ var Sequencer = class {
926
939
  * Returns the complete sequenced event for broadcasting.
927
940
  */
928
941
  async sequenceCommit(data) {
929
- const carBytes = await blocksToCarFile(data.commit, data.newBlocks);
942
+ const blocksToSend = new BlockMap();
943
+ blocksToSend.addMap(data.newBlocks);
944
+ blocksToSend.addMap(data.relevantBlocks);
945
+ const carBytes = await blocksToCarFile(data.commit, blocksToSend);
930
946
  const time = (/* @__PURE__ */ new Date()).toISOString();
931
947
  const eventPayload = {
932
948
  repo: data.did,
933
949
  commit: data.commit,
934
950
  rev: data.rev,
935
951
  since: data.since,
952
+ prevData: data.prevData,
936
953
  blocks: carBytes,
937
- ops: data.ops.map((op) => ({
938
- action: op.action,
939
- path: `${op.collection}/${op.rkey}`,
940
- cid: "cid" in op && op.cid ? op.cid : null
941
- })),
954
+ ops: data.ops.map((op) => {
955
+ const out = {
956
+ action: op.action,
957
+ path: `${op.collection}/${op.rkey}`,
958
+ cid: "cid" in op && op.cid ? op.cid : null
959
+ };
960
+ if (op.prev) out.prev = op.prev;
961
+ return out;
962
+ }),
942
963
  rebase: false,
943
- tooBig: carBytes.length > 1e6,
964
+ tooBig: false,
944
965
  blobs: [],
945
966
  time
946
967
  };
@@ -959,6 +980,84 @@ var Sequencer = class {
959
980
  };
960
981
  }
961
982
  /**
983
+ * Add an identity event to the firehose.
984
+ * `handle` is optional per sync 1.1; presence does not signal change.
985
+ */
986
+ async sequenceIdentity(input) {
987
+ const time = (/* @__PURE__ */ new Date()).toISOString();
988
+ const eventPayload = {
989
+ did: input.did,
990
+ time,
991
+ ...input.handle ? { handle: input.handle } : {}
992
+ };
993
+ const payload = encode$1(eventPayload);
994
+ const seq = this.sql.exec(`INSERT INTO firehose_events (event_type, payload)
995
+ VALUES ('identity', ?)
996
+ RETURNING seq`, payload).one().seq;
997
+ return {
998
+ seq,
999
+ type: "identity",
1000
+ event: {
1001
+ ...eventPayload,
1002
+ seq
1003
+ },
1004
+ time
1005
+ };
1006
+ }
1007
+ /**
1008
+ * Add a sync event to the firehose.
1009
+ * Used after repo state changes that don't produce a commit diff
1010
+ * (import, rebase, key rotation, account activation).
1011
+ */
1012
+ async sequenceSync(data) {
1013
+ const carBytes = await blocksToCarFile(data.cid, data.blocks);
1014
+ const time = (/* @__PURE__ */ new Date()).toISOString();
1015
+ const eventPayload = {
1016
+ did: data.did,
1017
+ rev: data.rev,
1018
+ blocks: carBytes,
1019
+ time
1020
+ };
1021
+ const payload = encode$1(eventPayload);
1022
+ const seq = this.sql.exec(`INSERT INTO firehose_events (event_type, payload)
1023
+ VALUES ('sync', ?)
1024
+ RETURNING seq`, payload).one().seq;
1025
+ return {
1026
+ seq,
1027
+ type: "sync",
1028
+ event: {
1029
+ ...eventPayload,
1030
+ seq
1031
+ },
1032
+ time
1033
+ };
1034
+ }
1035
+ /**
1036
+ * Add an account status event to the firehose.
1037
+ */
1038
+ async sequenceAccount(input) {
1039
+ const time = (/* @__PURE__ */ new Date()).toISOString();
1040
+ const eventPayload = {
1041
+ did: input.did,
1042
+ active: input.active,
1043
+ time,
1044
+ ...input.status ? { status: input.status } : {}
1045
+ };
1046
+ const payload = encode$1(eventPayload);
1047
+ const seq = this.sql.exec(`INSERT INTO firehose_events (event_type, payload)
1048
+ VALUES ('account', ?)
1049
+ RETURNING seq`, payload).one().seq;
1050
+ return {
1051
+ seq,
1052
+ type: "account",
1053
+ event: {
1054
+ ...eventPayload,
1055
+ seq
1056
+ },
1057
+ time
1058
+ };
1059
+ }
1060
+ /**
962
1061
  * Get events from a cursor position.
963
1062
  * Returns up to `limit` events after the cursor.
964
1063
  * Skips identity events that have empty payloads.
@@ -987,6 +1086,28 @@ var Sequencer = class {
987
1086
  },
988
1087
  time
989
1088
  });
1089
+ } else if (eventType === "sync") {
1090
+ const decoded = decode$1(payload);
1091
+ events.push({
1092
+ seq,
1093
+ type: "sync",
1094
+ event: {
1095
+ ...decoded,
1096
+ seq
1097
+ },
1098
+ time
1099
+ });
1100
+ } else if (eventType === "account") {
1101
+ const decoded = decode$1(payload);
1102
+ events.push({
1103
+ seq,
1104
+ type: "account",
1105
+ event: {
1106
+ ...decoded,
1107
+ seq
1108
+ },
1109
+ time
1110
+ });
990
1111
  } else {
991
1112
  const decoded = decode$1(payload);
992
1113
  events.push({
@@ -1010,6 +1131,15 @@ var Sequencer = class {
1010
1131
  return this.sql.exec("SELECT MAX(seq) as seq FROM firehose_events").one()?.seq ?? 0;
1011
1132
  }
1012
1133
  /**
1134
+ * Get the earliest sequence number still in the log.
1135
+ * Used to detect cursors that fall before the backfill window
1136
+ * (so the firehose can send an OutdatedCursor info frame).
1137
+ */
1138
+ getEarliestSeq() {
1139
+ const seq = this.sql.exec("SELECT MIN(seq) as seq FROM firehose_events").one()?.seq;
1140
+ return typeof seq === "number" ? seq : null;
1141
+ }
1142
+ /**
1013
1143
  * Prune old events to keep the log from growing indefinitely.
1014
1144
  * Keeps the most recent `keepCount` events.
1015
1145
  */
@@ -1166,6 +1296,8 @@ function rejectLegacyBlobRefs(value) {
1166
1296
 
1167
1297
  //#endregion
1168
1298
  //#region src/account-do.ts
1299
+ /** Sync 1.1 spec: at most 200 record operations per commit. */
1300
+ const MAX_OPS_PER_COMMIT = 200;
1169
1301
  /**
1170
1302
  * Account Durable Object - manages a single user's AT Protocol repository.
1171
1303
  *
@@ -1308,6 +1440,21 @@ var AccountDurableObject = class extends DurableObject {
1308
1440
  };
1309
1441
  }
1310
1442
  /**
1443
+ * RPC method: Check whether the repo contains any records in a collection.
1444
+ */
1445
+ async rpcHasRecordsInCollection(collection) {
1446
+ const repo = await this.getRepo();
1447
+ const storage = await this.getStorage();
1448
+ if (!storage.hasCollections() && await storage.getRoot()) {
1449
+ const seen = /* @__PURE__ */ new Set();
1450
+ for await (const record of repo.walkRecords()) if (!seen.has(record.collection)) {
1451
+ seen.add(record.collection);
1452
+ storage.addCollection(record.collection);
1453
+ }
1454
+ }
1455
+ return storage.getCollections().includes(collection);
1456
+ }
1457
+ /**
1311
1458
  * RPC method: Get a single record
1312
1459
  */
1313
1460
  async rpcGetRecord(collection, rkey) {
@@ -1371,34 +1518,31 @@ var AccountDurableObject = class extends DurableObject {
1371
1518
  record: jsonToLex(record)
1372
1519
  };
1373
1520
  const prevRev = repo.commit.rev;
1374
- const updatedRepo = await repo.applyWrites([createOp], keypair);
1521
+ const prevData = repo.commit.data;
1522
+ const commit = await repo.formatCommit([createOp], keypair);
1523
+ const updatedRepo = await repo.applyCommit(commit);
1375
1524
  try {
1376
1525
  const dataKey = `${collection}/${actualRkey}`;
1377
1526
  const recordCid = await updatedRepo.data.get(dataKey);
1378
1527
  if (!recordCid) throw new Error(`Failed to create record: ${collection}/${actualRkey}`);
1379
1528
  this.storage.addCollection(collection);
1380
1529
  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
1530
  const opWithCid = {
1389
1531
  ...createOp,
1390
1532
  cid: recordCid
1391
1533
  };
1392
1534
  const commitData = {
1393
1535
  did: updatedRepo.did,
1394
- commit: updatedRepo.cid,
1395
- rev: updatedRepo.commit.rev,
1536
+ commit: commit.cid,
1537
+ rev: commit.rev,
1396
1538
  since: prevRev,
1397
- newBlocks,
1539
+ prevData,
1540
+ newBlocks: commit.newBlocks,
1541
+ relevantBlocks: commit.relevantBlocks,
1398
1542
  ops: [opWithCid]
1399
1543
  };
1400
1544
  const event = await this.sequencer.sequenceCommit(commitData);
1401
- await this.broadcastCommit(event);
1545
+ await this.broadcastEvent(event);
1402
1546
  }
1403
1547
  this.repo = updatedRepo;
1404
1548
  return {
@@ -1422,33 +1566,35 @@ var AccountDurableObject = class extends DurableObject {
1422
1566
  await this.ensureActive();
1423
1567
  const repo = await this.getRepo();
1424
1568
  const keypair = await this.getKeypair();
1425
- if (!await repo.getRecord(collection, rkey)) return null;
1569
+ const existingCid = await repo.data.get(`${collection}/${rkey}`);
1570
+ if (!existingCid) return null;
1426
1571
  const deleteOp = {
1427
1572
  action: WriteOpAction.Delete,
1428
1573
  collection,
1429
1574
  rkey
1430
1575
  };
1431
1576
  const prevRev = repo.commit.rev;
1432
- const updatedRepo = await repo.applyWrites([deleteOp], keypair);
1577
+ const prevData = repo.commit.data;
1578
+ const commit = await repo.formatCommit([deleteOp], keypair);
1579
+ const updatedRepo = await repo.applyCommit(commit);
1433
1580
  try {
1434
1581
  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
1582
  const commitData = {
1443
1583
  did: updatedRepo.did,
1444
- commit: updatedRepo.cid,
1445
- rev: updatedRepo.commit.rev,
1584
+ commit: commit.cid,
1585
+ rev: commit.rev,
1446
1586
  since: prevRev,
1447
- newBlocks,
1448
- ops: [deleteOp]
1587
+ prevData,
1588
+ newBlocks: commit.newBlocks,
1589
+ relevantBlocks: commit.relevantBlocks,
1590
+ ops: [{
1591
+ ...deleteOp,
1592
+ cid: null,
1593
+ prev: existingCid
1594
+ }]
1449
1595
  };
1450
1596
  const event = await this.sequencer.sequenceCommit(commitData);
1451
- await this.broadcastCommit(event);
1597
+ await this.broadcastEvent(event);
1452
1598
  }
1453
1599
  this.repo = updatedRepo;
1454
1600
  let collectionStillHasRecords = false;
@@ -1474,7 +1620,8 @@ var AccountDurableObject = class extends DurableObject {
1474
1620
  await this.ensureActive();
1475
1621
  const repo = await this.getRepo();
1476
1622
  const keypair = await this.getKeypair();
1477
- const isUpdate = await repo.getRecord(collection, rkey) !== null;
1623
+ const existingCid = await repo.data.get(`${collection}/${rkey}`);
1624
+ const isUpdate = existingCid !== null;
1478
1625
  const normalizedRecord = jsonToLex(record);
1479
1626
  const op = isUpdate ? {
1480
1627
  action: WriteOpAction.Update,
@@ -1488,34 +1635,32 @@ var AccountDurableObject = class extends DurableObject {
1488
1635
  record: normalizedRecord
1489
1636
  };
1490
1637
  const prevRev = repo.commit.rev;
1491
- const updatedRepo = await repo.applyWrites([op], keypair);
1638
+ const prevData = repo.commit.data;
1639
+ const commit = await repo.formatCommit([op], keypair);
1640
+ const updatedRepo = await repo.applyCommit(commit);
1492
1641
  try {
1493
1642
  const dataKey = `${collection}/${rkey}`;
1494
1643
  const recordCid = await updatedRepo.data.get(dataKey);
1495
1644
  if (!recordCid) throw new Error(`Failed to put record: ${collection}/${rkey}`);
1496
1645
  this.storage.addCollection(collection);
1497
1646
  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
1647
  const opWithCid = {
1506
1648
  ...op,
1507
1649
  cid: recordCid
1508
1650
  };
1651
+ if (existingCid) opWithCid.prev = existingCid;
1509
1652
  const commitData = {
1510
1653
  did: updatedRepo.did,
1511
- commit: updatedRepo.cid,
1512
- rev: updatedRepo.commit.rev,
1654
+ commit: commit.cid,
1655
+ rev: commit.rev,
1513
1656
  since: prevRev,
1514
- newBlocks,
1657
+ prevData,
1658
+ newBlocks: commit.newBlocks,
1659
+ relevantBlocks: commit.relevantBlocks,
1515
1660
  ops: [opWithCid]
1516
1661
  };
1517
1662
  const event = await this.sequencer.sequenceCommit(commitData);
1518
- await this.broadcastCommit(event);
1663
+ await this.broadcastEvent(event);
1519
1664
  }
1520
1665
  this.repo = updatedRepo;
1521
1666
  return {
@@ -1537,6 +1682,7 @@ var AccountDurableObject = class extends DurableObject {
1537
1682
  */
1538
1683
  async rpcApplyWrites(writes) {
1539
1684
  await this.ensureActive();
1685
+ if (writes.length > MAX_OPS_PER_COMMIT) throw new Error(`InvalidRequest: applyWrites accepts at most ${MAX_OPS_PER_COMMIT} operations per call, got ${writes.length}`);
1540
1686
  const repo = await this.getRepo();
1541
1687
  const keypair = await this.getKeypair();
1542
1688
  const ops = [];
@@ -1600,8 +1746,23 @@ var AccountDurableObject = class extends DurableObject {
1600
1746
  action: WriteOpAction.Delete
1601
1747
  });
1602
1748
  } else throw new Error(`Unknown write type: ${write.$type}`);
1749
+ const prevCids = /* @__PURE__ */ new Map();
1750
+ for (const op of ops) {
1751
+ if (op.action === WriteOpAction.Create) continue;
1752
+ const key = `${op.collection}/${op.rkey}`;
1753
+ if (prevCids.has(key)) continue;
1754
+ const cid = await repo.data.get(key);
1755
+ if (cid) prevCids.set(key, cid);
1756
+ }
1757
+ const opCids = new Array(ops.length);
1758
+ for (let i = 0; i < ops.length; i++) {
1759
+ const op = ops[i];
1760
+ if (op.action !== WriteOpAction.Delete) opCids[i] = await cidForRecord(op.record);
1761
+ }
1603
1762
  const prevRev = repo.commit.rev;
1604
- const updatedRepo = await repo.applyWrites(ops, keypair);
1763
+ const prevData = repo.commit.data;
1764
+ const commit = await repo.formatCommit(ops, keypair);
1765
+ const updatedRepo = await repo.applyCommit(commit);
1605
1766
  try {
1606
1767
  for (const op of ops) if (op.action !== WriteOpAction.Delete) this.storage.addCollection(op.collection);
1607
1768
  const finalResults = [];
@@ -1609,42 +1770,42 @@ var AccountDurableObject = class extends DurableObject {
1609
1770
  for (let i = 0; i < results.length; i++) {
1610
1771
  const result = results[i];
1611
1772
  const op = ops[i];
1773
+ const prev = prevCids.get(`${op.collection}/${op.rkey}`);
1612
1774
  if (result.action === WriteOpAction.Delete) {
1613
1775
  finalResults.push({ $type: result.$type });
1614
- opsWithCids.push(op);
1776
+ opsWithCids.push({
1777
+ ...op,
1778
+ cid: null,
1779
+ ...prev ? { prev } : {}
1780
+ });
1615
1781
  } else {
1616
- const dataKey = `${result.collection}/${result.rkey}`;
1617
- const recordCid = await updatedRepo.data.get(dataKey);
1782
+ const recordCid = opCids[i];
1618
1783
  finalResults.push({
1619
1784
  $type: result.$type,
1620
1785
  uri: `at://${updatedRepo.did}/${result.collection}/${result.rkey}`,
1621
- cid: recordCid?.toString(),
1786
+ cid: recordCid.toString(),
1622
1787
  ...result.validationStatus !== void 0 ? { validationStatus: result.validationStatus } : {}
1623
1788
  });
1624
1789
  opsWithCids.push({
1625
1790
  ...op,
1626
- cid: recordCid
1791
+ cid: recordCid,
1792
+ ...prev ? { prev } : {}
1627
1793
  });
1628
1794
  }
1629
1795
  }
1630
1796
  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
1797
  const commitData = {
1639
1798
  did: updatedRepo.did,
1640
- commit: updatedRepo.cid,
1641
- rev: updatedRepo.commit.rev,
1799
+ commit: commit.cid,
1800
+ rev: commit.rev,
1642
1801
  since: prevRev,
1643
- newBlocks,
1802
+ prevData,
1803
+ newBlocks: commit.newBlocks,
1804
+ relevantBlocks: commit.relevantBlocks,
1644
1805
  ops: opsWithCids
1645
1806
  };
1646
1807
  const event = await this.sequencer.sequenceCommit(commitData);
1647
- await this.broadcastCommit(event);
1808
+ await this.broadcastEvent(event);
1648
1809
  }
1649
1810
  this.repo = updatedRepo;
1650
1811
  const deletedCollections = /* @__PURE__ */ new Set();
@@ -1822,29 +1983,14 @@ var AccountDurableObject = class extends DurableObject {
1822
1983
  return frame;
1823
1984
  }
1824
1985
  /**
1825
- * Encode a commit event frame.
1826
- */
1827
- encodeCommitFrame(event) {
1828
- return this.encodeFrame({
1829
- op: 1,
1830
- t: "#commit"
1831
- }, event.event);
1832
- }
1833
- /**
1834
- * Encode an identity event frame.
1835
- */
1836
- encodeIdentityFrame(event) {
1837
- return this.encodeFrame({
1838
- op: 1,
1839
- t: "#identity"
1840
- }, event.event);
1841
- }
1842
- /**
1843
1986
  * Encode any event frame based on its type.
1844
1987
  */
1845
1988
  encodeEventFrame(event) {
1846
- if (event.type === "identity") return this.encodeIdentityFrame(event);
1847
- return this.encodeCommitFrame(event);
1989
+ const header = {
1990
+ op: 1,
1991
+ t: `#${event.type}`
1992
+ };
1993
+ return this.encodeFrame(header, event.event);
1848
1994
  }
1849
1995
  /**
1850
1996
  * Encode an error frame.
@@ -1858,6 +2004,21 @@ var AccountDurableObject = class extends DurableObject {
1858
2004
  return this.encodeFrame(header, body);
1859
2005
  }
1860
2006
  /**
2007
+ * Encode an #info message (op:1, t:'#info'). Used for non-fatal
2008
+ * conditions like OutdatedCursor where the stream continues.
2009
+ */
2010
+ encodeInfoFrame(name, message) {
2011
+ const header = {
2012
+ op: 1,
2013
+ t: "#info"
2014
+ };
2015
+ const body = {
2016
+ name,
2017
+ message
2018
+ };
2019
+ return this.encodeFrame(header, body);
2020
+ }
2021
+ /**
1861
2022
  * Backfill firehose events from a cursor.
1862
2023
  */
1863
2024
  async backfillFirehose(ws, cursor) {
@@ -1868,7 +2029,14 @@ var AccountDurableObject = class extends DurableObject {
1868
2029
  ws.close(1008, "FutureCursor");
1869
2030
  return;
1870
2031
  }
1871
- const events = await this.sequencer.getEventsSince(cursor, 1e3);
2032
+ const earliestSeq = this.sequencer.getEarliestSeq();
2033
+ let effectiveCursor = cursor;
2034
+ if (earliestSeq !== null && cursor < earliestSeq - 1) {
2035
+ const info = this.encodeInfoFrame("OutdatedCursor", "Requested cursor exceeded retention window; some events skipped");
2036
+ ws.send(info);
2037
+ effectiveCursor = earliestSeq - 1;
2038
+ }
2039
+ const events = await this.sequencer.getEventsSince(effectiveCursor, 1e3);
1872
2040
  for (const event of events) {
1873
2041
  const frame = this.encodeEventFrame(event);
1874
2042
  ws.send(frame);
@@ -1883,9 +2051,9 @@ var AccountDurableObject = class extends DurableObject {
1883
2051
  }
1884
2052
  }
1885
2053
  /**
1886
- * Broadcast a commit event to all connected firehose clients.
2054
+ * Broadcast a sequenced event to all connected firehose clients.
1887
2055
  */
1888
- async broadcastCommit(event) {
2056
+ async broadcastEvent(event) {
1889
2057
  const frame = this.encodeEventFrame(event);
1890
2058
  for (const ws of this.ctx.getWebSockets()) try {
1891
2059
  ws.send(frame);
@@ -1963,16 +2131,55 @@ var AccountDurableObject = class extends DurableObject {
1963
2131
  return (await this.getStorage()).getActive();
1964
2132
  }
1965
2133
  /**
1966
- * RPC method: Activate account
2134
+ * RPC method: Activate account.
2135
+ * Emits #account + #identity + #sync per sync 1.1, so relays pick up
2136
+ * the new state without polling. #sync is only emitted when a repo
2137
+ * root exists (i.e. after migration import or initial commit).
1967
2138
  */
1968
2139
  async rpcActivateAccount() {
1969
- await (await this.getStorage()).setActive(true);
2140
+ const storage = await this.getStorage();
2141
+ const wasActive = await storage.getActive();
2142
+ await storage.setActive(true);
2143
+ if (wasActive || !this.sequencer) return;
2144
+ const account = await this.sequencer.sequenceAccount({
2145
+ did: this.env.DID,
2146
+ active: true
2147
+ });
2148
+ await this.broadcastEvent(account);
2149
+ const identity = await this.sequencer.sequenceIdentity({ did: this.env.DID });
2150
+ await this.broadcastEvent(identity);
2151
+ const root = await storage.getRoot();
2152
+ if (root) {
2153
+ const commitBytes = await storage.getBytes(root);
2154
+ if (commitBytes) {
2155
+ const repo = await this.getRepo();
2156
+ const blocks = new BlockMap();
2157
+ blocks.set(root, commitBytes);
2158
+ const sync = await this.sequencer.sequenceSync({
2159
+ did: this.env.DID,
2160
+ rev: repo.commit.rev,
2161
+ cid: root,
2162
+ blocks
2163
+ });
2164
+ await this.broadcastEvent(sync);
2165
+ }
2166
+ }
1970
2167
  }
1971
2168
  /**
1972
- * RPC method: Deactivate account
2169
+ * RPC method: Deactivate account.
2170
+ * Emits #account(active=false, status='deactivated') per sync 1.1.
1973
2171
  */
1974
2172
  async rpcDeactivateAccount() {
1975
- await (await this.getStorage()).setActive(false);
2173
+ const storage = await this.getStorage();
2174
+ const wasActive = await storage.getActive();
2175
+ await storage.setActive(false);
2176
+ if (!wasActive || !this.sequencer) return;
2177
+ const account = await this.sequencer.sequenceAccount({
2178
+ did: this.env.DID,
2179
+ active: false,
2180
+ status: "deactivated"
2181
+ });
2182
+ await this.broadcastEvent(account);
1976
2183
  }
1977
2184
  /**
1978
2185
  * RPC method: Count blocks in storage
@@ -2028,34 +2235,16 @@ var AccountDurableObject = class extends DurableObject {
2028
2235
  }
2029
2236
  /**
2030
2237
  * Emit an identity event to notify downstream services to refresh identity cache.
2238
+ * `handle` is optional per sync 1.1.
2031
2239
  */
2032
2240
  async rpcEmitIdentityEvent(handle) {
2033
2241
  await this.ensureStorageInitialized();
2034
- const time = (/* @__PURE__ */ new Date()).toISOString();
2035
- const seq = this.ctx.storage.sql.exec(`INSERT INTO firehose_events (event_type, payload)
2036
- VALUES ('identity', ?)
2037
- RETURNING seq`, new Uint8Array(0)).one().seq;
2038
- const header = {
2039
- op: 1,
2040
- t: "#identity"
2041
- };
2042
- const body = {
2043
- seq,
2242
+ const event = await this.sequencer.sequenceIdentity({
2044
2243
  did: this.env.DID,
2045
- time,
2046
- handle
2047
- };
2048
- const headerBytes = encode$1(header);
2049
- const bodyBytes = encode$1(body);
2050
- const frame = new Uint8Array(headerBytes.length + bodyBytes.length);
2051
- frame.set(headerBytes, 0);
2052
- frame.set(bodyBytes, headerBytes.length);
2053
- for (const ws of this.ctx.getWebSockets()) try {
2054
- ws.send(frame);
2055
- } catch (e) {
2056
- console.error("Error broadcasting identity event:", e);
2057
- }
2058
- return { seq };
2244
+ ...handle ? { handle } : {}
2245
+ });
2246
+ await this.broadcastEvent(event);
2247
+ return { seq: event.seq };
2059
2248
  }
2060
2249
  /**
2061
2250
  * RPC method: Health check - verifies storage is accessible
@@ -2782,6 +2971,9 @@ function createOAuthApp(accountDOGetter) {
2782
2971
  oauth.get("/.well-known/oauth-authorization-server", (c) => {
2783
2972
  return getProvider(c.env).handleMetadata();
2784
2973
  });
2974
+ oauth.get("/oauth/jwks", (c) => {
2975
+ return getProvider(c.env).handleJwks();
2976
+ });
2785
2977
  oauth.get("/.well-known/oauth-protected-resource", (c) => {
2786
2978
  const issuer = `https://${c.env.PDS_HOSTNAME}`;
2787
2979
  return c.json({
@@ -3321,6 +3513,43 @@ async function listRepos(c, accountDO) {
3321
3513
  active: true
3322
3514
  }] });
3323
3515
  }
3516
+ async function listReposByCollection(c, accountDO) {
3517
+ const collection = c.req.query("collection");
3518
+ if (!collection) return c.json({
3519
+ error: "InvalidRequest",
3520
+ message: "Missing required parameter: collection"
3521
+ }, 400);
3522
+ if (!isNsid(collection)) return c.json({
3523
+ error: "InvalidRequest",
3524
+ message: "Invalid collection format (must be NSID)"
3525
+ }, 400);
3526
+ const hasRecords = await accountDO.rpcHasRecordsInCollection(collection);
3527
+ return c.json({ repos: hasRecords ? [{ did: c.env.DID }] : [] });
3528
+ }
3529
+ async function getLatestCommit(c, accountDO) {
3530
+ const did = c.req.query("did");
3531
+ if (!did) return c.json({
3532
+ error: "InvalidRequest",
3533
+ message: "Missing required parameter: did"
3534
+ }, 400);
3535
+ if (!isDid(did)) return c.json({
3536
+ error: "InvalidRequest",
3537
+ message: "Invalid DID format"
3538
+ }, 400);
3539
+ if (did !== c.env.DID) return c.json({
3540
+ error: "RepoNotFound",
3541
+ message: `Repository not found for DID: ${did}`
3542
+ }, 404);
3543
+ const [data, active] = await Promise.all([accountDO.rpcGetRepoStatus(), accountDO.rpcGetActive()]);
3544
+ if (!active) return c.json({
3545
+ error: "RepoDeactivated",
3546
+ message: "Repository has been deactivated"
3547
+ }, 400);
3548
+ return c.json({
3549
+ cid: data.head,
3550
+ rev: data.rev
3551
+ });
3552
+ }
3324
3553
  async function listBlobs(c, _accountDO) {
3325
3554
  const did = c.req.query("did");
3326
3555
  if (!did) return c.json({
@@ -3734,7 +3963,6 @@ async function applyWrites(c, accountDO) {
3734
3963
  if (validateChecked instanceof Response) return validateChecked;
3735
3964
  const checkScope = buildScopeChecker(c);
3736
3965
  const preparedWrites = [];
3737
- const seenRkeys = /* @__PURE__ */ new Set();
3738
3966
  for (let i = 0; i < writes.length; i++) {
3739
3967
  const write = writes[i];
3740
3968
  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;
@@ -3760,14 +3988,6 @@ async function applyWrites(c, accountDO) {
3760
3988
  message: `Write ${i}: rkey must be a non-empty string`
3761
3989
  }, 400);
3762
3990
  }
3763
- if (typeof write.rkey === "string") {
3764
- const composite = `${write.collection}/${write.rkey}`;
3765
- if (seenRkeys.has(composite)) return c.json({
3766
- error: "InvalidRequest",
3767
- message: `Write ${i}: duplicate rkey in batch (${composite})`
3768
- }, 400);
3769
- seenRkeys.add(composite);
3770
- }
3771
3991
  if (action === "delete") {
3772
3992
  preparedWrites.push({
3773
3993
  $type: write.$type,
@@ -3999,13 +4219,11 @@ async function refreshSession(c, accountDO) {
3999
4219
  */
4000
4220
  async function getSession(c, accountDO) {
4001
4221
  const authHeader = c.req.header("Authorization");
4002
- if (!authHeader?.startsWith("Bearer ")) return c.json({
4222
+ if (!authHeader) return c.json({
4003
4223
  error: "AuthenticationRequired",
4004
4224
  message: "Access token required"
4005
4225
  }, 401);
4006
- const token = authHeader.slice(7);
4007
- const serviceDid = `did:web:${c.env.PDS_HOSTNAME}`;
4008
- if (token === c.env.AUTH_TOKEN) {
4226
+ const buildResponse = async () => {
4009
4227
  const { email: storedEmail } = await accountDO.rpcGetEmail();
4010
4228
  const email = storedEmail || c.env.EMAIL;
4011
4229
  return c.json({
@@ -4015,21 +4233,28 @@ async function getSession(c, accountDO) {
4015
4233
  emailConfirmed: true,
4016
4234
  active: true
4017
4235
  });
4236
+ };
4237
+ if (authHeader.startsWith("DPoP ")) {
4238
+ const tokenData = await getProvider(c.env).verifyAccessToken(c.req.raw);
4239
+ if (!tokenData || tokenData.sub !== c.env.DID) return c.json({
4240
+ error: "InvalidToken",
4241
+ message: "Invalid access token"
4242
+ }, 401, { "WWW-Authenticate": "DPoP error=\"invalid_token\", error_description=\"Invalid access token\"" });
4243
+ return buildResponse();
4018
4244
  }
4245
+ if (!authHeader.startsWith("Bearer ")) return c.json({
4246
+ error: "AuthenticationRequired",
4247
+ message: "Access token required"
4248
+ }, 401);
4249
+ const token = authHeader.slice(7);
4250
+ const serviceDid = `did:web:${c.env.PDS_HOSTNAME}`;
4251
+ if (token === c.env.AUTH_TOKEN) return buildResponse();
4019
4252
  try {
4020
4253
  if ((await verifyAccessToken(token, c.env.JWT_SECRET, serviceDid)).sub !== c.env.DID) return c.json({
4021
4254
  error: "AuthenticationRequired",
4022
4255
  message: "Invalid access token"
4023
4256
  }, 401);
4024
- const { email: storedEmail } = await accountDO.rpcGetEmail();
4025
- const email = storedEmail || c.env.EMAIL;
4026
- return c.json({
4027
- handle: c.env.HANDLE,
4028
- did: c.env.DID,
4029
- ...email ? { email } : {},
4030
- emailConfirmed: true,
4031
- active: true
4032
- });
4257
+ return buildResponse();
4033
4258
  } catch (err) {
4034
4259
  if (err instanceof TokenExpiredError) return c.json({
4035
4260
  error: "ExpiredToken",
@@ -4218,6 +4443,16 @@ async function listAppPasswords(c, accountDO) {
4218
4443
  })) });
4219
4444
  }
4220
4445
  /**
4446
+ * List invite codes for the account.
4447
+ * com.atproto.server.getAccountInviteCodes
4448
+ *
4449
+ * Cirrus is single-user with `inviteCodeRequired: false` in describeServer,
4450
+ * so there are no invite codes to list.
4451
+ */
4452
+ async function getAccountInviteCodes(c) {
4453
+ return c.json({ codes: [] });
4454
+ }
4455
+ /**
4221
4456
  * Revoke an app password by name.
4222
4457
  * com.atproto.server.revokeAppPassword
4223
4458
  */
@@ -4317,6 +4552,92 @@ async function validateMigrationToken(token, expectedDid, jwtSecret) {
4317
4552
  //#region src/xrpc/identity.ts
4318
4553
  const PLC_DIRECTORY = "https://plc.directory";
4319
4554
  /**
4555
+ * Build the DID document for the local account.
4556
+ *
4557
+ * Shared between /.well-known/did.json and the
4558
+ * com.atproto.identity.resolveDid / resolveIdentity endpoints.
4559
+ */
4560
+ function buildDidDocument(env$2) {
4561
+ return {
4562
+ "@context": [
4563
+ "https://www.w3.org/ns/did/v1",
4564
+ "https://w3id.org/security/multikey/v1",
4565
+ "https://w3id.org/security/suites/secp256k1-2019/v1"
4566
+ ],
4567
+ id: env$2.DID,
4568
+ alsoKnownAs: [`at://${env$2.HANDLE}`],
4569
+ verificationMethod: [{
4570
+ id: `${env$2.DID}#atproto`,
4571
+ type: "Multikey",
4572
+ controller: env$2.DID,
4573
+ publicKeyMultibase: env$2.SIGNING_KEY_PUBLIC
4574
+ }],
4575
+ service: [{
4576
+ id: "#atproto_pds",
4577
+ type: "AtprotoPersonalDataServer",
4578
+ serviceEndpoint: `https://${env$2.PDS_HOSTNAME}`
4579
+ }]
4580
+ };
4581
+ }
4582
+ /**
4583
+ * Resolve a DID to its DID document.
4584
+ *
4585
+ * For our local DID we serve the document directly. Any other DID is
4586
+ * passed through to the next handler (the AppView proxy).
4587
+ *
4588
+ * Endpoint: GET com.atproto.identity.resolveDid
4589
+ */
4590
+ async function resolveDid(c, next) {
4591
+ const did = c.req.query("did");
4592
+ if (!did) return c.json({
4593
+ error: "InvalidRequest",
4594
+ message: "Missing required parameter: did"
4595
+ }, 400);
4596
+ if (did === c.env.DID) return c.json({ didDoc: buildDidDocument(c.env) });
4597
+ await next();
4598
+ }
4599
+ /**
4600
+ * Resolve an identifier (handle or DID) to its full identity.
4601
+ *
4602
+ * For our local handle or DID we serve the response directly. Anything
4603
+ * else falls through to the AppView proxy.
4604
+ *
4605
+ * Endpoint: GET com.atproto.identity.resolveIdentity
4606
+ */
4607
+ async function resolveIdentity(c, next) {
4608
+ const identifier = c.req.query("identifier");
4609
+ if (!identifier) return c.json({
4610
+ error: "InvalidRequest",
4611
+ message: "Missing required parameter: identifier"
4612
+ }, 400);
4613
+ if (identifier === c.env.DID || identifier === c.env.HANDLE) return c.json({
4614
+ did: c.env.DID,
4615
+ handle: c.env.HANDLE,
4616
+ didDoc: buildDidDocument(c.env)
4617
+ });
4618
+ await next();
4619
+ }
4620
+ /**
4621
+ * Return recommended PLC credentials for the current account.
4622
+ *
4623
+ * Used by other PDSes during an inbound migration to discover the
4624
+ * keys / services they should attach to a new PLC operation.
4625
+ *
4626
+ * Endpoint: GET com.atproto.identity.getRecommendedDidCredentials
4627
+ */
4628
+ async function getRecommendedDidCredentials(c) {
4629
+ const signingKey = (await Secp256k1Keypair.import(c.env.SIGNING_KEY)).did();
4630
+ return c.json({
4631
+ rotationKeys: [signingKey],
4632
+ alsoKnownAs: [`at://${c.env.HANDLE}`],
4633
+ verificationMethods: { atproto: signingKey },
4634
+ services: { atproto_pds: {
4635
+ type: "AtprotoPersonalDataServer",
4636
+ endpoint: `https://${c.env.PDS_HOSTNAME}`
4637
+ } }
4638
+ });
4639
+ }
4640
+ /**
4320
4641
  * Request a PLC operation signature for outbound migration.
4321
4642
  *
4322
4643
  * In Bluesky's implementation, this sends an email with a token.
@@ -4836,7 +5157,7 @@ function renderDashboard(config) {
4836
5157
 
4837
5158
  //#endregion
4838
5159
  //#region package.json
4839
- var version = "0.15.2";
5160
+ var version = "0.16.0";
4840
5161
 
4841
5162
  //#endregion
4842
5163
  //#region src/index.ts
@@ -4888,27 +5209,7 @@ function getAccountDO(env$2) {
4888
5209
  return env$2.ACCOUNT.get(id);
4889
5210
  }
4890
5211
  app.get("/.well-known/did.json", (c) => {
4891
- const didDocument = {
4892
- "@context": [
4893
- "https://www.w3.org/ns/did/v1",
4894
- "https://w3id.org/security/multikey/v1",
4895
- "https://w3id.org/security/suites/secp256k1-2019/v1"
4896
- ],
4897
- id: c.env.DID,
4898
- alsoKnownAs: [`at://${c.env.HANDLE}`],
4899
- verificationMethod: [{
4900
- id: `${c.env.DID}#atproto`,
4901
- type: "Multikey",
4902
- controller: c.env.DID,
4903
- publicKeyMultibase: c.env.SIGNING_KEY_PUBLIC
4904
- }],
4905
- service: [{
4906
- id: "#atproto_pds",
4907
- type: "AtprotoPersonalDataServer",
4908
- serviceEndpoint: `https://${c.env.PDS_HOSTNAME}`
4909
- }]
4910
- };
4911
- return c.json(didDocument);
5212
+ return c.json(buildDidDocument(c.env));
4912
5213
  });
4913
5214
  app.get("/.well-known/atproto-did", (c) => {
4914
5215
  return new Response(c.env.DID, { headers: { "Content-Type": "text/plain" } });
@@ -4976,9 +5277,11 @@ app.get("/status", (c) => {
4976
5277
  });
4977
5278
  app.get("/xrpc/com.atproto.sync.getRepo", (c) => getRepo(c, getAccountDO(c.env)));
4978
5279
  app.get("/xrpc/com.atproto.sync.getRepoStatus", (c) => getRepoStatus(c, getAccountDO(c.env)));
5280
+ app.get("/xrpc/com.atproto.sync.getLatestCommit", (c) => getLatestCommit(c, getAccountDO(c.env)));
4979
5281
  app.get("/xrpc/com.atproto.sync.getBlocks", (c) => getBlocks(c, getAccountDO(c.env)));
4980
5282
  app.get("/xrpc/com.atproto.sync.getBlob", (c) => getBlob(c, getAccountDO(c.env)));
4981
5283
  app.get("/xrpc/com.atproto.sync.listRepos", (c) => listRepos(c, getAccountDO(c.env)));
5284
+ app.get("/xrpc/com.atproto.sync.listReposByCollection", (c) => listReposByCollection(c, getAccountDO(c.env)));
4982
5285
  app.get("/xrpc/com.atproto.sync.listBlobs", (c) => listBlobs(c, getAccountDO(c.env)));
4983
5286
  app.get("/xrpc/com.atproto.sync.getRecord", (c) => getRecord$1(c, getAccountDO(c.env)));
4984
5287
  app.get("/xrpc/com.atproto.sync.subscribeRepos", async (c) => {
@@ -5011,10 +5314,14 @@ app.post("/xrpc/com.atproto.repo.putRecord", requireAuth, (c) => putRecord(c, ge
5011
5314
  app.post("/xrpc/com.atproto.repo.importRepo", requireAuth, (c) => importRepo(c, getAccountDO(c.env)));
5012
5315
  app.get("/xrpc/com.atproto.repo.listMissingBlobs", requireAuth, (c) => listMissingBlobs(c, getAccountDO(c.env)));
5013
5316
  app.get("/xrpc/com.atproto.server.describeServer", describeServer);
5317
+ app.get("/xrpc/com.atproto.server.getAccountInviteCodes", requireAuth, getAccountInviteCodes);
5014
5318
  app.use("/xrpc/com.atproto.identity.resolveHandle", async (c, next) => {
5015
5319
  if (c.req.query("handle") === c.env.HANDLE) return c.json({ did: c.env.DID });
5016
5320
  await next();
5017
5321
  });
5322
+ app.use("/xrpc/com.atproto.identity.resolveDid", resolveDid);
5323
+ app.use("/xrpc/com.atproto.identity.resolveIdentity", resolveIdentity);
5324
+ app.get("/xrpc/com.atproto.identity.getRecommendedDidCredentials", requireAuth, getRecommendedDidCredentials);
5018
5325
  app.post("/xrpc/com.atproto.identity.requestPlcOperationSignature", requireAuth, requestPlcOperationSignature);
5019
5326
  app.post("/xrpc/com.atproto.identity.signPlcOperation", requireAuth, signPlcOperation);
5020
5327
  app.get("/xrpc/gg.mk.experimental.getMigrationToken", requireAuth, getMigrationToken);