@uuaid/pillar 2.6.1 → 2.7.1

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