@uuaid/pillar 2.6.0 → 2.7.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.
Files changed (62) hide show
  1. package/HOSTING-LIMITS.md +12 -0
  2. package/README.md +201 -5
  3. package/bin/carrier.mjs +72 -2
  4. package/bin/pillar-ask.mjs +4 -1
  5. package/bin/pillar-blob.mjs +6 -0
  6. package/bin/pillar-directory.mjs +280 -16
  7. package/bin/pillar-escrow.mjs +4 -1
  8. package/bin/pillar-group-v2.mjs +6 -0
  9. package/bin/pillar-notify.mjs +13 -0
  10. package/bin/pillar-responder.mjs +266 -23
  11. package/bin/pillar.mjs +504 -255
  12. package/package.json +17 -25
  13. package/src/cli-help.mjs +23 -0
  14. package/src/group-v2-cli.mjs +1 -1
  15. package/src/identity/trust.mjs +72 -6
  16. package/src/mailbox/mailbox.mjs +308 -12
  17. package/src/net/carrier-server.mjs +34 -2
  18. package/src/net/refusals.mjs +2 -0
  19. package/src/net/seed-registry.mjs +2 -1
  20. package/src/net/transport.mjs +308 -92
  21. package/src/node-check.mjs +29 -8
  22. package/src/notify-events.mjs +148 -0
  23. package/src/notify-log.mjs +124 -0
  24. package/src/notify-runner.mjs +372 -0
  25. package/src/notify-store.mjs +725 -0
  26. package/src/notify.mjs +350 -0
  27. package/src/pillar.mjs +382 -27
  28. package/src/readers.mjs +2 -2
  29. package/src/registry/federation.mjs +3056 -0
  30. package/src/registry/gossip.mjs +294 -0
  31. package/src/registry/heartbeats.mjs +195 -0
  32. package/src/registry/lineage-verifier.mjs +972 -0
  33. package/src/registry/lineage.mjs +984 -0
  34. package/src/registry/listings.mjs +549 -0
  35. package/src/registry/resolve.mjs +376 -0
  36. package/src/registry/stats.mjs +508 -0
  37. package/src/sqlite-loader.mjs +40 -0
  38. package/src/vendor/pillar-core.mjs +22 -0
  39. package/src/vendor/uuaid-soul.mjs +2246 -0
  40. package/src/vnext/a6b-common.mjs +270 -0
  41. package/src/vnext/b1-cli.mjs +970 -0
  42. package/src/vnext/card-cli.mjs +370 -0
  43. package/src/vnext/greeter-operator.mjs +160 -0
  44. package/src/vnext/greeter-suggest.mjs +318 -0
  45. package/src/vnext/greeter.mjs +571 -0
  46. package/src/vnext/homes.mjs +48 -0
  47. package/src/vnext/init-cli.mjs +489 -0
  48. package/src/vnext/intro-cli.mjs +81 -0
  49. package/src/vnext/json-dir-mailbox.mjs +296 -0
  50. package/src/vnext/jsonl-mailbox.mjs +1066 -0
  51. package/src/vnext/knock-answer.mjs +162 -0
  52. package/src/vnext/knock-cli.mjs +520 -0
  53. package/src/vnext/knock-lane.mjs +312 -0
  54. package/src/vnext/knock-responder.mjs +344 -0
  55. package/src/vnext/lineage-cli.mjs +653 -0
  56. package/src/vnext/listing-cli.mjs +323 -0
  57. package/src/vnext/resolve-cli.mjs +86 -0
  58. package/src/vnext/soul-cli.mjs +666 -0
  59. package/src/vnext/verify-cli.mjs +251 -0
  60. package/src/vnext/w4-redirect.mjs +178 -0
  61. package/src/vnext/wave-a.mjs +193 -0
  62. package/src/vnext/witness-cli.mjs +547 -0
@@ -0,0 +1,549 @@
1
+ /**
2
+ * Pillar vNext §3 — Single-registry `pillar-listing/1` store (Wave A).
3
+ *
4
+ * Enforces:
5
+ * - Closed `pillar-listing/1` schema shape (`v`, `lineage`, `uuaid`, `card`, `homes` 1..4 https,
6
+ * `issuedAt`, optional `stamp`, optional `withdrawn`, `sig`).
7
+ * - Withdrawal rule: `withdrawn === true` requires `card.does.length === 0`.
8
+ * - H-1: refuses `issuedAt > now + 5 min` (`future-ts`), records `receivedAt`, refuses
9
+ * `issuedAt <= stored.issuedAt` (`stale-listing`).
10
+ * - W-10 Sybil brake: first listing for a `lineage` requires `stamp` verified against
11
+ * `to = "pillar-listing/1:" + registryUuaid` (`stamp-required` / `stamp-binding` / `stamp-bits` / `stamp-day`)
12
+ * and enforces `<= 600` new lineages/hour/registry (`rate-limited`). Updates need no stamp.
13
+ * - Cryptographic verification of `listing.sig` over `"pillar-listing/1\n" + jcs(without sig)`
14
+ * using `card.publicKey`, `verifyCard` / `verifyArtifact` with stored lineage events when present,
15
+ * and lineage current-key check (`current === listing.uuaid === card.uuaid`).
16
+ * - Wave A liveness status computed from `lastSeen = listing.issuedAt` (`live` < 7d, `quiet` 7-30d,
17
+ * `dead` >= 30d or withdrawn).
18
+ * - Projection of non-withdrawn `live` listings into `directory.json` `agents[]`.
19
+ */
20
+ import { MAX_TOTAL_LINEAGE_BYTES, checkLineageTotalCap, openRegistryDb } from "./federation.mjs";
21
+ import { LINEAGE_LOG_VERSION, verifyLineageFull } from "./lineage-verifier.mjs";
22
+ import {
23
+ CARD_MAX_BYTES,
24
+ DEFAULT_STAMP_BITS,
25
+ LINEAGE_SKEW_MS,
26
+ isKeyDerivedUuaid,
27
+ isStrictEd25519PublicKey,
28
+ jcs,
29
+ verifyCard,
30
+ verifyLineageDoc,
31
+ verifyStamp,
32
+ } from "../vendor/pillar-core.mjs";
33
+ import { UUAID_RE, isPlainObject, isStrictDateTime } from "./lineage.mjs";
34
+
35
+ export const LISTING_VERSION = "pillar-listing/1";
36
+ export const MAX_NEW_LINEAGES_PER_HOUR = 600;
37
+ export const STATUS_LIVE_MS = 7 * 86_400_000;
38
+ export const STATUS_QUIET_MS = 30 * 86_400_000;
39
+ export const TOMBSTONE_RETENTION_MS = 365 * 86_400_000;
40
+ /**
41
+ * Read cost (V1 F2). Pruning re-verifies every listing, so it runs off the
42
+ * request path: at start and every PRUNE_INTERVAL_MS (startTombstonePruning).
43
+ * directory.json is rebuilt when a listing, heartbeat or lineage write
44
+ * happened, or after PROJECTION_MAX_AGE_MS (status is a function of time).
45
+ * A rebuild re-verifies only lineages written since, or not verified within
46
+ * EVAL_MEMO_MAX_AGE_MS; each prune pass re-verifies all of them.
47
+ */
48
+ export const PRUNE_INTERVAL_MS = 10 * 60_000;
49
+ export const PROJECTION_MAX_AGE_MS = 60_000;
50
+ export const EVAL_MEMO_MAX_AGE_MS = PRUNE_INTERVAL_MS;
51
+
52
+ const HEX128_RE = /^[0-9a-f]{128}$/;
53
+ const NONCE_RE = /^[0-9a-f]{1,32}$/;
54
+ const DAY_RE = /^\d{4}-\d{2}-\d{2}$/;
55
+ const STRICT_HTTPS_URI_RE =
56
+ /^https:\/\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})+)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
57
+
58
+ const LISTING_KEYS = new Set([
59
+ "v",
60
+ "lineage",
61
+ "uuaid",
62
+ "card",
63
+ "homes",
64
+ "stamp",
65
+ "issuedAt",
66
+ "sig",
67
+ "withdrawn",
68
+ ]);
69
+ const POW_KEYS = new Set(["type", "bits", "nonce", "day"]);
70
+
71
+ export function isDenseArray(a) {
72
+ if (!Array.isArray(a)) return false; // @rule reg.dense-is-array
73
+ for (let i = 0; i < a.length; i++) {
74
+ if (!Object.hasOwn(a, i)) return false; // @rule reg.dense-no-holes
75
+ }
76
+ return true;
77
+ }
78
+
79
+ export function isStrictHttpsUri(u) {
80
+ if (typeof u !== "string" || !u.startsWith("https://")) return false; // @rule reg.https-uri-prefix
81
+ if (!STRICT_HTTPS_URI_RE.test(u)) return false; // @rule reg.https-uri-rfc3986
82
+ try {
83
+ return new URL(u).protocol === "https:";
84
+ } catch {
85
+ return false;
86
+ }
87
+ }
88
+
89
+ export function isValidPowShape(p) {
90
+ if (!isPlainObject(p)) return false; // @rule reg.pow-plain
91
+ if (!Object.keys(p).every((k) => POW_KEYS.has(k))) return false; // @rule reg.pow-closed
92
+ if (p.type !== "pow") return false; // @rule reg.pow-type
93
+ if (!Number.isInteger(p.bits) || p.bits < 12 || p.bits > 24) return false; // @rule reg.pow-bits
94
+ if (typeof p.nonce !== "string" || !NONCE_RE.test(p.nonce)) return false; // @rule reg.pow-nonce
95
+ if (typeof p.day !== "string" || !DAY_RE.test(p.day) || !isStrictDateTime(`${p.day}T00:00:00Z`)) return false; // @rule reg.pow-day
96
+ return true;
97
+ }
98
+
99
+ function nowIso(now) {
100
+ if (typeof now === "string") return now;
101
+ const ms = typeof now === "number" ? now : Date.now();
102
+ return new Date(ms).toISOString().replace(/\.\d{3}Z$/, "Z");
103
+ }
104
+
105
+ /**
106
+ * Compute Wave A status from `lastSeen` (ISO timestamp) and `withdrawn` flag.
107
+ * withdrawn === true -> "dead"
108
+ * age < 7d -> "live"
109
+ * 7d <= age < 30d -> "quiet"
110
+ * age >= 30d -> "dead"
111
+ */
112
+ export function computeListingStatus(lastSeenIso, { withdrawn = false, tombstoned = false, now } = {}) {
113
+ if (withdrawn === true || tombstoned === true) return "dead"; // @rule reg.status-withdrawn
114
+ const nowMs = Date.parse(nowIso(now));
115
+ const seenMs = Date.parse(lastSeenIso);
116
+ const age = nowMs - seenMs;
117
+ if (age < STATUS_LIVE_MS) return "live"; // @rule reg.status-live
118
+ if (age < STATUS_QUIET_MS) return "quiet"; // @rule reg.status-quiet
119
+ return "dead";
120
+ }
121
+
122
+ export class ListingStore {
123
+ /**
124
+ * @param {object} opts
125
+ * db existing better-sqlite3 Database instance
126
+ * dbPath path to open if `db` is not supplied
127
+ * registryUuaid this registry's UUAID (required for W-10 stamp binding)
128
+ * lineageStore optional LineageStore for verifying lineage current key
129
+ * heartbeatStore optional HeartbeatStore for computing `lastSeen` & status
130
+ * requiredStampBits W-10 stamp difficulty bits (default 18; 12..24)
131
+ * maxNewLineagesPerHour W-10 new lineage admission rate cap (default 600)
132
+ */
133
+ constructor({
134
+ db,
135
+ dbPath = ":memory:",
136
+ registryUuaid,
137
+ lineageStore = null,
138
+ heartbeatStore = null,
139
+ federationStore = null,
140
+ requiredStampBits = DEFAULT_STAMP_BITS,
141
+ maxNewLineagesPerHour = MAX_NEW_LINEAGES_PER_HOUR,
142
+ maxTotalLineageBytes = MAX_TOTAL_LINEAGE_BYTES,
143
+ } = {}) {
144
+ if (typeof registryUuaid !== "string" || !UUAID_RE.test(registryUuaid)) {
145
+ throw new TypeError("ListingStore requires a valid registryUuaid");
146
+ }
147
+ if (!Number.isInteger(requiredStampBits) || requiredStampBits < 12 || requiredStampBits > 24) {
148
+ throw new TypeError("ListingStore: requiredStampBits must be an integer 12..24");
149
+ }
150
+ this._ownsDb = !db;
151
+ this.db = db ?? openRegistryDb(dbPath);
152
+ if (this._ownsDb) this.db.pragma("journal_mode = WAL");
153
+ this.registryUuaid = registryUuaid;
154
+ this.lineageStore = lineageStore;
155
+ this.heartbeatStore = heartbeatStore;
156
+ this.federationStore = federationStore;
157
+ this.requiredStampBits = requiredStampBits;
158
+ this.maxNewLineagesPerHour = maxNewLineagesPerHour;
159
+ this.maxTotalLineageBytes = maxTotalLineageBytes;
160
+ // Counts stored or pruned listings; _projection is the cached directory.json projection.
161
+ this.changes = 0;
162
+ this._projection = null;
163
+
164
+ this.db.exec(`
165
+ create table if not exists listing (
166
+ lineage text primary key,
167
+ uuaid text not null,
168
+ issued_at text not null,
169
+ issued_at_ms integer not null,
170
+ received_at text not null,
171
+ first_seen_ms integer not null,
172
+ withdrawn integer not null default 0,
173
+ listing_json text not null
174
+ );
175
+ create index if not exists idx_listing_uuaid on listing(uuaid);
176
+ create index if not exists idx_listing_first_seen on listing(first_seen_ms);
177
+ `);
178
+ }
179
+
180
+ close() {
181
+ if (this._ownsDb && this.db.open) this.db.close();
182
+ }
183
+
184
+ setHeartbeatStore(heartbeatStore) {
185
+ this.heartbeatStore = heartbeatStore;
186
+ this._projection = null;
187
+ }
188
+
189
+ setFederationStore(federationStore) {
190
+ this.federationStore = federationStore;
191
+ }
192
+
193
+ getByLineage(lineage) {
194
+ const row = this.db.prepare("select * from listing where lineage = ?").get(lineage);
195
+ return row ? { ...row, listing: JSON.parse(row.listing_json) } : null;
196
+ }
197
+
198
+ lookupByUuaidOrLineage(uuaid) {
199
+ const rows = this.db.prepare("select * from listing where lineage = ? or uuaid = ? limit 2").all(uuaid, uuaid);
200
+ if (rows.length > 1) return { ok: false, status: 409, reason: "ambiguous-uuaid" }; // @rule reg.listing-lookup-ambiguous
201
+ if (rows.length === 1) return { ok: true, row: { ...rows[0], listing: JSON.parse(rows[0].listing_json) } };
202
+ return { ok: false, status: 404, reason: "not-found" };
203
+ }
204
+
205
+ hasOtherLineage(uuaid, expectedLineage) {
206
+ const row = this.db
207
+ .prepare("select 1 from listing where (lineage = ? or uuaid = ?) and lineage != ? limit 1")
208
+ .get(uuaid, uuaid, expectedLineage);
209
+ return Boolean(row);
210
+ }
211
+
212
+ findByUuaidOrLineage(uuaid) {
213
+ const r = this.lookupByUuaidOrLineage(uuaid);
214
+ return r.ok ? r.row : null;
215
+ }
216
+
217
+ all() {
218
+ return this.db
219
+ .prepare("select * from listing order by issued_at_ms desc, lineage asc")
220
+ .all()
221
+ .map((row) => ({ ...row, listing: JSON.parse(row.listing_json) }));
222
+ }
223
+
224
+ /**
225
+ * Verify and store a `pillar-listing/1` document.
226
+ */
227
+ putListing(listing, { now, federated = false, peerUuaid = null, originUuaid = null, stampRegistry = null, knownPeerUuaids = [] } = {}) {
228
+ const stampRegCandidate = stampRegistry ?? originUuaid ?? null;
229
+ const nowStr = nowIso(now);
230
+ const nowMs = Date.parse(nowStr);
231
+
232
+ if (!isPlainObject(listing) || !Object.keys(listing).every((k) => LISTING_KEYS.has(k))) return { ok: false, reason: "malformed-artifact" }; // @rule reg.listing-closed
233
+ if (listing.v !== LISTING_VERSION) return { ok: false, reason: "bad-version" }; // @rule reg.listing-version
234
+ if (typeof listing.lineage !== "string" || !UUAID_RE.test(listing.lineage)) return { ok: false, reason: "bad-uuaid" }; // @rule reg.listing-lineage-uuaid
235
+ if (typeof listing.uuaid !== "string" || !UUAID_RE.test(listing.uuaid)) return { ok: false, reason: "bad-uuaid" }; // @rule reg.listing-uuaid
236
+ if (!isDenseArray(listing.homes) || listing.homes.length < 1 || listing.homes.length > 4 || !listing.homes.every(isStrictHttpsUri)) return { ok: false, reason: "bad-homes" }; // @rule reg.listing-homes
237
+ if (!isStrictDateTime(listing.issuedAt)) return { ok: false, reason: "bad-issued-at" }; // @rule reg.listing-issued-at
238
+ if (typeof listing.sig !== "string" || !HEX128_RE.test(listing.sig)) return { ok: false, reason: "bad-signature" }; // @rule reg.listing-sig-format
239
+ if (Object.hasOwn(listing, "withdrawn") && typeof listing.withdrawn !== "boolean") return { ok: false, reason: "malformed-artifact" }; // @rule reg.listing-withdrawn-type
240
+ if (!isPlainObject(listing.card)) return { ok: false, reason: "malformed-artifact" }; // @rule reg.listing-card-object
241
+
242
+ const issuedMs = Date.parse(listing.issuedAt);
243
+ if (issuedMs > nowMs + LINEAGE_SKEW_MS) return { ok: false, reason: "future-ts" }; // @rule reg.listing-future-ts
244
+
245
+ if (listing.withdrawn === true && (!isDenseArray(listing.card.does) || listing.card.does.length !== 0)) return { ok: false, reason: "withdrawn-does-nonempty" }; // @rule reg.listing-withdrawn-does
246
+ if (listing.card.lineage !== listing.lineage) return { ok: false, reason: "card-lineage-mismatch" }; // @rule reg.listing-card-lineage
247
+ if (listing.card.uuaid !== listing.uuaid) return { ok: false, reason: "card-uuaid-mismatch" }; // @rule reg.listing-card-uuaid
248
+
249
+ let cardBytes;
250
+ try {
251
+ cardBytes = Buffer.byteLength(jcs(listing.card), "utf8");
252
+ } catch {
253
+ return { ok: false, reason: "malformed-artifact" }; // @rule reg.listing-card-canonical
254
+ }
255
+ if (cardBytes > CARD_MAX_BYTES) return { ok: false, reason: "card-too-large" }; // @rule reg.listing-card-size
256
+
257
+ const existing = this.db
258
+ .prepare("select issued_at_ms, first_seen_ms from listing where lineage = ?")
259
+ .get(listing.lineage);
260
+
261
+ let matchedOrigin = null;
262
+ if (existing) {
263
+ if (issuedMs <= existing.issued_at_ms) return { ok: false, reason: "stale-listing" }; // @rule reg.listing-stale
264
+ if (Object.hasOwn(listing, "stamp")) {
265
+ if (!isValidPowShape(listing.stamp)) return { ok: false, reason: "malformed-stamp" }; // @rule reg.listing-update-stamp-shape
266
+ if (!federated && verifyStamp(listing.stamp, listing.lineage, `${LISTING_VERSION}:${this.registryUuaid}`, { now: listing.issuedAt, requiredBits: this.requiredStampBits }) === null) {
267
+ matchedOrigin = this.registryUuaid;
268
+ } else if (federated) {
269
+ const updPeers = [...new Set([stampRegCandidate, peerUuaid, ...knownPeerUuaids].filter((u) => typeof u === "string" && UUAID_RE.test(u)))];
270
+ let lastUpdStampErr = "stamp-binding";
271
+ for (const pUuaid of updPeers) {
272
+ const err = verifyStamp(listing.stamp, listing.lineage, `${LISTING_VERSION}:${pUuaid}`, { now: listing.issuedAt, requiredBits: this.requiredStampBits });
273
+ if (err === null) {
274
+ matchedOrigin = pUuaid;
275
+ break;
276
+ }
277
+ lastUpdStampErr = err;
278
+ }
279
+ if (!matchedOrigin) return { ok: false, reason: lastUpdStampErr };
280
+ }
281
+ }
282
+ } else if (federated) {
283
+ if (Object.hasOwn(listing, "stamp")) {
284
+ if (!isValidPowShape(listing.stamp)) return { ok: false, reason: "malformed-stamp" };
285
+ const candidatePeers = [...new Set([stampRegCandidate, peerUuaid, ...knownPeerUuaids].filter((u) => typeof u === "string" && UUAID_RE.test(u)))];
286
+ let lastStampErr = "stamp-binding";
287
+ for (const pUuaid of candidatePeers) {
288
+ const err = verifyStamp(listing.stamp, listing.lineage, `${LISTING_VERSION}:${pUuaid}`, {
289
+ now: listing.issuedAt,
290
+ requiredBits: this.requiredStampBits,
291
+ });
292
+ if (err === null) {
293
+ matchedOrigin = pUuaid;
294
+ break;
295
+ }
296
+ lastStampErr = err;
297
+ }
298
+ if (!matchedOrigin) return { ok: false, reason: lastStampErr };
299
+ }
300
+ } else {
301
+ if (!Object.hasOwn(listing, "stamp")) return { ok: false, reason: "stamp-required" }; // @rule reg.listing-stamp-required
302
+ if (!isValidPowShape(listing.stamp)) return { ok: false, reason: "malformed-stamp" }; // @rule reg.listing-first-stamp-shape
303
+ const stampErr = verifyStamp(
304
+ listing.stamp,
305
+ listing.lineage,
306
+ `${LISTING_VERSION}:${this.registryUuaid}`,
307
+ { now: nowStr, requiredBits: this.requiredStampBits },
308
+ );
309
+ if (stampErr !== null) return { ok: false, reason: stampErr }; // @rule reg.listing-stamp-verify
310
+ matchedOrigin = this.registryUuaid;
311
+ }
312
+
313
+ if (this.hasOtherLineage(listing.lineage, listing.lineage) || this.hasOtherLineage(listing.uuaid, listing.lineage)) return { ok: false, status: 409, reason: "ambiguous-uuaid" }; // @rule reg.listing-ambiguous-listing-store
314
+ if (this.lineageStore && (this.lineageStore.hasOtherLineage(listing.lineage, listing.lineage) || this.lineageStore.hasOtherLineage(listing.uuaid, listing.lineage))) return { ok: false, status: 409, reason: "ambiguous-uuaid" }; // @rule reg.listing-ambiguous-lineage-store
315
+
316
+ // Verify card (and lineage current key when lineage events exist).
317
+ const lineageEval = this.lineageStore ? this.lineageStore.evaluateLineage(listing.lineage, { now: nowStr }) : null;
318
+ if (lineageEval) {
319
+ if (!federated && lineageEval.tombstoned === true) return { ok: false, reason: "lineage-tombstoned" }; // @rule reg.listing-tombstoned
320
+ let expectedCurrent = lineageEval.current;
321
+ let expectedHead = lineageEval.head;
322
+ if (federated && lineageEval.tombstoned === true) {
323
+ const tombMs = lineageEval.tombstoneTs ? Date.parse(lineageEval.tombstoneTs) : -Infinity;
324
+ if (issuedMs > tombMs) return { ok: false, reason: "lineage-tombstoned" };
325
+ const preEvents = lineageEval.events.slice(0, -1);
326
+ if (!preEvents.length) return { ok: false, reason: "lineage-tombstoned" };
327
+ const preEval = verifyLineageFull({ v: LINEAGE_LOG_VERSION, events: preEvents, receipts: lineageEval.receipts }, { now: nowStr, allowBind: true });
328
+ const preOk = preEval.verdict === "valid" || preEval.verdict === "recovered" || preEval.verdict === "pending-recovery";
329
+ if (!preOk) return { ok: false, reason: preEval.reasons[0] ?? "card-lineage-unresolved" };
330
+ expectedCurrent = preEval.facts?.current ?? null;
331
+ expectedHead = preEval.facts?.head;
332
+ } else {
333
+ const resolvedOk =
334
+ lineageEval.verdict === "valid" || lineageEval.verdict === "recovered" || lineageEval.verdict === "pending-recovery";
335
+ if (!resolvedOk) return { ok: false, reason: lineageEval.verdict === "contested" ? "lineage-contested" : (lineageEval.reasons[0] ?? "card-lineage-unresolved") }; // @rule reg.listing-lineage-valid
336
+ }
337
+ const shapeCheck = verifyCard(listing.card, { now: nowStr });
338
+ const cardOk =
339
+ shapeCheck.verdict !== "invalid" &&
340
+ isStrictEd25519PublicKey(listing.card.publicKey) &&
341
+ isKeyDerivedUuaid(listing.card.uuaid, listing.card.publicKey) &&
342
+ verifyLineageDoc(listing.card, listing.card.publicKey, listing.card.sig) &&
343
+ listing.card.uuaid === expectedCurrent;
344
+ const cardFailReason = shapeCheck.verdict === "invalid" ? (shapeCheck.reasons[0] ?? "invalid-card") : (listing.card.uuaid !== expectedCurrent ? "card-key-not-current" : "invalid-card");
345
+ if (!cardOk) return { ok: false, reason: cardFailReason }; // @rule reg.listing-card-verify-lineage
346
+ if (Object.hasOwn(listing.card, "lineageHead") && listing.card.lineageHead !== expectedHead) return { ok: false, reason: "card-lineage-head-mismatch" }; // @rule reg.listing-card-lineage-head
347
+ } else {
348
+ if (listing.uuaid !== listing.lineage) return { ok: false, reason: "lineage-required" }; // @rule reg.listing-rotated-needs-lineage
349
+ if (Object.hasOwn(listing.card, "lineageHead")) return { ok: false, reason: "lineage-required" }; // @rule reg.listing-card-head-needs-lineage
350
+ const shapeCheck = verifyCard(listing.card, { now: nowStr });
351
+ if (shapeCheck.verdict === "invalid") return { ok: false, reason: shapeCheck.reasons[0] ?? "malformed-artifact" }; // @rule reg.listing-card-shape
352
+ if (!isStrictEd25519PublicKey(listing.card.publicKey)) return { ok: false, reason: "weak-key" }; // @rule reg.listing-card-strict-key
353
+ if (!isKeyDerivedUuaid(listing.card.uuaid, listing.card.publicKey)) return { ok: false, reason: "key-uuaid-mismatch" }; // @rule reg.listing-card-key-binding
354
+ if (!verifyLineageDoc(listing.card, listing.card.publicKey, listing.card.sig)) return { ok: false, reason: "bad-signature" }; // @rule reg.listing-card-sig
355
+ }
356
+
357
+ // Verify listing.sig over "pillar-listing/1\n" + jcs(without sig) using card.publicKey.
358
+ let sigOk = false;
359
+ try {
360
+ sigOk = verifyLineageDoc(listing, listing.card.publicKey, listing.sig);
361
+ } catch {
362
+ sigOk = false;
363
+ }
364
+ if (!sigOk) return { ok: false, reason: "bad-signature" }; // @rule reg.listing-sig
365
+
366
+ const serialized = JSON.stringify(listing);
367
+ const totalCap = checkLineageTotalCap(listing.lineage, Buffer.byteLength(serialized, "utf8"), {
368
+ maxTotalBytes: this.federationStore?.maxTotalLineageBytes ?? this.maxTotalLineageBytes,
369
+ listingStore: this,
370
+ heartbeatStore: this.heartbeatStore,
371
+ lineageStore: this.lineageStore,
372
+ excludeKind: "listing",
373
+ });
374
+ if (!totalCap.ok) return totalCap;
375
+
376
+ const tx = this.db.transaction(() => {
377
+ if (!existing) {
378
+ const recent = this.db
379
+ .prepare("select count(*) as n from listing where first_seen_ms > ?")
380
+ .get(nowMs - 3600_000).n;
381
+ if (recent >= this.maxNewLineagesPerHour) return { ok: false, reason: "rate-limited", status: 429 }; // @rule reg.listing-rate-limit
382
+ if (this.federationStore) {
383
+ const adm = this.federationStore.tryAdmitLineage(listing.lineage, {
384
+ now: nowStr,
385
+ source: federated ? "federation" : "direct",
386
+ });
387
+ if (!adm.ok) return { ok: false, reason: "rate-limited", status: 429 };
388
+ }
389
+ }
390
+
391
+ const withdrawnInt = listing.withdrawn === true ? 1 : 0;
392
+ if (existing) {
393
+ this.db
394
+ .prepare(`
395
+ update listing
396
+ set uuaid = ?, issued_at = ?, issued_at_ms = ?, received_at = ?, withdrawn = ?, listing_json = ?
397
+ where lineage = ?
398
+ `)
399
+ .run(listing.uuaid, listing.issuedAt, issuedMs, nowStr, withdrawnInt, serialized, listing.lineage);
400
+ } else {
401
+ this.db
402
+ .prepare(`
403
+ insert into listing (lineage, uuaid, issued_at, issued_at_ms, received_at, first_seen_ms, withdrawn, listing_json)
404
+ values (?, ?, ?, ?, ?, ?, ?, ?)
405
+ `)
406
+ .run(listing.lineage, listing.uuaid, listing.issuedAt, issuedMs, nowStr, nowMs, withdrawnInt, serialized);
407
+ }
408
+
409
+ if (this.federationStore) {
410
+ if (!Object.hasOwn(listing, "stamp")) {
411
+ this.federationStore.clearListingOrigin?.(listing.lineage);
412
+ } else if (matchedOrigin) {
413
+ this.federationStore.setListingOrigin?.(listing.lineage, matchedOrigin, { now: nowStr });
414
+ }
415
+ const doorUuaids = Array.isArray(listing.card?.doors) ? listing.card.doors.map((d) => d?.uuaid).filter(Boolean) : [];
416
+ this.federationStore.notifyLocalIngest(listing.lineage, listing.uuaid, ...doorUuaids);
417
+ }
418
+
419
+ return {
420
+ ok: true,
421
+ lineage: listing.lineage,
422
+ uuaid: listing.uuaid,
423
+ issuedAt: listing.issuedAt,
424
+ receivedAt: nowStr,
425
+ updated: Boolean(existing),
426
+ };
427
+ });
428
+
429
+ const res = tx();
430
+ if (res?.ok === true) this.changes++;
431
+ return res;
432
+ }
433
+
434
+ /**
435
+ * Prune dead / withdrawn / tombstoned listing rows that have been dead for `>= 365` days
436
+ * (`TOMBSTONE_RETENTION_MS`), while leaving `lineage_event` untouched (`T3.5`).
437
+ */
438
+ pruneExpiredTombstones({ now } = {}) {
439
+ const nowStr = nowIso(now);
440
+ const nowMs = Date.parse(nowStr);
441
+ const lineages = [];
442
+ const delStmt = this.db.prepare("delete from listing where lineage = ?");
443
+
444
+ for (const row of this.all()) {
445
+ const l = row.listing;
446
+ // A fresh verdict (maxAgeMs 0), kept for the next directory.json rebuild.
447
+ const evalRes = this.lineageStore ? this.lineageStore.evaluateLineageCached(l.lineage, { now: nowStr, maxAgeMs: 0 }) : null;
448
+ let deadSinceMs = null;
449
+ if (evalRes?.tombstoned === true) {
450
+ deadSinceMs = Date.parse(evalRes.tombstoneTs);
451
+ } else if (row.withdrawn === 1 || l.withdrawn === true) {
452
+ deadSinceMs = row.issued_at_ms;
453
+ } else {
454
+ const cur = evalRes && (evalRes.verdict === "valid" || evalRes.verdict === "recovered" || evalRes.verdict === "pending-recovery") ? evalRes.current : l.uuaid;
455
+ const hb = this.heartbeatStore ? this.heartbeatStore.getLatest(l.lineage) : null;
456
+ const lastSeenMs = hb && hb.uuaid === cur ? Math.max(row.issued_at_ms, hb.ts_ms) : row.issued_at_ms;
457
+ if (nowMs - lastSeenMs >= STATUS_QUIET_MS) deadSinceMs = lastSeenMs + STATUS_QUIET_MS;
458
+ }
459
+
460
+ if (deadSinceMs !== null && nowMs - deadSinceMs >= TOMBSTONE_RETENTION_MS) {
461
+ delStmt.run(l.lineage); // @rule reg.listing-prune-365d
462
+ if (this.heartbeatStore) this.heartbeatStore.deleteByLineage(l.lineage);
463
+ lineages.push(l.lineage);
464
+ this.changes++;
465
+ }
466
+ }
467
+
468
+ return { pruned: lineages.length, lineages };
469
+ }
470
+
471
+ /**
472
+ * Project non-withdrawn `live` listings into `directory.json` `agents[]` entries.
473
+ * All fields are JCS-safe (no floats) so `SeedRegistry.directoryEtag()` keeps working.
474
+ * No pruning here (V1 F2). The listing part is cached: rebuilt after a
475
+ * listing, heartbeat or lineage write, or PROJECTION_MAX_AGE_MS later.
476
+ */
477
+ projectLiveAgents({ now, staticAgents = [] } = {}) {
478
+ if (!this.lineageStore) throw new TypeError("ListingStore.projectLiveAgents requires a LineageStore"); // @rule reg.project-requires-lineage-store
479
+ const nowStr = nowIso(now);
480
+ const nowMs = Date.parse(nowStr);
481
+ const key = `${this.changes}/${this.lineageStore?.changes ?? 0}/${this.heartbeatStore?.changes ?? 0}`;
482
+ let cached = this._projection;
483
+ let fresh = Boolean(cached) && nowMs >= cached.atMs && nowMs - cached.atMs < PROJECTION_MAX_AGE_MS;
484
+ if (fresh && cached.key !== key) fresh = false; // @rule reg.project-cache-key
485
+ if (!fresh) {
486
+ cached = { key, atMs: nowMs, agents: this._projectListings(nowStr) };
487
+ this._projection = cached;
488
+ }
489
+ const seen = new Set(staticAgents.map((a) => a?.uuaid).filter(Boolean));
490
+ const projected = [...staticAgents];
491
+ for (const a of cached.agents) {
492
+ if (seen.has(a.uuaid)) continue;
493
+ seen.add(a.uuaid);
494
+ projected.push({ ...a });
495
+ }
496
+ return projected;
497
+ }
498
+
499
+ /** The listing part of projectLiveAgents, at `nowStr`, in store order. */
500
+ _projectListings(nowStr) {
501
+ const out = [];
502
+ for (const row of this.all()) {
503
+ const l = row.listing;
504
+ if (row.withdrawn === 1 || l.withdrawn === true) continue; // @rule reg.project-not-withdrawn
505
+ if (this.hasOtherLineage(l.lineage, l.lineage) || this.hasOtherLineage(l.uuaid, l.lineage)) continue; // @rule reg.project-ambiguous-listing-store
506
+ if (this.lineageStore.hasOtherLineage(l.lineage, l.lineage) || this.lineageStore.hasOtherLineage(l.uuaid, l.lineage)) continue; // @rule reg.project-ambiguous-lineage-store
507
+ const evalRes = this.lineageStore.evaluateLineageCached(l.lineage, { now: nowStr, maxAgeMs: EVAL_MEMO_MAX_AGE_MS });
508
+ if (evalRes?.tombstoned === true) continue; // @rule reg.project-not-tombstoned
509
+ if (evalRes !== null && ((evalRes.verdict !== "valid" && evalRes.verdict !== "recovered" && evalRes.verdict !== "pending-recovery") || evalRes.current !== l.uuaid)) continue; // @rule reg.project-lineage-current
510
+ const hb = this.heartbeatStore ? this.heartbeatStore.getLatest(l.lineage) : null;
511
+ const lastSeen = hb && hb.uuaid === l.uuaid && Date.parse(hb.ts) > Date.parse(l.issuedAt) ? hb.ts : l.issuedAt;
512
+ if (computeListingStatus(lastSeen, { withdrawn: false, now: nowStr }) !== "live") continue; // @rule reg.project-live-only
513
+ out.push({
514
+ uuaid: l.uuaid,
515
+ lineage: l.lineage,
516
+ publicKey: l.card.publicKey,
517
+ name: l.card.name,
518
+ carriers: l.card.carriers,
519
+ });
520
+ }
521
+ return out;
522
+ }
523
+ }
524
+
525
+ /**
526
+ * Prune off the request path (V1 F2): one pass now, then one every
527
+ * `intervalMs` (unref'd). A pass that throws is logged and the timer keeps
528
+ * running. Returns { stop, runNow, runs } (runs: the last 10 passes,
529
+ * { pruned, ms }).
530
+ */
531
+ export function startTombstonePruning(listingStore, { getNow = () => undefined, intervalMs = PRUNE_INTERVAL_MS, log = (m) => console.error(m), setIntervalFn = setInterval, clearIntervalFn = clearInterval } = {}) {
532
+ const runs = [];
533
+ const runNow = () => {
534
+ const t0 = performance.now();
535
+ try {
536
+ const r = listingStore.pruneExpiredTombstones({ now: getNow() });
537
+ runs.push({ pruned: r.pruned, ms: Math.round(performance.now() - t0) });
538
+ if (runs.length > 10) runs.shift();
539
+ return r;
540
+ } catch (e) {
541
+ log(`[registry] tombstone prune failed: ${e?.message ?? e}`);
542
+ return null;
543
+ }
544
+ };
545
+ runNow();
546
+ const timer = setIntervalFn(runNow, intervalMs);
547
+ timer?.unref?.();
548
+ return { stop: () => clearIntervalFn(timer), runNow, runs };
549
+ }