@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,333 @@
1
+ /**
2
+ * `pillar verify <file>` — offline vNext artifact verifier CLI backed by
3
+ * the vendored `@uuaid/pillar-client` core (`verifyArtifact` + `exitCodeFor`).
4
+ * `pillar verify <uuaid>` — live: core `resolve()` against a registry, which
5
+ * verifies the listing, card and lineage and fails closed (2.7.1 A9).
6
+ *
7
+ * Exit codes (V3):
8
+ * 0 valid
9
+ * 10 recovered | pending-recovery | contested
10
+ * 1 invalid (including non-JSON file content: invalid malformed-artifact)
11
+ * 2 indeterminate
12
+ * 64 usage error (VerifyUsageError, bad flag, missing/unreadable file)
13
+ *
14
+ * Never prints a stack trace on any artifact input or usage error.
15
+ */
16
+ import { existsSync, readFileSync } from "node:fs";
17
+ import {
18
+ VERDICT_VERSION,
19
+ VERIFY_TYPES,
20
+ VerifyUsageError,
21
+ detectArtifactType,
22
+ exitCodeFor,
23
+ verifyArtifact,
24
+ } from "../vendor/pillar-core.mjs";
25
+ import { isStrictIsoDateTime, nowIsoSeconds } from "./wave-a.mjs";
26
+ import { isValidUuaid } from "./a6b-common.mjs";
27
+ import { resolveLive } from "./resolve-cli.mjs";
28
+ import {
29
+ REGISTRY_STATS_VERDICT_TYPE,
30
+ TTFA_VERDICT_TYPE,
31
+ verifyStatsArtifact,
32
+ } from "../registry/stats.mjs";
33
+
34
+ export const VERIFY_CLI_TOOL = "pillar/2.7.1";
35
+ const TYPE_SET = new Set([...VERIFY_TYPES, TTFA_VERDICT_TYPE, REGISTRY_STATS_VERDICT_TYPE]);
36
+
37
+ const VALUE_FLAGS = new Set([
38
+ "home",
39
+ "type",
40
+ "now",
41
+ "uuaid",
42
+ "trusted-issuer",
43
+ "trusted-issuers",
44
+ "verifier-public-key",
45
+ "verifier-key",
46
+ "public-key",
47
+ "registry-uuaid",
48
+ "lineage",
49
+ "required-bits",
50
+ "unreceipted-owner-event",
51
+ ]);
52
+
53
+ const FORBIDDEN_FLAGS = new Set(["first-seen", "local-first-seen", "firstSeen", "localFirstSeen"]);
54
+
55
+ function makeMalformedVerdict(type, now) {
56
+ return {
57
+ v: VERDICT_VERSION,
58
+ type,
59
+ verdict: "invalid",
60
+ reasons: ["malformed-artifact"],
61
+ facts: {},
62
+ checkedAt: now,
63
+ resolved: false,
64
+ tool: VERIFY_CLI_TOOL,
65
+ };
66
+ }
67
+
68
+ function makeFaultVerdict(type, now) {
69
+ return {
70
+ v: VERDICT_VERSION,
71
+ type,
72
+ verdict: "indeterminate",
73
+ reasons: ["verifier-fault"],
74
+ facts: {},
75
+ checkedAt: now,
76
+ resolved: false,
77
+ tool: VERIFY_CLI_TOOL,
78
+ };
79
+ }
80
+
81
+ function formatHumanVerdict(v) {
82
+ const reasons = Array.isArray(v.reasons) && v.reasons.length ? ` ${v.reasons.join(",")}` : "";
83
+ const subj = typeof v.subject === "string" ? ` ${v.subject}` : "";
84
+ return `${v.verdict}${reasons}${subj} (${v.type})\n`;
85
+ }
86
+
87
+ function usageFail(errOut, msg) {
88
+ errOut(`${msg}\n`);
89
+ return { exitCode: 64, verdict: null };
90
+ }
91
+
92
+ function emitVerdict(verdict, json, out) {
93
+ const exitCode = exitCodeFor(verdict);
94
+ out(json ? `${JSON.stringify(verdict)}\n` : formatHumanVerdict(verdict));
95
+ return { exitCode, verdict };
96
+ }
97
+
98
+ /**
99
+ * Parse raw argv tokens after `verify`. Throws `VerifyUsageError` on any bad
100
+ * flag, missing value, forbidden option, or wrong positional count.
101
+ */
102
+ export function parseVerifyArgs(rawArgs) {
103
+ const args = Array.isArray(rawArgs) ? rawArgs : [];
104
+ const positionals = [];
105
+ let json = false;
106
+ let type;
107
+ let now;
108
+ let uuaid;
109
+ const trustedIssuers = [];
110
+ let verifierPublicKey;
111
+ let publicKey;
112
+ let registryUuaid;
113
+ let requireStamp = false;
114
+ let lineageFile;
115
+ let requiredBits;
116
+ let unreceiptedOwnerEvent;
117
+ let endOfFlags = false;
118
+
119
+ for (let i = 0; i < args.length; i++) {
120
+ const tok = args[i];
121
+ if (!endOfFlags && tok === "--") {
122
+ endOfFlags = true;
123
+ continue;
124
+ }
125
+ if (!endOfFlags && tok.startsWith("-") && tok !== "-") {
126
+ const isLong = tok.startsWith("--");
127
+ const eq = isLong ? tok.indexOf("=") : -1;
128
+ const key = isLong ? (eq === -1 ? tok.slice(2) : tok.slice(2, eq)) : "";
129
+ const hasEq = eq !== -1;
130
+
131
+ if (FORBIDDEN_FLAGS.has(key)) throw new VerifyUsageError(`verify: --${key} is forbidden (decision #15 c)`); // @rule verify-cli.forbid-first-seen
132
+
133
+ if (key === "json" || key === "require-stamp") {
134
+ if (hasEq) throw new VerifyUsageError(`verify: --${key} does not take a value`); // @rule verify-cli.json-no-value
135
+ if (key === "json") json = true;
136
+ else requireStamp = true;
137
+ continue;
138
+ }
139
+
140
+ if (!isLong || !VALUE_FLAGS.has(key)) throw new VerifyUsageError(`verify: unknown flag ${tok}`); // @rule verify-cli.unknown-flag
141
+
142
+ let val;
143
+ if (hasEq) {
144
+ val = tok.slice(eq + 1);
145
+ } else {
146
+ if (i + 1 >= args.length) throw new VerifyUsageError(`verify: --${key} requires a value`); // @rule verify-cli.flag-value-required
147
+ 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
148
+ val = args[++i];
149
+ }
150
+
151
+ if (key === "home") {
152
+ // Accepted as a no-op global flag for `pillar --home <dir> verify <file>`.
153
+ } else if (key === "type") type = val;
154
+ else if (key === "now") now = val;
155
+ else if (key === "uuaid") uuaid = val;
156
+ else if (key === "trusted-issuer") trustedIssuers.push(val);
157
+ else if (key === "trusted-issuers") trustedIssuers.push(...val.split(",").map((s) => s.trim()).filter(Boolean));
158
+ else if (key === "verifier-public-key" || key === "verifier-key") verifierPublicKey = val;
159
+ else if (key === "public-key") publicKey = val;
160
+ else if (key === "registry-uuaid") registryUuaid = val;
161
+ else if (key === "lineage") lineageFile = val;
162
+ else if (key === "required-bits") {
163
+ if (!/^\d+$/.test(val)) throw new VerifyUsageError(`verify: --required-bits must be an integer 12..24, got "${val}"`); // @rule verify-cli.required-bits-decimal
164
+ const n = Number(val);
165
+ 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
166
+ requiredBits = n;
167
+ } else if (key === "unreceipted-owner-event") {
168
+ if (val !== "ignored" && val !== "contested") throw new VerifyUsageError(`verify: --unreceipted-owner-event must be "ignored" or "contested"`); // @rule verify-cli.unreceipted-mode
169
+ unreceiptedOwnerEvent = val;
170
+ }
171
+ continue;
172
+ }
173
+ positionals.push(tok);
174
+ }
175
+
176
+ 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
177
+
178
+ const effectiveNow = now !== undefined ? now : nowIsoSeconds();
179
+ if (!isStrictIsoDateTime(effectiveNow)) throw new VerifyUsageError("verify: --now must be a valid ISO-8601 timestamp"); // @rule verify-cli.now-valid
180
+ if (type !== undefined && !TYPE_SET.has(type)) throw new VerifyUsageError(`verify: unknown --type "${type}"`); // @rule verify-cli.type-known
181
+
182
+ const opts = { now: effectiveNow };
183
+ if (type !== undefined) opts.type = type;
184
+ if (uuaid !== undefined) opts.uuaid = uuaid;
185
+ if (trustedIssuers.length > 0) opts.trustedIssuers = trustedIssuers;
186
+ if (verifierPublicKey !== undefined) opts.verifierPublicKey = verifierPublicKey;
187
+ if (publicKey !== undefined) opts.publicKey = publicKey;
188
+ if (registryUuaid !== undefined) opts.registryUuaid = registryUuaid;
189
+ if (requireStamp) opts.requireStamp = true;
190
+ if (requiredBits !== undefined) opts.requiredBits = requiredBits;
191
+ if (unreceiptedOwnerEvent !== undefined) opts.unreceiptedOwnerEvent = unreceiptedOwnerEvent;
192
+
193
+ return { file: positionals[0], json, lineageFile, opts };
194
+ }
195
+
196
+ /**
197
+ * Execute `pillar verify` with injectable streams. Returns `{ exitCode, verdict }`.
198
+ * Never throws; never prints a stack trace.
199
+ */
200
+ export function runVerifyCli(rawArgs, io = {}) {
201
+ const out = io.stdout ?? ((s) => process.stdout.write(s));
202
+ const errOut = io.stderr ?? ((s) => process.stderr.write(s));
203
+ const readStdin = io.readStdin ?? (() => readFileSync(0, "utf8"));
204
+
205
+ let parsed;
206
+ try {
207
+ parsed = parseVerifyArgs(rawArgs);
208
+ } catch (e) {
209
+ return usageFail(errOut, e instanceof Error ? e.message : String(e));
210
+ }
211
+
212
+ const { file, json, lineageFile, opts } = parsed;
213
+
214
+ if (lineageFile !== undefined) {
215
+ let rawLin = null;
216
+ try { rawLin = readFileSync(lineageFile, "utf8"); } catch { rawLin = null; }
217
+ if (rawLin === null) return usageFail(errOut, `verify: cannot read --lineage file "${lineageFile}"`); // @rule verify-cli.lineage-file-readable
218
+ try { opts.lineage = JSON.parse(rawLin); } catch { opts.lineage = undefined; }
219
+ if (opts.lineage === undefined) return usageFail(errOut, `verify: --lineage file "${lineageFile}" is not valid JSON`); // @rule verify-cli.lineage-file-json
220
+ }
221
+
222
+ let rawText = null;
223
+ try { rawText = file === "-" ? readStdin() : readFileSync(file, "utf8"); } catch { rawText = null; }
224
+ if (rawText === null) return usageFail(errOut, `verify: cannot read "${file}"`); // @rule verify-cli.file-readable
225
+
226
+ let artifact;
227
+ let jsonOk = true;
228
+ try { artifact = JSON.parse(rawText); } catch { jsonOk = false; }
229
+ if (!jsonOk) {
230
+ if (opts.type === undefined) return usageFail(errOut, "verify: cannot detect the artifact type; pass --type <t>"); // @rule verify-cli.non-json-no-type-64
231
+ return emitVerdict(makeMalformedVerdict(opts.type, opts.now), json, out); // @rule verify-cli.non-json-malformed
232
+ }
233
+
234
+ let verdict;
235
+ // B8 types (`pillar-ttfa-report/1`, `pillar-registry-stats/1`) are verified by
236
+ // `src/registry/stats.mjs` before the frozen core sees the artifact; the core
237
+ // does not know their versions and its own dispatch stays untouched.
238
+ const statsVerdict = verifyStatsArtifact(artifact, opts);
239
+ if (statsVerdict) {
240
+ return emitVerdict({ ...statsVerdict, tool: VERIFY_CLI_TOOL }, json, out);
241
+ }
242
+ try {
243
+ verdict = verifyArtifact(artifact, opts);
244
+ } catch (e) {
245
+ if (e instanceof VerifyUsageError) return usageFail(errOut, e.message); // @rule verify-cli.usage-error-64
246
+ let faultType = opts.type ?? null;
247
+ if (!faultType) {
248
+ try { faultType = detectArtifactType(artifact); } catch { faultType = null; }
249
+ }
250
+ if (!faultType) return usageFail(errOut, "verify: cannot detect the artifact type; pass --type <t>");
251
+ return emitVerdict(makeFaultVerdict(faultType, opts.now), json, out);
252
+ }
253
+
254
+ return emitVerdict({ ...verdict, tool: VERIFY_CLI_TOOL }, json, out);
255
+ }
256
+
257
+ export const VERIFY_USAGE = `usage:
258
+ pillar verify <file|-> [--type T] [--now ISO] [--json] [...] verify a saved artifact offline
259
+ (card, listing, lineage log, intro, heartbeat, ...)
260
+ pillar verify <uuaid> [--registry URL] [--now ISO] [--json] verify an agent live: resolve it from a
261
+ registry and check its listing, card and lineage
262
+ Exit: 0 valid, 10 recovered|pending-recovery|contested, 1 invalid or not verified, 2 indeterminate, 64 usage.
263
+ Default registry: config.json "registry", else https://pillar.uuaid.org.`;
264
+
265
+ /** The first positional of `pillar verify`, skipping flags and their values; null if none. */
266
+ function firstPositional(rawArgs) {
267
+ const args = Array.isArray(rawArgs) ? rawArgs : [];
268
+ for (let i = 0; i < args.length; i++) {
269
+ const tok = args[i];
270
+ if (tok === "--") return args[i + 1] ?? null;
271
+ if (typeof tok === "string" && tok.startsWith("-") && tok !== "-") {
272
+ const key = tok.startsWith("--") ? tok.slice(2).split("=")[0] : "";
273
+ if (!tok.includes("=") && (VALUE_FLAGS.has(key) || key === "registry")) i++;
274
+ continue;
275
+ }
276
+ return tok;
277
+ }
278
+ return null;
279
+ }
280
+
281
+ /**
282
+ * Which form a `pillar verify` call is: "uuaid" when its argument is a valid
283
+ * UUAID and no file of that name exists (a file always wins), else "file".
284
+ */
285
+ export function verifyForm(rawArgs) {
286
+ const target = firstPositional(rawArgs);
287
+ let live = typeof target === "string" && isValidUuaid(target);
288
+ if (live && existsSync(target)) live = false; // @rule verify-cli.file-wins
289
+ return live ? "uuaid" : "file";
290
+ }
291
+
292
+ /**
293
+ * `pillar verify <uuaid>`: core resolve (fail-closed) and the lineage verdict
294
+ * it carries. Exit as the file form: exitCodeFor(lineage verdict); 1 when the
295
+ * registry answer does not verify. Never throws; never prints a stack trace.
296
+ */
297
+ export async function runVerifyUuaidCli(rawArgs, io = {}) {
298
+ const out = io.stdout ?? ((s) => process.stdout.write(s));
299
+ const errOut = io.stderr ?? ((s) => process.stderr.write(s));
300
+ const live = await resolveLive(rawArgs, { cmdName: "verify", io });
301
+ if (live.usage) return { exitCode: live.usage.exitCode, verdict: null };
302
+ const { json, registryUrl, uuaid, result, error } = live;
303
+ if (error !== null || !result || result.ok !== true) {
304
+ const reason = error !== null ? "resolve-error" : (result?.reason ?? "failed");
305
+ const report = { ok: false, form: "uuaid", query: uuaid, registry: registryUrl, reason, ...(error !== null ? { message: error } : {}), ...(result?.statusCode ? { statusCode: result.statusCode } : {}) };
306
+ if (json) out(`${JSON.stringify(report)}\n`);
307
+ else errOut(`not verified ${uuaid}: ${reason}${result?.statusCode ? ` (HTTP ${result.statusCode})` : ""}${error !== null ? ` (${error})` : ""} [live, ${registryUrl}]\n`);
308
+ return { exitCode: 1, verdict: null }; // @rule verify-cli.uuaid-fail-closed
309
+ }
310
+ const verdict = { ...result.lineageVerdict, tool: VERIFY_CLI_TOOL };
311
+ const exitCode = exitCodeFor(verdict);
312
+ if (json) {
313
+ out(`${JSON.stringify({ ok: true, form: "uuaid", query: uuaid, registry: registryUrl, verdict, lineage: result.lineage, current: result.current, status: result.status, card: result.card, answeredBy: result.answer?.answeredBy ?? null })}\n`);
314
+ } else {
315
+ const lines = [
316
+ `${verdict.verdict}${verdict.reasons?.length ? ` ${verdict.reasons.join(",")}` : ""} ${uuaid} (live: listing, card and lineage verified)`,
317
+ ` lineage: ${result.lineage}`,
318
+ ` current: ${result.current}`,
319
+ ` status: ${result.status}`,
320
+ ...(result.card?.name ? [` name: ${result.card.name}`] : []),
321
+ ...(result.card?.publicKey ? [` publicKey: ${result.card.publicKey}`] : []),
322
+ ` registry: ${registryUrl}${result.answer?.answeredBy ? ` (answered by ${result.answer.answeredBy})` : ""}`,
323
+ ];
324
+ out(`${lines.join("\n")}\n`);
325
+ }
326
+ return { exitCode, verdict };
327
+ }
328
+
329
+ /** `pillar verify`, either form. */
330
+ export async function runVerifyCommand(rawArgs, io = {}) {
331
+ if (verifyForm(rawArgs) === "uuaid") return runVerifyUuaidCli(rawArgs, io);
332
+ return runVerifyCli(rawArgs, io);
333
+ }
@@ -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
+ }