@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,489 @@
1
+ /**
2
+ * `pillar init` and `pillar init --force` (owner decision #23, Wave A + Wave B B1).
3
+ *
4
+ * - Enforces `#23` D-1 5-condition default-switch gate (`assertWitnessSwitchGate`)
5
+ * before any key generation, signing, or disk write (`RT23-1`).
6
+ * - Supports `--no-witnesses` and `--preset <preset>` (defaulting to `--no-witnesses`
7
+ * on stateless presets `ci`, `init-action`, `worker`, `stateless`).
8
+ * - When witnessed mode is explicitly unlocked via all 5 switch conditions, enforces
9
+ * `D-4` (`validateWitnessSetD4`, `phase: "init"`, zero W2 at init, zero same-host)
10
+ * and requires `>= 2` live home `uuaid-lineage-seen/1` receipts (`publishSeq0ToHomes`)
11
+ * before writing keys or logs to disk.
12
+ * - `init --force` on an existing home rotates (#10 a) when the recovery sheet is
13
+ * provided, or refuses with `recover` as the fix.
14
+ */
15
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
16
+ import { homedir } from "node:os";
17
+ import { join } from "node:path";
18
+ import { defaultNotifyConfig } from "../notify.mjs";
19
+ import { Keychain, SELF_CERTIFYING_NAMESPACES, mintNamespace } from "../identity/keychain.mjs";
20
+ import {
21
+ DEFAULT_CONTEST_WINDOW,
22
+ LINEAGE_RECEIPTS_KEY,
23
+ MIN_CONTEST_MS,
24
+ WaveARefusalError,
25
+ assertWitnessSwitchGate,
26
+ durMs,
27
+ encodeRecoverySheet,
28
+ eventDigest,
29
+ generateIdentity,
30
+ inception,
31
+ isStatelessPreset,
32
+ verifyLineage,
33
+ } from "../vendor/pillar-core.mjs";
34
+ import { prepareWitnessedInit, publishWitnessedSeq0 } from "./b1-cli.mjs";
35
+ import { formatRotationOutput, rotateLineageHome } from "./lineage-cli.mjs";
36
+ import {
37
+ LINEAGE_LOG_KEY,
38
+ extractWaveAWitnessHomeOpts,
39
+ isStrictIsoDateTime,
40
+ keychainIdentityFromSeedHex,
41
+ nowIsoSeconds,
42
+ readRecoverySheetWords,
43
+ writeFileAtomic,
44
+ } from "./wave-a.mjs";
45
+
46
+ const INIT_VALUE_FLAGS = new Set([
47
+ "home",
48
+ "namespace",
49
+ "directory",
50
+ "carriers",
51
+ "now",
52
+ "contest-window",
53
+ "recovery-sheet",
54
+ "recovery-sheet-file",
55
+ "confirm",
56
+ "preset",
57
+ "witnesses",
58
+ "homes",
59
+ "witness-threshold",
60
+ "m",
61
+ "witness-file",
62
+ "homes-file",
63
+ ]);
64
+
65
+ export const DEFAULT_INIT_CARRIER = "https://pillar.uuaid.org";
66
+
67
+ const INIT_BOOL_FLAGS = new Set([
68
+ "refresh",
69
+ "force",
70
+ "json",
71
+ "libp2p",
72
+ "offline",
73
+ "no-witnesses",
74
+ "allow-insecure-loopback",
75
+ "no-notify",
76
+ ]);
77
+
78
+ function parseInitArgs(rawArgs) {
79
+ const args = Array.isArray(rawArgs) ? rawArgs : [];
80
+ const opts = {
81
+ home: null,
82
+ namespace: undefined,
83
+ refresh: false,
84
+ force: false,
85
+ libp2p: false,
86
+ offline: false,
87
+ noWitnesses: false,
88
+ noNotify: false,
89
+ allowInsecureLoopback: false,
90
+ preset: undefined,
91
+ directory: undefined,
92
+ carriers: undefined,
93
+ now: undefined,
94
+ contestWindow: undefined,
95
+ recoverySheet: undefined,
96
+ recoverySheetFile: undefined,
97
+ confirm: undefined,
98
+ witnessFile: undefined,
99
+ homesFile: undefined,
100
+ witnessThreshold: undefined,
101
+ m: undefined,
102
+ json: false,
103
+ };
104
+ const unknownFlags = [];
105
+ const flagErrors = [];
106
+ const positionals = [];
107
+ let endOfFlags = false;
108
+
109
+ for (let i = 0; i < args.length; i++) {
110
+ const tok = args[i];
111
+ if (!endOfFlags && tok === "--") {
112
+ endOfFlags = true;
113
+ continue;
114
+ }
115
+ if (!endOfFlags && tok.startsWith("-") && tok !== "-") {
116
+ if (!tok.startsWith("--")) {
117
+ unknownFlags.push(tok);
118
+ continue;
119
+ }
120
+ const eq = tok.indexOf("=");
121
+ const key = eq === -1 ? tok.slice(2) : tok.slice(2, eq);
122
+ const hasEq = eq !== -1;
123
+
124
+ if (INIT_BOOL_FLAGS.has(key)) {
125
+ if (hasEq) flagErrors.push(`init: --${key} does not take a value`);
126
+ else if (key === "no-witnesses") opts.noWitnesses = true;
127
+ else if (key === "no-notify") opts.noNotify = true;
128
+ else if (key === "allow-insecure-loopback") opts.allowInsecureLoopback = true;
129
+ else opts[key] = true;
130
+ continue;
131
+ }
132
+
133
+ if (!INIT_VALUE_FLAGS.has(key)) {
134
+ unknownFlags.push(tok);
135
+ continue;
136
+ }
137
+
138
+ let val;
139
+ if (hasEq) {
140
+ val = tok.slice(eq + 1);
141
+ } else if (i + 1 < args.length && !(args[i + 1].startsWith("-") && args[i + 1] !== "-")) {
142
+ val = args[++i];
143
+ } else if (key === "namespace" || key === "directory" || key === "confirm") {
144
+ val = true;
145
+ } else {
146
+ flagErrors.push(`init: --${key} requires a value`);
147
+ continue;
148
+ }
149
+
150
+ if (key === "home") opts.home = val;
151
+ else if (key === "namespace") opts.namespace = val;
152
+ else if (key === "directory") opts.directory = val;
153
+ else if (key === "carriers") opts.carriers = val;
154
+ else if (key === "now") opts.now = val;
155
+ else if (key === "contest-window") opts.contestWindow = val;
156
+ else if (key === "recovery-sheet") opts.recoverySheet = val;
157
+ else if (key === "recovery-sheet-file") opts.recoverySheetFile = val;
158
+ else if (key === "confirm") opts.confirm = val;
159
+ else if (key === "preset") opts.preset = val;
160
+ else if (key === "witness-file") opts.witnessFile = val;
161
+ else if (key === "homes-file") opts.homesFile = val;
162
+ else if (key === "witness-threshold") opts.witnessThreshold = val;
163
+ else if (key === "m") opts.m = val;
164
+ } else {
165
+ positionals.push(tok);
166
+ }
167
+ }
168
+ return { opts, unknownFlags, flagErrors, positionals };
169
+ }
170
+
171
+ function failInit(errOut, msg, exitCode = 1) {
172
+ errOut(`${msg}\n`);
173
+ return { exitCode };
174
+ }
175
+
176
+ function carriersFromDirectory(d) {
177
+ return [d.carrier, ...(Array.isArray(d.seeds) ? d.seeds.map((s) => s.url) : [])].filter(Boolean);
178
+ }
179
+
180
+ function mergeDirectoryAgents(home, d) {
181
+ if (!Array.isArray(d.agents)) return null;
182
+ const fleetPath = join(home, "fleet.json");
183
+ const prev = existsSync(fleetPath) ? JSON.parse(readFileSync(fleetPath, "utf-8")).fleet ?? {} : {};
184
+ const fleet = { ...prev };
185
+ let added = 0;
186
+ for (const a of d.agents) {
187
+ if (!a.uuaid || !a.publicKey) continue;
188
+ const key = typeof a.role === "string" && a.role ? a.role : a.uuaid;
189
+ fleet[key] = {
190
+ uuaid: a.uuaid,
191
+ publicKey: a.publicKey,
192
+ ...(prev[key]?.addrs ? { addrs: prev[key].addrs } : {}),
193
+ ...(prev[key]?.peerId ? { peerId: prev[key].peerId } : {}),
194
+ };
195
+ if (!prev[key]) added++;
196
+ }
197
+ writeFileSync(fleetPath, JSON.stringify({ fleet }, null, 2), { mode: 0o600 });
198
+ return { count: Object.keys(fleet).length, added };
199
+ }
200
+
201
+ async function fetchDirectory(url, errOut) {
202
+ const res = await fetch(url);
203
+ if (!res.ok) {
204
+ errOut(`directory fetch failed: ${url} -> ${res.status}\n`);
205
+ return null;
206
+ }
207
+ return res.json();
208
+ }
209
+
210
+ function readExistingConfig(home) {
211
+ const cfgPath = join(home, "config.json");
212
+ if (!existsSync(cfgPath)) return {};
213
+ return JSON.parse(readFileSync(cfgPath, "utf-8"));
214
+ }
215
+
216
+ /**
217
+ * Execute `pillar init` (and `init --force`, `init --refresh`) with injectable streams.
218
+ * Returns `{ exitCode, result? }`.
219
+ */
220
+ export async function runInitCli(rawArgs, io = {}) {
221
+ const out = io.stdout ?? ((s) => process.stdout.write(s));
222
+ const errOut = io.stderr ?? ((s) => process.stderr.write(s));
223
+ const passphrase = io.passphrase ?? process.env.PILLAR_PASSPHRASE ?? "";
224
+
225
+ const { opts, unknownFlags, flagErrors, positionals } = parseInitArgs(rawArgs);
226
+ const waveAOpts = extractWaveAWitnessHomeOpts(rawArgs);
227
+ if (opts.witnessFile || Array.isArray(io.witnessCandidates)) waveAOpts.witnesses = waveAOpts.witnesses ?? ["<file>"];
228
+ if (opts.homesFile || Array.isArray(io.homeRecords)) waveAOpts.homes = waveAOpts.homes ?? ["<file>"];
229
+
230
+ const statelessNoWitnesses = Boolean(opts.noWitnesses || isStatelessPreset(opts.preset));
231
+ const gateOpts = {
232
+ allowWitnessed: io.allowWitnessed,
233
+ noWitnesses: statelessNoWitnesses,
234
+ preset: opts.preset,
235
+ switchGate: io.switchGate,
236
+ requireDefaultSwitch: io.requireDefaultSwitch,
237
+ };
238
+
239
+ // Decision #23 D-1: check all 5 switch conditions BEFORE touching disk, generating keys, or signing.
240
+ let allowWitnessed = false;
241
+ try {
242
+ if (opts.force) {
243
+ ({ allowWitnessed } = assertWitnessSwitchGate(waveAOpts, gateOpts)); // @rule vnext.init-force-wave-a
244
+ } else {
245
+ ({ allowWitnessed } = assertWitnessSwitchGate(waveAOpts, gateOpts)); // @rule vnext.init-wave-a
246
+ }
247
+ } catch (e) {
248
+ errOut(`${e instanceof WaveARefusalError ? e.message : String(e)}\n`);
249
+ return { exitCode: 1, error: e };
250
+ }
251
+
252
+ if (unknownFlags.length > 0) return failInit(errOut, `init: unknown flag ${unknownFlags[0]}`, 64); // @rule vnext.init-unknown-flag
253
+ if (flagErrors.length > 0) return failInit(errOut, flagErrors[0], 64);
254
+ if (positionals.length > 0) return failInit(errOut, `init: unexpected argument "${positionals[0]}"`, 64); // @rule vnext.init-extra-arg
255
+
256
+ const home = opts.home || process.env.PILLAR_HOME || join(homedir(), ".pillar");
257
+ const kcPath = join(home, "keychain.json");
258
+ const logPath = join(home, LINEAGE_LOG_KEY);
259
+ const receiptsPath = join(home, LINEAGE_RECEIPTS_KEY);
260
+ const seedPath = join(home, "identity", "agent.seed");
261
+
262
+ // --refresh re-syncs carriers + address book without touching keychain or lineage.
263
+ if (opts.refresh) {
264
+ if (opts.noNotify) return failInit(errOut, "init --refresh leaves notify unchanged; set notify.enabled in config.json instead of --no-notify", 64);
265
+ if (!existsSync(kcPath)) return failInit(errOut, `refresh: no keychain at ${kcPath} — run pillar init first (refresh never mints keys)`);
266
+ if (typeof opts.directory !== "string") return failInit(errOut, "refresh: --directory <url> is required");
267
+ const d = await fetchDirectory(opts.directory, errOut);
268
+ if (!d) return { exitCode: 1 };
269
+ const list = carriersFromDirectory(d);
270
+ if (!list.length) return failInit(errOut, `refresh: directory ${opts.directory} lists no carrier and no seeds`);
271
+ const cfgPath = join(home, "config.json");
272
+ const cfg = existsSync(cfgPath) ? JSON.parse(readFileSync(cfgPath, "utf-8")) : {};
273
+ cfg.carriers = list;
274
+ writeFileSync(cfgPath, JSON.stringify(cfg, null, 2), { mode: 0o600 });
275
+ out(`carriers refreshed from ${opts.directory}: ${list.join(", ")}\n`);
276
+ const ab = mergeDirectoryAgents(home, d);
277
+ if (ab) out(`address book: ${ab.count} peers in ${join(home, "fleet.json")} (${ab.added} new from directory)\n`);
278
+ out(`refresh complete at ${home} (keychain untouched)\n`);
279
+ return { exitCode: 0 };
280
+ }
281
+
282
+ const hasExisting = existsSync(kcPath) || existsSync(logPath) || existsSync(seedPath);
283
+ if (hasExisting) {
284
+ const oldUuaid = existsSync(kcPath) ? new Keychain(kcPath).publicView()?.uuaid : null;
285
+ if (opts.force && opts.noNotify) return failInit(errOut, "init --force keeps this home's notify setting; set notify.enabled in config.json instead of --no-notify", 64);
286
+ if (!opts.force) return failInit(errOut, `this home already has an identity: ${oldUuaid ?? home}\n re-sync carriers and contacts, keeping it: pillar init --refresh --directory <url> --home ${home}\n rotate with your recovery sheet: pillar init --force --recovery-sheet "<24 words>" --home ${home}`); // @rule vnext.init-existing-refusal
287
+
288
+ let words = null;
289
+ try { words = readRecoverySheetWords(opts); } catch (e) {
290
+ return failInit(errOut, `init --force: cannot read recovery sheet (${e.message})`);
291
+ }
292
+ if (!words || words.length === 0 || !existsSync(logPath)) return failInit(errOut, `init --force: cannot rotate ${oldUuaid ?? home} without the recovery sheet and lineage log; pass --recovery-sheet "<24 words>" (or --recovery-sheet-file <path>), or use "pillar lineage recover" if the recovery sheet is lost`); // @rule vnext.init-force-recover-refusal
293
+
294
+ try {
295
+ const res = await rotateLineageHome({
296
+ home,
297
+ rawArgs,
298
+ recoverySheetWords: words,
299
+ now: opts.now,
300
+ contestWindow: opts.contestWindow,
301
+ passphrase,
302
+ skipWaveACheck: true,
303
+ allowWitnessed,
304
+ witnessFile: opts.witnessFile,
305
+ homesFile: opts.homesFile,
306
+ witnessCandidates: io.witnessCandidates,
307
+ homeRecords: io.homeRecords,
308
+ witnessThreshold: opts.witnessThreshold ?? opts.m,
309
+ localHostPublicKeys: io.localHostPublicKeys,
310
+ agentDeviceId: io.agentDeviceId,
311
+ fetch: io.fetch,
312
+ urlMap: io.urlMap,
313
+ allowInsecureLoopback: opts.allowInsecureLoopback || Boolean(io.allowInsecureLoopback),
314
+ });
315
+ const cfg = readExistingConfig(home);
316
+ if (typeof opts.directory === "string") {
317
+ const d = await fetchDirectory(opts.directory, errOut);
318
+ if (!d) return { exitCode: 1 };
319
+ const list = carriersFromDirectory(d);
320
+ if (list.length) cfg.carriers = list;
321
+ mergeDirectoryAgents(home, d);
322
+ } else if (opts.carriers !== undefined) {
323
+ cfg.carriers = opts.carriers.split(",").map((s) => s.trim()).filter(Boolean);
324
+ } else if (opts.offline) {
325
+ cfg.carriers = [];
326
+ }
327
+ if (opts.libp2p) cfg.carrierOnly = false;
328
+ if (Object.keys(cfg).length > 0) {
329
+ writeFileSync(join(home, "config.json"), JSON.stringify(cfg, null, 2), { mode: 0o600 });
330
+ }
331
+ out(formatRotationOutput(res, home, opts.json));
332
+ return { exitCode: 0, result: res };
333
+ } catch (e) {
334
+ errOut(`${e instanceof Error ? e.message : String(e)}\n`);
335
+ return { exitCode: 1, error: e };
336
+ }
337
+ }
338
+
339
+ let uuaidNamespace;
340
+ try { uuaidNamespace = mintNamespace(opts.namespace === undefined ? undefined : opts.namespace); } catch { uuaidNamespace = null; }
341
+ if (!uuaidNamespace) return failInit(errOut, `init: --namespace must be one of ${SELF_CERTIFYING_NAMESPACES.join(", ")}`); // @rule vnext.init-namespace
342
+
343
+ const ts = opts.now !== undefined ? opts.now : nowIsoSeconds();
344
+ if (!isStrictIsoDateTime(ts)) return failInit(errOut, "init: --now must be a valid ISO-8601 timestamp"); // @rule vnext.init-now-valid
345
+
346
+ const contestWindow = opts.contestWindow ?? DEFAULT_CONTEST_WINDOW;
347
+ const cwMs = durMs(contestWindow);
348
+ if (cwMs === null || cwMs < MIN_CONTEST_MS) return failInit(errOut, "init: --contest-window must be a valid duration >= P3D"); // @rule vnext.init-contest-window
349
+
350
+ const working = generateIdentity({ namespace: uuaidNamespace, objectType: "agent" });
351
+ const nextKey = generateIdentity({ namespace: uuaidNamespace, objectType: "agent" });
352
+ const recoverySheet = encodeRecoverySheet(nextKey.seedHex);
353
+
354
+ let witnessOpts = {};
355
+ let d4Warnings = [];
356
+ if (allowWitnessed && (opts.witnessFile || Array.isArray(io.witnessCandidates) || opts.homesFile || Array.isArray(io.homeRecords))) {
357
+ try {
358
+ const prep = prepareWitnessedInit({
359
+ working,
360
+ nextKey,
361
+ uuaidNamespace,
362
+ witnessFile: opts.witnessFile,
363
+ homesFile: opts.homesFile,
364
+ witnessCandidates: io.witnessCandidates,
365
+ homeRecords: io.homeRecords,
366
+ witnessThreshold: opts.witnessThreshold ?? opts.m,
367
+ localHostPublicKeys: io.localHostPublicKeys,
368
+ agentDeviceId: io.agentDeviceId,
369
+ });
370
+ witnessOpts = prep.witnessOpts;
371
+ d4Warnings = prep.warnings;
372
+ } catch (e) {
373
+ return failInit(errOut, e.message);
374
+ }
375
+ }
376
+
377
+ let inc;
378
+ try {
379
+ inc = inception(
380
+ working,
381
+ { uuaid: nextKey.uuaid, publicKeyHex: nextKey.publicKeyHex },
382
+ { ts, contestWindow, namespace: uuaidNamespace, ...witnessOpts },
383
+ );
384
+ } catch (e) {
385
+ return failInit(errOut, `init: ${e.message}`);
386
+ }
387
+
388
+ if (!allowWitnessed && ("witnesses" in inc || "witnessThreshold" in inc || "homes" in inc)) {
389
+ throw new Error("init: minted inception unexpectedly carried witness or home fields");
390
+ }
391
+ const check = verifyLineage([inc], { now: ts });
392
+ if (check.verdict !== "valid") {
393
+ throw new Error(`init: minted inception failed self-verification (${check.verdict}: ${check.reasons.join(", ")})`);
394
+ }
395
+
396
+ let seq0Receipts = [];
397
+ if (Array.isArray(inc.witnesses) && inc.witnesses.length > 0) {
398
+ try {
399
+ seq0Receipts = await publishWitnessedSeq0(inc, {
400
+ now: ts,
401
+ fetch: io.fetch,
402
+ urlMap: io.urlMap,
403
+ allowInsecureLoopback: opts.allowInsecureLoopback || Boolean(io.allowInsecureLoopback),
404
+ });
405
+ } catch (e) {
406
+ return failInit(errOut, e.message);
407
+ }
408
+ }
409
+
410
+ const cfg = {
411
+ listenAddrs: ["/ip4/0.0.0.0/tcp/0", "/ip4/0.0.0.0/tcp/0/ws"],
412
+ bootstrapPeers: [],
413
+ enableRelay: false,
414
+ dhtClientMode: true,
415
+ carrierOnly: !opts.libp2p,
416
+ ...(opts.preset ? { preset: opts.preset } : {}),
417
+ ...(statelessNoWitnesses ? { noWitnesses: true } : {}),
418
+ // New-mail notices: on unless --no-notify. Fresh init only; --refresh and
419
+ // --force never add or change it. Nothing is scheduled or installed here.
420
+ notify: defaultNotifyConfig({ enabled: !opts.noNotify }),
421
+ };
422
+ let dirData = null;
423
+ if (typeof opts.directory === "string") {
424
+ dirData = await fetchDirectory(opts.directory, errOut);
425
+ if (!dirData) return { exitCode: 1 };
426
+ const list = carriersFromDirectory(dirData);
427
+ if (!list.length) return failInit(errOut, `init: directory ${opts.directory} lists no carrier and no seeds`);
428
+ cfg.carriers = list;
429
+ } else if (opts.carriers !== undefined) {
430
+ cfg.carriers = opts.carriers.split(",").map((s) => s.trim()).filter(Boolean);
431
+ } else if (opts.offline) {
432
+ cfg.carriers = [];
433
+ } else {
434
+ cfg.carriers = [DEFAULT_INIT_CARRIER];
435
+ }
436
+
437
+ mkdirSync(home, { recursive: true });
438
+ const kc = new Keychain(kcPath);
439
+ kc.save(keychainIdentityFromSeedHex(working.seedHex, working.uuaid, ts), { passphrase });
440
+ writeFileAtomic(logPath, `${JSON.stringify([inc], null, 2)}\n`, 0o600);
441
+ if (seq0Receipts.length > 0) {
442
+ writeFileAtomic(receiptsPath, `${JSON.stringify(seq0Receipts, null, 2)}\n`, 0o600);
443
+ }
444
+ writeFileSync(join(home, "config.json"), JSON.stringify(cfg, null, 2), { mode: 0o600 });
445
+
446
+ let ab = null;
447
+ if (dirData) {
448
+ ab = mergeDirectoryAgents(home, dirData);
449
+ }
450
+
451
+ for (const w of d4Warnings) errOut(`warning: ${w}\n`);
452
+
453
+ const head = `sha256:${eventDigest(inc)}`;
454
+ const result = {
455
+ home,
456
+ uuaid: working.uuaid,
457
+ publicKey: working.publicKeyHex,
458
+ lineage: inc.lineage,
459
+ seq: 0,
460
+ head,
461
+ noWitnesses: statelessNoWitnesses || !Array.isArray(inc.witnesses),
462
+ ...(opts.preset ? { preset: opts.preset } : {}),
463
+ ...(seq0Receipts.length > 0 ? { receipts: seq0Receipts } : {}),
464
+ ...(d4Warnings.length > 0 ? { warnings: d4Warnings } : {}),
465
+ inception: inc,
466
+ recoverySheet,
467
+ };
468
+
469
+ if (opts.json) {
470
+ out(`${JSON.stringify(result)}\n`);
471
+ } else {
472
+ if (dirData && cfg.carriers) out(`carriers from directory (${opts.directory}): ${cfg.carriers.join(", ")}\n`);
473
+ if (ab) out(`address book: ${ab.count} peers in ${join(home, "fleet.json")} (${ab.added} new from directory)\n`);
474
+ out([
475
+ `initialized pillar at ${home}`,
476
+ `uuaid: ${working.uuaid}`,
477
+ `publicKey: ${working.publicKeyHex}`,
478
+ `lineage: ${inc.lineage} (seq 0, head ${head})`,
479
+ `recovery sheet (save offline — shown once, never stored in ${home}):`,
480
+ ` ${recoverySheet.join(" ")}`,
481
+ "",
482
+ `config: ${join(home, "config.json")}`,
483
+ `notify: ${opts.noNotify ? "off" : "on"} (no hook is set; set notify.hook in config.json, then print a resident unit to install yourself: pillar notify --print-unit launchd|systemd)`,
484
+ "edit bootstrapPeers to join a network, or run again with --directory <url> / --carriers a,b to wire seeds.",
485
+ "",
486
+ ].join("\n"));
487
+ }
488
+ return { exitCode: 0, result };
489
+ }
@@ -0,0 +1,81 @@
1
+ /**
2
+ * `pillar intro <introducee-uuaid> <to-uuaid> --note TEXT [--expires ISO] [--now ISO] [--out FILE] [--home DIR] [--json]`
3
+ *
4
+ * Signs a `pillar-intro/1` letter (`buildIntro`) using this home's active identity key.
5
+ */
6
+ import { INTRO_MAX_NOTE_CHARS, buildIntro } from "../vendor/pillar-core.mjs";
7
+ import {
8
+ failCli,
9
+ isValidUuaid,
10
+ loadHomeIdentity,
11
+ parseStrictFlags,
12
+ resolveHome,
13
+ } from "./a6b-common.mjs";
14
+ import { isStrictIsoDateTime, nowIsoSeconds, writeFileAtomic } from "./wave-a.mjs";
15
+
16
+ /**
17
+ * Execute `pillar intro` with injectable streams.
18
+ * Returns `{ exitCode, letter? }`.
19
+ */
20
+ export function runIntroCli(rawArgs, io = {}) {
21
+ const out = io.stdout ?? ((s) => process.stdout.write(s));
22
+ const errOut = io.stderr ?? ((s) => process.stderr.write(s));
23
+ const passphrase = io.passphrase ?? process.env.PILLAR_PASSPHRASE ?? "";
24
+
25
+ const parsed = parseStrictFlags(rawArgs, {
26
+ boolFlags: new Set(["json"]),
27
+ valueFlags: new Set(["home", "note", "expires", "now", "out"]),
28
+ cmdName: "intro",
29
+ });
30
+ if (!parsed.ok) return failCli(errOut, parsed.error, parsed.exitCode);
31
+
32
+ const { positionals, opts } = parsed;
33
+ if (positionals.length !== 2) return failCli(errOut, "usage: pillar intro <introducee-uuaid> <to-uuaid> --note TEXT [--expires ISO] [--now ISO] [--out FILE] [--json]", 64); // @rule intro-cli.arg-count
34
+
35
+ const [introducee, to] = positionals;
36
+ if (!isValidUuaid(introducee)) return failCli(errOut, `intro: invalid introducee UUAID "${introducee}"`, 64); // @rule intro-cli.introducee-uuaid
37
+ if (!isValidUuaid(to)) return failCli(errOut, `intro: invalid recipient UUAID "${to}"`, 64); // @rule intro-cli.to-uuaid
38
+ if (typeof opts.note !== "string" || opts.note.length === 0) return failCli(errOut, "intro: --note TEXT is required", 64); // @rule intro-cli.note-required
39
+ if ([...opts.note].length > INTRO_MAX_NOTE_CHARS) return failCli(errOut, `intro: --note exceeds ${INTRO_MAX_NOTE_CHARS} code points`, 64); // @rule intro-cli.note-length
40
+
41
+ const ts = opts.now !== undefined ? opts.now : nowIsoSeconds();
42
+ if (!isStrictIsoDateTime(ts)) return failCli(errOut, "intro: --now must be a valid ISO-8601 timestamp", 64); // @rule intro-cli.now-valid
43
+ if (opts.expires !== undefined && !isStrictIsoDateTime(opts.expires)) return failCli(errOut, "intro: --expires must be a valid ISO-8601 timestamp", 64); // @rule intro-cli.expires-valid
44
+
45
+ const home = resolveHome(opts);
46
+ let homeId;
47
+ try { homeId = loadHomeIdentity(home, passphrase); } catch (e) {
48
+ return failCli(errOut, `intro: ${e.message}`, 1);
49
+ }
50
+
51
+ let letter;
52
+ try {
53
+ letter = buildIntro(homeId.coreId, {
54
+ introducee,
55
+ to,
56
+ note: opts.note,
57
+ now: ts,
58
+ ...(opts.expires !== undefined ? { exp: opts.expires } : {}),
59
+ namespace: homeId.namespace,
60
+ });
61
+ } catch (e) {
62
+ return failCli(errOut, `intro: ${e.message}`, 64);
63
+ }
64
+
65
+ if (opts.out !== undefined) {
66
+ try {
67
+ writeFileAtomic(opts.out, `${JSON.stringify(letter, null, 2)}\n`, 0o600);
68
+ } catch (e) {
69
+ return failCli(errOut, `intro: cannot write "${opts.out}" (${e.message})`, 1);
70
+ }
71
+ }
72
+
73
+ if (opts.json) {
74
+ out(`${JSON.stringify(letter)}\n`);
75
+ } else if (opts.out !== undefined) {
76
+ out(`signed pillar-intro/1 -> ${opts.out}\n introducer: ${letter.introducer}\n introducee: ${letter.introducee}\n to: ${letter.to}\n exp: ${letter.exp}\n`);
77
+ } else {
78
+ out(`${JSON.stringify(letter, null, 2)}\n`);
79
+ }
80
+ return { exitCode: 0, letter };
81
+ }