@uuaid/pillar 2.6.1 → 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 (61) hide show
  1. package/README.md +201 -5
  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 +280 -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 +504 -255
  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 +308 -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 +308 -92
  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 +725 -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 +195 -0
  31. package/src/registry/lineage-verifier.mjs +972 -0
  32. package/src/registry/lineage.mjs +984 -0
  33. package/src/registry/listings.mjs +549 -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 +296 -0
  49. package/src/vnext/jsonl-mailbox.mjs +1066 -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 +86 -0
  57. package/src/vnext/soul-cli.mjs +666 -0
  58. package/src/vnext/verify-cli.mjs +251 -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,3056 @@
1
+ /**
2
+ * Pillar vNext §3 — Pull anti-entropy registry federation, `I-5` local re-verification,
3
+ * `T3.2` peer-integrity strikes & quarantine, `T3.4` 600/hour Sybil brake & 1 MiB per-lineage cap,
4
+ * `H-2` resolve upstream fan-out (`<= 4` peers, `depth <= 2`, `3,000 ms` budget) & negative cache,
5
+ * and `A11` `src/sqlite-loader.mjs` dual-mode (`better-sqlite3` + pure-JS) storage.
6
+ */
7
+ import { createHash } from "node:crypto";
8
+ import dns from "node:dns";
9
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
10
+ import { request as httpRequest } from "node:http";
11
+ import { request as httpsRequest } from "node:https";
12
+ import { dirname } from "node:path";
13
+ import { keyDerivesUuaid } from "../identity/keychain.mjs";
14
+ import { isPrivateHost, resolveSeedUrl } from "../net/seed-registry.mjs";
15
+ import { tryLoadBetterSqlite3 } from "../sqlite-loader.mjs";
16
+ import {
17
+ CARD_MAX_BYTES,
18
+ DEFAULT_STAMP_BITS,
19
+ HEARTBEAT_VERSION,
20
+ LINEAGE_SKEW_MS,
21
+ LINEAGE_VERSION,
22
+ LISTING_VERSION,
23
+ RESOLVE_VERSION,
24
+ eventDigest,
25
+ isKeyDerivedUuaid,
26
+ isStrictEd25519PublicKey,
27
+ jcs,
28
+ signBytes,
29
+ verifyArtifact,
30
+ verifyBytesStrict,
31
+ verifyCard,
32
+ verifyLineageDoc,
33
+ verifyStamp,
34
+ } from "../vendor/pillar-core.mjs";
35
+
36
+ const DIRECTORY_LISTING_TYPE = "uuaid.directory.listing.v1";
37
+ import {
38
+ HEX64_RE,
39
+ HEX128_RE,
40
+ LINEAGE_LOG_VERSION,
41
+ RECOVERY_EVENT_TYPES,
42
+ UUAID_RE,
43
+ checkEventTypeFields,
44
+ httpsOrigin,
45
+ isDenseArray,
46
+ isPlainObject,
47
+ isStrictDateTime,
48
+ sigsShapeOk,
49
+ verifyLineageFull,
50
+ } from "./lineage-verifier.mjs";
51
+
52
+ export const FEDERATION_PEERS_VERSION = "pillar-federation/1";
53
+ export const FEDERATION_CHANGES_VERSION = "pillar-federation-changes/1";
54
+ export const DEFAULT_PULL_INTERVAL_MS = 5 * 60_000;
55
+ export const DEFAULT_MAX_STRIKES = 3;
56
+ export const DEFAULT_QUARANTINE_COOLDOWN_MS = 3_600_000;
57
+ export const DEFAULT_CHANGES_LIMIT = 500;
58
+ export const MIN_CHANGES_LIMIT = 1;
59
+ export const MAX_CHANGES_LIMIT = 500;
60
+ export const MAX_PAGES_PER_PULL = 10;
61
+ export const MAX_TOTAL_LINEAGE_BYTES = 1024 * 1024;
62
+ export const DEFAULT_MAX_NEW_LINEAGES_PER_HOUR = 600;
63
+ export const MAX_RESOLVE_FANOUT = 4;
64
+ export const MAX_RESOLVE_DEPTH = 2;
65
+ export const DEFAULT_RESOLVE_TIMEOUT_MS = 3_000;
66
+ export const DEFAULT_NEGATIVE_CACHE_TTL_MS = 60_000;
67
+ export const DEFAULT_NEGATIVE_CACHE_MAX = 10_000;
68
+ export const DEFAULT_MAX_RESOLVE_MISSES_PER_IP_PER_MINUTE = 60;
69
+
70
+ const LISTING_ALLOWED_KEYS = new Set([
71
+ "v",
72
+ "lineage",
73
+ "uuaid",
74
+ "card",
75
+ "homes",
76
+ "stamp",
77
+ "issuedAt",
78
+ "sig",
79
+ "withdrawn",
80
+ ]);
81
+ const HEARTBEAT_ALLOWED_KEYS = new Set(["v", "uuaid", "lineage", "seq", "ts", "sig"]);
82
+ const POW_ALLOWED_KEYS = new Set(["type", "bits", "nonce", "day"]);
83
+ const FED_PEERS_KEYS = new Set(["v", "registry", "publicKey", "peers", "issuedAt", "sig"]);
84
+ const FED_PEER_ITEM_KEYS = new Set(["uuaid", "url", "publicKey"]);
85
+ const FED_CHANGES_KEYS = new Set([
86
+ "v",
87
+ "registry",
88
+ "since",
89
+ "nextCursor",
90
+ "hasMore",
91
+ "listings",
92
+ "stampRegistries",
93
+ "listingOrigins",
94
+ "heartbeats",
95
+ "lineageEvents",
96
+ ]);
97
+ const RESOLVE_ALLOWED_KEYS = new Set([
98
+ "v",
99
+ "query",
100
+ "lineage",
101
+ "current",
102
+ "status",
103
+ "lastSeen",
104
+ "card",
105
+ "doors",
106
+ "carriers",
107
+ "lineageVerdict",
108
+ "evidence",
109
+ "answeredBy",
110
+ "via",
111
+ ]);
112
+ const EVIDENCE_ALLOWED_KEYS = new Set(["heartbeat", "listing", "lineageHead"]);
113
+ const NONCE_RE = /^[0-9a-f]{1,32}$/;
114
+ const DAY_RE = /^\d{4}-\d{2}-\d{2}$/;
115
+ const CURSOR_RE = /^\d{1,16}$/;
116
+ const RESOLVED_VERDICTS = new Set(["valid", "recovered", "pending-recovery"]);
117
+
118
+ function nowIso(now) {
119
+ if (typeof now === "string") return now;
120
+ const ms = typeof now === "number" ? now : Date.now();
121
+ return new Date(ms).toISOString().replace(/\.\d{3}Z$/, "Z");
122
+ }
123
+
124
+ function sha256Utf8(str) {
125
+ return createHash("sha256").update(str, "utf8").digest("hex");
126
+ }
127
+
128
+ export function objectDigestHex(obj) {
129
+ try {
130
+ if (isPlainObject(obj) && obj.v === LINEAGE_VERSION) return eventDigest(obj);
131
+ return sha256Utf8(jcs(obj));
132
+ } catch {
133
+ try {
134
+ return sha256Utf8(JSON.stringify(obj) ?? String(obj));
135
+ } catch {
136
+ return sha256Utf8(String(obj));
137
+ }
138
+ }
139
+ }
140
+
141
+ function isStrictHttpsUrl(u) {
142
+ return httpsOrigin(u) !== null;
143
+ }
144
+
145
+ function isValidPowStampShape(p) {
146
+ if (!isPlainObject(p)) return false;
147
+ if (!Object.keys(p).every((k) => POW_ALLOWED_KEYS.has(k))) return false;
148
+ if (p.type !== "pow") return false;
149
+ if (!Number.isInteger(p.bits) || p.bits < 12 || p.bits > 24) return false;
150
+ if (typeof p.nonce !== "string" || !NONCE_RE.test(p.nonce)) return false;
151
+ if (typeof p.day !== "string" || !DAY_RE.test(p.day) || !isStrictDateTime(`${p.day}T00:00:00Z`)) return false;
152
+ return true;
153
+ }
154
+
155
+ function unwrapHost(hostname) {
156
+ const h = String(hostname ?? "").trim().toLowerCase();
157
+ return h.startsWith("[") && h.endsWith("]") ? h.slice(1, -1) : h;
158
+ }
159
+
160
+ function isLoopbackOnly(hostname) {
161
+ const h = unwrapHost(hostname).replace(/\.$/, "");
162
+ return h === "127.0.0.1" || h === "::1" || h === "localhost";
163
+ }
164
+
165
+ function normalizeSigner(signer) {
166
+ if (!signer) return null;
167
+ if (signer._identity && typeof signer.sign === "function") {
168
+ const id = signer._identity;
169
+ return {
170
+ uuaid: id.uuaid,
171
+ publicKey: id.publicKeyHex.toLowerCase(),
172
+ sign: (bytes) => Buffer.from(signer.sign(Buffer.from(bytes))).toString("hex"),
173
+ };
174
+ }
175
+ const pub = (signer.publicKey ?? signer.publicKeyHex ?? "").toLowerCase();
176
+ if (typeof signer.sign === "function" && signer.uuaid && HEX64_RE.test(pub)) {
177
+ return {
178
+ uuaid: signer.uuaid,
179
+ publicKey: pub,
180
+ sign: (bytes) => {
181
+ const out = signer.sign(Buffer.from(bytes));
182
+ return typeof out === "string" ? out.toLowerCase() : Buffer.from(out).toString("hex");
183
+ },
184
+ };
185
+ }
186
+ const seed = (signer.seedHex ?? "").toLowerCase();
187
+ if (signer.uuaid && HEX64_RE.test(pub) && HEX64_RE.test(seed)) {
188
+ return {
189
+ uuaid: signer.uuaid,
190
+ publicKey: pub,
191
+ sign: (bytes) => signBytes(seed, new Uint8Array(bytes)),
192
+ };
193
+ }
194
+ return null;
195
+ }
196
+
197
+ /**
198
+ * Domain-separated I-3 signing helper: signs `domain + "\n" + JCS(obj without sig/sigs)`
199
+ * and returns `{ ...unsigned, v: domain, sig }`.
200
+ */
201
+ export function signDomain(domain, obj, signer) {
202
+ if (typeof domain !== "string" || !domain.length) throw new TypeError("signDomain: domain is required"); // @rule fed.sign-domain-name
203
+ if (!isPlainObject(obj)) throw new TypeError("signDomain: obj must be a plain object"); // @rule fed.sign-domain-obj
204
+ const norm = normalizeSigner(signer);
205
+ if (!norm) throw new TypeError("signDomain: valid signer (Keychain or { uuaid, publicKeyHex, seedHex }) is required"); // @rule fed.sign-domain-signer
206
+ const { sig: _sig, sigs: _sigs, ...rest } = obj;
207
+ const unsigned = { ...rest, v: domain };
208
+ const preimage = Buffer.from(`${domain}\n${jcs(unsigned)}`, "utf8");
209
+ const sig = norm.sign(preimage);
210
+ return { ...unsigned, sig };
211
+ }
212
+
213
+ /**
214
+ * Verify a domain-separated I-3 object signed via `signDomain(domain, obj, signer)`.
215
+ */
216
+ export function verifyDomain(domain, obj, publicKeyHex, sigHex = obj?.sig) {
217
+ if (typeof domain !== "string" || !domain.length) return false;
218
+ if (!isPlainObject(obj) || obj.v !== domain) return false; // @rule fed.verify-domain-version
219
+ if (typeof sigHex !== "string" || !HEX128_RE.test(sigHex)) return false; // @rule fed.verify-domain-sig-hex
220
+ if (typeof publicKeyHex !== "string" || !HEX64_RE.test(publicKeyHex) || !isStrictEd25519PublicKey(publicKeyHex)) return false; // @rule fed.verify-domain-strict-key
221
+ const { sig: _sig, sigs: _sigs, ...unsigned } = obj;
222
+ let preimage;
223
+ try {
224
+ preimage = Buffer.from(`${domain}\n${jcs(unsigned)}`, "utf8");
225
+ } catch {
226
+ return false;
227
+ }
228
+ return verifyBytesStrict(publicKeyHex, new Uint8Array(preimage), sigHex); // @rule fed.verify-domain-sig
229
+ }
230
+
231
+ /**
232
+ * Resolve and SSRF-check a configured federation peer URL.
233
+ * Blocks private/loopback targets via `isPrivateHost` unless `allowPrivateUrls` is true
234
+ * or `urlMap` explicitly maps the URL/origin (`B9` `gossip.mjs` pattern).
235
+ */
236
+ export function resolvePeerTarget(rawUrl, { allowPrivateUrls = false, urlMap = null } = {}) {
237
+ if (typeof rawUrl !== "string" || !rawUrl.trim()) return { ok: false, reason: "bad-url" }; // @rule fed.peer-url-string
238
+ const clean = rawUrl.trim().replace(/\/+$/, "");
239
+ let rawParsed;
240
+ try {
241
+ rawParsed = new URL(clean);
242
+ } catch {
243
+ return { ok: false, reason: "bad-url" };
244
+ }
245
+ if (rawParsed.username || rawParsed.password || rawParsed.search || rawParsed.hash) {
246
+ return { ok: false, reason: "bad-url" }; // @rule fed.peer-url-clean
247
+ }
248
+
249
+ const rawOrigin = `${rawParsed.protocol}//${rawParsed.host}`;
250
+ const explicitMapTarget = urlMap && (Object.hasOwn(urlMap, clean) ? urlMap[clean] : (Object.hasOwn(urlMap, rawOrigin) ? urlMap[rawOrigin] : null));
251
+ const explicitlyMapped = typeof explicitMapTarget === "string" && explicitMapTarget.length > 0;
252
+ const targetStr = explicitlyMapped ? explicitMapTarget.replace(/\/+$/, "") : clean;
253
+
254
+ let parsed;
255
+ try {
256
+ parsed = new URL(targetStr);
257
+ } catch {
258
+ return { ok: false, reason: "bad-url" };
259
+ }
260
+
261
+ if (parsed.protocol !== "https:" && !((allowPrivateUrls || explicitlyMapped) && parsed.protocol === "http:")) {
262
+ return { ok: false, reason: "https-required" }; // @rule fed.peer-https-required
263
+ }
264
+ if (!allowPrivateUrls && !explicitlyMapped && isPrivateHost(parsed.hostname)) {
265
+ return { ok: false, reason: "private-host" }; // @rule fed.peer-ssrf-fence
266
+ }
267
+
268
+ let fallbackUrl = null;
269
+ if ((allowPrivateUrls || explicitlyMapped) && parsed.protocol === "https:" && isLoopbackOnly(parsed.hostname)) {
270
+ fallbackUrl = `http://${parsed.host}${parsed.pathname}`.replace(/\/+$/, "");
271
+ }
272
+
273
+ const publicUrl = rawParsed.protocol === "https:"
274
+ ? clean
275
+ : `https://${formatHostForHttps(rawParsed.hostname)}${rawParsed.port ? `:${rawParsed.port}` : ""}${rawParsed.pathname}`.replace(/\/+$/, "");
276
+
277
+ return {
278
+ ok: true,
279
+ peerKey: clean,
280
+ publicUrl,
281
+ primaryUrl: targetStr,
282
+ fallbackUrl,
283
+ origin: `${parsed.protocol}//${parsed.host}`,
284
+ explicitlyMapped,
285
+ };
286
+ }
287
+
288
+ const MAX_FED_RESPONSE_BYTES = 8 * 1024 * 1024;
289
+
290
+ function defaultDnsLookup(hostname, options, callback) {
291
+ return dns.lookup(hostname, options, callback);
292
+ }
293
+
294
+ /**
295
+ * Resolve, DNS-verify against private/loopback/link-local answers, and return a
296
+ * socket-pinned `lookup` callback (`resolveSeedUrl`) when `!allowPrivateUrls && !explicitlyMapped`.
297
+ */
298
+ export async function resolvePeerTargetPinned(
299
+ rawUrl,
300
+ { allowPrivateUrls = false, urlMap = null, lookup = defaultDnsLookup, signal, timeoutMs = 5_000 } = {},
301
+ ) {
302
+ const target = resolvePeerTarget(rawUrl, { allowPrivateUrls, urlMap });
303
+ if (!target.ok) return target;
304
+ if (allowPrivateUrls || target.explicitlyMapped) return { ...target, lookup: undefined };
305
+
306
+ const dnsRes = await resolveSeedUrl(target.primaryUrl, { allowPrivateUrls: false, lookup, signal, timeoutMs });
307
+ if (!dnsRes.ok) {
308
+ return { ok: false, reason: dnsRes.reason === "private-address" ? "private-host" : dnsRes.reason }; // @rule fed.peer-dns-ssrf
309
+ }
310
+ return { ...target, lookup: dnsRes.lookup, addresses: dnsRes.addresses };
311
+ }
312
+
313
+ function pinnedNodeFetch(input, init = {}) {
314
+ const u = new URL(String(input));
315
+ const reqFn = u.protocol === "https:" ? httpsRequest : httpRequest;
316
+ const headers = { ...(init.headers ?? {}) };
317
+ return new Promise((resolve, reject) => {
318
+ let settled = false;
319
+ const fail = (err) => {
320
+ if (settled) return;
321
+ settled = true;
322
+ reject(err);
323
+ };
324
+ const req = reqFn(
325
+ u,
326
+ {
327
+ method: init.method ?? "GET",
328
+ headers,
329
+ signal: init.signal,
330
+ lookup: init.lookup,
331
+ agent: false,
332
+ },
333
+ (res) => {
334
+ const status = res.statusCode ?? 0;
335
+ if (status >= 300 && status < 400) {
336
+ req.destroy();
337
+ fail(new Error(`redirect refused (${status})`));
338
+ return;
339
+ }
340
+ const chunks = [];
341
+ let bytes = 0;
342
+ res.on("data", (c) => {
343
+ bytes += c.length;
344
+ if (bytes > MAX_FED_RESPONSE_BYTES) {
345
+ req.destroy(new Error("federation response too large"));
346
+ return;
347
+ }
348
+ chunks.push(c);
349
+ });
350
+ res.on("end", () => {
351
+ if (settled) return;
352
+ settled = true;
353
+ const buf = Buffer.concat(chunks);
354
+ const rawHeaders = res.headers ?? {};
355
+ resolve({
356
+ ok: status >= 200 && status < 300,
357
+ status,
358
+ headers: {
359
+ ...rawHeaders,
360
+ get: (name) => {
361
+ const v = rawHeaders[String(name).toLowerCase()];
362
+ return Array.isArray(v) ? v[0] : (v ?? null);
363
+ },
364
+ },
365
+ text: async () => buf.toString("utf8"),
366
+ json: async () => JSON.parse(buf.toString("utf8")),
367
+ });
368
+ });
369
+ res.on("error", fail);
370
+ },
371
+ );
372
+ req.on("error", fail);
373
+ req.on("close", () => {
374
+ if (!settled) fail(init.signal?.reason ?? new Error("request closed prematurely"));
375
+ });
376
+ req.end();
377
+ });
378
+ }
379
+
380
+ function formatHostForHttps(h) {
381
+ return h.includes(":") && !h.startsWith("[") ? `[${h}]` : h;
382
+ }
383
+
384
+ const preferredBaseByPeerOrigin = new Map();
385
+
386
+ async function getJsonWithFallback(fetchFn, target, path, headers, timeoutMs, outerSignal = null) {
387
+ const tryOnce = async (base, ms) => {
388
+ if (outerSignal?.aborted || ms <= 0) return { ok: false, aborted: true };
389
+ const ac = new AbortController();
390
+ const onOuterAbort = () => ac.abort();
391
+ outerSignal?.addEventListener("abort", onOuterAbort, { once: true });
392
+ const timer = setTimeout(() => ac.abort(), ms);
393
+ timer.unref?.();
394
+ try {
395
+ const res = await fetchFn(`${base}${path}`, {
396
+ method: "GET",
397
+ headers: { accept: "application/json", ...headers },
398
+ redirect: "error", // @rule fed.http-no-redirect
399
+ ...(target.lookup ? { lookup: target.lookup } : {}),
400
+ signal: ac.signal,
401
+ });
402
+ if (res && res.status >= 300 && res.status < 400) return { ok: false, redirected: true };
403
+ return { ok: true, res };
404
+ } catch (err) {
405
+ const msg = String(err?.cause?.message ?? err?.message ?? "").toLowerCase();
406
+ return { ok: false, ...(msg.includes("redirect") ? { redirected: true } : {}) };
407
+ } finally {
408
+ clearTimeout(timer);
409
+ outerSignal?.removeEventListener("abort", onOuterAbort);
410
+ }
411
+ };
412
+
413
+ if (!target.fallbackUrl) {
414
+ const only = await tryOnce(target.primaryUrl, timeoutMs);
415
+ return only.res ?? null;
416
+ }
417
+
418
+ const cached = target.origin ? preferredBaseByPeerOrigin.get(target.origin) : null;
419
+ const firstBase = cached === target.fallbackUrl ? target.fallbackUrl : target.primaryUrl;
420
+ const secondBase = firstBase === target.primaryUrl ? target.fallbackUrl : target.primaryUrl;
421
+ const firstTimeout = firstBase === target.primaryUrl ? Math.min(timeoutMs, 250) : timeoutMs;
422
+
423
+ const first = await tryOnce(firstBase, firstTimeout);
424
+ if (first.redirected) return null;
425
+ if (first.ok) {
426
+ if (target.origin) {
427
+ if (preferredBaseByPeerOrigin.size > 256) preferredBaseByPeerOrigin.clear();
428
+ preferredBaseByPeerOrigin.set(target.origin, firstBase);
429
+ }
430
+ return first.res ?? null;
431
+ }
432
+ if (outerSignal?.aborted) return null;
433
+ const second = await tryOnce(secondBase, timeoutMs);
434
+ if (second.ok && target.origin) {
435
+ if (preferredBaseByPeerOrigin.size > 256) preferredBaseByPeerOrigin.clear();
436
+ preferredBaseByPeerOrigin.set(target.origin, secondBase);
437
+ }
438
+ return second.res ?? null;
439
+ }
440
+
441
+ // ---------------------------------------------------------------------------
442
+ // Pure-JS Registry DB Fallback (`A11` `PILLAR_DISABLE_SQLITE=1` compatibility)
443
+ // ---------------------------------------------------------------------------
444
+
445
+ /**
446
+ * Pure-JS relational table engine for `LineageStore`, `ListingStore`, `HeartbeatStore`,
447
+ * and `FederationStore` when `better-sqlite3` is absent (`tryLoadBetterSqlite3() === null`).
448
+ */
449
+ export class PureJsRegistryDb {
450
+ constructor(dbPath = ":memory:") {
451
+ this._isPureJs = true;
452
+ this.open = true;
453
+ this.dbPath = dbPath;
454
+ this._persistPath = typeof dbPath === "string" && dbPath !== ":memory:" ? `${dbPath}.purejs.json` : null;
455
+ this._listeners = new Set();
456
+ this._tables = {
457
+ listing: new Map(), // lineage -> row
458
+ heartbeat_latest: new Map(), // lineage -> row
459
+ lineage_event: new Map(), // `${lineage}:${digest}` -> row
460
+ lineage_uuaid: new Map(), // `${lineage}:${uuaid}` -> { lineage, uuaid }
461
+ lineage_receipt: new Map(), // `${lineage}:${event}:${registry}` -> row
462
+ lineage_claim_broadcast: new Map(), // `${lineage}:${claim_digest}` -> row
463
+ };
464
+ if (this._persistPath && existsSync(this._persistPath)) {
465
+ try {
466
+ const raw = JSON.parse(readFileSync(this._persistPath, "utf8"));
467
+ for (const k of Object.keys(this._tables)) {
468
+ if (Array.isArray(raw?.[k])) this._tables[k] = new Map(raw[k]);
469
+ }
470
+ } catch {}
471
+ }
472
+ }
473
+
474
+ _flush() {
475
+ if (!this._persistPath) return;
476
+ mkdirSync(dirname(this._persistPath), { recursive: true });
477
+ const out = {};
478
+ for (const [k, m] of Object.entries(this._tables)) out[k] = [...m.entries()];
479
+ const tmp = `${this._persistPath}.tmp`;
480
+ writeFileSync(tmp, JSON.stringify(out));
481
+ renameSync(tmp, this._persistPath);
482
+ }
483
+
484
+ onMutation(fn) {
485
+ this._listeners.add(fn);
486
+ return () => this._listeners.delete(fn);
487
+ }
488
+
489
+ _emit(action, kind, itemKey, lineage, digest, updatedAt) {
490
+ for (const fn of this._listeners) fn(action, kind, itemKey, lineage, digest, updatedAt);
491
+ }
492
+
493
+ pragma(str) {
494
+ if (String(str).includes("table_info(lineage_event)")) return [{ name: "complete" }];
495
+ return [];
496
+ }
497
+
498
+ exec() {}
499
+
500
+ transaction(fn) {
501
+ return (...args) => fn(...args);
502
+ }
503
+
504
+ close() {
505
+ this.open = false;
506
+ }
507
+
508
+ prepare(sql) {
509
+ const norm = sql.replace(/\s+/g, " ").trim().toLowerCase();
510
+ const t = this._tables;
511
+ const flush = () => this._flush();
512
+ const emit = (...a) => this._emit(...a);
513
+
514
+ if (norm === "pragma table_info(lineage_event)") {
515
+ return { all: () => [{ name: "complete" }] };
516
+ }
517
+
518
+ // ---- listing ----
519
+ if (norm === "select * from listing where lineage = ?") {
520
+ return { get: (lin) => (t.listing.has(lin) ? { ...t.listing.get(lin) } : undefined) };
521
+ }
522
+ if (norm === "select issued_at_ms, first_seen_ms from listing where lineage = ?") {
523
+ return {
524
+ get: (lin) => {
525
+ const r = t.listing.get(lin);
526
+ return r ? { issued_at_ms: r.issued_at_ms, first_seen_ms: r.first_seen_ms } : undefined;
527
+ },
528
+ };
529
+ }
530
+ if (norm === "select * from listing where lineage = ? or uuaid = ? limit 2") {
531
+ return {
532
+ all: (u1, u2) => {
533
+ const out = [];
534
+ for (const r of t.listing.values()) {
535
+ if (r.lineage === u1 || r.uuaid === u2) {
536
+ out.push({ ...r });
537
+ if (out.length >= 2) break;
538
+ }
539
+ }
540
+ return out;
541
+ },
542
+ };
543
+ }
544
+ if (norm === "select 1 from listing where (lineage = ? or uuaid = ?) and lineage != ? limit 1") {
545
+ return {
546
+ get: (u1, u2, exp) => {
547
+ for (const r of t.listing.values()) {
548
+ if ((r.lineage === u1 || r.uuaid === u2) && r.lineage !== exp) return { 1: 1 };
549
+ }
550
+ return undefined;
551
+ },
552
+ };
553
+ }
554
+ if (norm === "select * from listing order by issued_at_ms desc, lineage asc") {
555
+ return {
556
+ all: () =>
557
+ [...t.listing.values()]
558
+ .map((r) => ({ ...r }))
559
+ .sort((a, b) => b.issued_at_ms - a.issued_at_ms || (a.lineage < b.lineage ? -1 : a.lineage > b.lineage ? 1 : 0)),
560
+ };
561
+ }
562
+ if (norm === "select count(*) as n from listing where first_seen_ms > ?") {
563
+ return {
564
+ get: (ms) => {
565
+ let n = 0;
566
+ for (const r of t.listing.values()) if (r.first_seen_ms > ms) n += 1;
567
+ return { n };
568
+ },
569
+ };
570
+ }
571
+ if (norm.startsWith("update listing set uuaid = ?")) {
572
+ return {
573
+ run: (uuaid, issued_at, issued_at_ms, received_at, withdrawn, listing_json, lineage) => {
574
+ const cur = t.listing.get(lineage);
575
+ if (cur) {
576
+ t.listing.set(lineage, { ...cur, uuaid, issued_at, issued_at_ms, received_at, withdrawn, listing_json });
577
+ emit("upsert", "listing", lineage, lineage, null, received_at);
578
+ flush();
579
+ }
580
+ },
581
+ };
582
+ }
583
+ if (norm.startsWith("insert into listing")) {
584
+ return {
585
+ run: (lineage, uuaid, issued_at, issued_at_ms, received_at, first_seen_ms, withdrawn, listing_json) => {
586
+ t.listing.set(lineage, { lineage, uuaid, issued_at, issued_at_ms, received_at, first_seen_ms, withdrawn, listing_json });
587
+ emit("upsert", "listing", lineage, lineage, null, received_at);
588
+ flush();
589
+ },
590
+ };
591
+ }
592
+ if (norm === "delete from listing where lineage = ?") {
593
+ return {
594
+ run: (lineage) => {
595
+ if (t.listing.delete(lineage)) {
596
+ emit("delete", "listing", lineage, lineage, null, null);
597
+ flush();
598
+ }
599
+ },
600
+ };
601
+ }
602
+
603
+ // ---- heartbeat_latest ----
604
+ if (norm === "select * from heartbeat_latest where lineage = ?") {
605
+ return { get: (lin) => (t.heartbeat_latest.has(lin) ? { ...t.heartbeat_latest.get(lin) } : undefined) };
606
+ }
607
+ if (norm.startsWith("select seq,") && norm.includes("from heartbeat_latest where lineage = ?")) {
608
+ return {
609
+ get: (lin) => {
610
+ const r = t.heartbeat_latest.get(lin);
611
+ return r ? { seq: r.seq, ts_ms: r.ts_ms, received_at_ms: r.received_at_ms } : undefined;
612
+ },
613
+ };
614
+ }
615
+ if (norm === "delete from heartbeat_latest where lineage = ?") {
616
+ return {
617
+ run: (lineage) => {
618
+ if (t.heartbeat_latest.delete(lineage)) {
619
+ emit("delete", "heartbeat", lineage, lineage, null, null);
620
+ flush();
621
+ }
622
+ },
623
+ };
624
+ }
625
+ if (norm.startsWith("update heartbeat_latest set uuaid = ?")) {
626
+ return {
627
+ run: (uuaid, seq, ts, ts_ms, received_at, received_at_ms, heartbeat_json, lineage) => {
628
+ t.heartbeat_latest.set(lineage, { lineage, uuaid, seq, ts, ts_ms, received_at, received_at_ms, heartbeat_json });
629
+ emit("upsert", "heartbeat", lineage, lineage, null, received_at);
630
+ flush();
631
+ },
632
+ };
633
+ }
634
+ if (norm.startsWith("insert into heartbeat_latest")) {
635
+ return {
636
+ run: (lineage, uuaid, seq, ts, ts_ms, received_at, received_at_ms, heartbeat_json) => {
637
+ t.heartbeat_latest.set(lineage, { lineage, uuaid, seq, ts, ts_ms, received_at, received_at_ms, heartbeat_json });
638
+ emit("upsert", "heartbeat", lineage, lineage, null, received_at);
639
+ flush();
640
+ },
641
+ };
642
+ }
643
+
644
+ // ---- lineage_uuaid / lineage_event / lineage_receipt / lineage_claim_broadcast ----
645
+ if (norm === "insert or ignore into lineage_uuaid (lineage, uuaid) values (?, ?)") {
646
+ return {
647
+ run: (lineage, uuaid) => {
648
+ const k = `${lineage}:${uuaid}`;
649
+ if (!t.lineage_uuaid.has(k)) {
650
+ t.lineage_uuaid.set(k, { lineage, uuaid });
651
+ flush();
652
+ }
653
+ },
654
+ };
655
+ }
656
+ if (norm.startsWith("select distinct lineage from (") && norm.includes("limit 2")) {
657
+ return {
658
+ all: (u1, u2, u3) => {
659
+ const seen = new Set();
660
+ for (const r of t.lineage_event.values()) {
661
+ if (r.complete === 1 && (r.lineage === u1 || r.key_uuaid === u2)) seen.add(r.lineage);
662
+ }
663
+ for (const r of t.lineage_uuaid.values()) {
664
+ if (r.uuaid === u3) seen.add(r.lineage);
665
+ }
666
+ return [...seen].slice(0, 2).map((lineage) => ({ lineage }));
667
+ },
668
+ };
669
+ }
670
+ if (norm.startsWith("select 1 from (") && norm.includes("lineage != ?")) {
671
+ return {
672
+ get: (u1, u2, exp1, u3, exp2) => {
673
+ for (const r of t.lineage_event.values()) {
674
+ if (r.complete === 1 && (r.lineage === u1 || r.key_uuaid === u2) && r.lineage !== exp1) return { 1: 1 };
675
+ }
676
+ for (const r of t.lineage_uuaid.values()) {
677
+ if (r.uuaid === u3 && r.lineage !== exp2) return { 1: 1 };
678
+ }
679
+ return undefined;
680
+ },
681
+ };
682
+ }
683
+ if (norm === "select * from lineage_event where lineage = ? order by seq asc, digest asc") {
684
+ return {
685
+ all: (lin) =>
686
+ [...t.lineage_event.values()]
687
+ .filter((r) => r.lineage === lin)
688
+ .map((r) => ({ ...r }))
689
+ .sort((a, b) => a.seq - b.seq || (a.digest < b.digest ? -1 : a.digest > b.digest ? 1 : 0)),
690
+ };
691
+ }
692
+ if (norm === "select * from lineage_event where lineage = ? and complete = 1 order by seq asc, digest asc") {
693
+ return {
694
+ all: (lin) =>
695
+ [...t.lineage_event.values()]
696
+ .filter((r) => r.lineage === lin && r.complete === 1)
697
+ .map((r) => ({ ...r }))
698
+ .sort((a, b) => a.seq - b.seq || (a.digest < b.digest ? -1 : a.digest > b.digest ? 1 : 0)),
699
+ };
700
+ }
701
+ if (norm === "select digest, seq, prev, event_json from lineage_event where lineage = ? and digest = ? and complete = 1") {
702
+ return {
703
+ get: (lin, dig) => {
704
+ const r = t.lineage_event.get(`${lin}:${dig}`);
705
+ return r && r.complete === 1 ? { digest: r.digest, seq: r.seq, prev: r.prev, event_json: r.event_json } : undefined;
706
+ },
707
+ };
708
+ }
709
+ if (norm === "select count(*) as cnt, coalesce(sum(byte_len), 0) as total from lineage_event where lineage = ? and digest != ?") {
710
+ return {
711
+ get: (lin, dig) => {
712
+ let cnt = 0;
713
+ let total = 0;
714
+ for (const r of t.lineage_event.values()) {
715
+ if (r.lineage === lin && r.digest !== dig) {
716
+ cnt += 1;
717
+ total += r.byte_len;
718
+ }
719
+ }
720
+ return { cnt, total };
721
+ },
722
+ };
723
+ }
724
+ if (norm === "select coalesce(sum(byte_len), 0) as total from lineage_event where lineage = ?") {
725
+ return {
726
+ get: (lin) => {
727
+ let total = 0;
728
+ for (const r of t.lineage_event.values()) if (r.lineage === lin) total += r.byte_len;
729
+ return { total };
730
+ },
731
+ };
732
+ }
733
+ if (norm === "select digest, seq, prev, byte_len, event_json from lineage_event where lineage = ? and complete = 1 and digest != ? order by seq asc, digest asc") {
734
+ return {
735
+ all: (lin, dig) =>
736
+ [...t.lineage_event.values()]
737
+ .filter((r) => r.lineage === lin && r.complete === 1 && r.digest !== dig)
738
+ .map((r) => ({ digest: r.digest, seq: r.seq, prev: r.prev, byte_len: r.byte_len, event_json: r.event_json }))
739
+ .sort((a, b) => a.seq - b.seq || (a.digest < b.digest ? -1 : a.digest > b.digest ? 1 : 0)),
740
+ };
741
+ }
742
+ if (norm === "select digest from lineage_event where lineage = ? and complete = 0 and digest != ? order by received_at asc") {
743
+ return {
744
+ all: (lin, dig) =>
745
+ [...t.lineage_event.values()]
746
+ .filter((r) => r.lineage === lin && r.complete === 0 && r.digest !== dig)
747
+ .sort((a, b) => (a.received_at < b.received_at ? -1 : a.received_at > b.received_at ? 1 : 0))
748
+ .map((r) => ({ digest: r.digest })),
749
+ };
750
+ }
751
+ if (norm === "delete from lineage_event where lineage = ? and digest = ?") {
752
+ return {
753
+ run: (lin, dig) => {
754
+ const key = `${lin}:${dig}`;
755
+ if (t.lineage_event.delete(key)) {
756
+ emit("delete", "lineage", key, lin, dig, null);
757
+ flush();
758
+ }
759
+ },
760
+ };
761
+ }
762
+ if (norm === "select event_json, byte_len, complete from lineage_event where lineage = ? and digest = ?") {
763
+ return {
764
+ get: (lin, dig) => {
765
+ const r = t.lineage_event.get(`${lin}:${dig}`);
766
+ return r ? { event_json: r.event_json, byte_len: r.byte_len, complete: r.complete } : undefined;
767
+ },
768
+ };
769
+ }
770
+ if (norm === "update lineage_event set byte_len = ? where lineage = ?") {
771
+ return {
772
+ run: (byte_len, lin) => {
773
+ for (const [k, cur] of t.lineage_event.entries()) {
774
+ if (cur.lineage === lin) t.lineage_event.set(k, { ...cur, byte_len });
775
+ }
776
+ flush();
777
+ },
778
+ };
779
+ }
780
+ if (norm === "update lineage_event set event_json = ?, byte_len = ?, received_at = ? where lineage = ? and digest = ?") {
781
+ return {
782
+ run: (event_json, byte_len, received_at, lin, dig) => {
783
+ const key = `${lin}:${dig}`;
784
+ const cur = t.lineage_event.get(key);
785
+ if (cur) {
786
+ t.lineage_event.set(key, { ...cur, event_json, byte_len, received_at });
787
+ if (cur.complete === 1) emit("upsert", "lineage", key, lin, dig, received_at);
788
+ flush();
789
+ }
790
+ },
791
+ };
792
+ }
793
+ if (norm === "update lineage_event set key_uuaid = ?, event_json = ?, byte_len = ?, received_at = ?, complete = 1 where lineage = ? and digest = ?") {
794
+ return {
795
+ run: (key_uuaid, event_json, byte_len, received_at, lin, dig) => {
796
+ const key = `${lin}:${dig}`;
797
+ const cur = t.lineage_event.get(key);
798
+ if (cur) {
799
+ t.lineage_event.set(key, { ...cur, key_uuaid, event_json, byte_len, received_at, complete: 1 });
800
+ emit("upsert", "lineage", key, lin, dig, received_at);
801
+ flush();
802
+ }
803
+ },
804
+ };
805
+ }
806
+ if (norm.startsWith("insert into lineage_event") && norm.endsWith("0)")) {
807
+ return {
808
+ run: (lineage, digest, seq, prev, type, key_uuaid, event_json, byte_len, received_at) => {
809
+ t.lineage_event.set(`${lineage}:${digest}`, { lineage, digest, seq, prev, type, key_uuaid, event_json, byte_len, received_at, complete: 0 });
810
+ flush();
811
+ },
812
+ };
813
+ }
814
+ if (norm.startsWith("insert into lineage_event")) {
815
+ return {
816
+ run: (lineage, digest, seq, prev, type, key_uuaid, event_json, byte_len, received_at) => {
817
+ const key = `${lineage}:${digest}`;
818
+ t.lineage_event.set(key, { lineage, digest, seq, prev, type, key_uuaid, event_json, byte_len, received_at, complete: 1 });
819
+ emit("upsert", "lineage", key, lineage, digest, received_at);
820
+ flush();
821
+ },
822
+ };
823
+ }
824
+ if (norm === "select receipt_json from lineage_receipt where lineage = ? order by seen_at_ms asc, event asc, registry asc limit ?") {
825
+ return {
826
+ all: (lin, lim) =>
827
+ [...t.lineage_receipt.values()]
828
+ .filter((r) => r.lineage === lin)
829
+ .sort((a, b) => a.seen_at_ms - b.seen_at_ms || (a.event < b.event ? -1 : a.event > b.event ? 1 : 0) || (a.registry < b.registry ? -1 : a.registry > b.registry ? 1 : 0))
830
+ .slice(0, lim)
831
+ .map((r) => ({ receipt_json: r.receipt_json })),
832
+ };
833
+ }
834
+ if (norm === "select receipt_json from lineage_receipt where lineage = ? and event = ?") {
835
+ return {
836
+ all: (lin, ev) =>
837
+ [...t.lineage_receipt.values()]
838
+ .filter((r) => r.lineage === lin && r.event === ev)
839
+ .map((r) => ({ receipt_json: r.receipt_json })),
840
+ };
841
+ }
842
+ if (norm === "delete from lineage_receipt where lineage = ? and registry = ?") {
843
+ return {
844
+ run: (lin, reg) => {
845
+ for (const [k, r] of t.lineage_receipt.entries()) {
846
+ if (r.lineage === lin && r.registry === reg) t.lineage_receipt.delete(k);
847
+ }
848
+ flush();
849
+ },
850
+ };
851
+ }
852
+ if (norm === "select receipt_json from lineage_receipt where lineage = ? and event = ? and registry = ?") {
853
+ return {
854
+ get: (lin, ev, reg) => {
855
+ const r = t.lineage_receipt.get(`${lin}:${ev}:${reg}`);
856
+ return r ? { receipt_json: r.receipt_json } : undefined;
857
+ },
858
+ };
859
+ }
860
+ if (norm === "select seen_at_ms from lineage_receipt where lineage = ? and event = ? and registry = ?") {
861
+ return {
862
+ get: (lin, ev, reg) => {
863
+ const r = t.lineage_receipt.get(`${lin}:${ev}:${reg}`);
864
+ return r ? { seen_at_ms: r.seen_at_ms } : undefined;
865
+ },
866
+ };
867
+ }
868
+ if (norm === "select count(*) as n from lineage_receipt where lineage = ?") {
869
+ return {
870
+ get: (lin) => {
871
+ let n = 0;
872
+ for (const r of t.lineage_receipt.values()) if (r.lineage === lin) n += 1;
873
+ return { n };
874
+ },
875
+ };
876
+ }
877
+ if (norm.startsWith("insert into lineage_receipt")) {
878
+ return {
879
+ run: (lineage, event, registry, seen_at, seen_at_ms, sig, receipt_json) => {
880
+ t.lineage_receipt.set(`${lineage}:${event}:${registry}`, { lineage, event, registry, seen_at, seen_at_ms, sig, receipt_json });
881
+ flush();
882
+ },
883
+ };
884
+ }
885
+ if (norm.startsWith("select 1 from lineage_event e where e.lineage = ? and e.complete = 1 and e.type = 'recovery.claim'")) {
886
+ return {
887
+ get: (lin) => {
888
+ for (const r of t.lineage_event.values()) {
889
+ if (r.lineage === lin && r.complete === 1 && r.type === "recovery.claim" && !t.lineage_claim_broadcast.has(`${lin}:${r.digest}`)) {
890
+ return { 1: 1 };
891
+ }
892
+ }
893
+ return undefined;
894
+ },
895
+ };
896
+ }
897
+ if (norm === "select 1 from lineage_claim_broadcast where lineage = ? and claim_digest = ?") {
898
+ return { get: (lin, dig) => (t.lineage_claim_broadcast.has(`${lin}:${dig}`) ? { 1: 1 } : undefined) };
899
+ }
900
+ if (norm === "insert or ignore into lineage_claim_broadcast (lineage, claim_digest, broadcast_at) values (?, ?, ?)") {
901
+ return {
902
+ run: (lineage, claim_digest, broadcast_at) => {
903
+ const k = `${lineage}:${claim_digest}`;
904
+ if (!t.lineage_claim_broadcast.has(k)) {
905
+ t.lineage_claim_broadcast.set(k, { lineage, claim_digest, broadcast_at });
906
+ flush();
907
+ }
908
+ },
909
+ };
910
+ }
911
+
912
+ throw new Error(`PureJsRegistryDb: unsupported SQL: ${norm}`);
913
+ }
914
+ }
915
+
916
+ /**
917
+ * Open a `better-sqlite3` database when available (`src/sqlite-loader.mjs`), falling back
918
+ * to `PureJsRegistryDb` when `PILLAR_DISABLE_SQLITE=1` or native bindings are absent.
919
+ */
920
+ export function openRegistryDb(dbPath = ":memory:", { forcePureJs = false } = {}) {
921
+ const Database = forcePureJs ? null : tryLoadBetterSqlite3();
922
+ if (Database) {
923
+ const db = new Database(dbPath);
924
+ db.pragma("journal_mode = WAL");
925
+ return db;
926
+ }
927
+ return new PureJsRegistryDb(dbPath);
928
+ }
929
+
930
+ // ---------------------------------------------------------------------------
931
+ // Bounded LRU Negative Cache & Per-IP Miss Rate Limiter (`H-2`)
932
+ // ---------------------------------------------------------------------------
933
+
934
+ export class ResolveNegativeCache {
935
+ constructor({ ttlMs = DEFAULT_NEGATIVE_CACHE_TTL_MS, maxEntries = DEFAULT_NEGATIVE_CACHE_MAX } = {}) {
936
+ this.ttlMs = ttlMs;
937
+ this.maxEntries = maxEntries;
938
+ this._entries = new Map(); // uuaid -> expiresAtMs
939
+ }
940
+
941
+ get size() {
942
+ return this._entries.size;
943
+ }
944
+
945
+ has(uuaid, { now } = {}) {
946
+ if (typeof uuaid !== "string" || !this._entries.has(uuaid)) return false;
947
+ const nowMs = Date.parse(nowIso(now));
948
+ const expMs = this._entries.get(uuaid);
949
+ if (nowMs >= expMs) {
950
+ this._entries.delete(uuaid);
951
+ return false; // @rule h2.neg-cache-ttl-expiry
952
+ }
953
+ this._entries.delete(uuaid);
954
+ this._entries.set(uuaid, expMs);
955
+ return true;
956
+ }
957
+
958
+ set(uuaid, { now } = {}) {
959
+ if (typeof uuaid !== "string" || !UUAID_RE.test(uuaid)) return; // @rule h2.neg-cache-valid-uuaid
960
+ if (this.ttlMs <= 0 || this.maxEntries <= 0) return;
961
+ const nowMs = Date.parse(nowIso(now));
962
+ if (this._entries.has(uuaid)) this._entries.delete(uuaid);
963
+ if (this._entries.size >= this.maxEntries) {
964
+ const oldestKey = this._entries.keys().next().value;
965
+ if (oldestKey !== undefined) this._entries.delete(oldestKey); // @rule h2.neg-cache-lru-bound
966
+ }
967
+ this._entries.set(uuaid, nowMs + this.ttlMs);
968
+ }
969
+
970
+ invalidate(...uuaids) {
971
+ for (const u of uuaids) {
972
+ if (typeof u === "string" && u.length > 0) this._entries.delete(u); // @rule h2.neg-cache-invalidate
973
+ }
974
+ }
975
+
976
+ clear() {
977
+ this._entries.clear();
978
+ }
979
+ }
980
+
981
+ export function makeResolveMissRateLimiter({
982
+ maxPerMinute = DEFAULT_MAX_RESOLVE_MISSES_PER_IP_PER_MINUTE,
983
+ windowMs = 60_000,
984
+ getNow = () => undefined,
985
+ } = {}) {
986
+ const buckets = new Map();
987
+ return (ip) => {
988
+ const key = String(ip ?? "unknown");
989
+ const nowMs = Date.parse(nowIso(getNow()));
990
+ const prev = (buckets.get(key) ?? []).filter((t) => t > nowMs - windowMs);
991
+ if (prev.length >= maxPerMinute) {
992
+ buckets.set(key, prev);
993
+ return false; // @rule h2.miss-rate-limit-cap
994
+ }
995
+ prev.push(nowMs);
996
+ buckets.set(key, prev);
997
+ if (buckets.size > 10_000) {
998
+ for (const [k, arr] of buckets) {
999
+ if (!arr.some((t) => t > nowMs - windowMs)) buckets.delete(k);
1000
+ }
1001
+ }
1002
+ return true;
1003
+ };
1004
+ }
1005
+
1006
+ // ---------------------------------------------------------------------------
1007
+ // FederationStore (`peer_cursor`, `peer_strikes`, `lineage_admissions`, `federation_changes`)
1008
+ // ---------------------------------------------------------------------------
1009
+
1010
+ /**
1011
+ * Compute total stored UTF-8 state bytes for `lineage` across `listing`, `heartbeat_latest`,
1012
+ * and `lineage_event` (`<= 1 MiB` per-lineage cap, §3).
1013
+ */
1014
+ export function computeStoredLineageBytes(
1015
+ lineage,
1016
+ { listingStore = null, heartbeatStore = null, lineageStore = null, excludeKind = null, excludeEventDigest = null } = {},
1017
+ ) {
1018
+ let total = 0;
1019
+ if (excludeKind !== "listing" && listingStore) {
1020
+ const lRow = listingStore.getByLineage(lineage);
1021
+ if (lRow?.listing_json) total += Buffer.byteLength(lRow.listing_json, "utf8");
1022
+ }
1023
+ if (excludeKind !== "heartbeat" && heartbeatStore) {
1024
+ const hbRow = heartbeatStore.getLatest(lineage);
1025
+ if (hbRow?.heartbeat_json) total += Buffer.byteLength(hbRow.heartbeat_json, "utf8");
1026
+ }
1027
+ if (lineageStore) {
1028
+ const rows = lineageStore.getRows(lineage, { includeIncomplete: true });
1029
+ for (const r of rows) {
1030
+ if (excludeEventDigest && r.digest === excludeEventDigest) continue;
1031
+ total += Number(r.byte_len ?? Buffer.byteLength(r.event_json ?? "", "utf8"));
1032
+ }
1033
+ }
1034
+ return total;
1035
+ }
1036
+
1037
+ export function checkLineageTotalCap(
1038
+ lineage,
1039
+ incomingBytes,
1040
+ {
1041
+ maxTotalBytes = MAX_TOTAL_LINEAGE_BYTES,
1042
+ listingStore = null,
1043
+ heartbeatStore = null,
1044
+ lineageStore = null,
1045
+ excludeKind = null,
1046
+ excludeEventDigest = null,
1047
+ } = {},
1048
+ ) {
1049
+ const existing = computeStoredLineageBytes(lineage, {
1050
+ listingStore,
1051
+ heartbeatStore,
1052
+ lineageStore,
1053
+ excludeKind,
1054
+ excludeEventDigest,
1055
+ });
1056
+ if (existing + incomingBytes > maxTotalBytes) {
1057
+ return { ok: false, status: 413, reason: "lineage-cap-exceeded" }; // @rule sybil.lineage-total-1mib-cap
1058
+ }
1059
+ return { ok: true, totalBytes: existing + incomingBytes };
1060
+ }
1061
+
1062
+ function sanitizeExportListing(obj) {
1063
+ if (!isPlainObject(obj)) return null;
1064
+ if (obj.type === DIRECTORY_LISTING_TYPE || Object.hasOwn(obj, "aud")) return null; // @rule fed.changes-no-aud-listing
1065
+ if (obj.v !== LISTING_VERSION) return null; // @rule fed.changes-listing-version
1066
+ const copy = { ...obj };
1067
+ delete copy.status; // @rule fed.changes-no-status-verdict
1068
+ delete copy.verdict;
1069
+ delete copy.lineageVerdict;
1070
+ delete copy.lastSeen;
1071
+ delete copy.receivedAt;
1072
+ return copy;
1073
+ }
1074
+
1075
+ function sanitizeExportHeartbeat(obj) {
1076
+ if (!isPlainObject(obj) || obj.v !== HEARTBEAT_VERSION) return null; // @rule fed.changes-hb-version
1077
+ const copy = { ...obj };
1078
+ delete copy.status;
1079
+ delete copy.verdict;
1080
+ delete copy.receivedAt;
1081
+ return copy;
1082
+ }
1083
+
1084
+ function sanitizeExportLineageEvent(obj) {
1085
+ if (!isPlainObject(obj) || obj.v !== LINEAGE_VERSION) return null; // @rule fed.changes-lineage-version
1086
+ const copy = { ...obj };
1087
+ delete copy.status;
1088
+ delete copy.verdict;
1089
+ delete copy.lineageVerdict;
1090
+ return copy;
1091
+ }
1092
+
1093
+ export class FederationStore {
1094
+ /**
1095
+ * @param {object} opts
1096
+ * db optional shared SQLite or PureJsRegistryDb instance
1097
+ * dbPath path if opening own DB
1098
+ * forcePureJs force pure-JS mode even when better-sqlite3 is installed
1099
+ * lineageStore optional LineageStore
1100
+ * listingStore optional ListingStore
1101
+ * heartbeatStore optional HeartbeatStore
1102
+ * negativeCache optional ResolveNegativeCache invalidated on local writes
1103
+ * maxStrikes strike threshold before peer quarantine (default 3)
1104
+ * quarantineCooldownMs quarantine duration in ms (default 3,600,000)
1105
+ * maxNewLineagesPerHour registry-wide new-lineage admission ceiling (default 600)
1106
+ * maxTotalLineageBytes per-lineage total stored state ceiling (default 1,048,576)
1107
+ */
1108
+ constructor({
1109
+ db = null,
1110
+ dbPath = ":memory:",
1111
+ forcePureJs = false,
1112
+ lineageStore = null,
1113
+ listingStore = null,
1114
+ heartbeatStore = null,
1115
+ negativeCache = null,
1116
+ maxStrikes = DEFAULT_MAX_STRIKES,
1117
+ quarantineCooldownMs = DEFAULT_QUARANTINE_COOLDOWN_MS,
1118
+ maxNewLineagesPerHour = DEFAULT_MAX_NEW_LINEAGES_PER_HOUR,
1119
+ maxTotalLineageBytes = MAX_TOTAL_LINEAGE_BYTES,
1120
+ } = {}) {
1121
+ this._ownsDb = !db;
1122
+ this.db = db ?? openRegistryDb(dbPath, { forcePureJs });
1123
+ this.mode = this.db._isPureJs || forcePureJs ? "pure-js" : "sqlite";
1124
+ this.lineageStore = lineageStore;
1125
+ this.listingStore = listingStore;
1126
+ this.heartbeatStore = heartbeatStore;
1127
+ this.negativeCache = negativeCache ?? new ResolveNegativeCache();
1128
+ this.maxStrikes = maxStrikes;
1129
+ this.quarantineCooldownMs = quarantineCooldownMs;
1130
+ this.maxNewLineagesPerHour = maxNewLineagesPerHour;
1131
+ this.maxTotalLineageBytes = maxTotalLineageBytes;
1132
+ this._unsubPureJs = null;
1133
+
1134
+ if (this.mode === "sqlite") {
1135
+ this._initSqlite();
1136
+ } else {
1137
+ this._initPureJs(dbPath);
1138
+ }
1139
+ this._backfillExistingRecords();
1140
+ }
1141
+
1142
+ _initSqlite() {
1143
+ this.db.exec(`
1144
+ create table if not exists peer_cursor (
1145
+ peer_url text primary key,
1146
+ peer_uuaid text,
1147
+ cursor text not null default '0',
1148
+ deferred_since text,
1149
+ updated_at text not null
1150
+ );
1151
+
1152
+ create table if not exists peer_strikes (
1153
+ id integer primary key autoincrement,
1154
+ peer_url text not null,
1155
+ object_type text not null,
1156
+ reason text not null,
1157
+ digest text not null,
1158
+ created_at text not null,
1159
+ created_at_ms integer not null,
1160
+ reset integer not null default 0
1161
+ );
1162
+ create index if not exists idx_peer_strikes_peer on peer_strikes(peer_url, reset, created_at_ms);
1163
+
1164
+ create table if not exists lineage_admissions (
1165
+ lineage text primary key,
1166
+ admitted_at text not null,
1167
+ admitted_at_ms integer not null,
1168
+ source text not null
1169
+ );
1170
+ create index if not exists idx_lineage_admissions_ms on lineage_admissions(admitted_at_ms);
1171
+
1172
+ create table if not exists federation_changes (
1173
+ change_seq integer primary key autoincrement,
1174
+ kind text not null,
1175
+ item_key text not null,
1176
+ lineage text not null,
1177
+ digest text,
1178
+ updated_at text not null,
1179
+ raw_json text,
1180
+ unique (kind, item_key)
1181
+ );
1182
+ create index if not exists idx_federation_changes_seq on federation_changes(change_seq);
1183
+
1184
+ create table if not exists listing_origins (
1185
+ lineage text primary key,
1186
+ origin_uuaid text not null,
1187
+ updated_at text not null
1188
+ );
1189
+ `);
1190
+
1191
+ this._installSqliteTriggers();
1192
+ }
1193
+
1194
+ _installSqliteTriggers() {
1195
+ if (this.mode !== "sqlite") return;
1196
+ const hasTable = (name) =>
1197
+ Boolean(this.db.prepare("select 1 from sqlite_master where type = 'table' and name = ?").get(name));
1198
+
1199
+ if (hasTable("lineage_event")) {
1200
+ this.db.exec(`
1201
+ create trigger if not exists trg_fed_lineage_ins after insert on lineage_event when new.complete = 1 begin
1202
+ delete from federation_changes where kind = 'lineage' and item_key = (new.lineage || ':' || new.digest);
1203
+ insert into federation_changes (kind, item_key, lineage, digest, updated_at)
1204
+ values ('lineage', new.lineage || ':' || new.digest, new.lineage, new.digest, new.received_at);
1205
+ end;
1206
+ create trigger if not exists trg_fed_lineage_upd after update on lineage_event when new.complete = 1 begin
1207
+ delete from federation_changes where kind = 'lineage' and item_key = (new.lineage || ':' || new.digest);
1208
+ insert into federation_changes (kind, item_key, lineage, digest, updated_at)
1209
+ values ('lineage', new.lineage || ':' || new.digest, new.lineage, new.digest, new.received_at);
1210
+ end;
1211
+ create trigger if not exists trg_fed_lineage_del after delete on lineage_event begin
1212
+ delete from federation_changes where kind = 'lineage' and item_key = (old.lineage || ':' || old.digest);
1213
+ end;
1214
+ `);
1215
+ }
1216
+ if (hasTable("listing")) {
1217
+ this.db.exec(`
1218
+ create trigger if not exists trg_fed_listing_ins after insert on listing begin
1219
+ delete from federation_changes where kind = 'listing' and item_key = new.lineage;
1220
+ insert into federation_changes (kind, item_key, lineage, digest, updated_at)
1221
+ values ('listing', new.lineage, new.lineage, null, new.received_at);
1222
+ end;
1223
+ create trigger if not exists trg_fed_listing_upd after update on listing begin
1224
+ delete from federation_changes where kind = 'listing' and item_key = new.lineage;
1225
+ insert into federation_changes (kind, item_key, lineage, digest, updated_at)
1226
+ values ('listing', new.lineage, new.lineage, null, new.received_at);
1227
+ end;
1228
+ create trigger if not exists trg_fed_listing_del after delete on listing begin
1229
+ delete from federation_changes where kind = 'listing' and item_key = old.lineage;
1230
+ end;
1231
+ `);
1232
+ }
1233
+ if (hasTable("heartbeat_latest")) {
1234
+ this.db.exec(`
1235
+ create trigger if not exists trg_fed_hb_ins after insert on heartbeat_latest begin
1236
+ delete from federation_changes where kind = 'heartbeat' and item_key = new.lineage;
1237
+ insert into federation_changes (kind, item_key, lineage, digest, updated_at)
1238
+ values ('heartbeat', new.lineage, new.lineage, null, new.received_at);
1239
+ end;
1240
+ create trigger if not exists trg_fed_hb_upd after update on heartbeat_latest begin
1241
+ delete from federation_changes where kind = 'heartbeat' and item_key = new.lineage;
1242
+ insert into federation_changes (kind, item_key, lineage, digest, updated_at)
1243
+ values ('heartbeat', new.lineage, new.lineage, null, new.received_at);
1244
+ end;
1245
+ create trigger if not exists trg_fed_hb_del after delete on heartbeat_latest begin
1246
+ delete from federation_changes where kind = 'heartbeat' and item_key = old.lineage;
1247
+ end;
1248
+ `);
1249
+ }
1250
+ }
1251
+
1252
+ _initPureJs(dbPath) {
1253
+ this._purePath = typeof dbPath === "string" && dbPath !== ":memory:" ? `${dbPath}.fed.json` : null;
1254
+ this._mem = {
1255
+ nextChangeSeq: 1,
1256
+ nextStrikeId: 1,
1257
+ peer_cursor: new Map(), // peerUrl -> { peer_url, peer_uuaid, cursor, deferred_since, updated_at }
1258
+ peer_strikes: [], // [{ id, peer_url, object_type, reason, digest, created_at, created_at_ms, reset }]
1259
+ lineage_admissions: new Map(), // lineage -> { lineage, admitted_at, admitted_at_ms, source }
1260
+ listing_origins: new Map(), // lineage -> { lineage, origin_uuaid, updated_at }
1261
+ federation_changes: [], // [{ change_seq, kind, item_key, lineage, digest, updated_at, raw_json }]
1262
+ };
1263
+ if (this._purePath && existsSync(this._purePath)) {
1264
+ try {
1265
+ const parsed = JSON.parse(readFileSync(this._purePath, "utf8"));
1266
+ this._mem.nextChangeSeq = parsed.nextChangeSeq ?? 1;
1267
+ this._mem.nextStrikeId = parsed.nextStrikeId ?? 1;
1268
+ this._mem.peer_cursor = new Map(parsed.peer_cursor ?? []);
1269
+ this._mem.peer_strikes = parsed.peer_strikes ?? [];
1270
+ this._mem.lineage_admissions = new Map(parsed.lineage_admissions ?? []);
1271
+ this._mem.listing_origins = new Map(parsed.listing_origins ?? []);
1272
+ this._mem.federation_changes = parsed.federation_changes ?? [];
1273
+ } catch {}
1274
+ }
1275
+ if (this.db._isPureJs && typeof this.db.onMutation === "function") {
1276
+ this._unsubPureJs = this.db.onMutation((action, kind, itemKey, lineage, digest, updatedAt) => {
1277
+ if (action === "delete") {
1278
+ if (kind === "listing") this.clearListingOrigin(lineage);
1279
+ this.removeChange(kind, itemKey);
1280
+ } else {
1281
+ this.recordChange(kind, itemKey, lineage, digest, updatedAt ?? nowIso());
1282
+ }
1283
+ });
1284
+ }
1285
+ }
1286
+
1287
+ _flushPureJs() {
1288
+ if (this.mode !== "pure-js" || !this._purePath) return;
1289
+ mkdirSync(dirname(this._purePath), { recursive: true });
1290
+ const tmp = `${this._purePath}.tmp`;
1291
+ writeFileSync(
1292
+ tmp,
1293
+ JSON.stringify({
1294
+ nextChangeSeq: this._mem.nextChangeSeq,
1295
+ nextStrikeId: this._mem.nextStrikeId,
1296
+ peer_cursor: [...this._mem.peer_cursor.entries()],
1297
+ peer_strikes: this._mem.peer_strikes,
1298
+ lineage_admissions: [...this._mem.lineage_admissions.entries()],
1299
+ listing_origins: [...this._mem.listing_origins.entries()],
1300
+ federation_changes: this._mem.federation_changes,
1301
+ }),
1302
+ );
1303
+ renameSync(tmp, this._purePath);
1304
+ }
1305
+
1306
+ _backfillExistingRecords() {
1307
+ if (this.mode === "sqlite") {
1308
+ const hasTable = (name) =>
1309
+ Boolean(this.db.prepare("select 1 from sqlite_master where type = 'table' and name = ?").get(name));
1310
+ const existsChange = this.db.prepare("select 1 from federation_changes where kind = ? and item_key = ?");
1311
+ const insChange = this.db.prepare(
1312
+ "insert into federation_changes (kind, item_key, lineage, digest, updated_at) values (?, ?, ?, ?, ?)",
1313
+ );
1314
+ const insAdm = this.db.prepare(
1315
+ "insert or ignore into lineage_admissions (lineage, admitted_at, admitted_at_ms, source) values (?, ?, ?, 'backfill')",
1316
+ );
1317
+
1318
+ if (hasTable("lineage_event")) {
1319
+ const evRows = this.db
1320
+ .prepare("select lineage, digest, received_at from lineage_event where complete = 1 order by seq asc, received_at asc, digest asc")
1321
+ .all();
1322
+ for (const r of evRows) {
1323
+ const k = `${r.lineage}:${r.digest}`;
1324
+ if (!existsChange.get("lineage", k)) insChange.run("lineage", k, r.lineage, r.digest, r.received_at);
1325
+ }
1326
+ }
1327
+ if (hasTable("listing")) {
1328
+ const lRows = this.db.prepare("select lineage, received_at, first_seen_ms from listing order by first_seen_ms asc, lineage asc").all();
1329
+ for (const r of lRows) {
1330
+ if (!existsChange.get("listing", r.lineage)) insChange.run("listing", r.lineage, r.lineage, null, r.received_at);
1331
+ insAdm.run(r.lineage, r.received_at, r.first_seen_ms);
1332
+ }
1333
+ }
1334
+ if (hasTable("heartbeat_latest")) {
1335
+ const hbRows = this.db.prepare("select lineage, received_at from heartbeat_latest order by received_at_ms asc, lineage asc").all();
1336
+ for (const r of hbRows) {
1337
+ if (!existsChange.get("heartbeat", r.lineage)) insChange.run("heartbeat", r.lineage, r.lineage, null, r.received_at);
1338
+ }
1339
+ }
1340
+ } else if (this.db._isPureJs) {
1341
+ for (const r of [...this.db._tables.lineage_event.values()].filter((x) => x.complete === 1).sort((a, b) => a.seq - b.seq)) {
1342
+ const k = `${r.lineage}:${r.digest}`;
1343
+ if (!this._mem.federation_changes.some((c) => c.kind === "lineage" && c.item_key === k)) {
1344
+ this.recordChange("lineage", k, r.lineage, r.digest, r.received_at);
1345
+ }
1346
+ }
1347
+ for (const r of this.db._tables.listing.values()) {
1348
+ if (!this._mem.federation_changes.some((c) => c.kind === "listing" && c.item_key === r.lineage)) {
1349
+ this.recordChange("listing", r.lineage, r.lineage, null, r.received_at);
1350
+ }
1351
+ if (!this._mem.lineage_admissions.has(r.lineage)) {
1352
+ this._mem.lineage_admissions.set(r.lineage, {
1353
+ lineage: r.lineage,
1354
+ admitted_at: r.received_at,
1355
+ admitted_at_ms: r.first_seen_ms,
1356
+ source: "backfill",
1357
+ });
1358
+ }
1359
+ }
1360
+ for (const r of this.db._tables.heartbeat_latest.values()) {
1361
+ if (!this._mem.federation_changes.some((c) => c.kind === "heartbeat" && c.item_key === r.lineage)) {
1362
+ this.recordChange("heartbeat", r.lineage, r.lineage, null, r.received_at);
1363
+ }
1364
+ }
1365
+ }
1366
+ }
1367
+
1368
+ close() {
1369
+ this._unsubPureJs?.();
1370
+ if (this._ownsDb && this.db?.open) this.db.close();
1371
+ }
1372
+
1373
+ setStores({ lineageStore, listingStore, heartbeatStore } = {}) {
1374
+ if (lineageStore !== undefined) this.lineageStore = lineageStore;
1375
+ if (listingStore !== undefined) this.listingStore = listingStore;
1376
+ if (heartbeatStore !== undefined) this.heartbeatStore = heartbeatStore;
1377
+ this._installSqliteTriggers();
1378
+ this._backfillExistingRecords();
1379
+ }
1380
+
1381
+ notifyLocalIngest(...uuaids) {
1382
+ this.negativeCache.invalidate(...uuaids);
1383
+ }
1384
+
1385
+ recordChange(kind, itemKey, lineage, digest = null, updatedAt = nowIso(), rawJson = null) {
1386
+ if (this.mode === "sqlite") {
1387
+ const tx = this.db.transaction(() => {
1388
+ this.db.prepare("delete from federation_changes where kind = ? and item_key = ?").run(kind, itemKey);
1389
+ this.db
1390
+ .prepare("insert into federation_changes (kind, item_key, lineage, digest, updated_at, raw_json) values (?, ?, ?, ?, ?, ?)")
1391
+ .run(kind, itemKey, lineage, digest, updatedAt, rawJson);
1392
+ });
1393
+ tx();
1394
+ } else {
1395
+ this._mem.federation_changes = this._mem.federation_changes.filter((c) => !(c.kind === kind && c.item_key === itemKey));
1396
+ this._mem.federation_changes.push({
1397
+ change_seq: this._mem.nextChangeSeq++,
1398
+ kind,
1399
+ item_key: itemKey,
1400
+ lineage,
1401
+ digest,
1402
+ updated_at: updatedAt,
1403
+ raw_json: rawJson,
1404
+ });
1405
+ this._flushPureJs();
1406
+ }
1407
+ }
1408
+
1409
+ removeChange(kind, itemKey) {
1410
+ if (this.mode === "sqlite") {
1411
+ this.db.prepare("delete from federation_changes where kind = ? and item_key = ?").run(kind, itemKey);
1412
+ } else {
1413
+ this._mem.federation_changes = this._mem.federation_changes.filter((c) => !(c.kind === kind && c.item_key === itemKey));
1414
+ this._flushPureJs();
1415
+ }
1416
+ }
1417
+
1418
+ setListingOrigin(lineage, originUuaid, { now } = {}) {
1419
+ if (typeof lineage !== "string" || !UUAID_RE.test(lineage)) return;
1420
+ if (typeof originUuaid !== "string" || !UUAID_RE.test(originUuaid)) return;
1421
+ const updatedAt = nowIso(now);
1422
+ if (this.mode === "sqlite") {
1423
+ this.db
1424
+ .prepare(`
1425
+ insert into listing_origins (lineage, origin_uuaid, updated_at)
1426
+ values (?, ?, ?)
1427
+ on conflict(lineage) do update set origin_uuaid = excluded.origin_uuaid, updated_at = excluded.updated_at
1428
+ `)
1429
+ .run(lineage, originUuaid, updatedAt);
1430
+ } else {
1431
+ this._mem.listing_origins.set(lineage, { lineage, origin_uuaid: originUuaid, updated_at: updatedAt });
1432
+ this._flushPureJs();
1433
+ }
1434
+ }
1435
+
1436
+ getListingOrigin(lineage) {
1437
+ if (typeof lineage !== "string" || !UUAID_RE.test(lineage)) return null;
1438
+ if (this.mode === "sqlite") {
1439
+ return this.db.prepare("select origin_uuaid from listing_origins where lineage = ?").get(lineage)?.origin_uuaid ?? null;
1440
+ }
1441
+ return this._mem.listing_origins.get(lineage)?.origin_uuaid ?? null;
1442
+ }
1443
+
1444
+ clearListingOrigin(lineage) {
1445
+ if (typeof lineage !== "string") return;
1446
+ if (this.mode === "sqlite") {
1447
+ this.db.prepare("delete from listing_origins where lineage = ?").run(lineage);
1448
+ } else if (this._mem.listing_origins.delete(lineage)) {
1449
+ this._flushPureJs();
1450
+ }
1451
+ }
1452
+
1453
+ setStampRegistry(lineage, originUuaid, opts) {
1454
+ return this.setListingOrigin(lineage, originUuaid, opts);
1455
+ }
1456
+
1457
+ getStampRegistry(lineage) {
1458
+ return this.getListingOrigin(lineage);
1459
+ }
1460
+
1461
+ clearStampRegistry(lineage) {
1462
+ return this.clearListingOrigin(lineage);
1463
+ }
1464
+
1465
+ /**
1466
+ * Inject a raw item (`listing`, `heartbeat`, or `lineage` object) directly into the
1467
+ * outbound `/v1/federation/changes` feed (used by `T3.2` adversarial peer-poisoning tests).
1468
+ */
1469
+ injectRawChange(kind, obj, { now } = {}) {
1470
+ const updatedAt = nowIso(now);
1471
+ const lineage = typeof obj?.lineage === "string" ? obj.lineage : `injected-${Date.now()}`;
1472
+ const digest = kind === "lineage" ? objectDigestHex(obj) : null;
1473
+ const itemKey = kind === "lineage" ? `${lineage}:${digest}` : `${lineage}:${objectDigestHex(obj)}`;
1474
+ this.recordChange(kind, itemKey, lineage, digest, updatedAt, JSON.stringify(obj));
1475
+ }
1476
+
1477
+ _loadChangePayload(row) {
1478
+ if (typeof row.raw_json === "string" && row.raw_json.length > 0) {
1479
+ try {
1480
+ const rawObj = JSON.parse(row.raw_json);
1481
+ if (row.kind === "listing") return sanitizeExportListing(rawObj);
1482
+ if (row.kind === "heartbeat") return sanitizeExportHeartbeat(rawObj);
1483
+ if (row.kind === "lineage") return sanitizeExportLineageEvent(rawObj);
1484
+ } catch {
1485
+ return null;
1486
+ }
1487
+ }
1488
+ if (row.kind === "listing") {
1489
+ let lJson = null;
1490
+ if (this.listingStore) {
1491
+ lJson = this.listingStore.getByLineage(row.lineage)?.listing_json ?? null;
1492
+ } else if (this.mode === "sqlite") {
1493
+ lJson = this.db.prepare("select listing_json from listing where lineage = ?").get(row.lineage)?.listing_json ?? null;
1494
+ }
1495
+ if (!lJson) return null;
1496
+ return sanitizeExportListing(JSON.parse(lJson));
1497
+ }
1498
+ if (row.kind === "heartbeat") {
1499
+ let hbJson = null;
1500
+ if (this.heartbeatStore) {
1501
+ hbJson = this.heartbeatStore.getLatest(row.lineage)?.heartbeat_json ?? null;
1502
+ } else if (this.mode === "sqlite") {
1503
+ hbJson = this.db.prepare("select heartbeat_json from heartbeat_latest where lineage = ?").get(row.lineage)?.heartbeat_json ?? null;
1504
+ }
1505
+ if (!hbJson) return null;
1506
+ return sanitizeExportHeartbeat(JSON.parse(hbJson));
1507
+ }
1508
+ if (row.kind === "lineage") {
1509
+ let evJson = null;
1510
+ if (this.lineageStore) {
1511
+ const match = this.lineageStore.getRows(row.lineage).find((r) => r.digest === row.digest);
1512
+ evJson = match?.event_json ?? null;
1513
+ } else if (this.mode === "sqlite") {
1514
+ evJson = this.db
1515
+ .prepare("select event_json from lineage_event where lineage = ? and digest = ? and complete = 1")
1516
+ .get(row.lineage, row.digest)?.event_json ?? null;
1517
+ }
1518
+ if (!evJson) return null;
1519
+ return sanitizeExportLineageEvent(JSON.parse(evJson));
1520
+ }
1521
+ return null;
1522
+ }
1523
+
1524
+ /**
1525
+ * Build `GET /v1/federation/changes?since=<cursor>&limit=500` response.
1526
+ * Clamps `limit` to `1..500` (default `500`), ordered by monotonic `change_seq`.
1527
+ */
1528
+ getChanges({ registryUuaid, since = "0", limit = DEFAULT_CHANGES_LIMIT } = {}) {
1529
+ const sinceStr = since === undefined || since === null || since === "" ? "0" : String(since);
1530
+ if (!CURSOR_RE.test(sinceStr)) return { ok: false, status: 400, reason: "bad-cursor" }; // @rule fed.changes-cursor-format
1531
+ const sinceSeq = Number(sinceStr);
1532
+ if (!Number.isSafeInteger(sinceSeq) || sinceSeq < 0) return { ok: false, status: 400, reason: "bad-cursor" };
1533
+
1534
+ let clampedLimit = DEFAULT_CHANGES_LIMIT;
1535
+ if (limit !== undefined && limit !== null && limit !== "") {
1536
+ const parsedLim = typeof limit === "number" ? limit : (/^-?\d+$/.test(String(limit)) ? Number(limit) : NaN);
1537
+ if (!Number.isFinite(parsedLim)) return { ok: false, status: 400, reason: "bad-limit" }; // @rule fed.changes-limit-numeric
1538
+ clampedLimit = Math.min(MAX_CHANGES_LIMIT, Math.max(MIN_CHANGES_LIMIT, Math.trunc(parsedLim))); // @rule fed.changes-limit-clamp
1539
+ }
1540
+
1541
+ const rows =
1542
+ this.mode === "sqlite"
1543
+ ? this.db.prepare("select * from federation_changes where change_seq > ? order by change_seq asc").all(sinceSeq)
1544
+ : this._mem.federation_changes.filter((r) => r.change_seq > sinceSeq).sort((a, b) => a.change_seq - b.change_seq);
1545
+
1546
+ const listings = [];
1547
+ const stampRegistries = {};
1548
+ const heartbeats = [];
1549
+ const lineageEvents = [];
1550
+ let nextSeq = sinceSeq;
1551
+ let exportedCount = 0;
1552
+ let hasMore = false;
1553
+
1554
+ for (let i = 0; i < rows.length; i++) {
1555
+ const row = rows[i];
1556
+ const payload = this._loadChangePayload(row);
1557
+ if (!payload) {
1558
+ if (exportedCount < clampedLimit) nextSeq = row.change_seq;
1559
+ continue;
1560
+ }
1561
+ if (exportedCount >= clampedLimit) {
1562
+ hasMore = true;
1563
+ break;
1564
+ }
1565
+ nextSeq = row.change_seq;
1566
+ exportedCount += 1;
1567
+ if (row.kind === "listing") {
1568
+ listings.push(payload);
1569
+ if (!row.raw_json && Object.hasOwn(payload, "stamp") && isValidPowStampShape(payload.stamp)) {
1570
+ let orig = this.getListingOrigin(payload.lineage);
1571
+ if (
1572
+ !orig &&
1573
+ typeof registryUuaid === "string" &&
1574
+ UUAID_RE.test(registryUuaid) &&
1575
+ isStrictDateTime(payload.issuedAt) &&
1576
+ verifyStamp(payload.stamp, payload.lineage, `${LISTING_VERSION}:${registryUuaid}`, {
1577
+ now: payload.issuedAt,
1578
+ requiredBits: this.listingStore?.requiredStampBits ?? DEFAULT_STAMP_BITS,
1579
+ }) === null
1580
+ ) {
1581
+ orig = registryUuaid;
1582
+ }
1583
+ if (orig) stampRegistries[payload.lineage] = orig;
1584
+ }
1585
+ } else if (row.kind === "heartbeat") heartbeats.push(payload);
1586
+ else if (row.kind === "lineage") lineageEvents.push(payload);
1587
+ }
1588
+
1589
+ return {
1590
+ ok: true,
1591
+ body: {
1592
+ v: FEDERATION_CHANGES_VERSION,
1593
+ registry: registryUuaid,
1594
+ since: String(sinceSeq),
1595
+ nextCursor: String(nextSeq),
1596
+ hasMore,
1597
+ listings,
1598
+ ...(Object.keys(stampRegistries).length > 0 ? { stampRegistries } : {}),
1599
+ heartbeats,
1600
+ lineageEvents,
1601
+ },
1602
+ };
1603
+ }
1604
+
1605
+ // ---- Peer cursors ----
1606
+
1607
+ getPeerCursor(peerUrl) {
1608
+ if (this.mode === "sqlite") {
1609
+ const row = this.db.prepare("select * from peer_cursor where peer_url = ?").get(peerUrl);
1610
+ return row
1611
+ ? { peerUrl: row.peer_url, peerUuaid: row.peer_uuaid ?? null, cursor: row.cursor, deferredSince: row.deferred_since ?? null, updatedAt: row.updated_at }
1612
+ : { peerUrl, peerUuaid: null, cursor: "0", deferredSince: null, updatedAt: null };
1613
+ }
1614
+ const row = this._mem.peer_cursor.get(peerUrl);
1615
+ return row
1616
+ ? { peerUrl: row.peer_url, peerUuaid: row.peer_uuaid ?? null, cursor: row.cursor, deferredSince: row.deferred_since ?? null, updatedAt: row.updated_at }
1617
+ : { peerUrl, peerUuaid: null, cursor: "0", deferredSince: null, updatedAt: null };
1618
+ }
1619
+
1620
+ setPeerCursor(peerUrl, { cursor, deferredSince = null, peerUuaid = null, now } = {}) {
1621
+ const updatedAt = nowIso(now);
1622
+ const cur = this.getPeerCursor(peerUrl);
1623
+ const nextCursor = cursor !== undefined ? String(cursor) : cur.cursor;
1624
+ const nextDeferred = deferredSince !== undefined ? deferredSince : cur.deferredSince;
1625
+ const nextUuaid = peerUuaid ?? cur.peerUuaid;
1626
+
1627
+ if (this.mode === "sqlite") {
1628
+ this.db
1629
+ .prepare(`
1630
+ insert into peer_cursor (peer_url, peer_uuaid, cursor, deferred_since, updated_at)
1631
+ values (?, ?, ?, ?, ?)
1632
+ on conflict(peer_url) do update set
1633
+ peer_uuaid = excluded.peer_uuaid,
1634
+ cursor = excluded.cursor,
1635
+ deferred_since = excluded.deferred_since,
1636
+ updated_at = excluded.updated_at
1637
+ `)
1638
+ .run(peerUrl, nextUuaid, nextCursor, nextDeferred, updatedAt);
1639
+ } else {
1640
+ this._mem.peer_cursor.set(peerUrl, {
1641
+ peer_url: peerUrl,
1642
+ peer_uuaid: nextUuaid,
1643
+ cursor: nextCursor,
1644
+ deferred_since: nextDeferred,
1645
+ updated_at: updatedAt,
1646
+ });
1647
+ this._flushPureJs();
1648
+ }
1649
+ }
1650
+
1651
+ // ---- Peer-integrity strikes & quarantine (`T3.2`) ----
1652
+
1653
+ recordStrike({ peerUrl, objectType, reason, digest, now } = {}) {
1654
+ const createdAt = nowIso(now);
1655
+ const createdAtMs = Date.parse(createdAt);
1656
+ const safeDigest = typeof digest === "string" && digest.length > 0 ? digest : sha256Utf8(`${objectType}:${reason}`);
1657
+ if (this.mode === "sqlite") {
1658
+ const insStrike = this.db.prepare(
1659
+ "insert into peer_strikes (peer_url, object_type, reason, digest, created_at, created_at_ms, reset) values (?, ?, ?, ?, ?, ?, 0)",
1660
+ );
1661
+ insStrike.run(peerUrl, objectType, reason, safeDigest, createdAt, createdAtMs); // @rule fed.strike-recorded
1662
+ } else {
1663
+ this._mem.peer_strikes.push({
1664
+ id: this._mem.nextStrikeId++,
1665
+ peer_url: peerUrl,
1666
+ object_type: objectType,
1667
+ reason,
1668
+ digest: safeDigest,
1669
+ created_at: createdAt,
1670
+ created_at_ms: createdAtMs,
1671
+ reset: 0,
1672
+ });
1673
+ this._flushPureJs();
1674
+ }
1675
+ return {
1676
+ peerUrl,
1677
+ objectType,
1678
+ reason,
1679
+ digest: safeDigest,
1680
+ createdAt,
1681
+ quarantined: this.isQuarantined(peerUrl, { now: createdAt }),
1682
+ };
1683
+ }
1684
+
1685
+ getStrikes(peerUrl = null, { activeOnly = false, now } = {}) {
1686
+ const nowMs = Date.parse(nowIso(now));
1687
+ const cutoff = nowMs - this.quarantineCooldownMs;
1688
+ const raw =
1689
+ this.mode === "sqlite"
1690
+ ? peerUrl
1691
+ ? this.db.prepare("select * from peer_strikes where peer_url = ? order by id asc").all(peerUrl)
1692
+ : this.db.prepare("select * from peer_strikes order by id asc").all()
1693
+ : this._mem.peer_strikes.filter((r) => !peerUrl || r.peer_url === peerUrl);
1694
+
1695
+ return raw
1696
+ .filter((r) => !activeOnly || (r.reset === 0 && r.created_at_ms > cutoff))
1697
+ .map((r) => ({
1698
+ id: r.id,
1699
+ peerUrl: r.peer_url,
1700
+ objectType: r.object_type,
1701
+ reason: r.reason,
1702
+ digest: r.digest,
1703
+ createdAt: r.created_at,
1704
+ reset: Boolean(r.reset),
1705
+ }));
1706
+ }
1707
+
1708
+ activeStrikeCount(peerUrl, { now } = {}) {
1709
+ return this.getStrikes(peerUrl, { activeOnly: true, now }).length;
1710
+ }
1711
+
1712
+ isQuarantined(peerUrl, { now } = {}) {
1713
+ if (this.maxStrikes <= 0) return true;
1714
+ const count = this.activeStrikeCount(peerUrl, { now });
1715
+ return count >= this.maxStrikes; // @rule fed.quarantine-threshold
1716
+ }
1717
+
1718
+ resetPeerQuarantine(peerUrl) {
1719
+ if (this.mode === "sqlite") {
1720
+ this.db.prepare("update peer_strikes set reset = 1 where peer_url = ? and reset = 0").run(peerUrl); // @rule fed.quarantine-operator-reset
1721
+ } else {
1722
+ for (const s of this._mem.peer_strikes) {
1723
+ if (s.peer_url === peerUrl) s.reset = 1;
1724
+ }
1725
+ this._flushPureJs();
1726
+ }
1727
+ }
1728
+
1729
+ // ---- Shared 600/hour Sybil admission cap (`T3.4`) ----
1730
+
1731
+ hasAdmittedLineage(lineage) {
1732
+ if (this.mode === "sqlite") {
1733
+ if (this.db.prepare("select 1 from lineage_admissions where lineage = ?").get(lineage)) return true;
1734
+ } else if (this._mem.lineage_admissions.has(lineage)) {
1735
+ return true;
1736
+ }
1737
+ if (this.listingStore && this.listingStore.getByLineage(lineage)) return true;
1738
+ return false;
1739
+ }
1740
+
1741
+ countRecentAdmissions({ now } = {}) {
1742
+ const nowMs = Date.parse(nowIso(now));
1743
+ const cutoff = nowMs - 3_600_000;
1744
+ if (this.mode === "sqlite") {
1745
+ return this.db.prepare("select count(*) as n from lineage_admissions where admitted_at_ms > ?").get(cutoff).n;
1746
+ }
1747
+ let n = 0;
1748
+ for (const r of this._mem.lineage_admissions.values()) {
1749
+ if (r.admitted_at_ms > cutoff) n += 1;
1750
+ }
1751
+ return n;
1752
+ }
1753
+
1754
+ remainingAdmissionCapacity({ now } = {}) {
1755
+ return Math.max(0, this.maxNewLineagesPerHour - this.countRecentAdmissions({ now }));
1756
+ }
1757
+
1758
+ /**
1759
+ * Attempt to admit `lineage` against the registry-wide `600/hour` Sybil ceiling.
1760
+ * Existing admitted lineages always succeed without consuming a new slot.
1761
+ */
1762
+ tryAdmitLineage(lineage, { now, source = "direct" } = {}) {
1763
+ if (this.hasAdmittedLineage(lineage)) return { ok: true, alreadyAdmitted: true };
1764
+ const admittedAt = nowIso(now);
1765
+ const admittedAtMs = Date.parse(admittedAt);
1766
+ const recent = this.countRecentAdmissions({ now: admittedAt });
1767
+ if (recent >= this.maxNewLineagesPerHour) {
1768
+ return { ok: false, status: 429, reason: "rate-limited" }; // @rule sybil.admission-600-per-hour
1769
+ }
1770
+ if (this.mode === "sqlite") {
1771
+ this.db
1772
+ .prepare("insert or ignore into lineage_admissions (lineage, admitted_at, admitted_at_ms, source) values (?, ?, ?, ?)")
1773
+ .run(lineage, admittedAt, admittedAtMs, source);
1774
+ } else {
1775
+ this._mem.lineage_admissions.set(lineage, {
1776
+ lineage,
1777
+ admitted_at: admittedAt,
1778
+ admitted_at_ms: admittedAtMs,
1779
+ source,
1780
+ });
1781
+ this._flushPureJs();
1782
+ }
1783
+ return { ok: true, alreadyAdmitted: false };
1784
+ }
1785
+ }
1786
+
1787
+ // ---------------------------------------------------------------------------
1788
+ // Local Re-Verification Helpers (`I-5`)
1789
+ // ---------------------------------------------------------------------------
1790
+
1791
+ function collectLineageUuaidsFromEvent(ev) {
1792
+ const out = [];
1793
+ if (typeof ev?.lineage === "string") out.push(ev.lineage);
1794
+ if (typeof ev?.key?.uuaid === "string") out.push(ev.key.uuaid);
1795
+ if (typeof ev?.reveal?.uuaid === "string") out.push(ev.reveal.uuaid);
1796
+ if (typeof ev?.door?.uuaid === "string") out.push(ev.door.uuaid);
1797
+ if (Array.isArray(ev?.doors)) {
1798
+ for (const d of ev.doors) if (typeof d?.uuaid === "string") out.push(d.uuaid);
1799
+ }
1800
+ return out;
1801
+ }
1802
+
1803
+ function collectListingUuaids(listing) {
1804
+ const out = [];
1805
+ if (typeof listing?.lineage === "string") out.push(listing.lineage);
1806
+ if (typeof listing?.uuaid === "string") out.push(listing.uuaid);
1807
+ if (Array.isArray(listing?.card?.doors)) {
1808
+ for (const d of listing.card.doors) if (typeof d?.uuaid === "string") out.push(d.uuaid);
1809
+ }
1810
+ return out;
1811
+ }
1812
+
1813
+ /**
1814
+ * Verify a candidate `uuaid-lineage/1` event locally via `verifyLineageFull` before storing (`I-5`).
1815
+ * Returns `{ ok: true, digest, byteLen }` or `{ ok: false, reason, timingHold? }`.
1816
+ */
1817
+ export function verifyPulledLineageEvent(ev, lineageStore, { now } = {}) {
1818
+ const nowStr = nowIso(now);
1819
+ const nowMs = Date.parse(nowStr);
1820
+
1821
+ if (!isPlainObject(ev)) return { ok: false, reason: "malformed-artifact" }; // @rule fed.ver-ev-plain
1822
+ if (ev.v !== LINEAGE_VERSION) return { ok: false, reason: "unsupported-version" };
1823
+ if (typeof ev.lineage !== "string" || !UUAID_RE.test(ev.lineage)) return { ok: false, reason: "bad-uuaid" }; // @rule fed.ver-ev-uuaid
1824
+ if (!Number.isInteger(ev.seq) || ev.seq < 0) return { ok: false, reason: "bad-seq" };
1825
+ if (!isStrictDateTime(ev.ts)) return { ok: false, reason: "bad-ts" };
1826
+ if (Date.parse(ev.ts) > nowMs + LINEAGE_SKEW_MS && !(ev.seq > 0 && RECOVERY_EVENT_TYPES.has(ev.type))) {
1827
+ return { ok: false, reason: "future-ts" };
1828
+ }
1829
+ if (!sigsShapeOk(ev.sigs)) return { ok: false, reason: "bad-signature" }; // @rule fed.ver-ev-sigs-shape
1830
+ const fieldErr = checkEventTypeFields(ev);
1831
+ if (fieldErr) return { ok: false, reason: fieldErr }; // @rule fed.ver-ev-closed-fields
1832
+
1833
+ let digest;
1834
+ try {
1835
+ jcs(ev);
1836
+ digest = eventDigest(ev);
1837
+ } catch {
1838
+ return { ok: false, reason: "malformed-artifact" };
1839
+ }
1840
+
1841
+ const storedRows = lineageStore ? lineageStore.getRows(ev.lineage) : [];
1842
+ const storedEvents = storedRows.map((r) => JSON.parse(r.event_json));
1843
+ const storedReceipts = lineageStore ? lineageStore.getReceipts(ev.lineage) : [];
1844
+
1845
+ if (ev.type === "inception") {
1846
+ if (ev.seq !== 0 || ev.prev !== null) return { ok: false, reason: "prev-not-null" };
1847
+ } else {
1848
+ if (ev.seq <= 0 || typeof ev.prev !== "string" || !HEX64_RE.test(ev.prev)) return { ok: false, reason: "prev-mismatch" };
1849
+ if (!storedRows.some((r) => r.digest === ev.prev && r.seq === ev.seq - 1)) {
1850
+ return { ok: false, reason: "missing-prev" }; // @rule fed.ver-ev-missing-prev
1851
+ }
1852
+ }
1853
+
1854
+ const check = verifyLineageFull(
1855
+ { v: LINEAGE_LOG_VERSION, events: [...storedEvents, ev], receipts: storedReceipts },
1856
+ { now: nowStr, allowBind: true, ignoreRecoveryFutureTs: true },
1857
+ );
1858
+ if (!check._nodes.has(digest)) {
1859
+ const discReason = check.facts?.discarded?.find((x) => x.event === digest)?.reason;
1860
+ const reason = discReason ?? check.reasons[0] ?? "invalid-event";
1861
+ if (reason === "claim-unobserved" || reason === "final-not-yet-effective") {
1862
+ return { ok: false, reason, timingHold: true };
1863
+ }
1864
+ return { ok: false, reason }; // @rule fed.ver-ev-full-tree
1865
+ }
1866
+
1867
+ const byteLen = Buffer.byteLength(JSON.stringify(ev), "utf8");
1868
+ return { ok: true, digest, byteLen };
1869
+ }
1870
+
1871
+ function evaluateMergedLineageInMemory(pres, lineageStore, lineage, nowStr) {
1872
+ const byDigest = new Map();
1873
+ const existingReceipts = lineageStore ? lineageStore.getReceipts(lineage) : [];
1874
+ if (lineageStore) {
1875
+ for (const row of lineageStore.getRows(lineage)) {
1876
+ byDigest.set(row.digest, JSON.parse(row.event_json));
1877
+ }
1878
+ }
1879
+ for (const ev of pres.events) {
1880
+ byDigest.set(eventDigest(ev), ev);
1881
+ }
1882
+ const events = [...byDigest.values()].sort((a, b) => a.seq - b.seq || Date.parse(a.ts) - Date.parse(b.ts));
1883
+ const receipts = [...existingReceipts, ...(Array.isArray(pres.receipts) ? pres.receipts : [])].slice(0, 1024);
1884
+ const latestTs = events.reduce((acc, e) => (Date.parse(e.ts) > Date.parse(acc) ? e.ts : acc), events[0].ts);
1885
+ const lv = verifyLineageFull({ v: LINEAGE_LOG_VERSION, events, receipts }, { now: nowStr, allowBind: true });
1886
+ if (lv.verdict === "contested") {
1887
+ return { verdict: "contested", reasons: lv.reasons, events, receipts, current: null, head: undefined, latestTs, forked: true, tombstoned: false, raw: lv };
1888
+ }
1889
+ const tombstoned = Boolean(lv.facts?.tombstoned);
1890
+ const headDigest = typeof lv.facts?.head === "string" && lv.facts.head.startsWith("sha256:") ? lv.facts.head.slice(7) : null;
1891
+ const tombstoneTs = tombstoned && headDigest ? lv._nodes.get(headDigest)?.e?.ts : undefined;
1892
+ return {
1893
+ verdict: lv.verdict,
1894
+ reasons: lv.reasons,
1895
+ events,
1896
+ receipts,
1897
+ current: lv.facts?.current ?? null,
1898
+ head: lv.facts?.head,
1899
+ latestTs,
1900
+ forked: false,
1901
+ tombstoned,
1902
+ ...(tombstoneTs ? { tombstoneTs } : {}),
1903
+ raw: lv,
1904
+ };
1905
+ }
1906
+
1907
+ /**
1908
+ * Verify a candidate `pillar-listing/1` locally (`verifyArtifact` + current key match + `H-1` `future-ts`
1909
+ * + optional peer W-10 stamp verification) before storing (`I-5`).
1910
+ */
1911
+ export function verifyPulledListing(
1912
+ listing,
1913
+ {
1914
+ lineageStore = null,
1915
+ lineageEvalOverride = undefined,
1916
+ requiredStampBits = DEFAULT_STAMP_BITS,
1917
+ peerUuaid = null,
1918
+ originUuaid = null,
1919
+ stampRegistry = null,
1920
+ knownPeerUuaids = [],
1921
+ now,
1922
+ } = {},
1923
+ ) {
1924
+ const stampRegCandidate = stampRegistry ?? originUuaid ?? null;
1925
+ const nowStr = nowIso(now);
1926
+ const nowMs = Date.parse(nowStr);
1927
+
1928
+ if (!isPlainObject(listing)) return { ok: false, reason: "malformed-artifact" }; // @rule fed.ver-list-plain
1929
+ if (listing.type === DIRECTORY_LISTING_TYPE || Object.hasOwn(listing, "aud")) return { ok: false, reason: "aud-bound-listing" }; // @rule fed.ver-list-no-aud
1930
+ if (!Object.keys(listing).every((k) => LISTING_ALLOWED_KEYS.has(k))) return { ok: false, reason: "malformed-artifact" }; // @rule fed.ver-list-closed
1931
+ if (listing.v !== LISTING_VERSION) return { ok: false, reason: "bad-version" }; // @rule fed.ver-list-version
1932
+ if (typeof listing.lineage !== "string" || !UUAID_RE.test(listing.lineage)) return { ok: false, reason: "bad-uuaid" }; // @rule fed.ver-list-lineage
1933
+ if (typeof listing.uuaid !== "string" || !UUAID_RE.test(listing.uuaid)) return { ok: false, reason: "bad-uuaid" }; // @rule fed.ver-list-uuaid
1934
+ if (!isDenseArray(listing.homes) || listing.homes.length < 1 || listing.homes.length > 4 || !listing.homes.every(isStrictHttpsUrl)) {
1935
+ return { ok: false, reason: "bad-homes" }; // @rule fed.ver-list-homes
1936
+ }
1937
+ if (!isStrictDateTime(listing.issuedAt)) return { ok: false, reason: "bad-issued-at" }; // @rule fed.ver-list-issued-at
1938
+ if (Date.parse(listing.issuedAt) > nowMs + LINEAGE_SKEW_MS) return { ok: false, reason: "future-ts" }; // @rule fed.ver-list-future-ts
1939
+ if (typeof listing.sig !== "string" || !HEX128_RE.test(listing.sig)) return { ok: false, reason: "bad-signature" }; // @rule fed.ver-list-sig-hex
1940
+ if (Object.hasOwn(listing, "withdrawn") && typeof listing.withdrawn !== "boolean") return { ok: false, reason: "malformed-artifact" };
1941
+ if (listing.withdrawn === true && (!isDenseArray(listing.card?.does) || listing.card.does.length !== 0)) {
1942
+ return { ok: false, reason: "withdrawn-does-nonempty" }; // @rule fed.ver-list-withdrawn
1943
+ }
1944
+ if (!isPlainObject(listing.card)) return { ok: false, reason: "malformed-artifact" };
1945
+ if (listing.card.lineage !== listing.lineage) return { ok: false, reason: "card-lineage-mismatch" };
1946
+ if (listing.card.uuaid !== listing.uuaid) return { ok: false, reason: "card-uuaid-mismatch" };
1947
+
1948
+ let cardBytes;
1949
+ try {
1950
+ cardBytes = Buffer.byteLength(jcs(listing.card), "utf8");
1951
+ } catch {
1952
+ return { ok: false, reason: "malformed-artifact" };
1953
+ }
1954
+ if (cardBytes > CARD_MAX_BYTES) return { ok: false, reason: "card-too-large" };
1955
+
1956
+ if (Object.hasOwn(listing, "stamp") && !isValidPowStampShape(listing.stamp)) {
1957
+ return { ok: false, reason: "malformed-stamp" }; // @rule fed.ver-list-stamp-shape
1958
+ }
1959
+
1960
+ const lineageEval =
1961
+ lineageEvalOverride !== undefined ? lineageEvalOverride : lineageStore ? lineageStore.evaluateLineage(listing.lineage, { now: nowStr }) : null;
1962
+ if (lineageEval) {
1963
+ let expectedCurrent = lineageEval.current;
1964
+ let expectedHead = lineageEval.head;
1965
+ if (lineageEval.tombstoned === true) {
1966
+ const tombMs = lineageEval.tombstoneTs ? Date.parse(lineageEval.tombstoneTs) : -Infinity;
1967
+ if (Date.parse(listing.issuedAt) > tombMs) return { ok: false, reason: "lineage-tombstoned" }; // @rule fed.ver-list-after-tombstone
1968
+ const preEvents = lineageEval.events.slice(0, -1);
1969
+ if (!preEvents.length) return { ok: false, reason: "lineage-tombstoned" };
1970
+ const preEval = verifyLineageFull({ v: LINEAGE_LOG_VERSION, events: preEvents, receipts: lineageEval.receipts }, { now: nowStr, allowBind: true });
1971
+ if (!RESOLVED_VERDICTS.has(preEval.verdict)) return { ok: false, reason: preEval.reasons[0] ?? "card-lineage-unresolved" };
1972
+ expectedCurrent = preEval.facts?.current ?? null;
1973
+ expectedHead = preEval.facts?.head;
1974
+ } else if (!RESOLVED_VERDICTS.has(lineageEval.verdict)) {
1975
+ const linFailReason = lineageEval.verdict === "contested" ? "lineage-contested" : (lineageEval.reasons[0] ?? "card-lineage-unresolved");
1976
+ return { ok: false, reason: linFailReason }; // @rule fed.ver-list-lineage-resolved
1977
+ }
1978
+
1979
+ if (listing.uuaid !== expectedCurrent || listing.card.uuaid !== expectedCurrent) {
1980
+ return { ok: false, reason: "card-key-not-current" }; // @rule fed.ver-list-current-key
1981
+ }
1982
+ if (Object.hasOwn(listing.card, "lineageHead") && listing.card.lineageHead !== expectedHead) {
1983
+ return { ok: false, reason: "card-lineage-head-mismatch" }; // @rule fed.ver-list-head-match
1984
+ }
1985
+ const cardVer = verifyCard(listing.card, { now: nowStr });
1986
+ const cardOk =
1987
+ cardVer.verdict !== "invalid" &&
1988
+ isStrictEd25519PublicKey(listing.card.publicKey) &&
1989
+ isKeyDerivedUuaid(listing.card.uuaid, listing.card.publicKey) &&
1990
+ verifyLineageDoc(listing.card, listing.card.publicKey, listing.card.sig);
1991
+ const cardErrReason = cardVer.verdict === "invalid" ? (cardVer.reasons[0] ?? "invalid-card") : "bad-signature";
1992
+ if (!cardOk) return { ok: false, reason: cardErrReason }; // @rule fed.ver-list-card
1993
+ if (!verifyLineageDoc(listing, listing.card.publicKey, listing.sig)) return { ok: false, reason: "bad-signature" }; // @rule fed.ver-list-sig
1994
+ } else {
1995
+ const artVer = verifyArtifact(listing, { type: "listing", now: nowStr });
1996
+ if (artVer.verdict !== "valid") return { ok: false, reason: artVer.reasons[0] ?? "invalid-listing" }; // @rule fed.ver-list-artifact
1997
+ }
1998
+
1999
+ let matchedOrigin = null;
2000
+ if (Object.hasOwn(listing, "stamp")) {
2001
+ const candidatePeers = [...new Set([stampRegCandidate, peerUuaid, ...knownPeerUuaids].filter((u) => typeof u === "string" && UUAID_RE.test(u)))];
2002
+ let lastStampErr = "stamp-binding";
2003
+ for (const pUuaid of candidatePeers) {
2004
+ const err = verifyStamp(listing.stamp, listing.lineage, `${LISTING_VERSION}:${pUuaid}`, {
2005
+ now: listing.issuedAt,
2006
+ requiredBits: requiredStampBits,
2007
+ });
2008
+ if (err === null) {
2009
+ matchedOrigin = pUuaid;
2010
+ break;
2011
+ }
2012
+ lastStampErr = err;
2013
+ }
2014
+ if (!matchedOrigin) return { ok: false, reason: lastStampErr }; // @rule fed.ver-list-peer-stamp
2015
+ }
2016
+
2017
+ return { ok: true, byteLen: Buffer.byteLength(JSON.stringify(listing), "utf8"), matchedOrigin, stampRegistry: matchedOrigin };
2018
+ }
2019
+
2020
+ /**
2021
+ * Verify a candidate `pillar-heartbeat/1` locally (`verifyArtifact` + current key match + `H-1` `future-ts`)
2022
+ * before storing (`I-5`).
2023
+ */
2024
+ export function verifyPulledHeartbeat(
2025
+ hb,
2026
+ { lineageStore = null, listingStore = null, lineageEvalOverride = undefined, listingOverride = undefined, now } = {},
2027
+ ) {
2028
+ const nowStr = nowIso(now);
2029
+ const nowMs = Date.parse(nowStr);
2030
+
2031
+ if (!isPlainObject(hb) || !Object.keys(hb).every((k) => HEARTBEAT_ALLOWED_KEYS.has(k))) {
2032
+ return { ok: false, reason: "malformed-artifact" };
2033
+ }
2034
+ if (hb.v !== HEARTBEAT_VERSION) return { ok: false, reason: "bad-version" };
2035
+ if (typeof hb.lineage !== "string" || !UUAID_RE.test(hb.lineage)) return { ok: false, reason: "bad-uuaid" };
2036
+ if (typeof hb.uuaid !== "string" || !UUAID_RE.test(hb.uuaid)) return { ok: false, reason: "bad-uuaid" };
2037
+ if (!Number.isSafeInteger(hb.seq) || hb.seq < 0) return { ok: false, reason: "bad-seq" };
2038
+ if (!isStrictDateTime(hb.ts)) return { ok: false, reason: "bad-ts" };
2039
+ if (Date.parse(hb.ts) > nowMs + LINEAGE_SKEW_MS) return { ok: false, reason: "future-ts" }; // @rule fed.ver-hb-future-ts
2040
+ if (typeof hb.sig !== "string" || !HEX128_RE.test(hb.sig)) return { ok: false, reason: "bad-signature" };
2041
+
2042
+ const lineageEval =
2043
+ lineageEvalOverride !== undefined ? lineageEvalOverride : lineageStore ? lineageStore.evaluateLineage(hb.lineage, { now: nowStr }) : null;
2044
+ const listingRow =
2045
+ listingOverride !== undefined ? (listingOverride ? { listing: listingOverride } : null) : listingStore ? listingStore.getByLineage(hb.lineage) : null;
2046
+ if (!lineageEval && !listingRow) return { ok: false, reason: "not-found" }; // @rule fed.ver-hb-known-lineage
2047
+
2048
+ let pubKey = "";
2049
+ if (lineageEval) {
2050
+ if (lineageEval.tombstoned === true) {
2051
+ const tombMs = lineageEval.tombstoneTs ? Date.parse(lineageEval.tombstoneTs) : -Infinity;
2052
+ if (Date.parse(hb.ts) > tombMs) return { ok: false, reason: "lineage-tombstoned" };
2053
+ const preEvents = lineageEval.events.slice(0, -1);
2054
+ const preEval = preEvents.length
2055
+ ? verifyLineageFull({ v: LINEAGE_LOG_VERSION, events: preEvents, receipts: lineageEval.receipts }, { now: nowStr, allowBind: true })
2056
+ : null;
2057
+ const preCur = preEval && RESOLVED_VERDICTS.has(preEval.verdict) ? preEval.facts?.current : null;
2058
+ if (!preCur || hb.uuaid !== preCur) return { ok: false, reason: "card-key-not-current" };
2059
+ const keyEv = preEvents.find((e) => e?.key?.uuaid === hb.uuaid && typeof e.key.publicKey === "string");
2060
+ pubKey = keyEv?.key?.publicKey ?? "";
2061
+ const artVer = verifyArtifact(hb, { type: "heartbeat", now: nowStr, publicKey: pubKey });
2062
+ if (artVer.verdict !== "valid") return { ok: false, reason: artVer.reasons[0] ?? "bad-signature" };
2063
+ return { ok: true, skipTombstoned: true, byteLen: Buffer.byteLength(JSON.stringify(hb), "utf8") };
2064
+ }
2065
+ if (!RESOLVED_VERDICTS.has(lineageEval.verdict)) {
2066
+ return {
2067
+ ok: false,
2068
+ reason: lineageEval.verdict === "contested" ? "lineage-contested" : (lineageEval.reasons[0] ?? "card-lineage-unresolved"),
2069
+ };
2070
+ }
2071
+ if (hb.uuaid !== lineageEval.current) return { ok: false, reason: "card-key-not-current" }; // @rule fed.ver-hb-current-key
2072
+ const keyEv = lineageEval.events.find((e) => e?.key?.uuaid === hb.uuaid && typeof e.key.publicKey === "string");
2073
+ pubKey = keyEv?.key?.publicKey ?? (listingRow?.listing?.uuaid === hb.uuaid ? listingRow.listing.card?.publicKey ?? "" : "");
2074
+ } else {
2075
+ if (hb.uuaid !== listingRow.listing.uuaid) return { ok: false, reason: "card-key-not-current" }; // @rule fed.ver-hb-listing-key
2076
+ pubKey = listingRow.listing.card?.publicKey ?? "";
2077
+ }
2078
+
2079
+ const artVer = verifyArtifact(hb, { type: "heartbeat", now: nowStr, publicKey: pubKey });
2080
+ if (artVer.verdict !== "valid") return { ok: false, reason: artVer.reasons[0] ?? "bad-signature" }; // @rule fed.ver-hb-artifact
2081
+
2082
+ return { ok: true, byteLen: Buffer.byteLength(JSON.stringify(hb), "utf8") };
2083
+ }
2084
+
2085
+ /**
2086
+ * Verify a signed `pillar-federation/1` peer directory response.
2087
+ */
2088
+ export function verifyFederationPeersDoc(doc) {
2089
+ if (!isPlainObject(doc) || !Object.keys(doc).every((k) => FED_PEERS_KEYS.has(k))) {
2090
+ return { ok: false, reason: "malformed-federation-peers" }; // @rule fed.peers-closed
2091
+ }
2092
+ if (doc.v !== FEDERATION_PEERS_VERSION) return { ok: false, reason: "bad-version" }; // @rule fed.peers-version
2093
+ if (typeof doc.registry !== "string" || !UUAID_RE.test(doc.registry)) return { ok: false, reason: "bad-uuaid" }; // @rule fed.peers-registry-uuaid
2094
+ if (typeof doc.publicKey !== "string" || !HEX64_RE.test(doc.publicKey)) return { ok: false, reason: "bad-public-key" };
2095
+ if (!keyDerivesUuaid(doc.publicKey, doc.registry)) return { ok: false, reason: "key-uuaid-mismatch" }; // @rule fed.peers-key-binding
2096
+ if (!isStrictDateTime(doc.issuedAt)) return { ok: false, reason: "bad-issued-at" };
2097
+ if (!isDenseArray(doc.peers)) return { ok: false, reason: "bad-peers" };
2098
+ for (const p of doc.peers) {
2099
+ if (!isPlainObject(p) || !Object.keys(p).every((k) => FED_PEER_ITEM_KEYS.has(k))) {
2100
+ return { ok: false, reason: "bad-peer-entry" }; // @rule fed.peers-entry-closed
2101
+ }
2102
+ if (typeof p.url !== "string" || !isStrictHttpsUrl(p.url)) return { ok: false, reason: "bad-peer-url" };
2103
+ if (p.uuaid !== undefined && (typeof p.uuaid !== "string" || !UUAID_RE.test(p.uuaid))) return { ok: false, reason: "bad-peer-uuaid" };
2104
+ if (p.publicKey !== undefined) {
2105
+ if (typeof p.publicKey !== "string" || !HEX64_RE.test(p.publicKey) || !isStrictEd25519PublicKey(p.publicKey)) {
2106
+ return { ok: false, reason: "bad-peer-public-key" };
2107
+ }
2108
+ if (p.uuaid && !keyDerivesUuaid(p.publicKey, p.uuaid)) return { ok: false, reason: "peer-key-uuaid-mismatch" };
2109
+ }
2110
+ }
2111
+ if (!verifyDomain(FEDERATION_PEERS_VERSION, doc, doc.publicKey, doc.sig)) {
2112
+ return { ok: false, reason: "bad-signature" }; // @rule fed.peers-sig
2113
+ }
2114
+ return { ok: true, doc };
2115
+ }
2116
+
2117
+ // ---------------------------------------------------------------------------
2118
+ // FederationCoordinator — Pull Anti-Entropy + `H-2` Upstream Resolve
2119
+ // ---------------------------------------------------------------------------
2120
+
2121
+ function normalizeConfiguredPeer(entry) {
2122
+ if (typeof entry === "string") {
2123
+ const trimmed = entry.trim().replace(/\/+$/, "");
2124
+ return trimmed ? { url: trimmed, uuaid: null, publicKey: null } : null;
2125
+ }
2126
+ if (isPlainObject(entry) && typeof entry.url === "string" && entry.url.trim()) {
2127
+ return {
2128
+ url: entry.url.trim().replace(/\/+$/, ""),
2129
+ uuaid: typeof entry.uuaid === "string" && UUAID_RE.test(entry.uuaid) ? entry.uuaid : null,
2130
+ publicKey: typeof entry.publicKey === "string" && HEX64_RE.test(entry.publicKey.toLowerCase()) ? entry.publicKey.toLowerCase() : null,
2131
+ };
2132
+ }
2133
+ return null;
2134
+ }
2135
+
2136
+ export class FederationCoordinator {
2137
+ constructor({
2138
+ federationStore = null,
2139
+ db = null,
2140
+ dbPath = ":memory:",
2141
+ forcePureJs = false,
2142
+ lineageStore = null,
2143
+ listingStore = null,
2144
+ heartbeatStore = null,
2145
+ signer = null,
2146
+ keychain = null,
2147
+ registryUuaid = null,
2148
+ publicKey = null,
2149
+ peers = [],
2150
+ getSelfUrl = () => null,
2151
+ getNow = () => undefined,
2152
+ allowPrivateUrls = false,
2153
+ urlMap = null,
2154
+ fetch: fetchImpl = globalThis.fetch,
2155
+ lookup: lookupImpl = defaultDnsLookup,
2156
+ pullIntervalMs = DEFAULT_PULL_INTERVAL_MS,
2157
+ pullTimeoutMs = 5_000,
2158
+ pageLimit = DEFAULT_CHANGES_LIMIT,
2159
+ maxPagesPerPull = MAX_PAGES_PER_PULL,
2160
+ maxStrikes = DEFAULT_MAX_STRIKES,
2161
+ quarantineCooldownMs = DEFAULT_QUARANTINE_COOLDOWN_MS,
2162
+ maxNewLineagesPerHour = DEFAULT_MAX_NEW_LINEAGES_PER_HOUR,
2163
+ maxTotalLineageBytes = MAX_TOTAL_LINEAGE_BYTES,
2164
+ maxResolveFanout = MAX_RESOLVE_FANOUT,
2165
+ maxResolveDepth = MAX_RESOLVE_DEPTH,
2166
+ resolveTimeoutMs = DEFAULT_RESOLVE_TIMEOUT_MS,
2167
+ negativeCacheTtlMs = DEFAULT_NEGATIVE_CACHE_TTL_MS,
2168
+ negativeCacheMax = DEFAULT_NEGATIVE_CACHE_MAX,
2169
+ } = {}) {
2170
+ const normSigner = normalizeSigner(signer ?? keychain);
2171
+ this.signer = signer ?? keychain ?? null;
2172
+ this.registryUuaid = registryUuaid ?? normSigner?.uuaid ?? listingStore?.registryUuaid ?? lineageStore?.registryKey?.uuaid ?? null;
2173
+ this.publicKey = (publicKey ?? normSigner?.publicKey ?? lineageStore?.registryKey?.publicKey ?? "").toLowerCase() || null;
2174
+ this.lineageStore = lineageStore;
2175
+ this.listingStore = listingStore;
2176
+ this.heartbeatStore = heartbeatStore;
2177
+
2178
+ const negativeCache = new ResolveNegativeCache({ ttlMs: negativeCacheTtlMs, maxEntries: negativeCacheMax });
2179
+ this.store =
2180
+ federationStore ??
2181
+ new FederationStore({
2182
+ db: db ?? lineageStore?.db ?? listingStore?.db ?? heartbeatStore?.db ?? null,
2183
+ dbPath,
2184
+ forcePureJs,
2185
+ lineageStore,
2186
+ listingStore,
2187
+ heartbeatStore,
2188
+ negativeCache,
2189
+ maxStrikes,
2190
+ quarantineCooldownMs,
2191
+ maxNewLineagesPerHour,
2192
+ maxTotalLineageBytes,
2193
+ });
2194
+ this.store.setStores({ lineageStore, listingStore, heartbeatStore });
2195
+ this.negativeCache = this.store.negativeCache;
2196
+
2197
+ if (listingStore && typeof listingStore.setFederationStore === "function") listingStore.setFederationStore(this.store);
2198
+ if (heartbeatStore && typeof heartbeatStore.setFederationStore === "function") heartbeatStore.setFederationStore(this.store);
2199
+ if (lineageStore && typeof lineageStore.setFederationStore === "function") lineageStore.setFederationStore(this.store);
2200
+
2201
+ this.getSelfUrl = getSelfUrl;
2202
+ this.getNow = getNow;
2203
+ this.allowPrivateUrls = Boolean(allowPrivateUrls);
2204
+ this.urlMap = urlMap;
2205
+ this.fetch = fetchImpl;
2206
+ this.lookup = lookupImpl;
2207
+ this._usePinnedSocketFetch = fetchImpl === undefined || fetchImpl === globalThis.fetch;
2208
+ this.pullIntervalMs = pullIntervalMs;
2209
+ this.pullTimeoutMs = pullTimeoutMs;
2210
+ this.pageLimit = Math.min(MAX_CHANGES_LIMIT, Math.max(MIN_CHANGES_LIMIT, pageLimit));
2211
+ this.maxPagesPerPull = maxPagesPerPull;
2212
+ this.maxResolveFanout = maxResolveFanout;
2213
+ this.maxResolveDepth = maxResolveDepth;
2214
+ this.resolveTimeoutMs = resolveTimeoutMs;
2215
+
2216
+ this._peers = [];
2217
+ this.setPeers(peers);
2218
+ this._pullTimer = null;
2219
+ this._pulling = false;
2220
+ }
2221
+
2222
+ setPeers(peers = []) {
2223
+ const seen = new Set();
2224
+ const out = [];
2225
+ for (const raw of peers) {
2226
+ const p = normalizeConfiguredPeer(raw);
2227
+ if (!p || seen.has(p.url)) continue;
2228
+ seen.add(p.url);
2229
+ const saved = this.store.getPeerCursor(p.url);
2230
+ if (!p.uuaid && saved.peerUuaid) p.uuaid = saved.peerUuaid;
2231
+ out.push(p);
2232
+ }
2233
+ this._peers = out;
2234
+ }
2235
+
2236
+ getPeers() {
2237
+ return this._peers.map((p) => ({ ...p }));
2238
+ }
2239
+
2240
+ start() {
2241
+ if (this._pullTimer || !(this.pullIntervalMs > 0)) return;
2242
+ this._pullTimer = setInterval(() => {
2243
+ void this.pullOnce().catch(() => {});
2244
+ }, this.pullIntervalMs);
2245
+ this._pullTimer.unref?.();
2246
+ }
2247
+
2248
+ stop() {
2249
+ if (this._pullTimer) {
2250
+ clearInterval(this._pullTimer);
2251
+ this._pullTimer = null;
2252
+ }
2253
+ }
2254
+
2255
+ close() {
2256
+ this.stop();
2257
+ this.store.close();
2258
+ }
2259
+
2260
+ getStrikes(peerUrl = null, opts = {}) {
2261
+ return this.store.getStrikes(peerUrl, opts);
2262
+ }
2263
+
2264
+ isQuarantined(peerUrl, opts = {}) {
2265
+ const effNow = opts.now !== undefined ? opts.now : this.getNow();
2266
+ return this.store.isQuarantined(peerUrl, { ...opts, now: effNow });
2267
+ }
2268
+
2269
+ resetPeerQuarantine(peerUrl) {
2270
+ this.store.resetPeerQuarantine(peerUrl);
2271
+ }
2272
+
2273
+ /**
2274
+ * Build signed `GET /v1/federation/peers` document (`pillar-federation/1`).
2275
+ */
2276
+ getSignedPeers({ now } = {}) {
2277
+ const issuedAt = nowIso(now !== undefined ? now : this.getNow());
2278
+ const peersList = [];
2279
+ for (const p of this._peers) {
2280
+ const target = resolvePeerTarget(p.url, { allowPrivateUrls: this.allowPrivateUrls, urlMap: this.urlMap });
2281
+ const pubUrl = isStrictHttpsUrl(p.url) ? p.url : (target.ok ? target.publicUrl : null);
2282
+ if (!pubUrl || !isStrictHttpsUrl(pubUrl)) continue;
2283
+ peersList.push({
2284
+ ...(p.uuaid ? { uuaid: p.uuaid } : {}),
2285
+ url: pubUrl,
2286
+ ...(p.publicKey ? { publicKey: p.publicKey } : {}),
2287
+ });
2288
+ }
2289
+ return signDomain(
2290
+ FEDERATION_PEERS_VERSION,
2291
+ {
2292
+ registry: this.registryUuaid,
2293
+ publicKey: this.publicKey,
2294
+ peers: peersList,
2295
+ issuedAt,
2296
+ },
2297
+ this.signer,
2298
+ );
2299
+ }
2300
+
2301
+ getChanges({ since, limit } = {}) {
2302
+ return this.store.getChanges({
2303
+ registryUuaid: this.registryUuaid,
2304
+ since,
2305
+ limit,
2306
+ });
2307
+ }
2308
+
2309
+ _isSelfPeer(peer, target) {
2310
+ if (peer.uuaid && this.registryUuaid && peer.uuaid === this.registryUuaid) return true; // @rule fed.skip-self-uuaid
2311
+ const selfUrl = this.getSelfUrl?.();
2312
+ if (selfUrl) {
2313
+ const cleanSelf = String(selfUrl).replace(/\/+$/, "");
2314
+ if (peer.url === cleanSelf || target?.publicUrl === cleanSelf || target?.primaryUrl === cleanSelf) return true; // @rule fed.skip-self-url
2315
+ }
2316
+ return false;
2317
+ }
2318
+
2319
+ _fetchForTarget(target) {
2320
+ return target?.lookup && this._usePinnedSocketFetch ? pinnedNodeFetch : this.fetch;
2321
+ }
2322
+
2323
+ async _discoverPeerIdentity(peer, target, nowStr) {
2324
+ if (peer.uuaid && peer.publicKey) return { quarantined: false };
2325
+ const res = await getJsonWithFallback(this._fetchForTarget(target), target, "/v1/federation/peers", {}, this.pullTimeoutMs);
2326
+ if (res?.ok) {
2327
+ const doc = await res.json().catch(() => null);
2328
+ const ver = verifyFederationPeersDoc(doc);
2329
+ if (ver.ok) {
2330
+ if ((peer.uuaid && doc.registry !== peer.uuaid) || (peer.publicKey && doc.publicKey.toLowerCase() !== peer.publicKey)) {
2331
+ const st = this.store.recordStrike({
2332
+ peerUrl: peer.url,
2333
+ objectType: "federation-peers",
2334
+ reason: "peer-identity-mismatch",
2335
+ digest: objectDigestHex(doc),
2336
+ now: nowStr,
2337
+ });
2338
+ return { quarantined: st.quarantined };
2339
+ }
2340
+ peer.uuaid = doc.registry;
2341
+ peer.publicKey = doc.publicKey.toLowerCase();
2342
+ this.store.setPeerCursor(peer.url, { peerUuaid: peer.uuaid, now: nowStr });
2343
+ }
2344
+ }
2345
+ return { quarantined: false };
2346
+ }
2347
+
2348
+ _knownPeerUuaids() {
2349
+ return this._peers.map((p) => p.uuaid).filter(Boolean);
2350
+ }
2351
+
2352
+ _ingestPulledBatch(peer, body, nowStr) {
2353
+ let storedLineageEvents = 0;
2354
+ let storedListings = 0;
2355
+ let storedHeartbeats = 0;
2356
+ let deferredNewLineages = 0;
2357
+ let strikesAdded = 0;
2358
+ const deferredLineagesInBatch = new Set();
2359
+
2360
+ const recordAndCheckQuarantine = (objectType, reason, obj) => {
2361
+ const st = this.store.recordStrike({
2362
+ peerUrl: peer.url,
2363
+ objectType,
2364
+ reason,
2365
+ digest: objectDigestHex(obj),
2366
+ now: nowStr,
2367
+ });
2368
+ strikesAdded += 1;
2369
+ return st.quarantined;
2370
+ };
2371
+
2372
+ const rawEvents = body.lineageEvents;
2373
+ const sortedEvents = [...rawEvents].sort((a, b) => {
2374
+ const sa = Number.isInteger(a?.seq) ? a.seq : Number.MAX_SAFE_INTEGER;
2375
+ const sb = Number.isInteger(b?.seq) ? b.seq : Number.MAX_SAFE_INTEGER;
2376
+ return sa - sb;
2377
+ });
2378
+
2379
+ // 1. Lineage events (verified locally via verifyLineageFull before storing)
2380
+ for (const ev of sortedEvents) {
2381
+ const vEv = verifyPulledLineageEvent(ev, this.lineageStore, { now: nowStr });
2382
+ if (!vEv.ok) {
2383
+ if (vEv.timingHold) continue;
2384
+ if (recordAndCheckQuarantine("lineage", vEv.reason, ev)) break;
2385
+ continue;
2386
+ }
2387
+
2388
+ const capCheck = checkLineageTotalCap(ev.lineage, vEv.byteLen, {
2389
+ maxTotalBytes: this.store.maxTotalLineageBytes,
2390
+ listingStore: this.listingStore,
2391
+ heartbeatStore: this.heartbeatStore,
2392
+ lineageStore: this.lineageStore,
2393
+ excludeEventDigest: vEv.digest,
2394
+ });
2395
+ if (!capCheck.ok) continue;
2396
+
2397
+ const isExistingLin =
2398
+ this.store.hasAdmittedLineage(ev.lineage) ||
2399
+ Boolean(this.lineageStore && this.lineageStore.getRows(ev.lineage).length > 0);
2400
+ if (!isExistingLin) {
2401
+ const adm = this.store.tryAdmitLineage(ev.lineage, { now: nowStr, source: `peer:${peer.url}` });
2402
+ if (!adm.ok) { deferredNewLineages += 1; deferredLineagesInBatch.add(ev.lineage); continue; } // @rule sybil.pull-defer-excess-lineage
2403
+ }
2404
+
2405
+ const stRes = this.lineageStore.storeEvent(ev, { now: nowStr });
2406
+ if (stRes.ok) {
2407
+ storedLineageEvents += 1;
2408
+ this.negativeCache.invalidate(...collectLineageUuaidsFromEvent(ev));
2409
+ } else if (stRes.reason !== "lineage-cap-exceeded" && stRes.reason !== "claim-unobserved" && stRes.reason !== "contest-window-open") {
2410
+ if (recordAndCheckQuarantine("lineage", stRes.reason, ev)) break;
2411
+ }
2412
+ }
2413
+
2414
+ // 2. Listings (verified locally via verifyPulledListing + current-key match + H-1 future-ts)
2415
+ const knownPeerUuaids = this._knownPeerUuaids();
2416
+ const rawOrigins =
2417
+ peer.uuaid && isPlainObject(body.stampRegistries)
2418
+ ? body.stampRegistries
2419
+ : peer.uuaid && isPlainObject(body.listingOrigins)
2420
+ ? body.listingOrigins
2421
+ : null;
2422
+ for (const listing of body.listings) {
2423
+ if (this.store.isQuarantined(peer.url, { now: nowStr })) break; // @rule fed.batch-abort-on-quarantine
2424
+ if (isPlainObject(listing) && deferredLineagesInBatch.has(listing.lineage)) {
2425
+ deferredNewLineages += 1;
2426
+ continue;
2427
+ }
2428
+
2429
+ const originUuaid =
2430
+ rawOrigins && isPlainObject(listing) && typeof listing.lineage === "string" && Object.hasOwn(rawOrigins, listing.lineage)
2431
+ ? rawOrigins[listing.lineage]
2432
+ : null;
2433
+
2434
+ const vList = verifyPulledListing(listing, {
2435
+ lineageStore: this.lineageStore,
2436
+ requiredStampBits: this.listingStore?.requiredStampBits ?? DEFAULT_STAMP_BITS,
2437
+ peerUuaid: peer.uuaid,
2438
+ stampRegistry: originUuaid,
2439
+ knownPeerUuaids,
2440
+ now: nowStr,
2441
+ });
2442
+ if (!vList.ok) {
2443
+ if (recordAndCheckQuarantine("listing", vList.reason, listing)) break; // @rule fed.strike-bad-listing
2444
+ continue;
2445
+ }
2446
+
2447
+ const capCheck = checkLineageTotalCap(listing.lineage, vList.byteLen, {
2448
+ maxTotalBytes: this.store.maxTotalLineageBytes,
2449
+ listingStore: this.listingStore,
2450
+ heartbeatStore: this.heartbeatStore,
2451
+ lineageStore: this.lineageStore,
2452
+ excludeKind: "listing",
2453
+ });
2454
+ if (!capCheck.ok) continue;
2455
+
2456
+ const adm = this.store.tryAdmitLineage(listing.lineage, { now: nowStr, source: `peer:${peer.url}` });
2457
+ if (!adm.ok) { deferredNewLineages += 1; deferredLineagesInBatch.add(listing.lineage); continue; } // @rule sybil.pull-defer-excess-listing
2458
+
2459
+ const putRes = this.listingStore.putListing(listing, {
2460
+ now: nowStr,
2461
+ federated: true,
2462
+ peerUuaid: peer.uuaid,
2463
+ originUuaid: vList.matchedOrigin ?? originUuaid,
2464
+ knownPeerUuaids,
2465
+ });
2466
+ if (putRes.ok) {
2467
+ storedListings += 1;
2468
+ this.negativeCache.invalidate(...collectListingUuaids(listing));
2469
+ } else if (putRes.reason !== "stale-listing" && putRes.reason !== "lineage-cap-exceeded" && putRes.reason !== "rate-limited") {
2470
+ if (recordAndCheckQuarantine("listing", putRes.reason, listing)) break;
2471
+ }
2472
+ }
2473
+
2474
+ // 3. Heartbeats (verified locally via verifyPulledHeartbeat + H-1 future-ts)
2475
+ for (const hb of body.heartbeats) {
2476
+ if (this.store.isQuarantined(peer.url, { now: nowStr })) break;
2477
+ if (isPlainObject(hb) && deferredLineagesInBatch.has(hb.lineage)) continue;
2478
+
2479
+ const vHb = verifyPulledHeartbeat(hb, {
2480
+ lineageStore: this.lineageStore,
2481
+ listingStore: this.listingStore,
2482
+ now: nowStr,
2483
+ });
2484
+ if (!vHb.ok) {
2485
+ if (recordAndCheckQuarantine("heartbeat", vHb.reason, hb)) break; // @rule fed.strike-bad-heartbeat
2486
+ continue;
2487
+ }
2488
+ if (vHb.skipTombstoned) continue;
2489
+
2490
+ const capCheck = checkLineageTotalCap(hb.lineage, vHb.byteLen, {
2491
+ maxTotalBytes: this.store.maxTotalLineageBytes,
2492
+ listingStore: this.listingStore,
2493
+ heartbeatStore: this.heartbeatStore,
2494
+ lineageStore: this.lineageStore,
2495
+ excludeKind: "heartbeat",
2496
+ });
2497
+ if (!capCheck.ok) continue;
2498
+
2499
+ const putHb = this.heartbeatStore.putHeartbeat(hb, { now: nowStr, federated: true });
2500
+ if (putHb.ok) {
2501
+ storedHeartbeats += 1;
2502
+ this.negativeCache.invalidate(hb.lineage, hb.uuaid);
2503
+ } else if (putHb.reason !== "stale-heartbeat" && putHb.reason !== "rate-limited" && putHb.reason !== "lineage-cap-exceeded") {
2504
+ if (recordAndCheckQuarantine("heartbeat", putHb.reason, hb)) break;
2505
+ }
2506
+ }
2507
+
2508
+ return {
2509
+ storedLineageEvents,
2510
+ storedListings,
2511
+ storedHeartbeats,
2512
+ deferredNewLineages,
2513
+ strikesAdded,
2514
+ quarantined: this.store.isQuarantined(peer.url, { now: nowStr }),
2515
+ };
2516
+ }
2517
+
2518
+ async _pullRangeFromPeer(peer, target, startCursor, nowStr) {
2519
+ let cursor = startCursor;
2520
+ let earliestDeferredCursor = null;
2521
+ let completed = false;
2522
+ let pages = 0;
2523
+ let storedLineageEvents = 0;
2524
+ let storedListings = 0;
2525
+ let storedHeartbeats = 0;
2526
+ let deferredNewLineages = 0;
2527
+ let strikesAdded = 0;
2528
+
2529
+ while (pages < this.maxPagesPerPull) {
2530
+ pages += 1;
2531
+ const res = await getJsonWithFallback(
2532
+ this._fetchForTarget(target),
2533
+ target,
2534
+ `/v1/federation/changes?since=${encodeURIComponent(cursor)}&limit=${this.pageLimit}`,
2535
+ {},
2536
+ this.pullTimeoutMs,
2537
+ );
2538
+ if (!res?.ok) break;
2539
+ const body = await res.json().catch(() => null);
2540
+ const isOriginMapShape = (obj) =>
2541
+ isPlainObject(obj) &&
2542
+ Object.entries(obj).every(([k, v]) => UUAID_RE.test(k) && typeof v === "string" && UUAID_RE.test(v));
2543
+ const originsShapeOk =
2544
+ (!Object.hasOwn(body ?? {}, "stampRegistries") || isOriginMapShape(body.stampRegistries)) &&
2545
+ (!Object.hasOwn(body ?? {}, "listingOrigins") || isOriginMapShape(body.listingOrigins));
2546
+ if (
2547
+ !isPlainObject(body) ||
2548
+ !Object.keys(body).every((k) => FED_CHANGES_KEYS.has(k)) ||
2549
+ body.v !== FEDERATION_CHANGES_VERSION ||
2550
+ typeof body.nextCursor !== "string" ||
2551
+ !CURSOR_RE.test(body.nextCursor) ||
2552
+ typeof body.hasMore !== "boolean" ||
2553
+ !isDenseArray(body.listings) ||
2554
+ !isDenseArray(body.heartbeats) ||
2555
+ !isDenseArray(body.lineageEvents) ||
2556
+ !originsShapeOk ||
2557
+ (peer.uuaid && typeof body.registry === "string" && body.registry !== peer.uuaid)
2558
+ ) {
2559
+ this.store.recordStrike({
2560
+ peerUrl: peer.url,
2561
+ objectType: "federation-changes",
2562
+ reason: "malformed-federation-changes",
2563
+ digest: objectDigestHex(body),
2564
+ now: nowStr,
2565
+ });
2566
+ strikesAdded += 1;
2567
+ break; // @rule fed.changes-response-shape
2568
+ }
2569
+
2570
+ const pageStartCursor = cursor;
2571
+ const batch = this._ingestPulledBatch(peer, body, nowStr);
2572
+ storedLineageEvents += batch.storedLineageEvents;
2573
+ storedListings += batch.storedListings;
2574
+ storedHeartbeats += batch.storedHeartbeats;
2575
+ deferredNewLineages += batch.deferredNewLineages;
2576
+ strikesAdded += batch.strikesAdded;
2577
+
2578
+ if (batch.deferredNewLineages > 0 && earliestDeferredCursor === null) {
2579
+ earliestDeferredCursor = pageStartCursor;
2580
+ }
2581
+ if (BigInt(body.nextCursor) > BigInt(cursor)) {
2582
+ cursor = body.nextCursor;
2583
+ }
2584
+ if (batch.quarantined) break; // @rule fed.page-stop-on-quarantine
2585
+ if (!body.hasMore || body.nextCursor === pageStartCursor) {
2586
+ completed = !body.hasMore;
2587
+ break;
2588
+ }
2589
+ }
2590
+
2591
+ return {
2592
+ cursor,
2593
+ earliestDeferredCursor,
2594
+ completed,
2595
+ storedLineageEvents,
2596
+ storedListings,
2597
+ storedHeartbeats,
2598
+ deferredNewLineages,
2599
+ strikesAdded,
2600
+ };
2601
+ }
2602
+
2603
+ /**
2604
+ * Pull changes once from a single configured peer.
2605
+ */
2606
+ async pullPeer(peerInput, { now } = {}) {
2607
+ const peer = typeof peerInput === "string"
2608
+ ? this._peers.find((p) => p.url === peerInput.replace(/\/+$/, "")) ?? normalizeConfiguredPeer(peerInput)
2609
+ : peerInput;
2610
+ if (!peer || typeof this.fetch !== "function") return { ok: false, skipped: true, reason: "no-peer" };
2611
+
2612
+ const nowStr = nowIso(now !== undefined ? now : this.getNow());
2613
+ if (this.store.isQuarantined(peer.url, { now: nowStr })) {
2614
+ return { ok: false, skipped: true, quarantined: true, reason: "quarantined", peerUrl: peer.url }; // @rule fed.pull-skip-quarantined
2615
+ }
2616
+
2617
+ const prelim = resolvePeerTarget(peer.url, { allowPrivateUrls: this.allowPrivateUrls, urlMap: this.urlMap });
2618
+ if (prelim.ok && this._isSelfPeer(peer, prelim)) {
2619
+ return { ok: false, skipped: true, reason: "self-peer", peerUrl: peer.url };
2620
+ }
2621
+ if (this._isSelfPeer(peer, null)) {
2622
+ return { ok: false, skipped: true, reason: "self-peer", peerUrl: peer.url };
2623
+ }
2624
+
2625
+ const target = await resolvePeerTargetPinned(peer.url, {
2626
+ allowPrivateUrls: this.allowPrivateUrls,
2627
+ urlMap: this.urlMap,
2628
+ lookup: this.lookup,
2629
+ timeoutMs: this.pullTimeoutMs,
2630
+ });
2631
+ if (!target.ok) {
2632
+ return { ok: false, skipped: true, reason: target.reason, peerUrl: peer.url }; // @rule fed.pull-target-ssrf
2633
+ }
2634
+
2635
+ const disc = await this._discoverPeerIdentity(peer, target, nowStr);
2636
+ if (disc.quarantined) {
2637
+ return { ok: false, skipped: true, quarantined: true, reason: "quarantined", peerUrl: peer.url };
2638
+ }
2639
+ const curState = this.store.getPeerCursor(peer.url);
2640
+ let nextCursor = curState.cursor;
2641
+ let nextDeferred = curState.deferredSince;
2642
+
2643
+ let storedLineageEvents = 0;
2644
+ let storedListings = 0;
2645
+ let storedHeartbeats = 0;
2646
+ let deferredNewLineages = 0;
2647
+ let strikesAdded = 0;
2648
+
2649
+ // Replay previously deferred new lineages once hourly Sybil capacity opens
2650
+ if (nextDeferred !== null && this.store.remainingAdmissionCapacity({ now: nowStr }) > 0) {
2651
+ const replay = await this._pullRangeFromPeer(peer, target, nextDeferred, nowStr);
2652
+ storedLineageEvents += replay.storedLineageEvents;
2653
+ storedListings += replay.storedListings;
2654
+ storedHeartbeats += replay.storedHeartbeats;
2655
+ deferredNewLineages += replay.deferredNewLineages;
2656
+ strikesAdded += replay.strikesAdded;
2657
+ if (BigInt(replay.cursor) > BigInt(nextCursor)) nextCursor = replay.cursor;
2658
+ if (replay.earliestDeferredCursor !== null) {
2659
+ nextDeferred = replay.earliestDeferredCursor;
2660
+ } else if (BigInt(replay.cursor) < BigInt(nextCursor) || !replay.completed) {
2661
+ nextDeferred = replay.cursor; // @rule sybil.replay-keep-partial-deferred-cursor
2662
+ } else {
2663
+ nextDeferred = null;
2664
+ }
2665
+ }
2666
+
2667
+ // Always advance from current `nextCursor` so existing-lineage updates are never blocked
2668
+ if (!this.store.isQuarantined(peer.url, { now: nowStr })) {
2669
+ const head = await this._pullRangeFromPeer(peer, target, nextCursor, nowStr);
2670
+ storedLineageEvents += head.storedLineageEvents;
2671
+ storedListings += head.storedListings;
2672
+ storedHeartbeats += head.storedHeartbeats;
2673
+ deferredNewLineages += head.deferredNewLineages;
2674
+ strikesAdded += head.strikesAdded;
2675
+ if (BigInt(head.cursor) > BigInt(nextCursor)) nextCursor = head.cursor;
2676
+ if (head.earliestDeferredCursor !== null && nextDeferred === null) {
2677
+ nextDeferred = head.earliestDeferredCursor;
2678
+ }
2679
+ }
2680
+
2681
+ this.store.setPeerCursor(peer.url, {
2682
+ cursor: nextCursor,
2683
+ deferredSince: nextDeferred,
2684
+ peerUuaid: peer.uuaid,
2685
+ now: nowStr,
2686
+ });
2687
+
2688
+ return {
2689
+ ok: true,
2690
+ peerUrl: peer.url,
2691
+ peerUuaid: peer.uuaid,
2692
+ cursor: nextCursor,
2693
+ deferredSince: nextDeferred,
2694
+ storedLineageEvents,
2695
+ storedListings,
2696
+ storedHeartbeats,
2697
+ deferredNewLineages,
2698
+ strikesAdded,
2699
+ quarantined: this.store.isQuarantined(peer.url, { now: nowStr }),
2700
+ };
2701
+ }
2702
+
2703
+ /**
2704
+ * Pull from all configured peers sequentially (overlap-safe).
2705
+ */
2706
+ async pullOnce({ now } = {}) {
2707
+ if (this._pulling) return { ok: true, busy: true, peers: [] };
2708
+ this._pulling = true;
2709
+ try {
2710
+ const results = [];
2711
+ for (const peer of this._peers) {
2712
+ results.push(await this.pullPeer(peer, { now }));
2713
+ }
2714
+ return { ok: true, peers: results };
2715
+ } finally {
2716
+ this._pulling = false;
2717
+ }
2718
+ }
2719
+
2720
+ /**
2721
+ * `H-2` Upstream resolve fan-out on local miss:
2722
+ * - Rejects malformed UUAID (`400`, `0` upstream calls).
2723
+ * - Stops at `depth >= maxResolveDepth` (`2`, `0` upstream calls).
2724
+ * - Returns `404` immediately (`0` upstream calls) on negative-cache hit.
2725
+ * - Queries at most `<= 4` peers (`?depth=${depth + 1}`) within `3,000 ms` total timeout budget.
2726
+ * - Re-verifies upstream `evidence` (`lineage` log + `listing` + optional `heartbeat`) locally
2727
+ * before storing and returning local `answeredBy` + `via`.
2728
+ * - Records misses in the negative cache.
2729
+ */
2730
+ async resolveUpstream(
2731
+ uuaid,
2732
+ {
2733
+ depth = 0,
2734
+ visited = [],
2735
+ answeredBy,
2736
+ localResolve,
2737
+ now,
2738
+ } = {},
2739
+ ) {
2740
+ if (typeof uuaid !== "string" || !UUAID_RE.test(uuaid)) {
2741
+ return { ok: false, status: 400, reason: "bad-uuaid", upstreamCalls: 0 }; // @rule h2.reject-malformed-uuaid
2742
+ }
2743
+ if (!Number.isInteger(depth) || depth < 0) {
2744
+ return { ok: false, status: 400, reason: "bad-depth", upstreamCalls: 0 }; // @rule h2.reject-bad-depth
2745
+ }
2746
+ const nowStr = nowIso(now !== undefined ? now : this.getNow());
2747
+ if (this.negativeCache.has(uuaid, { now: nowStr })) {
2748
+ return { ok: false, status: 404, reason: "not-found", negativeCacheHit: true, upstreamCalls: 0 }; // @rule h2.neg-cache-short-circuit
2749
+ }
2750
+ if (depth >= this.maxResolveDepth) {
2751
+ return { ok: false, status: 404, reason: "not-found", depthCapped: true, upstreamCalls: 0 }; // @rule h2.depth-cap
2752
+ }
2753
+ if (typeof this.fetch !== "function" || this._peers.length === 0) {
2754
+ return { ok: false, status: 404, reason: "not-found", upstreamCalls: 0 };
2755
+ }
2756
+
2757
+ const visitedSet = new Set(visited.map((v) => String(v).trim().replace(/\/+$/, "")).filter(Boolean));
2758
+ const selfUrl = this.getSelfUrl?.();
2759
+ if (selfUrl) visitedSet.add(String(selfUrl).replace(/\/+$/, ""));
2760
+ if (this.registryUuaid) visitedSet.add(this.registryUuaid);
2761
+
2762
+ const candidatePeers = [];
2763
+ for (const peer of this._peers) {
2764
+ if (this.store.isQuarantined(peer.url, { now: nowStr })) continue; // @rule h2.skip-quarantined-peer
2765
+ const prelim = resolvePeerTarget(peer.url, { allowPrivateUrls: this.allowPrivateUrls, urlMap: this.urlMap });
2766
+ if (this._isSelfPeer(peer, prelim.ok ? prelim : null)) continue;
2767
+ if (visitedSet.has(peer.url) || (prelim.ok && visitedSet.has(prelim.publicUrl)) || (peer.uuaid && visitedSet.has(peer.uuaid))) continue;
2768
+ candidatePeers.push(peer);
2769
+ }
2770
+
2771
+ if (candidatePeers.length === 0) {
2772
+ return { ok: false, status: 404, reason: "not-found", upstreamCalls: 0 };
2773
+ }
2774
+
2775
+ const budgetAc = new AbortController();
2776
+ const startWall = Date.now();
2777
+ const deadlineWall = startWall + this.resolveTimeoutMs;
2778
+ let budgetTimer = null;
2779
+ if (this.resolveTimeoutMs > 0) budgetTimer = setTimeout(() => budgetAc.abort(), this.resolveTimeoutMs); // @rule h2.total-timeout-budget
2780
+ budgetTimer?.unref?.();
2781
+
2782
+ let upstreamCalls = 0;
2783
+ const nextVisitedHeader = [...visitedSet].slice(0, 8).join(",");
2784
+ const knownPeerUuaids = this._knownPeerUuaids();
2785
+
2786
+ try {
2787
+ for (let i = 0; i < candidatePeers.length; i++) {
2788
+ if (upstreamCalls >= this.maxResolveFanout) break; // @rule h2.fanout-cap-4
2789
+ if (budgetAc.signal.aborted) break;
2790
+ const remainingMs = deadlineWall - Date.now();
2791
+ if (remainingMs <= 0) break;
2792
+
2793
+ const peer = candidatePeers[i];
2794
+ const slotsLeft = Math.max(1, Math.min(this.maxResolveFanout - upstreamCalls, candidatePeers.length - i));
2795
+ const sliceMs = Math.min(this.pullTimeoutMs, Math.max(200, Math.ceil(remainingMs / slotsLeft)));
2796
+
2797
+ const target = await resolvePeerTargetPinned(peer.url, {
2798
+ allowPrivateUrls: this.allowPrivateUrls,
2799
+ urlMap: this.urlMap,
2800
+ lookup: this.lookup,
2801
+ signal: budgetAc.signal,
2802
+ timeoutMs: sliceMs,
2803
+ });
2804
+ if (!target.ok) continue; // @rule h2.peer-ssrf-fence
2805
+
2806
+ upstreamCalls += 1;
2807
+ const res = await getJsonWithFallback(
2808
+ this._fetchForTarget(target),
2809
+ target,
2810
+ `/v1/resolve/${encodeURIComponent(uuaid)}?depth=${depth + 1}`,
2811
+ nextVisitedHeader ? { "x-pillar-visited": nextVisitedHeader } : {},
2812
+ sliceMs,
2813
+ budgetAc.signal,
2814
+ );
2815
+ if (!res || res.status === 404) continue;
2816
+ if (!res.ok) continue;
2817
+
2818
+ const peerAns = await res.json().catch(() => null);
2819
+ const recordResolveStrike = (objectType, reason, obj) => {
2820
+ this.store.recordStrike({
2821
+ peerUrl: peer.url,
2822
+ objectType,
2823
+ reason,
2824
+ digest: objectDigestHex(obj),
2825
+ now: nowStr,
2826
+ });
2827
+ };
2828
+
2829
+ if (
2830
+ !isPlainObject(peerAns) ||
2831
+ !Object.keys(peerAns).every((k) => RESOLVE_ALLOWED_KEYS.has(k)) ||
2832
+ peerAns.v !== RESOLVE_VERSION ||
2833
+ peerAns.query !== uuaid ||
2834
+ typeof peerAns.lineage !== "string" ||
2835
+ !UUAID_RE.test(peerAns.lineage) ||
2836
+ typeof peerAns.current !== "string" ||
2837
+ !UUAID_RE.test(peerAns.current) ||
2838
+ !isStrictHttpsUrl(peerAns.answeredBy) ||
2839
+ (Object.hasOwn(peerAns, "via") && (!isDenseArray(peerAns.via) || !peerAns.via.every(isStrictHttpsUrl))) ||
2840
+ !isPlainObject(peerAns.evidence) ||
2841
+ !Object.keys(peerAns.evidence).every((k) => EVIDENCE_ALLOWED_KEYS.has(k))
2842
+ ) {
2843
+ recordResolveStrike("resolve", "malformed-resolve", peerAns); continue; // @rule h2.verify-upstream-resolve-shape
2844
+ }
2845
+
2846
+ const evObj = peerAns.evidence;
2847
+ const hasListing = Object.hasOwn(evObj, "listing");
2848
+ const hasHeartbeat = Object.hasOwn(evObj, "heartbeat");
2849
+ const hasLineageHead = Object.hasOwn(evObj, "lineageHead");
2850
+ const needsLineage =
2851
+ hasLineageHead ||
2852
+ Object.hasOwn(peerAns, "lineageVerdict") ||
2853
+ peerAns.current !== peerAns.lineage ||
2854
+ peerAns.query !== peerAns.lineage ||
2855
+ Boolean(isPlainObject(evObj.listing?.card) && Object.hasOwn(evObj.listing.card, "lineageHead")) ||
2856
+ !hasListing;
2857
+
2858
+ if (!hasListing && !hasLineageHead) { recordResolveStrike("resolve", "missing-evidence", peerAns); continue; } // @rule h2.verify-upstream-has-evidence
2859
+
2860
+ if (!needsLineage) {
2861
+ if (!isPlainObject(evObj.listing) || evObj.listing.lineage !== uuaid || evObj.listing.uuaid !== uuaid) {
2862
+ recordResolveStrike("listing", "listing-lineage-mismatch", evObj.listing);
2863
+ continue;
2864
+ }
2865
+ } else if (hasListing && (!isPlainObject(evObj.listing) || evObj.listing.lineage !== peerAns.lineage)) {
2866
+ recordResolveStrike("listing", "listing-lineage-mismatch", evObj.listing);
2867
+ continue;
2868
+ }
2869
+
2870
+ // Check 600/hour Sybil admission ceiling before storing a never-seen upstream lineage
2871
+ if (!this.store.hasAdmittedLineage(peerAns.lineage)) {
2872
+ if (this.store.remainingAdmissionCapacity({ now: nowStr }) <= 0) continue;
2873
+ }
2874
+
2875
+ let verifiedPres = null;
2876
+ let mergedLineageEval = undefined;
2877
+ let newLineageBytes = 0;
2878
+ if (needsLineage) {
2879
+ if (upstreamCalls >= this.maxResolveFanout) break; // @rule h2.lineage-respects-fanout-cap
2880
+ const remLinMs = deadlineWall - Date.now();
2881
+ if (remLinMs <= 0 || budgetAc.signal.aborted) break;
2882
+ upstreamCalls += 1;
2883
+ const linRes = await getJsonWithFallback(
2884
+ this._fetchForTarget(target),
2885
+ target,
2886
+ `/v1/lineage/${encodeURIComponent(peerAns.lineage)}`,
2887
+ {},
2888
+ remLinMs,
2889
+ budgetAc.signal,
2890
+ );
2891
+ if (!linRes?.ok) continue;
2892
+ const pres = await linRes.json().catch(() => null);
2893
+ if (!isPlainObject(pres) || pres.v !== LINEAGE_LOG_VERSION || !isDenseArray(pres.events) || pres.events.length === 0) {
2894
+ recordResolveStrike("lineage", "malformed-lineage-log", pres);
2895
+ continue;
2896
+ }
2897
+ const fullVer = verifyLineageFull(pres, { now: nowStr, allowBind: true });
2898
+ const linVerOk = RESOLVED_VERDICTS.has(fullVer.verdict) || fullVer.verdict === "contested";
2899
+ if (!linVerOk) { recordResolveStrike("lineage", fullVer.reasons[0] ?? "invalid-lineage", pres); continue; } // @rule h2.verify-upstream-lineage
2900
+ if (fullVer.subject !== peerAns.lineage) {
2901
+ recordResolveStrike("lineage", "lineage-mismatch", pres);
2902
+ continue;
2903
+ }
2904
+ let queryBoundInLineage = false;
2905
+ if (fullVer._nodes instanceof Map) {
2906
+ for (const node of fullVer._nodes.values()) {
2907
+ const ev = node?.e;
2908
+ if (!ev) continue;
2909
+ if (
2910
+ ev.lineage === uuaid ||
2911
+ ev.key?.uuaid === uuaid ||
2912
+ (ev.type === "door.add" && ev.door?.uuaid === uuaid) ||
2913
+ (ev.type === "inception" && Array.isArray(ev.doors) && ev.doors.some((d) => d?.uuaid === uuaid))
2914
+ ) {
2915
+ queryBoundInLineage = true;
2916
+ break;
2917
+ }
2918
+ }
2919
+ }
2920
+ if (!queryBoundInLineage) { recordResolveStrike("resolve", "query-uuaid-unbound", peerAns); continue; } // @rule h2.verify-upstream-query-bound
2921
+ const expectedCur = fullVer.verdict === "contested" ? peerAns.lineage : fullVer.facts?.current;
2922
+ if (expectedCur !== peerAns.current) {
2923
+ recordResolveStrike("resolve", "current-mismatch", peerAns);
2924
+ continue;
2925
+ }
2926
+ const presBytes = pres.events.reduce((acc, e) => acc + Buffer.byteLength(JSON.stringify(e), "utf8"), 0);
2927
+ if (pres.events.length > 256 || presBytes > Math.min(512 * 1024, this.store.maxTotalLineageBytes)) continue;
2928
+ const existingDigests = new Set(this.lineageStore ? this.lineageStore.getRows(peerAns.lineage).map((r) => r.digest) : []);
2929
+ for (const ev of pres.events) {
2930
+ if (!existingDigests.has(eventDigest(ev))) newLineageBytes += Buffer.byteLength(JSON.stringify(ev), "utf8");
2931
+ }
2932
+ verifiedPres = pres;
2933
+ mergedLineageEval = evaluateMergedLineageInMemory(pres, this.lineageStore, peerAns.lineage, nowStr);
2934
+ }
2935
+
2936
+ let vList = null;
2937
+ let headerOrigin = null;
2938
+ if (hasListing) {
2939
+ if (!isPlainObject(evObj.listing) || evObj.listing.lineage !== peerAns.lineage) {
2940
+ recordResolveStrike("listing", "listing-lineage-mismatch", evObj.listing);
2941
+ continue;
2942
+ }
2943
+ if (!peer.uuaid && Object.hasOwn(evObj.listing, "stamp") && upstreamCalls < this.maxResolveFanout) {
2944
+ upstreamCalls += 1;
2945
+ const disc = await this._discoverPeerIdentity(peer, target, nowStr);
2946
+ if (disc.quarantined) continue;
2947
+ }
2948
+ const rawHdrOrigin = peer.uuaid
2949
+ ? (res.headers?.get?.("x-pillar-stamp-registry") ??
2950
+ res.headers?.["x-pillar-stamp-registry"] ??
2951
+ res.headers?.get?.("x-pillar-listing-origin") ??
2952
+ res.headers?.["x-pillar-listing-origin"] ??
2953
+ null)
2954
+ : null;
2955
+ headerOrigin =
2956
+ typeof rawHdrOrigin === "string" && UUAID_RE.test(rawHdrOrigin.trim()) ? rawHdrOrigin.trim() : null;
2957
+ vList = verifyPulledListing(evObj.listing, {
2958
+ lineageStore: this.lineageStore,
2959
+ lineageEvalOverride: verifiedPres ? mergedLineageEval : undefined,
2960
+ requiredStampBits: this.listingStore?.requiredStampBits ?? DEFAULT_STAMP_BITS,
2961
+ peerUuaid: peer.uuaid,
2962
+ stampRegistry: headerOrigin,
2963
+ knownPeerUuaids: this._knownPeerUuaids(),
2964
+ now: nowStr,
2965
+ });
2966
+ if (!vList.ok) { recordResolveStrike("listing", vList.reason, evObj.listing); continue; } // @rule h2.verify-upstream-listing
2967
+ }
2968
+
2969
+ let vHb = null;
2970
+ if (hasHeartbeat && this.heartbeatStore) {
2971
+ vHb = verifyPulledHeartbeat(evObj.heartbeat, {
2972
+ lineageStore: this.lineageStore,
2973
+ listingStore: this.listingStore,
2974
+ lineageEvalOverride: verifiedPres ? mergedLineageEval : undefined,
2975
+ listingOverride: hasListing ? evObj.listing : undefined,
2976
+ now: nowStr,
2977
+ });
2978
+ if (!vHb.ok) { recordResolveStrike("heartbeat", vHb.reason, evObj.heartbeat); continue; } // @rule h2.verify-upstream-heartbeat
2979
+ }
2980
+
2981
+ // Check combined 1 MiB byte cap and admit/ingest ONLY after all evidence passed in-memory verification
2982
+ const candListBytes = hasListing ? (vList?.byteLen ?? 0) : null;
2983
+ const candHbBytes = hasHeartbeat && this.heartbeatStore && !vHb?.skipTombstoned ? (vHb?.byteLen ?? 0) : null;
2984
+ const curListRow = this.listingStore?.getByLineage(peerAns.lineage) ?? null;
2985
+ const curHbRow = this.heartbeatStore?.getLatest(peerAns.lineage) ?? null;
2986
+ const curLinBytes = this.lineageStore
2987
+ ? this.lineageStore.getRows(peerAns.lineage, { includeIncomplete: true }).reduce((acc, r) => acc + (r.byte_len ?? 0), 0)
2988
+ : 0;
2989
+ const projectedBytes =
2990
+ curLinBytes +
2991
+ newLineageBytes +
2992
+ (candListBytes !== null ? candListBytes : curListRow ? Buffer.byteLength(curListRow.listing_json ?? JSON.stringify(curListRow.listing), "utf8") : 0) +
2993
+ (candHbBytes !== null ? candHbBytes : curHbRow ? Buffer.byteLength(curHbRow.heartbeat_json ?? JSON.stringify(curHbRow.heartbeat), "utf8") : 0);
2994
+ if (projectedBytes > this.store.maxTotalLineageBytes) continue;
2995
+
2996
+ const adm = this.store.tryAdmitLineage(peerAns.lineage, { now: nowStr, source: `resolve:${peer.url}` });
2997
+ if (!adm.ok) continue;
2998
+
2999
+ if (verifiedPres && this.lineageStore) {
3000
+ const ing = this.lineageStore.ingestPresentation(verifiedPres, { now: nowStr });
3001
+ if (!ing.ok) continue;
3002
+ for (const ev of verifiedPres.events) this.negativeCache.invalidate(...collectLineageUuaidsFromEvent(ev));
3003
+ }
3004
+
3005
+ if (hasListing && this.listingStore) {
3006
+ const putL = this.listingStore.putListing(evObj.listing, {
3007
+ now: nowStr,
3008
+ federated: true,
3009
+ peerUuaid: peer.uuaid,
3010
+ stampRegistry: vList?.matchedOrigin ?? headerOrigin,
3011
+ knownPeerUuaids: this._knownPeerUuaids(),
3012
+ });
3013
+ if (!putL.ok && putL.reason !== "stale-listing") continue;
3014
+ this.negativeCache.invalidate(...collectListingUuaids(evObj.listing));
3015
+ }
3016
+
3017
+ if (hasHeartbeat && this.heartbeatStore && !vHb?.skipTombstoned) {
3018
+ const putHb = this.heartbeatStore.putHeartbeat(evObj.heartbeat, { now: nowStr, federated: true });
3019
+ if (putHb.ok) {
3020
+ this.negativeCache.invalidate(evObj.heartbeat.lineage, evObj.heartbeat.uuaid);
3021
+ }
3022
+ }
3023
+
3024
+ const localBuilt = localResolve(uuaid, nowStr);
3025
+ if (!localBuilt.ok) {
3026
+ if (localBuilt.status !== 409) {
3027
+ recordResolveStrike("resolve", localBuilt.reason ?? "unresolvable-evidence", peerAns);
3028
+ }
3029
+ continue;
3030
+ }
3031
+ const viaList = [];
3032
+ for (const hop of [peerAns.answeredBy, ...(peerAns.via ?? [])]) {
3033
+ if (isStrictHttpsUrl(hop) && hop !== answeredBy && !viaList.includes(hop)) viaList.push(hop);
3034
+ }
3035
+ const resolvedOrigin = this.store.getListingOrigin(localBuilt.answer.lineage);
3036
+ return {
3037
+ ok: true,
3038
+ status: 200,
3039
+ upstreamCalls,
3040
+ listingOrigin: resolvedOrigin,
3041
+ stampRegistry: resolvedOrigin,
3042
+ answer: {
3043
+ ...localBuilt.answer,
3044
+ answeredBy,
3045
+ ...(viaList.length > 0 ? { via: viaList } : {}),
3046
+ },
3047
+ };
3048
+ }
3049
+ } finally {
3050
+ clearTimeout(budgetTimer);
3051
+ }
3052
+
3053
+ this.negativeCache.set(uuaid, { now: nowStr }); // @rule h2.record-miss-in-neg-cache
3054
+ return { ok: false, status: 404, reason: "not-found", upstreamCalls };
3055
+ }
3056
+ }