@uuaid/pillar 2.6.1 → 2.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +325 -7
  2. package/bin/carrier.mjs +21 -0
  3. package/bin/pillar-ask.mjs +4 -1
  4. package/bin/pillar-blob.mjs +6 -0
  5. package/bin/pillar-directory.mjs +282 -16
  6. package/bin/pillar-escrow.mjs +4 -1
  7. package/bin/pillar-group-v2.mjs +6 -0
  8. package/bin/pillar-notify.mjs +13 -0
  9. package/bin/pillar-responder.mjs +266 -23
  10. package/bin/pillar.mjs +512 -257
  11. package/package.json +17 -25
  12. package/src/cli-help.mjs +23 -0
  13. package/src/group-v2-cli.mjs +1 -1
  14. package/src/identity/trust.mjs +72 -6
  15. package/src/mailbox/mailbox.mjs +313 -12
  16. package/src/net/carrier-server.mjs +34 -2
  17. package/src/net/refusals.mjs +2 -0
  18. package/src/net/seed-registry.mjs +2 -1
  19. package/src/net/transport.mjs +320 -91
  20. package/src/node-check.mjs +29 -8
  21. package/src/notify-events.mjs +148 -0
  22. package/src/notify-log.mjs +124 -0
  23. package/src/notify-runner.mjs +372 -0
  24. package/src/notify-store.mjs +736 -0
  25. package/src/notify.mjs +350 -0
  26. package/src/pillar.mjs +382 -27
  27. package/src/readers.mjs +2 -2
  28. package/src/registry/federation.mjs +3056 -0
  29. package/src/registry/gossip.mjs +294 -0
  30. package/src/registry/heartbeats.mjs +205 -0
  31. package/src/registry/lineage-verifier.mjs +972 -0
  32. package/src/registry/lineage.mjs +984 -0
  33. package/src/registry/listings.mjs +612 -0
  34. package/src/registry/resolve.mjs +376 -0
  35. package/src/registry/stats.mjs +508 -0
  36. package/src/sqlite-loader.mjs +40 -0
  37. package/src/vendor/pillar-core.mjs +22 -0
  38. package/src/vendor/uuaid-soul.mjs +2246 -0
  39. package/src/vnext/a6b-common.mjs +270 -0
  40. package/src/vnext/b1-cli.mjs +970 -0
  41. package/src/vnext/card-cli.mjs +370 -0
  42. package/src/vnext/greeter-operator.mjs +160 -0
  43. package/src/vnext/greeter-suggest.mjs +318 -0
  44. package/src/vnext/greeter.mjs +571 -0
  45. package/src/vnext/homes.mjs +48 -0
  46. package/src/vnext/init-cli.mjs +489 -0
  47. package/src/vnext/intro-cli.mjs +81 -0
  48. package/src/vnext/json-dir-mailbox.mjs +304 -0
  49. package/src/vnext/jsonl-mailbox.mjs +1132 -0
  50. package/src/vnext/knock-answer.mjs +162 -0
  51. package/src/vnext/knock-cli.mjs +520 -0
  52. package/src/vnext/knock-lane.mjs +312 -0
  53. package/src/vnext/knock-responder.mjs +344 -0
  54. package/src/vnext/lineage-cli.mjs +653 -0
  55. package/src/vnext/listing-cli.mjs +323 -0
  56. package/src/vnext/resolve-cli.mjs +104 -0
  57. package/src/vnext/soul-cli.mjs +666 -0
  58. package/src/vnext/verify-cli.mjs +333 -0
  59. package/src/vnext/w4-redirect.mjs +178 -0
  60. package/src/vnext/wave-a.mjs +193 -0
  61. package/src/vnext/witness-cli.mjs +547 -0
@@ -0,0 +1,294 @@
1
+ /**
2
+ * Pillar vNext §2 — Full-log home gossip (`uuaid-lineage-log/1`) and corroborated
3
+ * `recovery.claim` carrier broadcast (`kind: "lineage"`, `uuaid-pillar-envelope/2`).
4
+ *
5
+ * Security invariants (BRIEF-B9 / RedTeam single-home-decides):
6
+ * - SSRF fence (`isPrivateHost`) blocks private/loopback targets unless `allowPrivateUrls` is set.
7
+ * - Each home signs `uuaid-lineage-seen/1` ONLY for events it verified and stored itself;
8
+ * gossip replicates full `uuaid-lineage-log/1` presentations and never re-signs peer timestamps.
9
+ * - Carrier claim broadcast fires ONLY once `>= 2` eligible homes have stamped the claim.
10
+ */
11
+ import { seal } from "../net/envelope.mjs";
12
+ import { isPrivateHost } from "../net/seed-registry.mjs";
13
+ import { httpsOrigin, isPlainObject } from "./lineage-verifier.mjs";
14
+
15
+ const DEFAULT_GOSSIP_TIMEOUT_MS = 2000;
16
+
17
+ function unwrapHost(hostname) {
18
+ const h = String(hostname ?? "").trim().toLowerCase();
19
+ return h.startsWith("[") && h.endsWith("]") ? h.slice(1, -1) : h;
20
+ }
21
+
22
+ function isLoopbackOnly(hostname) {
23
+ const h = unwrapHost(hostname).replace(/\.$/, "");
24
+ return h === "127.0.0.1" || h === "::1" || h === "localhost";
25
+ }
26
+
27
+ /**
28
+ * Resolve and SSRF-check an outbound `https://` home or carrier URL.
29
+ * Returns `{ ok: true, primaryUrl, fallbackUrl }` or `{ ok: false, reason }`.
30
+ */
31
+ export function resolveOutboundTarget(rawUrl, { allowPrivateUrls = false, urlMap = null } = {}) {
32
+ const origin = httpsOrigin(rawUrl);
33
+ if (!origin) return { ok: false, reason: "bad-url" }; // @rule gossip.https-origin
34
+
35
+ const clean = String(rawUrl).replace(/\/+$/, "");
36
+ const mapped = (urlMap && (urlMap[clean] ?? urlMap[origin])) ? String(urlMap[clean] ?? urlMap[origin]).replace(/\/+$/, "") : clean;
37
+
38
+ let parsed;
39
+ try {
40
+ parsed = new URL(mapped);
41
+ } catch {
42
+ return { ok: false, reason: "bad-url" };
43
+ }
44
+
45
+ if (parsed.protocol !== "https:" && !(allowPrivateUrls && parsed.protocol === "http:")) {
46
+ return { ok: false, reason: "https-required" }; // @rule gossip.mapped-scheme
47
+ }
48
+ if (!allowPrivateUrls && isPrivateHost(parsed.hostname)) {
49
+ return { ok: false, reason: "private-host" }; // @rule gossip.ssrf-fence
50
+ }
51
+
52
+ let fallbackUrl = null;
53
+ if (allowPrivateUrls && parsed.protocol === "https:" && isLoopbackOnly(parsed.hostname)) {
54
+ fallbackUrl = `http://${parsed.host}${parsed.pathname}`.replace(/\/+$/, "");
55
+ }
56
+ return { ok: true, primaryUrl: mapped, fallbackUrl, origin };
57
+ }
58
+
59
+ const preferredBaseByOrigin = new Map();
60
+
61
+ async function postJsonWithFallback(fetchFn, target, path, bodyObj, headers, timeoutMs) {
62
+ const tryOnce = async (base, ms) => {
63
+ const ac = new AbortController();
64
+ const timer = setTimeout(() => ac.abort(), ms);
65
+ timer.unref?.();
66
+ try {
67
+ const res = await fetchFn(`${base}${path}`, {
68
+ method: "POST",
69
+ headers: { "content-type": "application/json", accept: "application/json", ...headers },
70
+ body: JSON.stringify(bodyObj),
71
+ signal: ac.signal,
72
+ });
73
+ return { ok: true, res };
74
+ } catch {
75
+ return { ok: false };
76
+ } finally {
77
+ clearTimeout(timer);
78
+ }
79
+ };
80
+
81
+ if (!target.fallbackUrl) {
82
+ const only = await tryOnce(target.primaryUrl, timeoutMs);
83
+ return only.res ?? null;
84
+ }
85
+
86
+ const cached = target.origin ? preferredBaseByOrigin.get(target.origin) : null;
87
+ const firstBase = cached === target.fallbackUrl ? target.fallbackUrl : target.primaryUrl;
88
+ const secondBase = firstBase === target.primaryUrl ? target.fallbackUrl : target.primaryUrl;
89
+ const firstTimeout = firstBase === target.primaryUrl ? Math.min(timeoutMs, 250) : timeoutMs;
90
+
91
+ const first = await tryOnce(firstBase, firstTimeout);
92
+ if (first.ok) {
93
+ if (target.origin) {
94
+ if (preferredBaseByOrigin.size > 256) preferredBaseByOrigin.clear();
95
+ preferredBaseByOrigin.set(target.origin, firstBase);
96
+ }
97
+ return first.res ?? null;
98
+ }
99
+ const second = await tryOnce(secondBase, timeoutMs);
100
+ if (second.ok && target.origin) {
101
+ if (preferredBaseByOrigin.size > 256) preferredBaseByOrigin.clear();
102
+ preferredBaseByOrigin.set(target.origin, secondBase);
103
+ }
104
+ return second.res ?? null;
105
+ }
106
+
107
+ export class GossipCoordinator {
108
+ constructor({
109
+ lineageStore,
110
+ listingStore = null,
111
+ keychain = null,
112
+ registryUuaid = null,
113
+ getSelfUrl = () => null,
114
+ getNow = () => undefined,
115
+ defaultCarrierUrl = null,
116
+ allowPrivateUrls = false,
117
+ urlMap = null,
118
+ fetch: fetchImpl = globalThis.fetch,
119
+ timeoutMs = DEFAULT_GOSSIP_TIMEOUT_MS,
120
+ } = {}) {
121
+ this.lineageStore = lineageStore;
122
+ this.listingStore = listingStore;
123
+ this.keychain = keychain;
124
+ this.registryUuaid = registryUuaid ?? keychain?._identity?.uuaid ?? lineageStore?.registryKey?.uuaid ?? null;
125
+ this.getSelfUrl = getSelfUrl;
126
+ this.getNow = getNow;
127
+ this.defaultCarrierUrl = defaultCarrierUrl;
128
+ this.allowPrivateUrls = Boolean(allowPrivateUrls);
129
+ this.urlMap = urlMap;
130
+ this.fetch = fetchImpl;
131
+ this.timeoutMs = timeoutMs;
132
+ this._inFlight = new Set();
133
+ this._dirty = new Map();
134
+ }
135
+
136
+ _peerHomesFor(lineage) {
137
+ const selfOrigin = httpsOrigin(this.getSelfUrl?.());
138
+ return this.lineageStore.getDeclaredHomes(lineage).filter((h) => {
139
+ if (this.registryUuaid && h.uuaid === this.registryUuaid) return false; // @rule gossip.skip-self-uuaid
140
+ const orig = httpsOrigin(h.url);
141
+ if (!orig || (selfOrigin && orig === selfOrigin)) return false; // @rule gossip.skip-self-origin
142
+ return true;
143
+ });
144
+ }
145
+
146
+ /**
147
+ * Push full `uuaid-lineage-log/1` presentation to all declared sibling homes of `lineage`,
148
+ * ingest any new peer receipts returned by those homes, and broadcast newly corroborated claims.
149
+ */
150
+ async syncLineage(lineage, { now, getNow } = {}) {
151
+ if (typeof this.fetch !== "function" || !this.lineageStore) return { pushed: 0, broadcast: 0 };
152
+ if (this._inFlight.has(lineage)) {
153
+ this._dirty.set(lineage, { now, getNow });
154
+ return { pushed: 0, broadcast: 0 };
155
+ }
156
+ const readNow = () => (now !== undefined ? now : (getNow ?? this.getNow)?.());
157
+ const presRes = this.lineageStore.getPresentation(lineage);
158
+ if (!presRes.ok) return { pushed: 0, broadcast: 0 };
159
+
160
+ const peers = this._peerHomesFor(lineage);
161
+ let pushed = 0;
162
+ let learnedFromPeers = false;
163
+
164
+ if (peers.length > 0) {
165
+ this._inFlight.add(lineage);
166
+ try {
167
+ await Promise.all(
168
+ peers.map(async (peer) => {
169
+ const target = resolveOutboundTarget(peer.url, { allowPrivateUrls: this.allowPrivateUrls, urlMap: this.urlMap });
170
+ if (!target.ok) return;
171
+ const res = await postJsonWithFallback(
172
+ this.fetch,
173
+ target,
174
+ "/v1/lineage",
175
+ presRes.presentation,
176
+ { "x-pillar-gossip": "1" },
177
+ this.timeoutMs,
178
+ );
179
+ if (!res?.ok) return;
180
+ pushed += 1;
181
+ const reply = await res.json().catch(() => null);
182
+ if (isPlainObject(reply) && isPlainObject(reply.presentation)) {
183
+ const ing = this.lineageStore.ingestPresentation(reply.presentation, { now: readNow() });
184
+ if (ing.ok && ing.changed) learnedFromPeers = true;
185
+ }
186
+ }),
187
+ );
188
+
189
+ if (learnedFromPeers) {
190
+ const mergedPres = this.lineageStore.getPresentation(lineage);
191
+ if (mergedPres.ok) {
192
+ let learnedInRound2 = false;
193
+ await Promise.all(
194
+ peers.map(async (peer) => {
195
+ const target = resolveOutboundTarget(peer.url, { allowPrivateUrls: this.allowPrivateUrls, urlMap: this.urlMap });
196
+ if (!target.ok) return;
197
+ const res2 = await postJsonWithFallback(
198
+ this.fetch,
199
+ target,
200
+ "/v1/lineage",
201
+ mergedPres.presentation,
202
+ { "x-pillar-gossip": "1" },
203
+ this.timeoutMs,
204
+ );
205
+ if (!res2?.ok) return;
206
+ const reply2 = await res2.json().catch(() => null);
207
+ if (isPlainObject(reply2) && isPlainObject(reply2.presentation)) {
208
+ const ing2 = this.lineageStore.ingestPresentation(reply2.presentation, { now: readNow() });
209
+ if (ing2.ok && ing2.changed) learnedInRound2 = true;
210
+ }
211
+ }),
212
+ );
213
+ if (learnedInRound2) this._dirty.set(lineage, { now, getNow });
214
+ }
215
+ }
216
+ } finally {
217
+ this._inFlight.delete(lineage);
218
+ if (this._dirty.has(lineage)) {
219
+ const nextOpts = this._dirty.get(lineage);
220
+ this._dirty.delete(lineage);
221
+ setImmediate(() => { void this.syncLineage(lineage, nextOpts).catch(() => {}); });
222
+ }
223
+ }
224
+ }
225
+
226
+ const broadcast = await this.broadcastCorroboratedClaims(lineage, { now: readNow() });
227
+ return { pushed, broadcast };
228
+ }
229
+
230
+ /**
231
+ * Broadcast newly corroborated `recovery.claim` events (`>= 2` eligible home receipts)
232
+ * as sealed `kind: "lineage"` envelopes to the lineage's active `carriers[]` (for both
233
+ * the parent working key and active doors).
234
+ */
235
+ async broadcastCorroboratedClaims(lineage, { now, getNow } = {}) {
236
+ if (!this.keychain?._identity || typeof this.fetch !== "function" || !this.lineageStore) return 0;
237
+ const effectiveNow = now !== undefined ? now : (getNow ?? this.getNow)?.();
238
+
239
+ const listingRow = this.listingStore ? this.listingStore.getByLineage(lineage) : null;
240
+ const rawCarriers = [
241
+ ...(Array.isArray(listingRow?.listing?.card?.carriers) ? listingRow.listing.card.carriers : []),
242
+ ...(this.defaultCarrierUrl ? [this.defaultCarrierUrl] : []),
243
+ ];
244
+ const seenOrigins = new Set();
245
+ const carrierTargets = [];
246
+ for (const cUrl of rawCarriers) {
247
+ const t = resolveOutboundTarget(cUrl, { allowPrivateUrls: this.allowPrivateUrls, urlMap: this.urlMap });
248
+ if (!t.ok || seenOrigins.has(t.origin)) continue;
249
+ seenOrigins.add(t.origin);
250
+ carrierTargets.push(t);
251
+ }
252
+ if (!carrierTargets.length) return 0;
253
+
254
+ const pending = this.lineageStore.getPendingClaimBroadcasts(lineage, { now: effectiveNow });
255
+ if (!pending.length) return 0;
256
+
257
+ const presRes = this.lineageStore.getPresentation(lineage);
258
+ if (!presRes.ok) return 0;
259
+
260
+ let deliveredClaims = 0;
261
+ const createdAt = new Date().toISOString();
262
+
263
+ for (const item of pending) {
264
+ let anyAccepted = false;
265
+ for (const rcpt of item.recipients) {
266
+ if (!rcpt?.uuaid || !rcpt?.publicKey) continue;
267
+ const shortRec = String(rcpt.uuaid).split(":").pop().slice(0, 12);
268
+ const envId = `env-claim-${item.claimDigest.slice(0, 24)}-${shortRec}`;
269
+ let env;
270
+ try {
271
+ env = seal(this.keychain, {
272
+ recipient: rcpt.uuaid,
273
+ recipientPublicKey: rcpt.publicKey,
274
+ kind: "lineage",
275
+ payload: presRes.presentation,
276
+ id: envId,
277
+ createdAt,
278
+ });
279
+ } catch {
280
+ continue;
281
+ }
282
+ for (const ct of carrierTargets) {
283
+ const res = await postJsonWithFallback(this.fetch, ct, "/v1/envelopes", env, {}, this.timeoutMs);
284
+ if (res && (res.status === 200 || res.status === 202)) anyAccepted = true;
285
+ }
286
+ }
287
+ if (anyAccepted) {
288
+ this.lineageStore.markClaimBroadcast(lineage, item.claimDigest, { now: effectiveNow });
289
+ deliveredClaims += 1;
290
+ }
291
+ }
292
+ return deliveredClaims;
293
+ }
294
+ }
@@ -0,0 +1,205 @@
1
+ /**
2
+ * Pillar vNext §3 — Single-registry `pillar-heartbeat/1` store (Wave B row B2).
3
+ *
4
+ * Enforces:
5
+ * - Closed `pillar-heartbeat/1` schema shape (`{ v, uuaid, lineage, seq, ts, sig }`).
6
+ * - H-1 clock guard: refuses `ts > now + 5 min` (`future-ts`).
7
+ * - Lineage / listing existence (`404` `not-found`), non-tombstoned check (`lineage-tombstoned`),
8
+ * and current-key binding (`card-key-not-current`).
9
+ * - Strict Ed25519 key & domain-separated signature check (`"pillar-heartbeat/1\n" + jcs(without sig)`).
10
+ * - Strictly increasing `seq` (`seq > prev.seq`, else `stale-heartbeat`).
11
+ * - `<= 1` accepted heartbeat per `3,600,000 ms` (`1 hour`) per lineage (`429` `rate-limited`).
12
+ */
13
+ import { MAX_TOTAL_LINEAGE_BYTES, checkLineageTotalCap, openRegistryDb } from "./federation.mjs";
14
+ import {
15
+ LINEAGE_SKEW_MS,
16
+ isKeyDerivedUuaid,
17
+ isStrictEd25519PublicKey,
18
+ jcs,
19
+ verifyLineageDoc,
20
+ } from "../vendor/pillar-core.mjs";
21
+ import { UUAID_RE, isPlainObject, isStrictDateTime } from "./lineage.mjs";
22
+
23
+ export const HEARTBEAT_VERSION = "pillar-heartbeat/1";
24
+ export const HEARTBEAT_RATE_WINDOW_MS = 3_600_000;
25
+ export const MAX_HEARTBEAT_BODY = 8 * 1024;
26
+
27
+ const HEX128_RE = /^[0-9a-f]{128}$/;
28
+ const HEARTBEAT_KEYS = new Set(["v", "uuaid", "lineage", "seq", "ts", "sig"]);
29
+ const RESOLVED_VERDICTS = new Set(["valid", "recovered", "pending-recovery"]);
30
+
31
+ function nowIso(now) {
32
+ if (typeof now === "string") return now;
33
+ const ms = typeof now === "number" ? now : Date.now();
34
+ return new Date(ms).toISOString().replace(/\.\d{3}Z$/, "Z");
35
+ }
36
+
37
+ export class HeartbeatStore {
38
+ /**
39
+ * @param {object} opts
40
+ * db existing better-sqlite3 Database instance
41
+ * dbPath path to open if `db` is not supplied
42
+ * lineageStore optional LineageStore
43
+ * listingStore optional ListingStore
44
+ * minIntervalMs per-lineage minimum interval between accepted heartbeats (default 3,600,000 ms)
45
+ */
46
+ constructor({
47
+ db,
48
+ dbPath = ":memory:",
49
+ lineageStore = null,
50
+ listingStore = null,
51
+ federationStore = null,
52
+ minIntervalMs = HEARTBEAT_RATE_WINDOW_MS,
53
+ maxTotalLineageBytes = MAX_TOTAL_LINEAGE_BYTES,
54
+ } = {}) {
55
+ this._ownsDb = !db;
56
+ this.db = db ?? openRegistryDb(dbPath);
57
+ if (this._ownsDb) this.db.pragma("journal_mode = WAL");
58
+ this.lineageStore = lineageStore;
59
+ this.listingStore = listingStore;
60
+ this.federationStore = federationStore;
61
+ this.minIntervalMs = minIntervalMs;
62
+ // Counts stored or deleted heartbeats (read caches compare it: V1 F2).
63
+ this.changes = 0;
64
+ this.maxTotalLineageBytes = maxTotalLineageBytes;
65
+
66
+ this.db.exec(`
67
+ create table if not exists heartbeat_latest (
68
+ lineage text primary key,
69
+ uuaid text not null,
70
+ seq integer not null,
71
+ ts text not null,
72
+ ts_ms integer not null,
73
+ received_at text not null,
74
+ received_at_ms integer not null,
75
+ heartbeat_json text not null
76
+ );
77
+ `);
78
+ }
79
+
80
+ close() {
81
+ if (this._ownsDb && this.db.open) this.db.close();
82
+ }
83
+
84
+ setFederationStore(federationStore) {
85
+ this.federationStore = federationStore;
86
+ }
87
+
88
+ getLatest(lineage) {
89
+ const row = this.db.prepare("select * from heartbeat_latest where lineage = ?").get(lineage);
90
+ return row ? { ...row, heartbeat: JSON.parse(row.heartbeat_json) } : null;
91
+ }
92
+
93
+ deleteByLineage(lineage) {
94
+ this.db.prepare("delete from heartbeat_latest where lineage = ?").run(lineage);
95
+ this.changes++;
96
+ }
97
+
98
+ /**
99
+ * Verify and record a `pillar-heartbeat/1` artifact.
100
+ */
101
+ putHeartbeat(hb, { now, federated = false } = {}) {
102
+ const nowStr = nowIso(now);
103
+ const nowMs = Date.parse(nowStr);
104
+
105
+ if (!isPlainObject(hb) || !Object.keys(hb).every((k) => HEARTBEAT_KEYS.has(k))) return { ok: false, status: 400, reason: "malformed-artifact" }; // @rule reg.hb-closed
106
+ if (hb.v !== HEARTBEAT_VERSION) return { ok: false, status: 400, reason: "bad-version" }; // @rule reg.hb-version
107
+ if (typeof hb.lineage !== "string" || !UUAID_RE.test(hb.lineage)) return { ok: false, status: 400, reason: "bad-uuaid" }; // @rule reg.hb-lineage-uuaid
108
+ if (typeof hb.uuaid !== "string" || !UUAID_RE.test(hb.uuaid)) return { ok: false, status: 400, reason: "bad-uuaid" }; // @rule reg.hb-uuaid
109
+ if (!Number.isSafeInteger(hb.seq) || hb.seq < 0) return { ok: false, status: 400, reason: "bad-seq" }; // @rule reg.hb-seq
110
+ if (!isStrictDateTime(hb.ts)) return { ok: false, status: 400, reason: "bad-ts" }; // @rule reg.hb-ts
111
+ const tsMs = Date.parse(hb.ts);
112
+ if (tsMs > nowMs + LINEAGE_SKEW_MS) return { ok: false, status: 400, reason: "future-ts" }; // @rule reg.hb-future-ts
113
+ if (typeof hb.sig !== "string" || !HEX128_RE.test(hb.sig)) return { ok: false, status: 400, reason: "bad-signature" }; // @rule reg.hb-sig-format
114
+
115
+ try {
116
+ jcs(hb);
117
+ } catch {
118
+ return { ok: false, status: 400, reason: "malformed-artifact" };
119
+ }
120
+
121
+ const lineageEval = this.lineageStore ? this.lineageStore.evaluateLineage(hb.lineage, { now: nowStr }) : null;
122
+ const listingRow = this.listingStore ? this.listingStore.getByLineage(hb.lineage) : null;
123
+ if (!lineageEval && !listingRow) return { ok: false, status: 404, reason: "not-found" }; // @rule reg.hb-not-found
124
+
125
+ let pubKey = "";
126
+ if (lineageEval) {
127
+ if (lineageEval.tombstoned === true) return { ok: false, status: 400, reason: "lineage-tombstoned" }; // @rule reg.hb-tombstoned
128
+ if (!RESOLVED_VERDICTS.has(lineageEval.verdict)) return { ok: false, status: 400, reason: lineageEval.verdict === "contested" ? "lineage-contested" : (lineageEval.reasons[0] ?? "card-lineage-unresolved") }; // @rule reg.hb-lineage-valid
129
+ if (hb.uuaid !== lineageEval.current) return { ok: false, status: 400, reason: "card-key-not-current" }; // @rule reg.hb-key-current
130
+ const keyEv = lineageEval.events.find((e) => e?.key?.uuaid === hb.uuaid && typeof e.key.publicKey === "string");
131
+ pubKey = keyEv?.key?.publicKey ?? (listingRow?.listing?.uuaid === hb.uuaid ? listingRow.listing.card?.publicKey ?? "" : "");
132
+ } else {
133
+ if (hb.uuaid !== listingRow.listing.uuaid) return { ok: false, status: 400, reason: "card-key-not-current" }; // @rule reg.hb-listing-key-current
134
+ pubKey = listingRow.listing.card?.publicKey ?? "";
135
+ }
136
+
137
+ if (!isStrictEd25519PublicKey(pubKey)) return { ok: false, status: 400, reason: "weak-key" }; // @rule reg.hb-strict-key
138
+ if (!isKeyDerivedUuaid(hb.uuaid, pubKey)) return { ok: false, status: 400, reason: "key-uuaid-mismatch" }; // @rule reg.hb-key-binding
139
+ if (!verifyLineageDoc(hb, pubKey, hb.sig)) return { ok: false, status: 400, reason: "bad-signature" }; // @rule reg.hb-sig
140
+
141
+ const serialized = JSON.stringify(hb);
142
+ const totalCap = checkLineageTotalCap(hb.lineage, Buffer.byteLength(serialized, "utf8"), {
143
+ maxTotalBytes: this.federationStore?.maxTotalLineageBytes ?? this.maxTotalLineageBytes,
144
+ listingStore: this.listingStore,
145
+ heartbeatStore: this,
146
+ lineageStore: this.lineageStore,
147
+ excludeKind: "heartbeat",
148
+ });
149
+ if (!totalCap.ok) return totalCap;
150
+
151
+ const tx = this.db.transaction(() => {
152
+ const existing = this.db.prepare("select * from heartbeat_latest where lineage = ?").get(hb.lineage);
153
+
154
+ // V1 F6 (2.7.1 A7): the seq and the rate window belong to the key that
155
+ // posted them. After a rotation the new key starts fresh, so a stolen old
156
+ // key's seq 2^53-1 cannot block the owner. Under one key a newer `ts` also
157
+ // passes (signed by the current key, and a replay never has a newer ts),
158
+ // so a client that lost its heartbeat state recovers after one window.
159
+ // An older `ts` never replaces a newer one, whatever its seq: once a
160
+ // client restarts at seq 1, its old high-seq heartbeats are replays.
161
+ let prev = existing ?? null;
162
+ if (prev && prev.uuaid !== hb.uuaid) prev = null; // @rule reg.hb-seq-per-key
163
+ let stale = Boolean(prev) && hb.seq <= prev.seq;
164
+ if (stale && tsMs > prev.ts_ms) stale = false; // @rule reg.hb-newer-ts
165
+ if (prev && tsMs < prev.ts_ms) stale = true; // @rule reg.hb-older-ts
166
+ if (stale) return { ok: false, status: 400, reason: "stale-heartbeat" }; // @rule reg.hb-stale-seq
167
+ if (!federated && prev && nowMs - prev.received_at_ms < this.minIntervalMs) return { ok: false, status: 429, reason: "rate-limited" }; // @rule reg.hb-rate-limit
168
+ if (federated && prev && tsMs - prev.ts_ms < this.minIntervalMs) return { ok: false, status: 429, reason: "rate-limited" };
169
+
170
+ if (existing) {
171
+ this.db
172
+ .prepare(`
173
+ update heartbeat_latest
174
+ set uuaid = ?, seq = ?, ts = ?, ts_ms = ?, received_at = ?, received_at_ms = ?, heartbeat_json = ?
175
+ where lineage = ?
176
+ `)
177
+ .run(hb.uuaid, hb.seq, hb.ts, tsMs, nowStr, nowMs, serialized, hb.lineage);
178
+ } else {
179
+ this.db
180
+ .prepare(`
181
+ insert into heartbeat_latest (lineage, uuaid, seq, ts, ts_ms, received_at, received_at_ms, heartbeat_json)
182
+ values (?, ?, ?, ?, ?, ?, ?, ?)
183
+ `)
184
+ .run(hb.lineage, hb.uuaid, hb.seq, hb.ts, tsMs, nowStr, nowMs, serialized);
185
+ }
186
+
187
+ if (this.federationStore) {
188
+ this.federationStore.notifyLocalIngest(hb.lineage, hb.uuaid);
189
+ }
190
+
191
+ return {
192
+ ok: true,
193
+ lineage: hb.lineage,
194
+ uuaid: hb.uuaid,
195
+ seq: hb.seq,
196
+ ts: hb.ts,
197
+ receivedAt: nowStr,
198
+ };
199
+ });
200
+
201
+ const res = tx();
202
+ if (res?.ok === true) this.changes++;
203
+ return res;
204
+ }
205
+ }