@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.
- package/README.md +201 -5
- package/bin/carrier.mjs +21 -0
- package/bin/pillar-ask.mjs +4 -1
- package/bin/pillar-blob.mjs +6 -0
- package/bin/pillar-directory.mjs +280 -16
- package/bin/pillar-escrow.mjs +4 -1
- package/bin/pillar-group-v2.mjs +6 -0
- package/bin/pillar-notify.mjs +13 -0
- package/bin/pillar-responder.mjs +266 -23
- package/bin/pillar.mjs +504 -255
- package/package.json +17 -25
- package/src/cli-help.mjs +23 -0
- package/src/group-v2-cli.mjs +1 -1
- package/src/identity/trust.mjs +72 -6
- package/src/mailbox/mailbox.mjs +308 -12
- package/src/net/carrier-server.mjs +34 -2
- package/src/net/refusals.mjs +2 -0
- package/src/net/seed-registry.mjs +2 -1
- package/src/net/transport.mjs +308 -92
- package/src/node-check.mjs +29 -8
- package/src/notify-events.mjs +148 -0
- package/src/notify-log.mjs +124 -0
- package/src/notify-runner.mjs +372 -0
- package/src/notify-store.mjs +725 -0
- package/src/notify.mjs +350 -0
- package/src/pillar.mjs +382 -27
- package/src/readers.mjs +2 -2
- package/src/registry/federation.mjs +3056 -0
- package/src/registry/gossip.mjs +294 -0
- package/src/registry/heartbeats.mjs +195 -0
- package/src/registry/lineage-verifier.mjs +972 -0
- package/src/registry/lineage.mjs +984 -0
- package/src/registry/listings.mjs +549 -0
- package/src/registry/resolve.mjs +376 -0
- package/src/registry/stats.mjs +508 -0
- package/src/sqlite-loader.mjs +40 -0
- package/src/vendor/pillar-core.mjs +22 -0
- package/src/vendor/uuaid-soul.mjs +2246 -0
- package/src/vnext/a6b-common.mjs +270 -0
- package/src/vnext/b1-cli.mjs +970 -0
- package/src/vnext/card-cli.mjs +370 -0
- package/src/vnext/greeter-operator.mjs +160 -0
- package/src/vnext/greeter-suggest.mjs +318 -0
- package/src/vnext/greeter.mjs +571 -0
- package/src/vnext/homes.mjs +48 -0
- package/src/vnext/init-cli.mjs +489 -0
- package/src/vnext/intro-cli.mjs +81 -0
- package/src/vnext/json-dir-mailbox.mjs +296 -0
- package/src/vnext/jsonl-mailbox.mjs +1066 -0
- package/src/vnext/knock-answer.mjs +162 -0
- package/src/vnext/knock-cli.mjs +520 -0
- package/src/vnext/knock-lane.mjs +312 -0
- package/src/vnext/knock-responder.mjs +344 -0
- package/src/vnext/lineage-cli.mjs +653 -0
- package/src/vnext/listing-cli.mjs +323 -0
- package/src/vnext/resolve-cli.mjs +86 -0
- package/src/vnext/soul-cli.mjs +666 -0
- package/src/vnext/verify-cli.mjs +251 -0
- package/src/vnext/w4-redirect.mjs +178 -0
- package/src/vnext/wave-a.mjs +193 -0
- package/src/vnext/witness-cli.mjs +547 -0
|
@@ -0,0 +1,547 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pillar vNext Wave B B1 — Interactive witness rules (`D-2`, `D-3`, `D-4`),
|
|
3
|
+
* recovery-sheet corroboration warning (`exportRecoverySheetCheck`), and HTTP
|
|
4
|
+
* home lineage fetch/publish helpers for `@uuaid/pillar` CLI.
|
|
5
|
+
*
|
|
6
|
+
* Uses the byte-pinned vendored core (`../vendor/pillar-core.mjs`).
|
|
7
|
+
*/
|
|
8
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
|
|
9
|
+
import { dirname, join } from "node:path";
|
|
10
|
+
import {
|
|
11
|
+
durMs,
|
|
12
|
+
eligibleHomes,
|
|
13
|
+
eventDigest,
|
|
14
|
+
keyRecord,
|
|
15
|
+
nextCommitment,
|
|
16
|
+
parseUuaid,
|
|
17
|
+
verifyLineageDoc,
|
|
18
|
+
verifyLineageFromHomes,
|
|
19
|
+
verifySeenReceipt,
|
|
20
|
+
vouchRecoveryClaim,
|
|
21
|
+
} from "../vendor/pillar-core.mjs";
|
|
22
|
+
import { isLoopbackHostname } from "./a6b-common.mjs";
|
|
23
|
+
import { isStrictIsoDateTime, nowIsoSeconds, writeFileAtomic } from "./wave-a.mjs";
|
|
24
|
+
|
|
25
|
+
export const WITNESS_CLAIMS_STATE_KEY = "witness/claims.json";
|
|
26
|
+
export const WITNESS_AUDIT_LOG_KEY = "witness/audit.jsonl";
|
|
27
|
+
|
|
28
|
+
const HEX64_RE = /^[0-9a-f]{64}$/;
|
|
29
|
+
const HEX128_RE = /^[0-9a-f]{128}$/;
|
|
30
|
+
const UUAID_RE = /^uuaid:[a-z][a-z0-9-]{0,31}:[a-z][a-z0-9-]{0,31}:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
31
|
+
|
|
32
|
+
export function stripShaPrefix(value) {
|
|
33
|
+
const s = typeof value === "string" ? value.trim().toLowerCase() : "";
|
|
34
|
+
return s.startsWith("sha256:") ? s.slice(7) : s;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function formatFingerprint16(hexOrPrefixed) {
|
|
38
|
+
const clean = stripShaPrefix(hexOrPrefixed);
|
|
39
|
+
if (!HEX64_RE.test(clean)) throw new TypeError("formatFingerprint16: expected 64 lowercase hex chars"); // @rule pillar-witness.fp-input-hex64
|
|
40
|
+
return `${clean.slice(0, 16)}...${clean.slice(-16)}`;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function matchesFingerprint16(fullHexOrPrefixed, candidate) {
|
|
44
|
+
const full = stripShaPrefix(fullHexOrPrefixed);
|
|
45
|
+
const cand = stripShaPrefix(candidate);
|
|
46
|
+
if (!HEX64_RE.test(full)) return false;
|
|
47
|
+
if (HEX64_RE.test(cand)) return cand === full; // @rule pillar-witness.fp-exact-64
|
|
48
|
+
const m = /^([0-9a-f]{16,32})\.\.\.([0-9a-f]{16,32})$/.exec(cand);
|
|
49
|
+
if (!m) return false; // @rule pillar-witness.fp-min16-both-ends
|
|
50
|
+
if (!full.startsWith(m[1]) || !full.endsWith(m[2])) return false; // @rule pillar-witness.fp-prefix-suffix-match
|
|
51
|
+
return true;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function chainActiveState(log) {
|
|
55
|
+
let key = log?.[0]?.key ?? null;
|
|
56
|
+
let next = typeof log?.[0]?.next === "string" ? log[0].next : "";
|
|
57
|
+
let contestWindow = "P7D";
|
|
58
|
+
let witnesses = [];
|
|
59
|
+
let witnessThreshold = 0;
|
|
60
|
+
let homes = [];
|
|
61
|
+
const doors = new Map();
|
|
62
|
+
const lineagePublicKeys = new Set();
|
|
63
|
+
const nextCommitments = new Set();
|
|
64
|
+
const claimsByDigest = new Map();
|
|
65
|
+
|
|
66
|
+
for (const ev of Array.isArray(log) ? log : []) {
|
|
67
|
+
if (!ev || typeof ev !== "object") continue;
|
|
68
|
+
if (typeof ev.key?.publicKey === "string") lineagePublicKeys.add(ev.key.publicKey.toLowerCase());
|
|
69
|
+
if (typeof ev.reveal?.publicKey === "string") lineagePublicKeys.add(ev.reveal.publicKey.toLowerCase());
|
|
70
|
+
if (typeof ev.next === "string") nextCommitments.add(ev.next.toLowerCase());
|
|
71
|
+
if (typeof ev.contestWindow === "string") contestWindow = ev.contestWindow;
|
|
72
|
+
if (ev.type === "inception") {
|
|
73
|
+
if (ev.key && typeof ev.next === "string") { key = ev.key; next = ev.next; }
|
|
74
|
+
witnesses = Array.isArray(ev.witnesses) ? ev.witnesses : [];
|
|
75
|
+
witnessThreshold = typeof ev.witnessThreshold === "number" ? ev.witnessThreshold : 0;
|
|
76
|
+
homes = Array.isArray(ev.homes) ? ev.homes : [];
|
|
77
|
+
for (const d of Array.isArray(ev.doors) ? ev.doors : []) {
|
|
78
|
+
if (d?.uuaid && d?.publicKey) doors.set(d.uuaid, d);
|
|
79
|
+
}
|
|
80
|
+
} else if (ev.type === "rotation") {
|
|
81
|
+
if (ev.key && typeof ev.next === "string") { key = ev.key; next = ev.next; }
|
|
82
|
+
if ("witnesses" in ev) {
|
|
83
|
+
witnesses = Array.isArray(ev.witnesses) ? ev.witnesses : [];
|
|
84
|
+
witnessThreshold = typeof ev.witnessThreshold === "number" ? ev.witnessThreshold : 0;
|
|
85
|
+
} else if (typeof ev.witnessThreshold === "number") {
|
|
86
|
+
witnessThreshold = ev.witnessThreshold;
|
|
87
|
+
}
|
|
88
|
+
if ("homes" in ev) homes = Array.isArray(ev.homes) ? ev.homes : [];
|
|
89
|
+
} else if (ev.type === "recovery.claim" && ev.key && typeof ev.next === "string") {
|
|
90
|
+
try { claimsByDigest.set(eventDigest(ev), { key: ev.key, next: ev.next }); } catch {}
|
|
91
|
+
} else if (ev.type === "recovery.final" && typeof ev.claim === "string") {
|
|
92
|
+
const fc = claimsByDigest.get(stripShaPrefix(ev.claim));
|
|
93
|
+
if (fc) { key = fc.key; next = fc.next; }
|
|
94
|
+
} else if (ev.type === "door.add" && ev.door?.uuaid && ev.door?.publicKey) {
|
|
95
|
+
doors.set(ev.door.uuaid, ev.door);
|
|
96
|
+
} else if (ev.type === "door.retire") {
|
|
97
|
+
const retiredId = typeof ev.door === "string" ? ev.door : ev.door?.uuaid;
|
|
98
|
+
if (retiredId) doors.delete(retiredId);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
return {
|
|
103
|
+
key,
|
|
104
|
+
next,
|
|
105
|
+
contestWindow,
|
|
106
|
+
witnesses,
|
|
107
|
+
witnessThreshold,
|
|
108
|
+
homes,
|
|
109
|
+
doors: [...doors.values()],
|
|
110
|
+
lineagePublicKeys: [...lineagePublicKeys],
|
|
111
|
+
nextCommitments: [...nextCommitments],
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function validateWitnessSetD4(candidates, opts = {}) {
|
|
116
|
+
const warnings = [];
|
|
117
|
+
const bad = (reason) => ({ ok: false, reason, warnings });
|
|
118
|
+
if (!Array.isArray(candidates) || candidates.length < 2 || candidates.length > 16) {
|
|
119
|
+
return bad("witness-count-min-2"); // @rule pillar-d4.min-two-witnesses
|
|
120
|
+
}
|
|
121
|
+
const ns = opts.namespace ?? "pillar";
|
|
122
|
+
const m = opts.witnessThreshold ?? opts.m ?? Math.ceil((candidates.length + 1) / 2);
|
|
123
|
+
if (!Number.isInteger(m) || m < 2 || m > candidates.length) {
|
|
124
|
+
return bad("witness-threshold-min-2"); // @rule pillar-d4.threshold-min-2
|
|
125
|
+
}
|
|
126
|
+
const lc = (arr) => (Array.isArray(arr) ? arr.map((x) => String(x).toLowerCase()) : []);
|
|
127
|
+
const forbiddenPubs = new Set([
|
|
128
|
+
...lc(opts.lineagePublicKeys),
|
|
129
|
+
...lc(opts.doorPublicKeys),
|
|
130
|
+
...lc(opts.homePublicKeys),
|
|
131
|
+
]);
|
|
132
|
+
const localPubs = new Set(lc(opts.localHostPublicKeys));
|
|
133
|
+
const forbiddenNext = new Set(lc(opts.nextCommitments));
|
|
134
|
+
const recentKnocks = new Set(Array.isArray(opts.recentKnockUuaids) ? opts.recentKnockUuaids : []);
|
|
135
|
+
|
|
136
|
+
const seenUuaids = new Set();
|
|
137
|
+
const seenDevices = new Set();
|
|
138
|
+
const witnesses = [];
|
|
139
|
+
|
|
140
|
+
for (const c of candidates) {
|
|
141
|
+
let rec;
|
|
142
|
+
try { rec = keyRecord(c, ns); } catch { return bad("key-uuaid-mismatch"); }
|
|
143
|
+
if (seenUuaids.has(rec.uuaid)) return bad("witness-duplicate"); // @rule pillar-d4.no-dup-witness
|
|
144
|
+
seenUuaids.add(rec.uuaid);
|
|
145
|
+
if (forbiddenPubs.has(rec.publicKey) || forbiddenNext.has(nextCommitment(rec))) {
|
|
146
|
+
return bad("witness-not-disjoint"); // @rule pillar-d4.disjoint-keys
|
|
147
|
+
}
|
|
148
|
+
if (c?.sameHost === true || localPubs.has(rec.publicKey) || (opts.agentDeviceId && c?.deviceId === opts.agentDeviceId)) {
|
|
149
|
+
return bad("witness-on-same-host"); // @rule pillar-d4.zero-same-host
|
|
150
|
+
}
|
|
151
|
+
const dev = typeof c?.deviceId === "string" ? c.deviceId.trim() : "";
|
|
152
|
+
if (dev) {
|
|
153
|
+
if (seenDevices.has(dev)) return bad("multiple-witnesses-same-device"); // @rule pillar-d4.max-one-per-device
|
|
154
|
+
seenDevices.add(dev);
|
|
155
|
+
}
|
|
156
|
+
if (c?.tier === "W2") {
|
|
157
|
+
if (opts.phase === "init") return bad("w2-witness-forbidden-at-init"); // @rule pillar-d4.w2-rotate-only
|
|
158
|
+
if (c?.fromRecentKnock === true || recentKnocks.has(rec.uuaid)) {
|
|
159
|
+
return bad("w2-witness-from-recent-knock"); // @rule pillar-d4.w2-never-recent-knock
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
witnesses.push(rec);
|
|
163
|
+
}
|
|
164
|
+
if (witnesses.length === 2 && m === 2) {
|
|
165
|
+
warnings.push("n=2,m=2 loses recovery on single witness loss; recommend n=3,m=2"); // @rule pillar-d4.warn-2of2
|
|
166
|
+
}
|
|
167
|
+
return { ok: true, witnesses, witnessThreshold: m, warnings };
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export function validStampTimesForEvent(receipts, lineage, targetDigestHex, eligHomes, now) {
|
|
171
|
+
const byHome = new Map();
|
|
172
|
+
for (const rec of Array.isArray(receipts) ? receipts : []) {
|
|
173
|
+
for (const h of eligHomes) {
|
|
174
|
+
if (rec?.registry !== h.uuaid) continue;
|
|
175
|
+
const v = verifySeenReceipt(rec, {
|
|
176
|
+
lineage,
|
|
177
|
+
event: targetDigestHex,
|
|
178
|
+
home: h,
|
|
179
|
+
now,
|
|
180
|
+
});
|
|
181
|
+
if (!v.ok) continue;
|
|
182
|
+
const t = Date.parse(rec.seenAt);
|
|
183
|
+
const prev = byHome.get(h.uuaid);
|
|
184
|
+
if (prev === undefined || t < prev) byHome.set(h.uuaid, t);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
return [...byHome.values()].sort((a, b) => a - b);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
export function exportRecoverySheetCheck(log, receipts, opts = {}) {
|
|
191
|
+
const now = opts.now ?? nowIsoSeconds();
|
|
192
|
+
const st = chainActiveState(log);
|
|
193
|
+
let est = log[0];
|
|
194
|
+
for (const ev of log) {
|
|
195
|
+
if (ev?.type === "inception" || ev?.type === "rotation") est = ev;
|
|
196
|
+
if (ev?.type === "recovery.final") est = ev; // @rule pillar-sheet.include-recovery-final
|
|
197
|
+
}
|
|
198
|
+
const digest = eventDigest(est);
|
|
199
|
+
const elig = eligibleHomes(st.homes, st.witnesses);
|
|
200
|
+
if (!elig.length && !st.witnesses.length) {
|
|
201
|
+
return { corroborated: true, stampsFound: 0, stampsRequired: 0, eventDigest: digest, seq: est.seq, warning: null };
|
|
202
|
+
}
|
|
203
|
+
const stampsFound = validStampTimesForEvent(receipts, log[0].lineage, digest, elig, now).length;
|
|
204
|
+
const uncorroboratedResult = {
|
|
205
|
+
corroborated: false,
|
|
206
|
+
stampsFound,
|
|
207
|
+
stampsRequired: 2,
|
|
208
|
+
eventDigest: digest,
|
|
209
|
+
seq: est.seq,
|
|
210
|
+
warningCode: "rotation-uncorroborated",
|
|
211
|
+
warning: `seq ${est.seq} (${formatFingerprint16(digest)}) has ${stampsFound}/2 home stamps; keep previous recovery sheet until >= 2 homes stamp`,
|
|
212
|
+
};
|
|
213
|
+
if (stampsFound < 2) return uncorroboratedResult; // @rule pillar-sheet.warn-under-two-stamps
|
|
214
|
+
return { corroborated: true, stampsFound, stampsRequired: 2, eventDigest: digest, seq: est.seq, warning: null };
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
export function resolveHomeTargetUrl(baseUrl, pathSuffix, { urlMap, allowInsecureLoopback = false } = {}) {
|
|
218
|
+
let u;
|
|
219
|
+
try { u = new URL(baseUrl); } catch { return null; }
|
|
220
|
+
const origin = `${u.protocol}//${u.host}`;
|
|
221
|
+
let mapped = urlMap?.[baseUrl] ?? urlMap?.[origin] ?? origin;
|
|
222
|
+
if (allowInsecureLoopback && mapped.startsWith("https://")) {
|
|
223
|
+
const mu = new URL(mapped);
|
|
224
|
+
if (isLoopbackHostname(mu.hostname)) mapped = `http://${mu.host}`;
|
|
225
|
+
}
|
|
226
|
+
return `${mapped.replace(/\/+$/, "")}${pathSuffix}`;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
export async function pullLineageHomes(lineage, homes, {
|
|
230
|
+
localEvents = [],
|
|
231
|
+
localReceipts = [],
|
|
232
|
+
now = nowIsoSeconds(),
|
|
233
|
+
fetch: fetchFn = globalThis.fetch,
|
|
234
|
+
timeoutMs = 5000,
|
|
235
|
+
urlMap,
|
|
236
|
+
allowInsecureLoopback = false,
|
|
237
|
+
} = {}) {
|
|
238
|
+
const byDigest = new Map();
|
|
239
|
+
const recMap = new Map();
|
|
240
|
+
const homeEventSets = new Map();
|
|
241
|
+
|
|
242
|
+
const addEv = (ev) => {
|
|
243
|
+
if (!ev || typeof ev !== "object" || ev.v !== "uuaid-lineage/1") return null;
|
|
244
|
+
try {
|
|
245
|
+
const d = eventDigest(ev);
|
|
246
|
+
const prev = byDigest.get(d);
|
|
247
|
+
if (prev && Array.isArray(prev.sigs) && Array.isArray(ev.sigs)) {
|
|
248
|
+
const merged = [...prev.sigs];
|
|
249
|
+
for (const s of ev.sigs) {
|
|
250
|
+
if (s && !merged.some((m) => m.by === s.by && m.sig === s.sig)) merged.push(s);
|
|
251
|
+
}
|
|
252
|
+
byDigest.set(d, { ...prev, sigs: merged });
|
|
253
|
+
} else if (!prev) {
|
|
254
|
+
byDigest.set(d, ev);
|
|
255
|
+
}
|
|
256
|
+
return d;
|
|
257
|
+
} catch {
|
|
258
|
+
return null;
|
|
259
|
+
}
|
|
260
|
+
};
|
|
261
|
+
|
|
262
|
+
const addRec = (rec) => {
|
|
263
|
+
if (!rec || typeof rec !== "object" || rec.lineage !== lineage) return;
|
|
264
|
+
const h = homes.find((x) => x.uuaid === rec.registry);
|
|
265
|
+
if (!h) return;
|
|
266
|
+
if (!verifySeenReceipt(rec, { lineage, home: h, now }).ok) return;
|
|
267
|
+
const key = `${rec.registry}:${rec.event}`;
|
|
268
|
+
const prev = recMap.get(key);
|
|
269
|
+
if (!prev || Date.parse(rec.seenAt) < Date.parse(prev.seenAt)) recMap.set(key, rec);
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
for (const e of localEvents) addEv(e);
|
|
273
|
+
for (const r of localReceipts) addRec(r);
|
|
274
|
+
|
|
275
|
+
const responses = await Promise.all(
|
|
276
|
+
homes.map(async (h) => {
|
|
277
|
+
const target = resolveHomeTargetUrl(h.url, `/v1/lineage/${encodeURIComponent(lineage)}`, { urlMap, allowInsecureLoopback });
|
|
278
|
+
if (!target) return { registry: h.uuaid, unreachable: true };
|
|
279
|
+
const ctrl = new AbortController();
|
|
280
|
+
const timer = setTimeout(() => ctrl.abort(), timeoutMs);
|
|
281
|
+
try {
|
|
282
|
+
const res = await fetchFn(target, { headers: { accept: "application/json" }, signal: ctrl.signal });
|
|
283
|
+
if (!res.ok) return { registry: h.uuaid, unreachable: true };
|
|
284
|
+
const body = await res.json().catch(() => null);
|
|
285
|
+
if (!body || typeof body !== "object" || body.v !== "uuaid-lineage-log/1" || !Array.isArray(body.events)) {
|
|
286
|
+
return { registry: h.uuaid, events: [null] };
|
|
287
|
+
}
|
|
288
|
+
const set = new Set();
|
|
289
|
+
for (const e of body.events) {
|
|
290
|
+
const d = addEv(e);
|
|
291
|
+
if (d) set.add(d);
|
|
292
|
+
}
|
|
293
|
+
homeEventSets.set(h.uuaid, set);
|
|
294
|
+
const recs = Array.isArray(body.receipts) ? body.receipts : [];
|
|
295
|
+
for (const r of recs) addRec(r);
|
|
296
|
+
return { registry: h.uuaid, events: body.events, receipts: recs };
|
|
297
|
+
} catch {
|
|
298
|
+
return { registry: h.uuaid, unreachable: true };
|
|
299
|
+
} finally {
|
|
300
|
+
clearTimeout(timer);
|
|
301
|
+
}
|
|
302
|
+
}),
|
|
303
|
+
);
|
|
304
|
+
|
|
305
|
+
return { responses, byDigest, recMap, homeEventSets };
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
export async function postLineageEventToHomes(ev, lineage, homes, {
|
|
309
|
+
now = nowIsoSeconds(),
|
|
310
|
+
fetch: fetchFn = globalThis.fetch,
|
|
311
|
+
timeoutMs = 5000,
|
|
312
|
+
urlMap,
|
|
313
|
+
allowInsecureLoopback = false,
|
|
314
|
+
} = {}) {
|
|
315
|
+
const evDigest = eventDigest(ev);
|
|
316
|
+
const receipts = [];
|
|
317
|
+
const refusals = [];
|
|
318
|
+
let acceptedCount = 0;
|
|
319
|
+
|
|
320
|
+
await Promise.all(
|
|
321
|
+
homes.map(async (h) => {
|
|
322
|
+
const target = resolveHomeTargetUrl(h.url, "/v1/lineage", { urlMap, allowInsecureLoopback });
|
|
323
|
+
if (!target) {
|
|
324
|
+
refusals.push({ home: h.uuaid, url: h.url, statusCode: null, reason: "invalid-home-url" });
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
const ctrl = new AbortController();
|
|
328
|
+
const timer = setTimeout(() => ctrl.abort(), timeoutMs);
|
|
329
|
+
try {
|
|
330
|
+
const res = await fetchFn(target, {
|
|
331
|
+
method: "POST",
|
|
332
|
+
headers: { "content-type": "application/json", accept: "application/json" },
|
|
333
|
+
body: JSON.stringify(ev),
|
|
334
|
+
signal: ctrl.signal,
|
|
335
|
+
});
|
|
336
|
+
const body = await res.json().catch(() => null);
|
|
337
|
+
if (!res.ok) {
|
|
338
|
+
const reason = typeof body?.reason === "string" ? body.reason : typeof body?.error === "string" ? body.error : `http-${res.status}`;
|
|
339
|
+
refusals.push({ home: h.uuaid, url: h.url, statusCode: res.status, reason });
|
|
340
|
+
return;
|
|
341
|
+
}
|
|
342
|
+
acceptedCount++;
|
|
343
|
+
const candList = [
|
|
344
|
+
...(body?.receipt ? [body.receipt] : []),
|
|
345
|
+
...(Array.isArray(body?.receipts) ? body.receipts : []),
|
|
346
|
+
];
|
|
347
|
+
for (const cand of candList) {
|
|
348
|
+
if (verifySeenReceipt(cand, {
|
|
349
|
+
lineage,
|
|
350
|
+
event: evDigest,
|
|
351
|
+
home: h,
|
|
352
|
+
now,
|
|
353
|
+
}).ok) {
|
|
354
|
+
receipts.push(cand);
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
} catch (e) {
|
|
358
|
+
refusals.push({ home: h.uuaid, url: h.url, statusCode: null, reason: e instanceof Error ? e.message : "network-error" });
|
|
359
|
+
} finally {
|
|
360
|
+
clearTimeout(timer);
|
|
361
|
+
}
|
|
362
|
+
}),
|
|
363
|
+
);
|
|
364
|
+
|
|
365
|
+
return { acceptedCount, receipts, refusals };
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
export async function witnessVouchHome({
|
|
369
|
+
witnessHome,
|
|
370
|
+
witnessSigner,
|
|
371
|
+
lineage,
|
|
372
|
+
homes,
|
|
373
|
+
claimDigest: wantedRaw,
|
|
374
|
+
claimEvent,
|
|
375
|
+
confirmedNewKeyFingerprint,
|
|
376
|
+
confirmedMethod,
|
|
377
|
+
cardName,
|
|
378
|
+
now: rawNow,
|
|
379
|
+
fetch: fetchFn = globalThis.fetch,
|
|
380
|
+
timeoutMs = 5000,
|
|
381
|
+
urlMap,
|
|
382
|
+
allowInsecureLoopback = false,
|
|
383
|
+
namespace,
|
|
384
|
+
}) {
|
|
385
|
+
if (claimEvent !== undefined) return { ok: false, reason: "claim-must-be-fetched-from-home" }; // @rule pillar-d2.never-accept-claimant-payload
|
|
386
|
+
if (typeof lineage !== "string" || !UUAID_RE.test(lineage)) return { ok: false, reason: "bad-lineage" }; // @rule pillar-d2.lineage-uuaid
|
|
387
|
+
const now = rawNow ?? nowIsoSeconds();
|
|
388
|
+
if (!isStrictIsoDateTime(now)) throw new TypeError("witness vouch: --now must be a strict ISO-8601 timestamp"); // @rule pillar-d2.now-strict
|
|
389
|
+
if (typeof confirmedMethod !== "string" || !confirmedMethod.trim()) return { ok: false, reason: "confirmation-method-required" }; // @rule pillar-d3.method-required
|
|
390
|
+
if (typeof fetchFn !== "function" || !Array.isArray(homes) || homes.length < 2) return { ok: false, reason: "homes-required" }; // @rule pillar-d2.homes-min2
|
|
391
|
+
|
|
392
|
+
const ns = namespace ?? parseUuaid(lineage).namespace;
|
|
393
|
+
const wRec = keyRecord(witnessSigner, ns);
|
|
394
|
+
let { responses, byDigest, recMap } = await pullLineageHomes(lineage, homes, {
|
|
395
|
+
now,
|
|
396
|
+
fetch: fetchFn,
|
|
397
|
+
timeoutMs,
|
|
398
|
+
urlMap,
|
|
399
|
+
allowInsecureLoopback,
|
|
400
|
+
});
|
|
401
|
+
|
|
402
|
+
const evalBase = (rs, m) => {
|
|
403
|
+
const parentDigests = new Set([...m.values()].map((e) => e?.prev).filter((p) => typeof p === "string"));
|
|
404
|
+
const finalClaims = new Set([...m.values()].filter((e) => e?.type === "recovery.final" && typeof e.claim === "string").map((e) => stripShaPrefix(e.claim)));
|
|
405
|
+
const dgOf = (e) => { try { return e && typeof e === "object" ? eventDigest(e) : ""; } catch { return ""; } };
|
|
406
|
+
const v1 = verifyLineageFromHomes(
|
|
407
|
+
lineage,
|
|
408
|
+
rs.map((r) => ({ ...r, events: Array.isArray(r.events) ? r.events.filter((e) => !(e && typeof e === "object" && e.type === "recovery.claim" && !parentDigests.has(dgOf(e)))) : r.events })),
|
|
409
|
+
{ now },
|
|
410
|
+
);
|
|
411
|
+
if (v1.verdict === "valid" || v1.verdict === "recovered") return v1;
|
|
412
|
+
return verifyLineageFromHomes(
|
|
413
|
+
lineage,
|
|
414
|
+
rs.map((r) => ({
|
|
415
|
+
...r,
|
|
416
|
+
events: Array.isArray(r.events)
|
|
417
|
+
? r.events.filter((e) => !(e && typeof e === "object" && ((e.type === "recovery.claim" && !finalClaims.has(dgOf(e))) || (e.type === "recovery.veto" && !finalClaims.has(stripShaPrefix(e.claim ?? ""))))))
|
|
418
|
+
: r.events,
|
|
419
|
+
})),
|
|
420
|
+
{ now },
|
|
421
|
+
);
|
|
422
|
+
};
|
|
423
|
+
const baseV = evalBase(responses, byDigest);
|
|
424
|
+
if (baseV.verdict !== "valid" && baseV.verdict !== "recovered") {
|
|
425
|
+
return { ok: false, reason: baseV.reasons[0] ?? `lineage-${baseV.verdict}` }; // @rule pillar-d2.base-lineage-valid
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
const headHex = stripShaPrefix(baseV.facts.head ?? "");
|
|
429
|
+
const wanted = wantedRaw ? stripShaPrefix(wantedRaw) : "";
|
|
430
|
+
|
|
431
|
+
const chain = [];
|
|
432
|
+
for (let cur = byDigest.get(headHex); cur; cur = typeof cur.prev === "string" ? byDigest.get(cur.prev) : undefined) {
|
|
433
|
+
chain.unshift(cur);
|
|
434
|
+
}
|
|
435
|
+
const st = chainActiveState(chain);
|
|
436
|
+
const declHomes = st.homes.length ? st.homes : [...homes];
|
|
437
|
+
const elig = eligibleHomes(declHomes, st.witnesses);
|
|
438
|
+
|
|
439
|
+
let fullPull = null;
|
|
440
|
+
if (st.homes.some((h) => !homes.some((o) => o?.uuaid === h.uuaid && o?.publicKey === h.publicKey && o?.url === h.url))) fullPull = await pullLineageHomes(lineage, st.homes, { localEvents: [...byDigest.values()], localReceipts: [], now, fetch: fetchFn, timeoutMs, urlMap, allowInsecureLoopback }); // @rule pillar-d2.pull-all-declared-homes
|
|
441
|
+
if (fullPull) {
|
|
442
|
+
responses = fullPull.responses;
|
|
443
|
+
byDigest = fullPull.byDigest;
|
|
444
|
+
recMap = fullPull.recMap;
|
|
445
|
+
const baseV2 = evalBase(responses, byDigest);
|
|
446
|
+
if ((baseV2.verdict !== "valid" && baseV2.verdict !== "recovered") || stripShaPrefix(baseV2.facts.head ?? "") !== headHex) {
|
|
447
|
+
return { ok: false, reason: baseV2.reasons[0] ?? "claim-parent-not-head" };
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
const hit = [...byDigest.entries()].find(([d, e]) => e?.type === "recovery.claim" && (!wanted || d === wanted));
|
|
452
|
+
if (!hit) return { ok: false, reason: "claim-not-found-on-homes" }; // @rule pillar-d2.claim-on-home
|
|
453
|
+
const [claimDigest, claim] = hit;
|
|
454
|
+
if (claim.prev !== headHex) return { ok: false, reason: "claim-parent-not-head" }; // @rule pillar-d2.claim-prev-is-head
|
|
455
|
+
|
|
456
|
+
let cKey;
|
|
457
|
+
try { cKey = keyRecord(claim.key, ns); } catch { return { ok: false, reason: "key-uuaid-mismatch" }; }
|
|
458
|
+
const hasSig = (doc, u, pk) =>
|
|
459
|
+
Array.isArray(doc?.sigs) &&
|
|
460
|
+
doc.sigs.some((s) => s?.by === u && HEX128_RE.test(s?.sig ?? "") && verifyLineageDoc(doc, pk, s.sig));
|
|
461
|
+
if (cKey.uuaid !== claim.key?.uuaid || !hasSig(claim, cKey.uuaid, cKey.publicKey)) {
|
|
462
|
+
return { ok: false, reason: "claim-missing-newkey-sig" }; // @rule pillar-d2.claim-self-sig
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
if (!st.witnesses.some((w) => w.uuaid === wRec.uuaid && w.publicKey === wRec.publicKey)) {
|
|
466
|
+
return { ok: false, reason: "not-a-designated-witness" }; // @rule pillar-d2.must-be-witness
|
|
467
|
+
}
|
|
468
|
+
if (!matchesFingerprint16(cKey.publicKey, confirmedNewKeyFingerprint)) {
|
|
469
|
+
return { ok: false, reason: "fingerprint-mismatch" }; // @rule pillar-d3.fingerprint-match
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
const statePath = join(witnessHome, WITNESS_CLAIMS_STATE_KEY);
|
|
473
|
+
const priors = existsSync(statePath) ? JSON.parse(readFileSync(statePath, "utf8")) : [];
|
|
474
|
+
const allRecs = [...recMap.values()];
|
|
475
|
+
const tipSeq = chain[chain.length - 1]?.seq ?? 0;
|
|
476
|
+
const unreachElig = elig.filter((eh) => responses.some((r) => r.registry === eh.uuaid && r.unreachable)).length;
|
|
477
|
+
const isVerifiedVeto = (vd, ve, prDigest, Ec) => {
|
|
478
|
+
if (ve?.type !== "recovery.veto" || ve.seq !== tipSeq + 2 || ve.prev !== prDigest || ve.claim !== prDigest || !isStrictIsoDateTime(ve.ts)) return false;
|
|
479
|
+
let sigOk = Boolean(st.key && hasSig(ve, st.key.uuaid, st.key.publicKey));
|
|
480
|
+
if (!sigOk && typeof ve.nextKey === "string") {
|
|
481
|
+
try {
|
|
482
|
+
const nr = keyRecord({ publicKeyHex: ve.nextKey }, ns);
|
|
483
|
+
sigOk = nextCommitment(nr) === st.next && hasSig(ve, nr.uuaid, nr.publicKey);
|
|
484
|
+
} catch {}
|
|
485
|
+
}
|
|
486
|
+
if (!sigOk) return false; // @rule pillar-d2.verify-veto-sig
|
|
487
|
+
return validStampTimesForEvent(allRecs, lineage, vd, elig, now).filter((t) => t < Ec).length >= 2;
|
|
488
|
+
};
|
|
489
|
+
for (const pr of priors.filter((p) => p.lineage === lineage && p.claimDigest !== claimDigest)) {
|
|
490
|
+
const cTs = validStampTimesForEvent(allRecs, lineage, pr.claimDigest, elig, now);
|
|
491
|
+
const corr = cTs.length + unreachElig >= 2;
|
|
492
|
+
const stale = pr.prev !== headHex;
|
|
493
|
+
const Ec = cTs.length >= 2 ? cTs[1] + (durMs(st.contestWindow) ?? 7 * 86_400_000) : Infinity;
|
|
494
|
+
const vetoed = !stale && [...byDigest.entries()].some(([vd, ve]) => isVerifiedVeto(vd, ve, pr.claimDigest, Ec));
|
|
495
|
+
if (pr.keyPublicKey !== cKey.publicKey || pr.next !== claim.next) {
|
|
496
|
+
if (corr && !stale && !vetoed) return { ok: false, reason: "conflicting-claim-active" }; // @rule pillar-d2.refuse-conflicting-claim
|
|
497
|
+
} else {
|
|
498
|
+
if (corr && !stale && !vetoed) return { ok: false, reason: "prior-claim-still-live" }; // @rule pillar-d2.refuse-live-duplicate
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
const vouched = vouchRecoveryClaim(claim, witnessSigner, ns);
|
|
503
|
+
const posted = await postLineageEventToHomes(vouched, lineage, declHomes, {
|
|
504
|
+
now,
|
|
505
|
+
fetch: fetchFn,
|
|
506
|
+
timeoutMs,
|
|
507
|
+
urlMap,
|
|
508
|
+
allowInsecureLoopback,
|
|
509
|
+
});
|
|
510
|
+
|
|
511
|
+
const nextPriors = [
|
|
512
|
+
...priors.filter((p) => p.claimDigest !== claimDigest),
|
|
513
|
+
{
|
|
514
|
+
lineage,
|
|
515
|
+
claimDigest,
|
|
516
|
+
keyUuaid: cKey.uuaid,
|
|
517
|
+
keyPublicKey: cKey.publicKey,
|
|
518
|
+
next: claim.next,
|
|
519
|
+
prev: String(claim.prev),
|
|
520
|
+
signedAt: now,
|
|
521
|
+
},
|
|
522
|
+
];
|
|
523
|
+
writeFileAtomic(statePath, `${JSON.stringify(nextPriors, null, 2)}\n`, 0o600);
|
|
524
|
+
|
|
525
|
+
const auditPath = join(witnessHome, WITNESS_AUDIT_LOG_KEY);
|
|
526
|
+
mkdirSync(dirname(auditPath), { recursive: true });
|
|
527
|
+
const auditEntry = `${JSON.stringify({ lineage, claim: claimDigest, newKey: cKey.uuaid, next: claim.next, method: confirmedMethod.trim(), at: now })}\n`;
|
|
528
|
+
appendFileSync(auditPath, auditEntry, { mode: 0o600 }); // @rule pillar-d3.local-audit-log
|
|
529
|
+
|
|
530
|
+
return {
|
|
531
|
+
ok: true,
|
|
532
|
+
claimDigest,
|
|
533
|
+
vouchedEvent: vouched,
|
|
534
|
+
homesUpdated: posted.acceptedCount,
|
|
535
|
+
receipts: posted.receipts,
|
|
536
|
+
display: {
|
|
537
|
+
lineage,
|
|
538
|
+
cardName: cardName ?? null,
|
|
539
|
+
prev: String(claim.prev),
|
|
540
|
+
prevFingerprint: formatFingerprint16(String(claim.prev)),
|
|
541
|
+
newKey: cKey,
|
|
542
|
+
newKeyFingerprint: formatFingerprint16(cKey.publicKey),
|
|
543
|
+
next: claim.next,
|
|
544
|
+
nextFingerprint: formatFingerprint16(claim.next),
|
|
545
|
+
},
|
|
546
|
+
};
|
|
547
|
+
}
|