@uuaid/pillar 2.6.0 → 2.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/HOSTING-LIMITS.md +12 -0
  2. package/README.md +201 -5
  3. package/bin/carrier.mjs +72 -2
  4. package/bin/pillar-ask.mjs +4 -1
  5. package/bin/pillar-blob.mjs +6 -0
  6. package/bin/pillar-directory.mjs +280 -16
  7. package/bin/pillar-escrow.mjs +4 -1
  8. package/bin/pillar-group-v2.mjs +6 -0
  9. package/bin/pillar-notify.mjs +13 -0
  10. package/bin/pillar-responder.mjs +266 -23
  11. package/bin/pillar.mjs +504 -255
  12. package/package.json +17 -25
  13. package/src/cli-help.mjs +23 -0
  14. package/src/group-v2-cli.mjs +1 -1
  15. package/src/identity/trust.mjs +72 -6
  16. package/src/mailbox/mailbox.mjs +308 -12
  17. package/src/net/carrier-server.mjs +34 -2
  18. package/src/net/refusals.mjs +2 -0
  19. package/src/net/seed-registry.mjs +2 -1
  20. package/src/net/transport.mjs +308 -92
  21. package/src/node-check.mjs +29 -8
  22. package/src/notify-events.mjs +148 -0
  23. package/src/notify-log.mjs +124 -0
  24. package/src/notify-runner.mjs +372 -0
  25. package/src/notify-store.mjs +725 -0
  26. package/src/notify.mjs +350 -0
  27. package/src/pillar.mjs +382 -27
  28. package/src/readers.mjs +2 -2
  29. package/src/registry/federation.mjs +3056 -0
  30. package/src/registry/gossip.mjs +294 -0
  31. package/src/registry/heartbeats.mjs +195 -0
  32. package/src/registry/lineage-verifier.mjs +972 -0
  33. package/src/registry/lineage.mjs +984 -0
  34. package/src/registry/listings.mjs +549 -0
  35. package/src/registry/resolve.mjs +376 -0
  36. package/src/registry/stats.mjs +508 -0
  37. package/src/sqlite-loader.mjs +40 -0
  38. package/src/vendor/pillar-core.mjs +22 -0
  39. package/src/vendor/uuaid-soul.mjs +2246 -0
  40. package/src/vnext/a6b-common.mjs +270 -0
  41. package/src/vnext/b1-cli.mjs +970 -0
  42. package/src/vnext/card-cli.mjs +370 -0
  43. package/src/vnext/greeter-operator.mjs +160 -0
  44. package/src/vnext/greeter-suggest.mjs +318 -0
  45. package/src/vnext/greeter.mjs +571 -0
  46. package/src/vnext/homes.mjs +48 -0
  47. package/src/vnext/init-cli.mjs +489 -0
  48. package/src/vnext/intro-cli.mjs +81 -0
  49. package/src/vnext/json-dir-mailbox.mjs +296 -0
  50. package/src/vnext/jsonl-mailbox.mjs +1066 -0
  51. package/src/vnext/knock-answer.mjs +162 -0
  52. package/src/vnext/knock-cli.mjs +520 -0
  53. package/src/vnext/knock-lane.mjs +312 -0
  54. package/src/vnext/knock-responder.mjs +344 -0
  55. package/src/vnext/lineage-cli.mjs +653 -0
  56. package/src/vnext/listing-cli.mjs +323 -0
  57. package/src/vnext/resolve-cli.mjs +86 -0
  58. package/src/vnext/soul-cli.mjs +666 -0
  59. package/src/vnext/verify-cli.mjs +251 -0
  60. package/src/vnext/w4-redirect.mjs +178 -0
  61. package/src/vnext/wave-a.mjs +193 -0
  62. package/src/vnext/witness-cli.mjs +547 -0
@@ -0,0 +1,251 @@
1
+ /**
2
+ * `pillar verify <file>` — offline vNext artifact verifier CLI backed by
3
+ * the vendored `@uuaid/pillar-client` core (`verifyArtifact` + `exitCodeFor`).
4
+ *
5
+ * Exit codes (V3):
6
+ * 0 valid
7
+ * 10 recovered | pending-recovery | contested
8
+ * 1 invalid (including non-JSON file content: invalid malformed-artifact)
9
+ * 2 indeterminate
10
+ * 64 usage error (VerifyUsageError, bad flag, missing/unreadable file)
11
+ *
12
+ * Never prints a stack trace on any artifact input or usage error.
13
+ */
14
+ import { readFileSync } from "node:fs";
15
+ import {
16
+ VERDICT_VERSION,
17
+ VERIFY_TYPES,
18
+ VerifyUsageError,
19
+ detectArtifactType,
20
+ exitCodeFor,
21
+ verifyArtifact,
22
+ } from "../vendor/pillar-core.mjs";
23
+ import { isStrictIsoDateTime, nowIsoSeconds } from "./wave-a.mjs";
24
+ import {
25
+ REGISTRY_STATS_VERDICT_TYPE,
26
+ TTFA_VERDICT_TYPE,
27
+ verifyStatsArtifact,
28
+ } from "../registry/stats.mjs";
29
+
30
+ export const VERIFY_CLI_TOOL = "pillar/2.7.0";
31
+ const TYPE_SET = new Set([...VERIFY_TYPES, TTFA_VERDICT_TYPE, REGISTRY_STATS_VERDICT_TYPE]);
32
+
33
+ const VALUE_FLAGS = new Set([
34
+ "home",
35
+ "type",
36
+ "now",
37
+ "uuaid",
38
+ "trusted-issuer",
39
+ "trusted-issuers",
40
+ "verifier-public-key",
41
+ "verifier-key",
42
+ "public-key",
43
+ "registry-uuaid",
44
+ "lineage",
45
+ "required-bits",
46
+ "unreceipted-owner-event",
47
+ ]);
48
+
49
+ const FORBIDDEN_FLAGS = new Set(["first-seen", "local-first-seen", "firstSeen", "localFirstSeen"]);
50
+
51
+ function makeMalformedVerdict(type, now) {
52
+ return {
53
+ v: VERDICT_VERSION,
54
+ type,
55
+ verdict: "invalid",
56
+ reasons: ["malformed-artifact"],
57
+ facts: {},
58
+ checkedAt: now,
59
+ resolved: false,
60
+ tool: VERIFY_CLI_TOOL,
61
+ };
62
+ }
63
+
64
+ function makeFaultVerdict(type, now) {
65
+ return {
66
+ v: VERDICT_VERSION,
67
+ type,
68
+ verdict: "indeterminate",
69
+ reasons: ["verifier-fault"],
70
+ facts: {},
71
+ checkedAt: now,
72
+ resolved: false,
73
+ tool: VERIFY_CLI_TOOL,
74
+ };
75
+ }
76
+
77
+ function formatHumanVerdict(v) {
78
+ const reasons = Array.isArray(v.reasons) && v.reasons.length ? ` ${v.reasons.join(",")}` : "";
79
+ const subj = typeof v.subject === "string" ? ` ${v.subject}` : "";
80
+ return `${v.verdict}${reasons}${subj} (${v.type})\n`;
81
+ }
82
+
83
+ function usageFail(errOut, msg) {
84
+ errOut(`${msg}\n`);
85
+ return { exitCode: 64, verdict: null };
86
+ }
87
+
88
+ function emitVerdict(verdict, json, out) {
89
+ const exitCode = exitCodeFor(verdict);
90
+ out(json ? `${JSON.stringify(verdict)}\n` : formatHumanVerdict(verdict));
91
+ return { exitCode, verdict };
92
+ }
93
+
94
+ /**
95
+ * Parse raw argv tokens after `verify`. Throws `VerifyUsageError` on any bad
96
+ * flag, missing value, forbidden option, or wrong positional count.
97
+ */
98
+ export function parseVerifyArgs(rawArgs) {
99
+ const args = Array.isArray(rawArgs) ? rawArgs : [];
100
+ const positionals = [];
101
+ let json = false;
102
+ let type;
103
+ let now;
104
+ let uuaid;
105
+ const trustedIssuers = [];
106
+ let verifierPublicKey;
107
+ let publicKey;
108
+ let registryUuaid;
109
+ let requireStamp = false;
110
+ let lineageFile;
111
+ let requiredBits;
112
+ let unreceiptedOwnerEvent;
113
+ let endOfFlags = false;
114
+
115
+ for (let i = 0; i < args.length; i++) {
116
+ const tok = args[i];
117
+ if (!endOfFlags && tok === "--") {
118
+ endOfFlags = true;
119
+ continue;
120
+ }
121
+ if (!endOfFlags && tok.startsWith("-") && tok !== "-") {
122
+ const isLong = tok.startsWith("--");
123
+ const eq = isLong ? tok.indexOf("=") : -1;
124
+ const key = isLong ? (eq === -1 ? tok.slice(2) : tok.slice(2, eq)) : "";
125
+ const hasEq = eq !== -1;
126
+
127
+ if (FORBIDDEN_FLAGS.has(key)) throw new VerifyUsageError(`verify: --${key} is forbidden (decision #15 c)`); // @rule verify-cli.forbid-first-seen
128
+
129
+ if (key === "json" || key === "require-stamp") {
130
+ if (hasEq) throw new VerifyUsageError(`verify: --${key} does not take a value`); // @rule verify-cli.json-no-value
131
+ if (key === "json") json = true;
132
+ else requireStamp = true;
133
+ continue;
134
+ }
135
+
136
+ if (!isLong || !VALUE_FLAGS.has(key)) throw new VerifyUsageError(`verify: unknown flag ${tok}`); // @rule verify-cli.unknown-flag
137
+
138
+ let val;
139
+ if (hasEq) {
140
+ val = tok.slice(eq + 1);
141
+ } else {
142
+ if (i + 1 >= args.length) throw new VerifyUsageError(`verify: --${key} requires a value`); // @rule verify-cli.flag-value-required
143
+ if (typeof args[i + 1] === "string" && args[i + 1].startsWith("-") && args[i + 1] !== "-") throw new VerifyUsageError(`verify: --${key} requires a value`); // @rule verify-cli.flag-value-not-flag
144
+ val = args[++i];
145
+ }
146
+
147
+ if (key === "home") {
148
+ // Accepted as a no-op global flag for `pillar --home <dir> verify <file>`.
149
+ } else if (key === "type") type = val;
150
+ else if (key === "now") now = val;
151
+ else if (key === "uuaid") uuaid = val;
152
+ else if (key === "trusted-issuer") trustedIssuers.push(val);
153
+ else if (key === "trusted-issuers") trustedIssuers.push(...val.split(",").map((s) => s.trim()).filter(Boolean));
154
+ else if (key === "verifier-public-key" || key === "verifier-key") verifierPublicKey = val;
155
+ else if (key === "public-key") publicKey = val;
156
+ else if (key === "registry-uuaid") registryUuaid = val;
157
+ else if (key === "lineage") lineageFile = val;
158
+ else if (key === "required-bits") {
159
+ if (!/^\d+$/.test(val)) throw new VerifyUsageError(`verify: --required-bits must be an integer 12..24, got "${val}"`); // @rule verify-cli.required-bits-decimal
160
+ const n = Number(val);
161
+ if (!Number.isSafeInteger(n) || n < 12 || n > 24) throw new VerifyUsageError(`verify: --required-bits must be an integer 12..24, got "${val}"`); // @rule verify-cli.required-bits-number
162
+ requiredBits = n;
163
+ } else if (key === "unreceipted-owner-event") {
164
+ if (val !== "ignored" && val !== "contested") throw new VerifyUsageError(`verify: --unreceipted-owner-event must be "ignored" or "contested"`); // @rule verify-cli.unreceipted-mode
165
+ unreceiptedOwnerEvent = val;
166
+ }
167
+ continue;
168
+ }
169
+ positionals.push(tok);
170
+ }
171
+
172
+ if (positionals.length !== 1) throw new VerifyUsageError("usage: pillar verify <file|-> [--json] [--type <t>] [--now <iso>] [--uuaid <uuaid>] [--trusted-issuer <hex>] [--verifier-public-key <hex>] [--public-key <hex>] [--registry-uuaid <uuaid>] [--require-stamp] [--lineage <file>] [--required-bits <n>]"); // @rule verify-cli.file-arg-count
173
+
174
+ const effectiveNow = now !== undefined ? now : nowIsoSeconds();
175
+ if (!isStrictIsoDateTime(effectiveNow)) throw new VerifyUsageError("verify: --now must be a valid ISO-8601 timestamp"); // @rule verify-cli.now-valid
176
+ if (type !== undefined && !TYPE_SET.has(type)) throw new VerifyUsageError(`verify: unknown --type "${type}"`); // @rule verify-cli.type-known
177
+
178
+ const opts = { now: effectiveNow };
179
+ if (type !== undefined) opts.type = type;
180
+ if (uuaid !== undefined) opts.uuaid = uuaid;
181
+ if (trustedIssuers.length > 0) opts.trustedIssuers = trustedIssuers;
182
+ if (verifierPublicKey !== undefined) opts.verifierPublicKey = verifierPublicKey;
183
+ if (publicKey !== undefined) opts.publicKey = publicKey;
184
+ if (registryUuaid !== undefined) opts.registryUuaid = registryUuaid;
185
+ if (requireStamp) opts.requireStamp = true;
186
+ if (requiredBits !== undefined) opts.requiredBits = requiredBits;
187
+ if (unreceiptedOwnerEvent !== undefined) opts.unreceiptedOwnerEvent = unreceiptedOwnerEvent;
188
+
189
+ return { file: positionals[0], json, lineageFile, opts };
190
+ }
191
+
192
+ /**
193
+ * Execute `pillar verify` with injectable streams. Returns `{ exitCode, verdict }`.
194
+ * Never throws; never prints a stack trace.
195
+ */
196
+ export function runVerifyCli(rawArgs, io = {}) {
197
+ const out = io.stdout ?? ((s) => process.stdout.write(s));
198
+ const errOut = io.stderr ?? ((s) => process.stderr.write(s));
199
+ const readStdin = io.readStdin ?? (() => readFileSync(0, "utf8"));
200
+
201
+ let parsed;
202
+ try {
203
+ parsed = parseVerifyArgs(rawArgs);
204
+ } catch (e) {
205
+ return usageFail(errOut, e instanceof Error ? e.message : String(e));
206
+ }
207
+
208
+ const { file, json, lineageFile, opts } = parsed;
209
+
210
+ if (lineageFile !== undefined) {
211
+ let rawLin = null;
212
+ try { rawLin = readFileSync(lineageFile, "utf8"); } catch { rawLin = null; }
213
+ if (rawLin === null) return usageFail(errOut, `verify: cannot read --lineage file "${lineageFile}"`); // @rule verify-cli.lineage-file-readable
214
+ try { opts.lineage = JSON.parse(rawLin); } catch { opts.lineage = undefined; }
215
+ if (opts.lineage === undefined) return usageFail(errOut, `verify: --lineage file "${lineageFile}" is not valid JSON`); // @rule verify-cli.lineage-file-json
216
+ }
217
+
218
+ let rawText = null;
219
+ try { rawText = file === "-" ? readStdin() : readFileSync(file, "utf8"); } catch { rawText = null; }
220
+ if (rawText === null) return usageFail(errOut, `verify: cannot read "${file}"`); // @rule verify-cli.file-readable
221
+
222
+ let artifact;
223
+ let jsonOk = true;
224
+ try { artifact = JSON.parse(rawText); } catch { jsonOk = false; }
225
+ if (!jsonOk) {
226
+ if (opts.type === undefined) return usageFail(errOut, "verify: cannot detect the artifact type; pass --type <t>"); // @rule verify-cli.non-json-no-type-64
227
+ return emitVerdict(makeMalformedVerdict(opts.type, opts.now), json, out); // @rule verify-cli.non-json-malformed
228
+ }
229
+
230
+ let verdict;
231
+ // B8 types (`pillar-ttfa-report/1`, `pillar-registry-stats/1`) are verified by
232
+ // `src/registry/stats.mjs` before the frozen core sees the artifact; the core
233
+ // does not know their versions and its own dispatch stays untouched.
234
+ const statsVerdict = verifyStatsArtifact(artifact, opts);
235
+ if (statsVerdict) {
236
+ return emitVerdict({ ...statsVerdict, tool: VERIFY_CLI_TOOL }, json, out);
237
+ }
238
+ try {
239
+ verdict = verifyArtifact(artifact, opts);
240
+ } catch (e) {
241
+ if (e instanceof VerifyUsageError) return usageFail(errOut, e.message); // @rule verify-cli.usage-error-64
242
+ let faultType = opts.type ?? null;
243
+ if (!faultType) {
244
+ try { faultType = detectArtifactType(artifact); } catch { faultType = null; }
245
+ }
246
+ if (!faultType) return usageFail(errOut, "verify: cannot detect the artifact type; pass --type <t>");
247
+ return emitVerdict(makeFaultVerdict(faultType, opts.now), json, out);
248
+ }
249
+
250
+ return emitVerdict({ ...verdict, tool: VERIFY_CLI_TOOL }, json, out);
251
+ }
@@ -0,0 +1,178 @@
1
+ /**
2
+ * Pillar vNext §2 — W-4 sender redirect policy, `@uuaid/pillar` side (B5, T2.7).
3
+ */
4
+ import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
5
+ import { dirname, join } from "node:path";
6
+ import { isValidUuaid } from "./a6b-common.mjs";
7
+
8
+ export const W4_REDIRECT_MAP_FILENAME = "w4-redirect.json";
9
+ export const W4_CONFIRM_CODE = "confirm-recovered-redirect";
10
+ export const W4_BLOCKED_PREFIX = "redirect-blocked:";
11
+ export const W4_CAPABILITY_BIT = "w4SenderRedirect";
12
+ export const W4_BLOCKED_VERDICTS = new Set(["pending-recovery", "contested", "invalid", "indeterminate"]);
13
+ export const W4_MAP_MAX_ENTRIES = 256;
14
+ const HEAD_RE = /^sha256:[0-9a-f]{64}$/;
15
+ const RECORD_KEYS = new Set(["queried", "current", "lineage", "lineageHead", "verdict", "confirmed", "updatedAt"]);
16
+ const CONFIRM_KEYS = new Set(["current", "lineageHead"]);
17
+ const VERDICTS = ["valid", "recovered", "pending-recovery", "contested", "invalid", "indeterminate"];
18
+ const hasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
19
+ const isPlain = (x) => {
20
+ if (!x || typeof x !== "object" || Array.isArray(x)) return false;
21
+ const proto = Object.getPrototypeOf(x);
22
+ return proto === Object.prototype || proto === null;
23
+ };
24
+ const isPlainClosed = (x, allow) =>
25
+ isPlain(x) && Reflect.ownKeys(x).every((k) => typeof k === "string" && k !== "__proto__" && k !== "prototype" && k !== "constructor" && allow.has(k));
26
+
27
+ export function w4IsBlockedVerdict(v) {
28
+ let ok = false;
29
+ ok = typeof v === "string" && W4_BLOCKED_VERDICTS.has(v); // @rule w4p.blocked-set
30
+ return ok;
31
+ }
32
+
33
+ export function w4BlockedCode(v) {
34
+ if (!w4IsBlockedVerdict(v)) throw new TypeError("w4: not a blocked verdict"); // @rule w4p.blocked-code-guard
35
+ return `${W4_BLOCKED_PREFIX}${v}`;
36
+ }
37
+
38
+ export function isW4SenderRedirectEnabled(capabilities) {
39
+ if (!isPlain(capabilities)) return false; // @rule w4p.capability-default-off
40
+ let en = false;
41
+ en = capabilities[W4_CAPABILITY_BIT] === true; // @rule w4p.capability-explicit-true
42
+ return en;
43
+ }
44
+
45
+ function verdictOf(v) {
46
+ let out;
47
+ out = VERDICTS.find((c) => v?.verdict === c); // @rule w4p.verdict-allowlist
48
+ return out;
49
+ }
50
+
51
+ function headOf(verdict) {
52
+ const f = verdict?.facts?.head;
53
+ let out;
54
+ if (typeof f === "string" && HEAD_RE.test(f)) out = f; // @rule w4p.head-from-verified-facts
55
+ return out;
56
+ }
57
+
58
+ export function w4ClassifyVerifiedTarget(q, res) {
59
+ if (!isValidUuaid(q)) throw new TypeError("w4: bad queried uuaid"); // @rule w4p.classify-uuaid
60
+ if (!isPlain(res)) throw new TypeError("w4: bad resolve result"); // @rule w4p.classify-res-shape
61
+ const rr = res ?? {}, verdict = rr.lineageVerdict, v = verdictOf(verdict);
62
+ const card = rr.ok === true && isPlain(rr.card) ? rr.card : undefined, head = headOf(verdict);
63
+ let current, lineage, m = {};
64
+ current = isValidUuaid(verdict?.facts?.current) ? verdict.facts.current : rr.ok === true && isValidUuaid(rr.current) ? rr.current : undefined; // @rule w4p.classify-current-verified
65
+ lineage = rr.ok === true && isValidUuaid(rr.lineage) ? rr.lineage : isValidUuaid(verdict?.subject) ? verdict.subject : undefined; // @rule w4p.classify-lineage-verified
66
+ m = { ...(v !== undefined ? { verdict: v } : {}), ...(current !== undefined ? { current } : {}), ...(lineage !== undefined ? { lineage } : {}), ...(head !== undefined ? { lineageHead: head } : {}), ...(card !== undefined ? { card } : {}) }; // @rule w4p.classify-meta
67
+
68
+ if (rr.ok !== true) {
69
+ if (v !== undefined && w4IsBlockedVerdict(v)) return { kind: "blocked-verdict", ...m }; // @rule w4p.classify-fail-verdict
70
+ return { kind: "unresolved", ...m }; // @rule w4p.classify-fail-recovered-pending
71
+ }
72
+ if (current !== undefined && q === current) return { kind: "active-current", ...m }; // @rule w4p.classify-active-current
73
+ const activeFactDoors = Array.isArray(verdict?.facts?.doors) ? verdict.facts.doors.filter((k) => isValidUuaid(k)) : [];
74
+ const retiredFactDoors = Array.isArray(verdict?.facts?.retiredDoors) ? verdict.facts.retiredDoors.filter((k) => isValidUuaid(k)) : [];
75
+ if (activeFactDoors.includes(q)) return { kind: "active-door", ...m }; // @rule w4p.classify-active-door
76
+ if (retiredFactDoors.includes(q)) return { kind: "retired-door", ...m }; // @rule w4p.classify-retired-door
77
+ const keyPath = Array.isArray(verdict?.facts?.keyPath) ? verdict.facts.keyPath.filter((k) => isValidUuaid(k)) : [];
78
+ if (keyPath.includes(q) && current !== undefined && q !== current) return { kind: "retired-key", ...m }; // @rule w4p.classify-retired-key
79
+ return { kind: "unresolved", ...m };
80
+ }
81
+
82
+ export function w4ApplyPolicy(c, opts) {
83
+ if (!isPlain(opts)) throw new TypeError("w4: bad opts"); // @rule w4p.policy-opts
84
+ const o = opts ?? {};
85
+ if (!isValidUuaid(o.queried)) throw new TypeError("w4: bad queried uuaid"); // @rule w4p.policy-queried
86
+ const now = o.now ?? new Date().toISOString().replace(/\.\d{3}Z$/, "Z");
87
+ if (typeof now !== "string" || Number.isNaN(Date.parse(now)) || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(now)) throw new TypeError("w4: bad now"); // @rule w4p.policy-now
88
+ const confirm = o.confirmRecovered;
89
+
90
+ if (c.kind === "active-current" || c.kind === "active-door") return { action: "send-direct", kind: c.kind }; // @rule w4p.policy-send-direct
91
+ if (c.kind === "blocked-verdict") {
92
+ if (c.verdict === undefined || !w4IsBlockedVerdict(c.verdict)) throw new TypeError("w4: blocked classification lacks blocked verdict"); // @rule w4p.policy-blocked-guard
93
+ let out = { action: "unresolved", kind: "unresolved" };
94
+ out = { action: "blocked", kind: "blocked-verdict", code: w4BlockedCode(c.verdict), verdict: c.verdict }; // @rule w4p.policy-blocked
95
+ return out;
96
+ }
97
+ if (c.kind !== "retired-key" && c.kind !== "retired-door") return { action: "unresolved", kind: "unresolved" }; // @rule w4p.policy-unresolved
98
+
99
+ const redirectable = () => {
100
+ if (!c.current || !c.lineage || !c.lineageHead) throw new TypeError("w4: classification lacks verified redirect facts"); // @rule w4p.redirect-facts-required
101
+ return { current: c.current ?? "", lineage: c.lineage ?? "", head: c.lineageHead ?? "" };
102
+ };
103
+
104
+ if (c.verdict === "valid") {
105
+ const { current, lineage, head } = redirectable();
106
+ if (c.verdict === "valid") return { action: "redirect", kind: c.kind, record: { queried: o.queried, current, lineage, lineageHead: head, verdict: "valid", updatedAt: now } }; // @rule w4p.policy-redirect-valid
107
+ }
108
+
109
+ if (c.verdict === "recovered") {
110
+ const { current, lineage, head } = redirectable();
111
+ const rec = () => ({ queried: o.queried, current, lineage, lineageHead: head, verdict: "recovered", confirmed: true, updatedAt: now });
112
+ if (confirm === true) return { action: "redirect", kind: c.kind, record: rec() }; // @rule w4p.policy-redirect-recovered-confirmed
113
+ if (isPlain(confirm)) {
114
+ let closedOk = true, nonEmpty = true, curOk = true, headOk = true;
115
+ closedOk = isPlainClosed(confirm, CONFIRM_KEYS); // @rule w4p.policy-confirm-closed
116
+ nonEmpty = hasOwn(confirm, "current") || hasOwn(confirm, "lineageHead"); // @rule w4p.policy-confirm-nonempty
117
+ curOk = !hasOwn(confirm, "current") || confirm.current === current; // @rule w4p.policy-confirm-current-match
118
+ headOk = !hasOwn(confirm, "lineageHead") || confirm.lineageHead === head; // @rule w4p.policy-confirm-head-match
119
+ if (closedOk && nonEmpty && curOk && headOk) return { action: "redirect", kind: c.kind, record: rec() }; // @rule w4p.policy-redirect-recovered-confirmed-obj
120
+ }
121
+ if (c.verdict === "recovered") return { action: "refuse-confirm", kind: c.kind, details: { queried: o.queried, current, lineage, lineageHead: head, witnessRecovery: true } }; // @rule w4p.policy-refuse-recovered
122
+ }
123
+
124
+ if (c.verdict !== undefined && w4IsBlockedVerdict(c.verdict)) return { action: "blocked", kind: "blocked-verdict", code: w4BlockedCode(c.verdict), verdict: c.verdict }; // @rule w4p.policy-retired-blocked
125
+ if (!c.verdict || !w4IsBlockedVerdict(c.verdict)) throw new TypeError("w4: retired classification lacks a locally-verified verdict"); // @rule w4p.policy-unverified-verdict
126
+ throw new TypeError("unreachable");
127
+ }
128
+
129
+ function isRecord(v) {
130
+ if (!isPlainClosed(v, RECORD_KEYS)) return false; // @rule w4p.record-closed-shape
131
+ const r = v ?? {};
132
+ if (!isValidUuaid(r.queried) || !isValidUuaid(r.current) || !isValidUuaid(r.lineage)) return false; // @rule w4p.record-uaids
133
+ if (typeof r.lineageHead !== "string" || !HEAD_RE.test(r.lineageHead)) return false; // @rule w4p.record-head
134
+ if (r.verdict !== "valid" && r.verdict !== "recovered") return false; // @rule w4p.record-verdict
135
+ if (r.verdict === "recovered" && r.confirmed !== true) return false; // @rule w4p.record-recovered-confirmed
136
+ if (r.verdict === "valid" && r.confirmed === true) return false; // @rule w4p.record-valid-unconfirmed
137
+ if (typeof r.updatedAt !== "string" || Number.isNaN(Date.parse(r.updatedAt)) || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(r.updatedAt)) return false; // @rule w4p.record-updated-at
138
+ return true;
139
+ }
140
+
141
+ export function loadRedirectMap(home) {
142
+ const p = join(home, W4_REDIRECT_MAP_FILENAME);
143
+ let raw = "";
144
+ try { raw = readFileSync(p, "utf8"); }
145
+ catch (e) {
146
+ if (e?.code === "ENOENT") return {}; // @rule w4p.map-missing
147
+ throw e;
148
+ }
149
+ let parsed, badJ = false;
150
+ try { parsed = JSON.parse(raw); } catch { badJ = true; }
151
+ if (badJ) return {}; // @rule w4p.map-bad-json
152
+ if (!isPlain(parsed)) throw new TypeError("w4: redirect map is valid JSON but not an object"); // @rule w4p.map-not-object
153
+ const out = {};
154
+ for (const [k, v] of Object.entries(parsed ?? {})) {
155
+ if (!isValidUuaid(k) || !isRecord(v)) continue; // @rule w4p.map-entry-validate
156
+ out[k] = v;
157
+ if (Object.keys(out).length >= W4_MAP_MAX_ENTRIES) break; // @rule w4p.map-entry-cap
158
+ }
159
+ return out;
160
+ }
161
+
162
+ export function recordRedirect(home, record) {
163
+ if (!isRecord(record)) throw new TypeError("w4: bad redirect record"); // @rule w4p.record-persist-validate
164
+ const map = loadRedirectMap(home);
165
+ map[record.queried] = record; // @rule w4p.record-upsert
166
+ const entries = Object.entries(map);
167
+ if (entries.length > W4_MAP_MAX_ENTRIES) {
168
+ entries.sort((a, b) => (a[1].updatedAt < b[1].updatedAt ? -1 : 1)); // @rule w4p.record-evict-oldest
169
+ for (const [k] of entries.slice(0, entries.length - W4_MAP_MAX_ENTRIES)) delete map[k];
170
+ }
171
+ const p = join(home, W4_REDIRECT_MAP_FILENAME);
172
+ mkdirSync(dirname(p), { recursive: true }); // @rule w4p.record-mkdir
173
+ const tmp = `${p}.tmp.${process.pid}.${Date.now()}`;
174
+ writeFileSync(tmp, `${JSON.stringify(map, null, 2)}\n`, { mode: 0o600 });
175
+ chmodSync(tmp, 0o600);
176
+ renameSync(tmp, p);
177
+ return record;
178
+ }
@@ -0,0 +1,193 @@
1
+ /**
2
+ * Shared Wave A helpers for `@uuaid/pillar` 2.7.0 vNext CLI verbs.
3
+ *
4
+ * Uses the byte-pinned vendored core (`../vendor/pillar-core.mjs`).
5
+ * Enforces owner decision #23 (Wave A): zero witnesses, zero homes,
6
+ * refusal identical to `open()` before any keygen, signing, or disk write.
7
+ */
8
+ import { createPrivateKey, createPublicKey } from "node:crypto";
9
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
10
+ import { dirname } from "node:path";
11
+ import {
12
+ CARD_KEY,
13
+ LINEAGE_LOG_KEY,
14
+ WAVE_A_WITNESS_HOME_REFUSAL_CODE,
15
+ WaveARefusalError,
16
+ assertWaveANoWitnessesOrHomes,
17
+ eventDigest,
18
+ } from "../vendor/pillar-core.mjs";
19
+
20
+ export {
21
+ CARD_KEY,
22
+ LINEAGE_LOG_KEY,
23
+ WAVE_A_WITNESS_HOME_REFUSAL_CODE,
24
+ WaveARefusalError,
25
+ assertWaveANoWitnessesOrHomes,
26
+ eventDigest,
27
+ };
28
+
29
+ const PKCS8_ED25519_PREFIX = Buffer.from("302e020100300506032b657004220420", "hex");
30
+ const STRICT_ISO_DT_RE = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(Z|[+-](\d{2}):(\d{2}))$/;
31
+ const DAYS_IN_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
32
+
33
+ const WITNESS_FLAGS = new Set([
34
+ "witness",
35
+ "witnesses",
36
+ "add-witness",
37
+ "remove-witness",
38
+ "set-witnesses",
39
+ ]);
40
+
41
+ const HOME_REGISTRY_FLAGS = new Set([
42
+ "homes",
43
+ "home-registry",
44
+ "home-registries",
45
+ "lineage-home",
46
+ "lineage-homes",
47
+ "add-home",
48
+ "remove-home",
49
+ "set-homes",
50
+ ]);
51
+
52
+ const THRESHOLD_FLAGS = new Set(["witness-threshold"]);
53
+ const M_FLAGS = new Set(["m"]);
54
+
55
+ export function nowIsoSeconds() {
56
+ return new Date().toISOString().replace(/\.\d{3}Z$/, "Z");
57
+ }
58
+
59
+ export function isStrictIsoDateTime(value) {
60
+ if (typeof value !== "string") return false;
61
+ const m = STRICT_ISO_DT_RE.exec(value);
62
+ if (!m) return false;
63
+ const year = +m[1];
64
+ const month = +m[2];
65
+ const day = +m[3];
66
+ const hr = +m[4];
67
+ const min = +m[5];
68
+ const sec = +m[6];
69
+ const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
70
+ const maxDay = month === 2 && leap ? 29 : (DAYS_IN_MONTH[month] ?? 0);
71
+ if (month < 1 || month > 12 || day < 1 || day > maxDay) return false;
72
+ if (hr > 23 || min > 59 || sec > 59 || (m[7] !== "Z" && (+m[8] > 23 || +m[9] > 59))) return false;
73
+ return Number.isFinite(Date.parse(value));
74
+ }
75
+
76
+ function normalizeFlagName(rawKey) {
77
+ return rawKey
78
+ .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
79
+ .replace(/_/g, "-")
80
+ .toLowerCase();
81
+ }
82
+
83
+ /**
84
+ * Scan raw CLI argv tokens (after the command/subcommand) for any witness,
85
+ * lineage-home, or witness-threshold option. Note: `--home` (singular) is
86
+ * pillar's local data directory path and is NOT a lineage home registry option.
87
+ *
88
+ * Returns an object suitable for `assertWaveANoWitnessesOrHomes(opts)`.
89
+ */
90
+ export function extractWaveAWitnessHomeOpts(rawArgs) {
91
+ const out = {};
92
+ const list = Array.isArray(rawArgs) ? rawArgs : [];
93
+ const witnesses = [];
94
+ const homes = [];
95
+ let sawWitness = false;
96
+ let sawHome = false;
97
+
98
+ for (let i = 0; i < list.length; i++) {
99
+ const token = list[i];
100
+ if (typeof token !== "string" || token === "--") continue;
101
+ if (/^-m\d/.test(token)) { out.m = token.slice(2); continue; } // @rule vnext.wave-a-glued-m
102
+ if (token === "-m" || token.startsWith("-m=")) {
103
+ const val = token.startsWith("-m=")
104
+ ? token.slice(3)
105
+ : (i + 1 < list.length && typeof list[i + 1] === "string" && !list[i + 1].startsWith("-") ? list[++i] : true);
106
+ out.m = val;
107
+ continue;
108
+ }
109
+ if (!token.startsWith("--") || token.length <= 2) continue;
110
+ const eq = token.indexOf("=");
111
+ const rawKey = eq === -1 ? token.slice(2) : token.slice(2, eq);
112
+ const key = normalizeFlagName(rawKey);
113
+ const hasEq = eq !== -1;
114
+ let val;
115
+ if (hasEq) {
116
+ val = token.slice(eq + 1);
117
+ } else if (i + 1 < list.length && typeof list[i + 1] === "string" && !list[i + 1].startsWith("-")) {
118
+ val = list[i + 1];
119
+ } else {
120
+ val = true;
121
+ }
122
+
123
+ if (WITNESS_FLAGS.has(key)) {
124
+ sawWitness = true;
125
+ if (typeof val === "string" && val.trim().length > 0) {
126
+ witnesses.push(...val.split(",").map((s) => s.trim()).filter(Boolean));
127
+ }
128
+ } else if (HOME_REGISTRY_FLAGS.has(key)) {
129
+ sawHome = true;
130
+ if (typeof val === "string" && val.trim().length > 0) {
131
+ homes.push(...val.split(",").map((s) => s.trim()).filter(Boolean));
132
+ }
133
+ } else if (THRESHOLD_FLAGS.has(key)) {
134
+ out.witnessThreshold = val;
135
+ } else if (M_FLAGS.has(key)) {
136
+ out.m = val;
137
+ }
138
+ }
139
+
140
+ if (sawWitness) {
141
+ out.witnesses = witnesses.length > 0 ? witnesses : ["<named>"];
142
+ }
143
+ if (sawHome) {
144
+ out.homes = homes.length > 0 ? homes : ["<named>"];
145
+ }
146
+ return out;
147
+ }
148
+
149
+ /** Convert a 32-byte Ed25519 seed hex + UUAID into a Keychain-saveable identity object. */
150
+ export function keychainIdentityFromSeedHex(seedHex, uuaid, createdAt) {
151
+ const seed = Buffer.from(seedHex, "hex");
152
+ const privateKey = createPrivateKey({
153
+ key: Buffer.concat([PKCS8_ED25519_PREFIX, seed]),
154
+ format: "der",
155
+ type: "pkcs8",
156
+ });
157
+ const publicKey = createPublicKey(privateKey);
158
+ const pubDer = publicKey.export({ type: "spki", format: "der" });
159
+ const rawPub = pubDer.subarray(pubDer.length - 32);
160
+ return {
161
+ uuaid,
162
+ publicKey,
163
+ privateKey,
164
+ publicKeyHex: Buffer.from(rawPub).toString("hex"),
165
+ createdAt: createdAt ?? nowIsoSeconds(),
166
+ };
167
+ }
168
+
169
+ /** Extract the 32-byte Ed25519 seed hex from a loaded Keychain identity object. */
170
+ export function seedHexFromKeychainIdentity(identity) {
171
+ const der = identity.privateKey.export({ type: "pkcs8", format: "der" });
172
+ return Buffer.from(der.subarray(der.length - 32)).toString("hex");
173
+ }
174
+
175
+ /** Write a file atomically via sibling temp file + rename. */
176
+ export function writeFileAtomic(filePath, content, mode = 0o600) {
177
+ mkdirSync(dirname(filePath), { recursive: true });
178
+ const tmp = `${filePath}.tmp-${process.pid}-${Math.random().toString(16).slice(2, 10)}`;
179
+ writeFileSync(tmp, content, { mode });
180
+ renameSync(tmp, filePath);
181
+ }
182
+
183
+ /** Read recovery sheet words from `--recovery-sheet` or `--recovery-sheet-file`. */
184
+ export function readRecoverySheetWords(opts) {
185
+ if (typeof opts.recoverySheet === "string") {
186
+ return opts.recoverySheet.trim().split(/\s+/).filter(Boolean);
187
+ }
188
+ if (typeof opts.recoverySheetFile === "string") {
189
+ const text = readFileSync(opts.recoverySheetFile, "utf8");
190
+ return text.trim().split(/\s+/).filter(Boolean);
191
+ }
192
+ return null;
193
+ }