@getcirrus/pds 0.15.2 → 0.17.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
  *
@@ -1371,34 +1503,31 @@ var AccountDurableObject = class extends DurableObject {
1371
1503
  record: jsonToLex(record)
1372
1504
  };
1373
1505
  const prevRev = repo.commit.rev;
1374
- const updatedRepo = await repo.applyWrites([createOp], keypair);
1506
+ const prevData = repo.commit.data;
1507
+ const commit = await repo.formatCommit([createOp], keypair);
1508
+ const updatedRepo = await repo.applyCommit(commit);
1375
1509
  try {
1376
1510
  const dataKey = `${collection}/${actualRkey}`;
1377
1511
  const recordCid = await updatedRepo.data.get(dataKey);
1378
1512
  if (!recordCid) throw new Error(`Failed to create record: ${collection}/${actualRkey}`);
1379
1513
  this.storage.addCollection(collection);
1380
1514
  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
1515
  const opWithCid = {
1389
1516
  ...createOp,
1390
1517
  cid: recordCid
1391
1518
  };
1392
1519
  const commitData = {
1393
1520
  did: updatedRepo.did,
1394
- commit: updatedRepo.cid,
1395
- rev: updatedRepo.commit.rev,
1521
+ commit: commit.cid,
1522
+ rev: commit.rev,
1396
1523
  since: prevRev,
1397
- newBlocks,
1524
+ prevData,
1525
+ newBlocks: commit.newBlocks,
1526
+ relevantBlocks: commit.relevantBlocks,
1398
1527
  ops: [opWithCid]
1399
1528
  };
1400
1529
  const event = await this.sequencer.sequenceCommit(commitData);
1401
- await this.broadcastCommit(event);
1530
+ await this.broadcastEvent(event);
1402
1531
  }
1403
1532
  this.repo = updatedRepo;
1404
1533
  return {
@@ -1422,33 +1551,35 @@ var AccountDurableObject = class extends DurableObject {
1422
1551
  await this.ensureActive();
1423
1552
  const repo = await this.getRepo();
1424
1553
  const keypair = await this.getKeypair();
1425
- if (!await repo.getRecord(collection, rkey)) return null;
1554
+ const existingCid = await repo.data.get(`${collection}/${rkey}`);
1555
+ if (!existingCid) return null;
1426
1556
  const deleteOp = {
1427
1557
  action: WriteOpAction.Delete,
1428
1558
  collection,
1429
1559
  rkey
1430
1560
  };
1431
1561
  const prevRev = repo.commit.rev;
1432
- const updatedRepo = await repo.applyWrites([deleteOp], keypair);
1562
+ const prevData = repo.commit.data;
1563
+ const commit = await repo.formatCommit([deleteOp], keypair);
1564
+ const updatedRepo = await repo.applyCommit(commit);
1433
1565
  try {
1434
1566
  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
1567
  const commitData = {
1443
1568
  did: updatedRepo.did,
1444
- commit: updatedRepo.cid,
1445
- rev: updatedRepo.commit.rev,
1569
+ commit: commit.cid,
1570
+ rev: commit.rev,
1446
1571
  since: prevRev,
1447
- newBlocks,
1448
- ops: [deleteOp]
1572
+ prevData,
1573
+ newBlocks: commit.newBlocks,
1574
+ relevantBlocks: commit.relevantBlocks,
1575
+ ops: [{
1576
+ ...deleteOp,
1577
+ cid: null,
1578
+ prev: existingCid
1579
+ }]
1449
1580
  };
1450
1581
  const event = await this.sequencer.sequenceCommit(commitData);
1451
- await this.broadcastCommit(event);
1582
+ await this.broadcastEvent(event);
1452
1583
  }
1453
1584
  this.repo = updatedRepo;
1454
1585
  let collectionStillHasRecords = false;
@@ -1474,7 +1605,8 @@ var AccountDurableObject = class extends DurableObject {
1474
1605
  await this.ensureActive();
1475
1606
  const repo = await this.getRepo();
1476
1607
  const keypair = await this.getKeypair();
1477
- const isUpdate = await repo.getRecord(collection, rkey) !== null;
1608
+ const existingCid = await repo.data.get(`${collection}/${rkey}`);
1609
+ const isUpdate = existingCid !== null;
1478
1610
  const normalizedRecord = jsonToLex(record);
1479
1611
  const op = isUpdate ? {
1480
1612
  action: WriteOpAction.Update,
@@ -1488,34 +1620,32 @@ var AccountDurableObject = class extends DurableObject {
1488
1620
  record: normalizedRecord
1489
1621
  };
1490
1622
  const prevRev = repo.commit.rev;
1491
- const updatedRepo = await repo.applyWrites([op], keypair);
1623
+ const prevData = repo.commit.data;
1624
+ const commit = await repo.formatCommit([op], keypair);
1625
+ const updatedRepo = await repo.applyCommit(commit);
1492
1626
  try {
1493
1627
  const dataKey = `${collection}/${rkey}`;
1494
1628
  const recordCid = await updatedRepo.data.get(dataKey);
1495
1629
  if (!recordCid) throw new Error(`Failed to put record: ${collection}/${rkey}`);
1496
1630
  this.storage.addCollection(collection);
1497
1631
  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
1632
  const opWithCid = {
1506
1633
  ...op,
1507
1634
  cid: recordCid
1508
1635
  };
1636
+ if (existingCid) opWithCid.prev = existingCid;
1509
1637
  const commitData = {
1510
1638
  did: updatedRepo.did,
1511
- commit: updatedRepo.cid,
1512
- rev: updatedRepo.commit.rev,
1639
+ commit: commit.cid,
1640
+ rev: commit.rev,
1513
1641
  since: prevRev,
1514
- newBlocks,
1642
+ prevData,
1643
+ newBlocks: commit.newBlocks,
1644
+ relevantBlocks: commit.relevantBlocks,
1515
1645
  ops: [opWithCid]
1516
1646
  };
1517
1647
  const event = await this.sequencer.sequenceCommit(commitData);
1518
- await this.broadcastCommit(event);
1648
+ await this.broadcastEvent(event);
1519
1649
  }
1520
1650
  this.repo = updatedRepo;
1521
1651
  return {
@@ -1537,6 +1667,7 @@ var AccountDurableObject = class extends DurableObject {
1537
1667
  */
1538
1668
  async rpcApplyWrites(writes) {
1539
1669
  await this.ensureActive();
1670
+ 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
1671
  const repo = await this.getRepo();
1541
1672
  const keypair = await this.getKeypair();
1542
1673
  const ops = [];
@@ -1600,8 +1731,23 @@ var AccountDurableObject = class extends DurableObject {
1600
1731
  action: WriteOpAction.Delete
1601
1732
  });
1602
1733
  } else throw new Error(`Unknown write type: ${write.$type}`);
1734
+ const prevCids = /* @__PURE__ */ new Map();
1735
+ for (const op of ops) {
1736
+ if (op.action === WriteOpAction.Create) continue;
1737
+ const key = `${op.collection}/${op.rkey}`;
1738
+ if (prevCids.has(key)) continue;
1739
+ const cid = await repo.data.get(key);
1740
+ if (cid) prevCids.set(key, cid);
1741
+ }
1742
+ const opCids = new Array(ops.length);
1743
+ for (let i = 0; i < ops.length; i++) {
1744
+ const op = ops[i];
1745
+ if (op.action !== WriteOpAction.Delete) opCids[i] = await cidForRecord(op.record);
1746
+ }
1603
1747
  const prevRev = repo.commit.rev;
1604
- const updatedRepo = await repo.applyWrites(ops, keypair);
1748
+ const prevData = repo.commit.data;
1749
+ const commit = await repo.formatCommit(ops, keypair);
1750
+ const updatedRepo = await repo.applyCommit(commit);
1605
1751
  try {
1606
1752
  for (const op of ops) if (op.action !== WriteOpAction.Delete) this.storage.addCollection(op.collection);
1607
1753
  const finalResults = [];
@@ -1609,42 +1755,42 @@ var AccountDurableObject = class extends DurableObject {
1609
1755
  for (let i = 0; i < results.length; i++) {
1610
1756
  const result = results[i];
1611
1757
  const op = ops[i];
1758
+ const prev = prevCids.get(`${op.collection}/${op.rkey}`);
1612
1759
  if (result.action === WriteOpAction.Delete) {
1613
1760
  finalResults.push({ $type: result.$type });
1614
- opsWithCids.push(op);
1761
+ opsWithCids.push({
1762
+ ...op,
1763
+ cid: null,
1764
+ ...prev ? { prev } : {}
1765
+ });
1615
1766
  } else {
1616
- const dataKey = `${result.collection}/${result.rkey}`;
1617
- const recordCid = await updatedRepo.data.get(dataKey);
1767
+ const recordCid = opCids[i];
1618
1768
  finalResults.push({
1619
1769
  $type: result.$type,
1620
1770
  uri: `at://${updatedRepo.did}/${result.collection}/${result.rkey}`,
1621
- cid: recordCid?.toString(),
1771
+ cid: recordCid.toString(),
1622
1772
  ...result.validationStatus !== void 0 ? { validationStatus: result.validationStatus } : {}
1623
1773
  });
1624
1774
  opsWithCids.push({
1625
1775
  ...op,
1626
- cid: recordCid
1776
+ cid: recordCid,
1777
+ ...prev ? { prev } : {}
1627
1778
  });
1628
1779
  }
1629
1780
  }
1630
1781
  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
1782
  const commitData = {
1639
1783
  did: updatedRepo.did,
1640
- commit: updatedRepo.cid,
1641
- rev: updatedRepo.commit.rev,
1784
+ commit: commit.cid,
1785
+ rev: commit.rev,
1642
1786
  since: prevRev,
1643
- newBlocks,
1787
+ prevData,
1788
+ newBlocks: commit.newBlocks,
1789
+ relevantBlocks: commit.relevantBlocks,
1644
1790
  ops: opsWithCids
1645
1791
  };
1646
1792
  const event = await this.sequencer.sequenceCommit(commitData);
1647
- await this.broadcastCommit(event);
1793
+ await this.broadcastEvent(event);
1648
1794
  }
1649
1795
  this.repo = updatedRepo;
1650
1796
  const deletedCollections = /* @__PURE__ */ new Set();
@@ -1822,29 +1968,14 @@ var AccountDurableObject = class extends DurableObject {
1822
1968
  return frame;
1823
1969
  }
1824
1970
  /**
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
1971
  * Encode any event frame based on its type.
1844
1972
  */
1845
1973
  encodeEventFrame(event) {
1846
- if (event.type === "identity") return this.encodeIdentityFrame(event);
1847
- return this.encodeCommitFrame(event);
1974
+ const header = {
1975
+ op: 1,
1976
+ t: `#${event.type}`
1977
+ };
1978
+ return this.encodeFrame(header, event.event);
1848
1979
  }
1849
1980
  /**
1850
1981
  * Encode an error frame.
@@ -1858,6 +1989,21 @@ var AccountDurableObject = class extends DurableObject {
1858
1989
  return this.encodeFrame(header, body);
1859
1990
  }
1860
1991
  /**
1992
+ * Encode an #info message (op:1, t:'#info'). Used for non-fatal
1993
+ * conditions like OutdatedCursor where the stream continues.
1994
+ */
1995
+ encodeInfoFrame(name, message) {
1996
+ const header = {
1997
+ op: 1,
1998
+ t: "#info"
1999
+ };
2000
+ const body = {
2001
+ name,
2002
+ message
2003
+ };
2004
+ return this.encodeFrame(header, body);
2005
+ }
2006
+ /**
1861
2007
  * Backfill firehose events from a cursor.
1862
2008
  */
1863
2009
  async backfillFirehose(ws, cursor) {
@@ -1868,7 +2014,14 @@ var AccountDurableObject = class extends DurableObject {
1868
2014
  ws.close(1008, "FutureCursor");
1869
2015
  return;
1870
2016
  }
1871
- const events = await this.sequencer.getEventsSince(cursor, 1e3);
2017
+ const earliestSeq = this.sequencer.getEarliestSeq();
2018
+ let effectiveCursor = cursor;
2019
+ if (earliestSeq !== null && cursor < earliestSeq - 1) {
2020
+ const info = this.encodeInfoFrame("OutdatedCursor", "Requested cursor exceeded retention window; some events skipped");
2021
+ ws.send(info);
2022
+ effectiveCursor = earliestSeq - 1;
2023
+ }
2024
+ const events = await this.sequencer.getEventsSince(effectiveCursor, 1e3);
1872
2025
  for (const event of events) {
1873
2026
  const frame = this.encodeEventFrame(event);
1874
2027
  ws.send(frame);
@@ -1883,9 +2036,9 @@ var AccountDurableObject = class extends DurableObject {
1883
2036
  }
1884
2037
  }
1885
2038
  /**
1886
- * Broadcast a commit event to all connected firehose clients.
2039
+ * Broadcast a sequenced event to all connected firehose clients.
1887
2040
  */
1888
- async broadcastCommit(event) {
2041
+ async broadcastEvent(event) {
1889
2042
  const frame = this.encodeEventFrame(event);
1890
2043
  for (const ws of this.ctx.getWebSockets()) try {
1891
2044
  ws.send(frame);
@@ -1963,16 +2116,55 @@ var AccountDurableObject = class extends DurableObject {
1963
2116
  return (await this.getStorage()).getActive();
1964
2117
  }
1965
2118
  /**
1966
- * RPC method: Activate account
2119
+ * RPC method: Activate account.
2120
+ * Emits #account + #identity + #sync per sync 1.1, so relays pick up
2121
+ * the new state without polling. #sync is only emitted when a repo
2122
+ * root exists (i.e. after migration import or initial commit).
1967
2123
  */
1968
2124
  async rpcActivateAccount() {
1969
- await (await this.getStorage()).setActive(true);
2125
+ const storage = await this.getStorage();
2126
+ const wasActive = await storage.getActive();
2127
+ await storage.setActive(true);
2128
+ if (wasActive || !this.sequencer) return;
2129
+ const account = await this.sequencer.sequenceAccount({
2130
+ did: this.env.DID,
2131
+ active: true
2132
+ });
2133
+ await this.broadcastEvent(account);
2134
+ const identity = await this.sequencer.sequenceIdentity({ did: this.env.DID });
2135
+ await this.broadcastEvent(identity);
2136
+ const root = await storage.getRoot();
2137
+ if (root) {
2138
+ const commitBytes = await storage.getBytes(root);
2139
+ if (commitBytes) {
2140
+ const repo = await this.getRepo();
2141
+ const blocks = new BlockMap();
2142
+ blocks.set(root, commitBytes);
2143
+ const sync = await this.sequencer.sequenceSync({
2144
+ did: this.env.DID,
2145
+ rev: repo.commit.rev,
2146
+ cid: root,
2147
+ blocks
2148
+ });
2149
+ await this.broadcastEvent(sync);
2150
+ }
2151
+ }
1970
2152
  }
1971
2153
  /**
1972
- * RPC method: Deactivate account
2154
+ * RPC method: Deactivate account.
2155
+ * Emits #account(active=false, status='deactivated') per sync 1.1.
1973
2156
  */
1974
2157
  async rpcDeactivateAccount() {
1975
- await (await this.getStorage()).setActive(false);
2158
+ const storage = await this.getStorage();
2159
+ const wasActive = await storage.getActive();
2160
+ await storage.setActive(false);
2161
+ if (!wasActive || !this.sequencer) return;
2162
+ const account = await this.sequencer.sequenceAccount({
2163
+ did: this.env.DID,
2164
+ active: false,
2165
+ status: "deactivated"
2166
+ });
2167
+ await this.broadcastEvent(account);
1976
2168
  }
1977
2169
  /**
1978
2170
  * RPC method: Count blocks in storage
@@ -2028,34 +2220,16 @@ var AccountDurableObject = class extends DurableObject {
2028
2220
  }
2029
2221
  /**
2030
2222
  * Emit an identity event to notify downstream services to refresh identity cache.
2223
+ * `handle` is optional per sync 1.1.
2031
2224
  */
2032
2225
  async rpcEmitIdentityEvent(handle) {
2033
2226
  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,
2227
+ const event = await this.sequencer.sequenceIdentity({
2044
2228
  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 };
2229
+ ...handle ? { handle } : {}
2230
+ });
2231
+ await this.broadcastEvent(event);
2232
+ return { seq: event.seq };
2059
2233
  }
2060
2234
  /**
2061
2235
  * RPC method: Health check - verifies storage is accessible
@@ -2782,6 +2956,9 @@ function createOAuthApp(accountDOGetter) {
2782
2956
  oauth.get("/.well-known/oauth-authorization-server", (c) => {
2783
2957
  return getProvider(c.env).handleMetadata();
2784
2958
  });
2959
+ oauth.get("/oauth/jwks", (c) => {
2960
+ return getProvider(c.env).handleJwks();
2961
+ });
2785
2962
  oauth.get("/.well-known/oauth-protected-resource", (c) => {
2786
2963
  const issuer = `https://${c.env.PDS_HOSTNAME}`;
2787
2964
  return c.json({
@@ -3321,6 +3498,30 @@ async function listRepos(c, accountDO) {
3321
3498
  active: true
3322
3499
  }] });
3323
3500
  }
3501
+ async function getLatestCommit(c, accountDO) {
3502
+ const did = c.req.query("did");
3503
+ if (!did) return c.json({
3504
+ error: "InvalidRequest",
3505
+ message: "Missing required parameter: did"
3506
+ }, 400);
3507
+ if (!isDid(did)) return c.json({
3508
+ error: "InvalidRequest",
3509
+ message: "Invalid DID format"
3510
+ }, 400);
3511
+ if (did !== c.env.DID) return c.json({
3512
+ error: "RepoNotFound",
3513
+ message: `Repository not found for DID: ${did}`
3514
+ }, 404);
3515
+ const [data, active] = await Promise.all([accountDO.rpcGetRepoStatus(), accountDO.rpcGetActive()]);
3516
+ if (!active) return c.json({
3517
+ error: "RepoDeactivated",
3518
+ message: "Repository has been deactivated"
3519
+ }, 400);
3520
+ return c.json({
3521
+ cid: data.head,
3522
+ rev: data.rev
3523
+ });
3524
+ }
3324
3525
  async function listBlobs(c, _accountDO) {
3325
3526
  const did = c.req.query("did");
3326
3527
  if (!did) return c.json({
@@ -3569,7 +3770,7 @@ async function getRecord(c, accountDO) {
3569
3770
  if (!result) return c.json({
3570
3771
  error: "RecordNotFound",
3571
3772
  message: `Record not found: ${collection}/${rkey}`
3572
- }, 404);
3773
+ }, 400);
3573
3774
  return c.json({
3574
3775
  uri: `at://${repo}/${collection}/${rkey}`,
3575
3776
  cid: result.cid,
@@ -3665,11 +3866,7 @@ async function deleteRecord(c, accountDO) {
3665
3866
  if (scopeError) return scopeError;
3666
3867
  try {
3667
3868
  const result = await accountDO.rpcDeleteRecord(collection, rkey);
3668
- if (!result) return c.json({
3669
- error: "RecordNotFound",
3670
- message: `Record not found: ${collection}/${rkey}`
3671
- }, 404);
3672
- return c.json(result);
3869
+ return c.json(result ?? {});
3673
3870
  } catch (err) {
3674
3871
  const deactivatedError = checkAccountDeactivatedError(c, err);
3675
3872
  if (deactivatedError) return deactivatedError;
@@ -3734,7 +3931,6 @@ async function applyWrites(c, accountDO) {
3734
3931
  if (validateChecked instanceof Response) return validateChecked;
3735
3932
  const checkScope = buildScopeChecker(c);
3736
3933
  const preparedWrites = [];
3737
- const seenRkeys = /* @__PURE__ */ new Set();
3738
3934
  for (let i = 0; i < writes.length; i++) {
3739
3935
  const write = writes[i];
3740
3936
  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 +3956,6 @@ async function applyWrites(c, accountDO) {
3760
3956
  message: `Write ${i}: rkey must be a non-empty string`
3761
3957
  }, 400);
3762
3958
  }
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
3959
  if (action === "delete") {
3772
3960
  preparedWrites.push({
3773
3961
  $type: write.$type,
@@ -3999,13 +4187,11 @@ async function refreshSession(c, accountDO) {
3999
4187
  */
4000
4188
  async function getSession(c, accountDO) {
4001
4189
  const authHeader = c.req.header("Authorization");
4002
- if (!authHeader?.startsWith("Bearer ")) return c.json({
4190
+ if (!authHeader) return c.json({
4003
4191
  error: "AuthenticationRequired",
4004
4192
  message: "Access token required"
4005
4193
  }, 401);
4006
- const token = authHeader.slice(7);
4007
- const serviceDid = `did:web:${c.env.PDS_HOSTNAME}`;
4008
- if (token === c.env.AUTH_TOKEN) {
4194
+ const buildResponse = async () => {
4009
4195
  const { email: storedEmail } = await accountDO.rpcGetEmail();
4010
4196
  const email = storedEmail || c.env.EMAIL;
4011
4197
  return c.json({
@@ -4015,21 +4201,28 @@ async function getSession(c, accountDO) {
4015
4201
  emailConfirmed: true,
4016
4202
  active: true
4017
4203
  });
4204
+ };
4205
+ if (authHeader.startsWith("DPoP ")) {
4206
+ const tokenData = await getProvider(c.env).verifyAccessToken(c.req.raw);
4207
+ if (!tokenData || tokenData.sub !== c.env.DID) return c.json({
4208
+ error: "InvalidToken",
4209
+ message: "Invalid access token"
4210
+ }, 401, { "WWW-Authenticate": "DPoP error=\"invalid_token\", error_description=\"Invalid access token\"" });
4211
+ return buildResponse();
4018
4212
  }
4213
+ if (!authHeader.startsWith("Bearer ")) return c.json({
4214
+ error: "AuthenticationRequired",
4215
+ message: "Access token required"
4216
+ }, 401);
4217
+ const token = authHeader.slice(7);
4218
+ const serviceDid = `did:web:${c.env.PDS_HOSTNAME}`;
4219
+ if (token === c.env.AUTH_TOKEN) return buildResponse();
4019
4220
  try {
4020
4221
  if ((await verifyAccessToken(token, c.env.JWT_SECRET, serviceDid)).sub !== c.env.DID) return c.json({
4021
4222
  error: "AuthenticationRequired",
4022
4223
  message: "Invalid access token"
4023
4224
  }, 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
- });
4225
+ return buildResponse();
4033
4226
  } catch (err) {
4034
4227
  if (err instanceof TokenExpiredError) return c.json({
4035
4228
  error: "ExpiredToken",
@@ -4218,6 +4411,16 @@ async function listAppPasswords(c, accountDO) {
4218
4411
  })) });
4219
4412
  }
4220
4413
  /**
4414
+ * List invite codes for the account.
4415
+ * com.atproto.server.getAccountInviteCodes
4416
+ *
4417
+ * Cirrus is single-user with `inviteCodeRequired: false` in describeServer,
4418
+ * so there are no invite codes to list.
4419
+ */
4420
+ async function getAccountInviteCodes(c) {
4421
+ return c.json({ codes: [] });
4422
+ }
4423
+ /**
4221
4424
  * Revoke an app password by name.
4222
4425
  * com.atproto.server.revokeAppPassword
4223
4426
  */
@@ -4317,6 +4520,53 @@ async function validateMigrationToken(token, expectedDid, jwtSecret) {
4317
4520
  //#region src/xrpc/identity.ts
4318
4521
  const PLC_DIRECTORY = "https://plc.directory";
4319
4522
  /**
4523
+ * Build the DID document for the local account.
4524
+ *
4525
+ * Served by /.well-known/did.json.
4526
+ */
4527
+ function buildDidDocument(env$2) {
4528
+ return {
4529
+ "@context": [
4530
+ "https://www.w3.org/ns/did/v1",
4531
+ "https://w3id.org/security/multikey/v1",
4532
+ "https://w3id.org/security/suites/secp256k1-2019/v1"
4533
+ ],
4534
+ id: env$2.DID,
4535
+ alsoKnownAs: [`at://${env$2.HANDLE}`],
4536
+ verificationMethod: [{
4537
+ id: `${env$2.DID}#atproto`,
4538
+ type: "Multikey",
4539
+ controller: env$2.DID,
4540
+ publicKeyMultibase: env$2.SIGNING_KEY_PUBLIC
4541
+ }],
4542
+ service: [{
4543
+ id: "#atproto_pds",
4544
+ type: "AtprotoPersonalDataServer",
4545
+ serviceEndpoint: `https://${env$2.PDS_HOSTNAME}`
4546
+ }]
4547
+ };
4548
+ }
4549
+ /**
4550
+ * Return recommended PLC credentials for the current account.
4551
+ *
4552
+ * Used by other PDSes during an inbound migration to discover the
4553
+ * keys / services they should attach to a new PLC operation.
4554
+ *
4555
+ * Endpoint: GET com.atproto.identity.getRecommendedDidCredentials
4556
+ */
4557
+ async function getRecommendedDidCredentials(c) {
4558
+ const signingKey = (await Secp256k1Keypair.import(c.env.SIGNING_KEY)).did();
4559
+ return c.json({
4560
+ rotationKeys: [signingKey],
4561
+ alsoKnownAs: [`at://${c.env.HANDLE}`],
4562
+ verificationMethods: { atproto: signingKey },
4563
+ services: { atproto_pds: {
4564
+ type: "AtprotoPersonalDataServer",
4565
+ endpoint: `https://${c.env.PDS_HOSTNAME}`
4566
+ } }
4567
+ });
4568
+ }
4569
+ /**
4320
4570
  * Request a PLC operation signature for outbound migration.
4321
4571
  *
4322
4572
  * In Bluesky's implementation, this sends an email with a token.
@@ -4836,7 +5086,7 @@ function renderDashboard(config) {
4836
5086
 
4837
5087
  //#endregion
4838
5088
  //#region package.json
4839
- var version = "0.15.2";
5089
+ var version = "0.17.0";
4840
5090
 
4841
5091
  //#endregion
4842
5092
  //#region src/index.ts
@@ -4888,27 +5138,7 @@ function getAccountDO(env$2) {
4888
5138
  return env$2.ACCOUNT.get(id);
4889
5139
  }
4890
5140
  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);
5141
+ return c.json(buildDidDocument(c.env));
4912
5142
  });
4913
5143
  app.get("/.well-known/atproto-did", (c) => {
4914
5144
  return new Response(c.env.DID, { headers: { "Content-Type": "text/plain" } });
@@ -4976,6 +5206,7 @@ app.get("/status", (c) => {
4976
5206
  });
4977
5207
  app.get("/xrpc/com.atproto.sync.getRepo", (c) => getRepo(c, getAccountDO(c.env)));
4978
5208
  app.get("/xrpc/com.atproto.sync.getRepoStatus", (c) => getRepoStatus(c, getAccountDO(c.env)));
5209
+ app.get("/xrpc/com.atproto.sync.getLatestCommit", (c) => getLatestCommit(c, getAccountDO(c.env)));
4979
5210
  app.get("/xrpc/com.atproto.sync.getBlocks", (c) => getBlocks(c, getAccountDO(c.env)));
4980
5211
  app.get("/xrpc/com.atproto.sync.getBlob", (c) => getBlob(c, getAccountDO(c.env)));
4981
5212
  app.get("/xrpc/com.atproto.sync.listRepos", (c) => listRepos(c, getAccountDO(c.env)));
@@ -5011,10 +5242,12 @@ app.post("/xrpc/com.atproto.repo.putRecord", requireAuth, (c) => putRecord(c, ge
5011
5242
  app.post("/xrpc/com.atproto.repo.importRepo", requireAuth, (c) => importRepo(c, getAccountDO(c.env)));
5012
5243
  app.get("/xrpc/com.atproto.repo.listMissingBlobs", requireAuth, (c) => listMissingBlobs(c, getAccountDO(c.env)));
5013
5244
  app.get("/xrpc/com.atproto.server.describeServer", describeServer);
5245
+ app.get("/xrpc/com.atproto.server.getAccountInviteCodes", requireAuth, getAccountInviteCodes);
5014
5246
  app.use("/xrpc/com.atproto.identity.resolveHandle", async (c, next) => {
5015
5247
  if (c.req.query("handle") === c.env.HANDLE) return c.json({ did: c.env.DID });
5016
5248
  await next();
5017
5249
  });
5250
+ app.get("/xrpc/com.atproto.identity.getRecommendedDidCredentials", requireAuth, getRecommendedDidCredentials);
5018
5251
  app.post("/xrpc/com.atproto.identity.requestPlcOperationSignature", requireAuth, requestPlcOperationSignature);
5019
5252
  app.post("/xrpc/com.atproto.identity.signPlcOperation", requireAuth, signPlcOperation);
5020
5253
  app.get("/xrpc/gg.mk.experimental.getMigrationToken", requireAuth, getMigrationToken);