@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.
- package/README.md +325 -7
- 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 +282 -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 +512 -257
- 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 +313 -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 +320 -91
- 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 +736 -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 +205 -0
- package/src/registry/lineage-verifier.mjs +972 -0
- package/src/registry/lineage.mjs +984 -0
- package/src/registry/listings.mjs +612 -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 +304 -0
- package/src/vnext/jsonl-mailbox.mjs +1132 -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 +104 -0
- package/src/vnext/soul-cli.mjs +666 -0
- package/src/vnext/verify-cli.mjs +333 -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,653 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `pillar lineage` CLI verbs (Wave A + Wave B B1, decisions #10 (a), #17, #19, #23, #29):
|
|
3
|
+
* - `show`: reads and verifies `<home>/lineage/log.json` (+ `lineage/receipts.json`)
|
|
4
|
+
* - `rotate`: enforces `#23` D-1 5-condition switch gate + `D-4` witness rules, signs
|
|
5
|
+
* a #10 (a) rotation, re-signs `card/card.json`, and publishes to active homes
|
|
6
|
+
* - `door add` / `door retire`: co-signed #29 door lifecycle + card sync
|
|
7
|
+
* - `recover claim` / `recover veto` / `recover finalize`: threshold witness recovery & veto
|
|
8
|
+
* - `witness vouch`: `D-2` & `D-3` fetch-from-home witness vouching + local audit log
|
|
9
|
+
* - `bind`: `T2.6` legacy `agent-commons/key-continuity/1` binding
|
|
10
|
+
* - `tombstone`: `#19` irreversible sunset (`--confirm <lineage>` required)
|
|
11
|
+
* - `export-recovery-sheet`: warns until witnessed rotation has `>= 2` home stamps
|
|
12
|
+
*/
|
|
13
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
14
|
+
import { homedir } from "node:os";
|
|
15
|
+
import { join } from "node:path";
|
|
16
|
+
import { Keychain } from "../identity/keychain.mjs";
|
|
17
|
+
import { Mailbox } from "../mailbox/mailbox.mjs";
|
|
18
|
+
import { describeProcess, otherLiveLeases, processesWithMailboxOpen } from "../readers.mjs";
|
|
19
|
+
import {
|
|
20
|
+
MIN_CONTEST_MS,
|
|
21
|
+
WaveARefusalError,
|
|
22
|
+
assertWitnessSwitchGate,
|
|
23
|
+
durMs,
|
|
24
|
+
encodeRecoverySheet,
|
|
25
|
+
eventDigest,
|
|
26
|
+
generateIdentity,
|
|
27
|
+
identityFromSeed,
|
|
28
|
+
isStatelessPreset,
|
|
29
|
+
nextCommitment,
|
|
30
|
+
parseUuaid,
|
|
31
|
+
resignCardForLineage,
|
|
32
|
+
rotation,
|
|
33
|
+
tryDecodeRecoverySheet,
|
|
34
|
+
verifyCard,
|
|
35
|
+
verifyLineage,
|
|
36
|
+
} from "../vendor/pillar-core.mjs";
|
|
37
|
+
import {
|
|
38
|
+
loadHomeReceipts,
|
|
39
|
+
mergeAndSaveReceipts,
|
|
40
|
+
persistWorkingKey,
|
|
41
|
+
prepareWitnessedRotationChanges,
|
|
42
|
+
runBindCli,
|
|
43
|
+
runDoorCli,
|
|
44
|
+
runExportRecoverySheetCli,
|
|
45
|
+
runRecoverCli,
|
|
46
|
+
runTombstoneCli,
|
|
47
|
+
runWitnessCli,
|
|
48
|
+
} from "./b1-cli.mjs";
|
|
49
|
+
import {
|
|
50
|
+
CARD_KEY,
|
|
51
|
+
LINEAGE_LOG_KEY,
|
|
52
|
+
extractWaveAWitnessHomeOpts,
|
|
53
|
+
isStrictIsoDateTime,
|
|
54
|
+
nowIsoSeconds,
|
|
55
|
+
readRecoverySheetWords,
|
|
56
|
+
seedHexFromKeychainIdentity,
|
|
57
|
+
writeFileAtomic,
|
|
58
|
+
} from "./wave-a.mjs";
|
|
59
|
+
import { chainActiveState, postLineageEventToHomes } from "./witness-cli.mjs";
|
|
60
|
+
|
|
61
|
+
export const ROTATION_PENDING_STATUS = "pending confirmation";
|
|
62
|
+
|
|
63
|
+
const LINEAGE_VALUE_FLAGS = new Set([
|
|
64
|
+
"home",
|
|
65
|
+
"now",
|
|
66
|
+
"contest-window",
|
|
67
|
+
"recovery-sheet",
|
|
68
|
+
"recovery-sheet-file",
|
|
69
|
+
"confirm",
|
|
70
|
+
"reason",
|
|
71
|
+
"preset",
|
|
72
|
+
"witness-file",
|
|
73
|
+
"homes-file",
|
|
74
|
+
"witness-threshold",
|
|
75
|
+
"m",
|
|
76
|
+
"door",
|
|
77
|
+
"door-seed",
|
|
78
|
+
"door-home",
|
|
79
|
+
"purpose",
|
|
80
|
+
"not-after",
|
|
81
|
+
"legacy-file",
|
|
82
|
+
"old-seed",
|
|
83
|
+
"old-home",
|
|
84
|
+
"relation",
|
|
85
|
+
"lineage",
|
|
86
|
+
"claim",
|
|
87
|
+
"claimed-at",
|
|
88
|
+
"new-seed",
|
|
89
|
+
"witness-seed",
|
|
90
|
+
"witness-home",
|
|
91
|
+
"fingerprint",
|
|
92
|
+
"method",
|
|
93
|
+
"card-name",
|
|
94
|
+
"claim-file",
|
|
95
|
+
"claim-json",
|
|
96
|
+
]);
|
|
97
|
+
|
|
98
|
+
const LINEAGE_BOOL_FLAGS = new Set([
|
|
99
|
+
"json",
|
|
100
|
+
"no-witnesses",
|
|
101
|
+
"allow-insecure-loopback",
|
|
102
|
+
"generate",
|
|
103
|
+
]);
|
|
104
|
+
|
|
105
|
+
function parseLineageArgs(rawArgs) {
|
|
106
|
+
const args = Array.isArray(rawArgs) ? rawArgs : [];
|
|
107
|
+
const positionals = [];
|
|
108
|
+
const unknownFlags = [];
|
|
109
|
+
const flagErrors = [];
|
|
110
|
+
const opts = {
|
|
111
|
+
home: null,
|
|
112
|
+
json: false,
|
|
113
|
+
noWitnesses: false,
|
|
114
|
+
allowInsecureLoopback: false,
|
|
115
|
+
generate: false,
|
|
116
|
+
now: undefined,
|
|
117
|
+
contestWindow: undefined,
|
|
118
|
+
recoverySheet: undefined,
|
|
119
|
+
recoverySheetFile: undefined,
|
|
120
|
+
confirm: undefined,
|
|
121
|
+
reason: undefined,
|
|
122
|
+
preset: undefined,
|
|
123
|
+
witnessFile: undefined,
|
|
124
|
+
homesFile: undefined,
|
|
125
|
+
witnessThreshold: undefined,
|
|
126
|
+
m: undefined,
|
|
127
|
+
door: undefined,
|
|
128
|
+
doorSeed: undefined,
|
|
129
|
+
doorHome: undefined,
|
|
130
|
+
purpose: undefined,
|
|
131
|
+
notAfter: undefined,
|
|
132
|
+
legacyFile: undefined,
|
|
133
|
+
oldSeed: undefined,
|
|
134
|
+
oldHome: undefined,
|
|
135
|
+
relation: undefined,
|
|
136
|
+
lineage: undefined,
|
|
137
|
+
claim: undefined,
|
|
138
|
+
claimedAt: undefined,
|
|
139
|
+
newSeed: undefined,
|
|
140
|
+
witnessSeed: undefined,
|
|
141
|
+
witnessHome: undefined,
|
|
142
|
+
witnessSeeds: [],
|
|
143
|
+
witnessHomes: [],
|
|
144
|
+
fingerprint: undefined,
|
|
145
|
+
method: undefined,
|
|
146
|
+
cardName: undefined,
|
|
147
|
+
claimFile: undefined,
|
|
148
|
+
claimJson: undefined,
|
|
149
|
+
};
|
|
150
|
+
let endOfFlags = false;
|
|
151
|
+
for (let i = 0; i < args.length; i++) {
|
|
152
|
+
const tok = args[i];
|
|
153
|
+
if (!endOfFlags && tok === "--") {
|
|
154
|
+
endOfFlags = true;
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
if (!endOfFlags && tok.startsWith("-") && tok !== "-") {
|
|
158
|
+
if (!tok.startsWith("--")) {
|
|
159
|
+
unknownFlags.push(tok);
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
const eq = tok.indexOf("=");
|
|
163
|
+
const key = eq === -1 ? tok.slice(2) : tok.slice(2, eq);
|
|
164
|
+
const hasEq = eq !== -1;
|
|
165
|
+
if (LINEAGE_BOOL_FLAGS.has(key)) {
|
|
166
|
+
if (hasEq) flagErrors.push(`lineage: --${key} does not take a value`);
|
|
167
|
+
else if (key === "json") opts.json = true;
|
|
168
|
+
else if (key === "no-witnesses") opts.noWitnesses = true;
|
|
169
|
+
else if (key === "allow-insecure-loopback") opts.allowInsecureLoopback = true;
|
|
170
|
+
else if (key === "generate") opts.generate = true;
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
if (!LINEAGE_VALUE_FLAGS.has(key)) {
|
|
174
|
+
unknownFlags.push(tok);
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
let val;
|
|
178
|
+
if (hasEq) {
|
|
179
|
+
val = tok.slice(eq + 1);
|
|
180
|
+
} else {
|
|
181
|
+
if (i + 1 >= args.length || (args[i + 1].startsWith("-") && args[i + 1] !== "-")) {
|
|
182
|
+
flagErrors.push(`lineage: --${key} requires a value`);
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
val = args[++i];
|
|
186
|
+
}
|
|
187
|
+
if (key === "home") opts.home = val;
|
|
188
|
+
else if (key === "now") opts.now = val;
|
|
189
|
+
else if (key === "contest-window") opts.contestWindow = val;
|
|
190
|
+
else if (key === "recovery-sheet") opts.recoverySheet = val;
|
|
191
|
+
else if (key === "recovery-sheet-file") opts.recoverySheetFile = val;
|
|
192
|
+
else if (key === "confirm") opts.confirm = val;
|
|
193
|
+
else if (key === "reason") opts.reason = val;
|
|
194
|
+
else if (key === "preset") opts.preset = val;
|
|
195
|
+
else if (key === "witness-file") opts.witnessFile = val;
|
|
196
|
+
else if (key === "homes-file") opts.homesFile = val;
|
|
197
|
+
else if (key === "witness-threshold") opts.witnessThreshold = val;
|
|
198
|
+
else if (key === "m") opts.m = val;
|
|
199
|
+
else if (key === "door") opts.door = val;
|
|
200
|
+
else if (key === "door-seed") opts.doorSeed = val;
|
|
201
|
+
else if (key === "door-home") opts.doorHome = val;
|
|
202
|
+
else if (key === "purpose") opts.purpose = val;
|
|
203
|
+
else if (key === "not-after") opts.notAfter = val;
|
|
204
|
+
else if (key === "legacy-file") opts.legacyFile = val;
|
|
205
|
+
else if (key === "old-seed") opts.oldSeed = val;
|
|
206
|
+
else if (key === "old-home") opts.oldHome = val;
|
|
207
|
+
else if (key === "relation") opts.relation = val;
|
|
208
|
+
else if (key === "lineage") opts.lineage = val;
|
|
209
|
+
else if (key === "claim") opts.claim = val;
|
|
210
|
+
else if (key === "claimed-at") opts.claimedAt = val;
|
|
211
|
+
else if (key === "new-seed") opts.newSeed = val;
|
|
212
|
+
else if (key === "witness-seed") { opts.witnessSeed = val; opts.witnessSeeds.push(val); }
|
|
213
|
+
else if (key === "witness-home") { opts.witnessHome = val; opts.witnessHomes.push(val); }
|
|
214
|
+
else if (key === "fingerprint") opts.fingerprint = val;
|
|
215
|
+
else if (key === "method") opts.method = val;
|
|
216
|
+
else if (key === "card-name") opts.cardName = val;
|
|
217
|
+
else if (key === "claim-file") opts.claimFile = val;
|
|
218
|
+
else if (key === "claim-json") opts.claimJson = val;
|
|
219
|
+
} else {
|
|
220
|
+
positionals.push(tok);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
return { sub: positionals[0], rest: positionals.slice(1), opts, unknownFlags, flagErrors };
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function resolveHome(opts) {
|
|
227
|
+
return opts.home || process.env.PILLAR_HOME || join(homedir(), ".pillar");
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function failLineage(errOut, msg, exitCode = 1) {
|
|
231
|
+
errOut(`${msg}\n`);
|
|
232
|
+
return { exitCode };
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function loadOptionalOutgoingSigner(home, tipPublicKey, passphrase) {
|
|
236
|
+
const kcPath = join(home, "keychain.json");
|
|
237
|
+
if (existsSync(kcPath)) {
|
|
238
|
+
try {
|
|
239
|
+
const kc = new Keychain(kcPath);
|
|
240
|
+
const id = kc.load({ passphrase });
|
|
241
|
+
if (id.publicKeyHex === tipPublicKey) {
|
|
242
|
+
return { seedHex: seedHexFromKeychainIdentity(id), publicKeyHex: id.publicKeyHex, uuaid: id.uuaid };
|
|
243
|
+
}
|
|
244
|
+
} catch { /* outgoing key optional per decision #10 (a) */ }
|
|
245
|
+
}
|
|
246
|
+
const seedPath = join(home, "identity", "agent.seed");
|
|
247
|
+
if (existsSync(seedPath)) {
|
|
248
|
+
try {
|
|
249
|
+
const seedHex = readFileSync(seedPath, "utf8").trim().toLowerCase();
|
|
250
|
+
if (/^[0-9a-f]{64}$/.test(seedHex)) {
|
|
251
|
+
const id = identityFromSeed(new Uint8Array(Buffer.from(seedHex, "hex")));
|
|
252
|
+
if (id.publicKeyHex === tipPublicKey) {
|
|
253
|
+
return { seedHex, publicKeyHex: id.publicKeyHex };
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
} catch { /* outgoing key optional per decision #10 (a) */ }
|
|
257
|
+
}
|
|
258
|
+
return null;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function checkMailboxIdle(home) {
|
|
262
|
+
const mbPath = join(home, "mailbox.db");
|
|
263
|
+
if (!existsSync(mbPath)) return null;
|
|
264
|
+
const mb = new Mailbox(mbPath);
|
|
265
|
+
let live = [];
|
|
266
|
+
try { live = otherLiveLeases(mb); } finally { mb.close(); }
|
|
267
|
+
if (live.length > 0) {
|
|
268
|
+
return `refusing to rotate while ${live.map(describeProcess).join("; ")} is reading this home — stop it first`;
|
|
269
|
+
}
|
|
270
|
+
const holders = processesWithMailboxOpen(mbPath);
|
|
271
|
+
if (holders.length > 0) {
|
|
272
|
+
return `refusing to rotate while ${holders.map((p) => `${p.command} (pid ${p.pid})`).join("; ")} has this home's mailbox open — stop it first`;
|
|
273
|
+
}
|
|
274
|
+
return null;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function prepareNextCard(cardPath, newWorking, updatedLog, receipts, ts) {
|
|
278
|
+
let oldCard;
|
|
279
|
+
try { oldCard = JSON.parse(readFileSync(cardPath, "utf8")); } catch (e) {
|
|
280
|
+
throw new Error(`lineage rotate: ${cardPath} is not valid JSON (${e.message})`);
|
|
281
|
+
}
|
|
282
|
+
if (!oldCard || typeof oldCard !== "object" || Array.isArray(oldCard)) {
|
|
283
|
+
throw new Error(`lineage rotate: ${cardPath} must be a JSON object`);
|
|
284
|
+
}
|
|
285
|
+
const pres = Array.isArray(receipts) && receipts.length > 0
|
|
286
|
+
? { v: "uuaid-lineage-log/1", events: updatedLog, receipts }
|
|
287
|
+
: updatedLog;
|
|
288
|
+
const nextCard = resignCardForLineage(oldCard, newWorking, updatedLog, { now: ts, receipts });
|
|
289
|
+
const cardVerdict = verifyCard(nextCard, { now: ts, lineage: pres });
|
|
290
|
+
if (cardVerdict.verdict !== "valid") {
|
|
291
|
+
throw new Error(`lineage rotate: rebuilt card failed verification (${cardVerdict.verdict}: ${cardVerdict.reasons.join(", ")})`);
|
|
292
|
+
}
|
|
293
|
+
return nextCard;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* Perform a #10 (a) lineage rotation on `home`.
|
|
298
|
+
* Synchronous when no active homes need HTTP publishing (preserving sync A6a callers),
|
|
299
|
+
* and returns a Promise when publishing `rot` to declared homes.
|
|
300
|
+
*/
|
|
301
|
+
export function rotateLineageHome({
|
|
302
|
+
home,
|
|
303
|
+
rawArgs = [],
|
|
304
|
+
recoverySheetWords,
|
|
305
|
+
now,
|
|
306
|
+
contestWindow,
|
|
307
|
+
reason,
|
|
308
|
+
passphrase = "",
|
|
309
|
+
skipWaveACheck = false,
|
|
310
|
+
allowWitnessed: precomputedAllowWitnessed,
|
|
311
|
+
noWitnesses = false,
|
|
312
|
+
preset,
|
|
313
|
+
switchGate,
|
|
314
|
+
requireDefaultSwitch,
|
|
315
|
+
witnessFile,
|
|
316
|
+
homesFile,
|
|
317
|
+
witnessCandidates,
|
|
318
|
+
homeRecords,
|
|
319
|
+
witnessThreshold,
|
|
320
|
+
localHostPublicKeys,
|
|
321
|
+
agentDeviceId,
|
|
322
|
+
recentKnockUuaids,
|
|
323
|
+
fetch: fetchFn,
|
|
324
|
+
urlMap,
|
|
325
|
+
allowInsecureLoopback = false,
|
|
326
|
+
unknownFlags = [],
|
|
327
|
+
flagErrors = [],
|
|
328
|
+
extraArgs = [],
|
|
329
|
+
}) {
|
|
330
|
+
const waveAOpts = extractWaveAWitnessHomeOpts(rawArgs);
|
|
331
|
+
if (witnessFile || Array.isArray(witnessCandidates)) waveAOpts.witnesses = waveAOpts.witnesses ?? ["<file>"];
|
|
332
|
+
if (homesFile || Array.isArray(homeRecords)) waveAOpts.homes = waveAOpts.homes ?? ["<file>"];
|
|
333
|
+
|
|
334
|
+
const gateOpts = {
|
|
335
|
+
allowWitnessed: precomputedAllowWitnessed,
|
|
336
|
+
noWitnesses: Boolean(noWitnesses || isStatelessPreset(preset)),
|
|
337
|
+
preset,
|
|
338
|
+
switchGate,
|
|
339
|
+
requireDefaultSwitch,
|
|
340
|
+
};
|
|
341
|
+
let allowWitnessed = Boolean(precomputedAllowWitnessed);
|
|
342
|
+
if (!skipWaveACheck) ({ allowWitnessed } = assertWitnessSwitchGate(waveAOpts, gateOpts)); // @rule vnext.lineage-rotate-wave-a
|
|
343
|
+
|
|
344
|
+
if (unknownFlags.length > 0) throw new Error(`lineage rotate: unknown flag ${unknownFlags[0]}`); // @rule vnext.lineage-rotate-unknown-flag
|
|
345
|
+
if (flagErrors.length > 0) {
|
|
346
|
+
const err = new Error(flagErrors[0]);
|
|
347
|
+
err.exitCode = 64;
|
|
348
|
+
throw err;
|
|
349
|
+
}
|
|
350
|
+
if (extraArgs.length > 0) throw new Error(`lineage rotate: unexpected argument "${extraArgs[0]}"`); // @rule vnext.lineage-rotate-extra-arg
|
|
351
|
+
|
|
352
|
+
const ts = now !== undefined ? now : nowIsoSeconds();
|
|
353
|
+
if (!isStrictIsoDateTime(ts)) throw new Error("lineage rotate: --now must be a valid ISO-8601 timestamp"); // @rule vnext.lineage-now-valid
|
|
354
|
+
|
|
355
|
+
let changes = {};
|
|
356
|
+
if (contestWindow !== undefined) {
|
|
357
|
+
const cwMs = durMs(contestWindow);
|
|
358
|
+
if (cwMs === null || cwMs < MIN_CONTEST_MS) throw new Error("lineage rotate: --contest-window must be a valid duration >= P3D"); // @rule vnext.lineage-contest-window
|
|
359
|
+
changes = { contestWindow };
|
|
360
|
+
}
|
|
361
|
+
if (reason !== undefined) changes = { ...changes, reason };
|
|
362
|
+
|
|
363
|
+
if (!Array.isArray(recoverySheetWords) || recoverySheetWords.length === 0) throw new Error("lineage rotate: recovery sheet is required (--recovery-sheet or --recovery-sheet-file)"); // @rule vnext.lineage-rotate-needs-sheet
|
|
364
|
+
|
|
365
|
+
const logPath = join(home, LINEAGE_LOG_KEY);
|
|
366
|
+
if (!existsSync(logPath)) throw new Error(`lineage rotate: no lineage log found at ${logPath}`); // @rule vnext.lineage-log-exists
|
|
367
|
+
|
|
368
|
+
let log;
|
|
369
|
+
try { log = JSON.parse(readFileSync(logPath, "utf8")); } catch { log = null; }
|
|
370
|
+
if (!Array.isArray(log) || log.length === 0) throw new Error(`lineage rotate: ${logPath} is not a valid lineage event array`); // @rule vnext.lineage-log-json
|
|
371
|
+
|
|
372
|
+
const existingReceipts = loadHomeReceipts(home);
|
|
373
|
+
const prevPres = existingReceipts.length ? { v: "uuaid-lineage-log/1", events: log, receipts: existingReceipts } : log;
|
|
374
|
+
const prevVerdict = verifyLineage(prevPres, { now: ts });
|
|
375
|
+
if (prevVerdict.verdict !== "valid" && prevVerdict.verdict !== "recovered") {
|
|
376
|
+
throw new Error(`lineage rotate: stored lineage failed verification (${prevVerdict.verdict}: ${prevVerdict.reasons.join(", ")})`); // @rule vnext.lineage-existing-valid
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
const namespace = parseUuaid(log[0].lineage).namespace;
|
|
380
|
+
const decoded = tryDecodeRecoverySheet(recoverySheetWords, { namespace });
|
|
381
|
+
if (!decoded.ok) throw new Error(`lineage rotate: invalid recovery sheet (${decoded.reason})`); // @rule vnext.lineage-sheet-decode
|
|
382
|
+
|
|
383
|
+
let curTip = log[log.length - 1];
|
|
384
|
+
for (let i = log.length - 1; i >= 0; i--) {
|
|
385
|
+
if (typeof log[i]?.next === "string" && log[i]?.key?.uuaid === prevVerdict.facts.current) {
|
|
386
|
+
curTip = log[i];
|
|
387
|
+
break;
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
if (nextCommitment(decoded) !== curTip.next) throw new Error("lineage rotate: recovery sheet does not match the committed next key (next-commitment mismatch)"); // @rule vnext.lineage-next-commitment-match
|
|
391
|
+
|
|
392
|
+
const busyErr = checkMailboxIdle(home);
|
|
393
|
+
if (busyErr) throw new Error(busyErr);
|
|
394
|
+
|
|
395
|
+
const curSigner = loadOptionalOutgoingSigner(home, curTip.key.publicKey, passphrase);
|
|
396
|
+
const newWorking = generateIdentity({ namespace, objectType: "agent" });
|
|
397
|
+
const newNext = generateIdentity({ namespace, objectType: "agent" });
|
|
398
|
+
const newRecoverySheet = encodeRecoverySheet(newNext.seedHex);
|
|
399
|
+
|
|
400
|
+
let warnings = [];
|
|
401
|
+
let activeHomes = chainActiveState(log).homes;
|
|
402
|
+
if (allowWitnessed && (witnessFile || homesFile || Array.isArray(witnessCandidates) || Array.isArray(homeRecords))) {
|
|
403
|
+
const prep = prepareWitnessedRotationChanges({
|
|
404
|
+
log,
|
|
405
|
+
newWorking,
|
|
406
|
+
newNext,
|
|
407
|
+
uuaidNamespace: namespace,
|
|
408
|
+
witnessFile,
|
|
409
|
+
homesFile,
|
|
410
|
+
witnessCandidates,
|
|
411
|
+
homeRecords,
|
|
412
|
+
witnessThreshold,
|
|
413
|
+
localHostPublicKeys,
|
|
414
|
+
agentDeviceId,
|
|
415
|
+
recentKnockUuaids,
|
|
416
|
+
});
|
|
417
|
+
changes = { ...changes, ...prep.changes };
|
|
418
|
+
warnings = prep.warnings;
|
|
419
|
+
activeHomes = prep.activeHomes;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
const rot = rotation(
|
|
423
|
+
log,
|
|
424
|
+
curSigner,
|
|
425
|
+
{ seedHex: decoded.seedHex, publicKeyHex: decoded.publicKeyHex, uuaid: decoded.uuaid },
|
|
426
|
+
{ seedHex: newWorking.seedHex, publicKeyHex: newWorking.publicKeyHex, uuaid: newWorking.uuaid },
|
|
427
|
+
{ uuaid: newNext.uuaid, publicKeyHex: newNext.publicKeyHex },
|
|
428
|
+
ts,
|
|
429
|
+
changes,
|
|
430
|
+
);
|
|
431
|
+
|
|
432
|
+
if (!allowWitnessed && ("witnesses" in rot || "witnessThreshold" in rot || "homes" in rot)) {
|
|
433
|
+
throw new Error("lineage rotate: signed rotation unexpectedly carried witness or home fields");
|
|
434
|
+
}
|
|
435
|
+
const updatedLog = [...log, rot];
|
|
436
|
+
const afterPres = existingReceipts.length ? { v: "uuaid-lineage-log/1", events: updatedLog, receipts: existingReceipts } : updatedLog;
|
|
437
|
+
const afterVerdict = verifyLineage(afterPres, { now: ts });
|
|
438
|
+
if (afterVerdict.verdict !== "valid" && afterVerdict.verdict !== "recovered") {
|
|
439
|
+
throw new Error(`lineage rotate: signed rotation failed verification (${afterVerdict.verdict}: ${afterVerdict.reasons.join(", ")})`);
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
const head = `sha256:${eventDigest(rot)}`;
|
|
443
|
+
const cardPath = join(home, CARD_KEY);
|
|
444
|
+
|
|
445
|
+
let nextCard = null;
|
|
446
|
+
if (existsSync(cardPath)) nextCard = prepareNextCard(cardPath, newWorking, updatedLog, existingReceipts, ts); // @rule vnext.lineage-card-before-write
|
|
447
|
+
|
|
448
|
+
persistWorkingKey(home, newWorking, curTip.key.uuaid, ts, passphrase);
|
|
449
|
+
if (nextCard !== null) {
|
|
450
|
+
writeFileAtomic(cardPath, `${JSON.stringify(nextCard, null, 2)}\n`, 0o600);
|
|
451
|
+
}
|
|
452
|
+
writeFileAtomic(logPath, `${JSON.stringify(updatedLog, null, 2)}\n`, 0o600);
|
|
453
|
+
|
|
454
|
+
const baseResult = {
|
|
455
|
+
status: ROTATION_PENDING_STATUS,
|
|
456
|
+
lineage: log[0].lineage,
|
|
457
|
+
previousUuaid: curTip.key.uuaid,
|
|
458
|
+
uuaid: newWorking.uuaid,
|
|
459
|
+
publicKey: newWorking.publicKeyHex,
|
|
460
|
+
seq: rot.seq,
|
|
461
|
+
head,
|
|
462
|
+
...(warnings.length ? { warnings } : {}),
|
|
463
|
+
event: rot,
|
|
464
|
+
recoverySheet: newRecoverySheet,
|
|
465
|
+
};
|
|
466
|
+
|
|
467
|
+
if (!Array.isArray(activeHomes) || activeHomes.length === 0) {
|
|
468
|
+
return baseResult;
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
return (async () => {
|
|
472
|
+
const posted = await postLineageEventToHomes(rot, log[0].lineage, activeHomes, {
|
|
473
|
+
now: ts,
|
|
474
|
+
fetch: fetchFn,
|
|
475
|
+
urlMap,
|
|
476
|
+
allowInsecureLoopback,
|
|
477
|
+
});
|
|
478
|
+
const mergedReceipts = mergeAndSaveReceipts(home, existingReceipts, posted.receipts);
|
|
479
|
+
return {
|
|
480
|
+
...baseResult,
|
|
481
|
+
homesAccepted: posted.acceptedCount,
|
|
482
|
+
receipts: posted.receipts,
|
|
483
|
+
totalReceipts: mergedReceipts.length,
|
|
484
|
+
refusals: posted.refusals,
|
|
485
|
+
};
|
|
486
|
+
})();
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
export function formatRotationOutput(res, home, json) {
|
|
490
|
+
if (json) {
|
|
491
|
+
return `${JSON.stringify({
|
|
492
|
+
status: res.status,
|
|
493
|
+
lineage: res.lineage,
|
|
494
|
+
previousUuaid: res.previousUuaid,
|
|
495
|
+
uuaid: res.uuaid,
|
|
496
|
+
publicKey: res.publicKey,
|
|
497
|
+
seq: res.seq,
|
|
498
|
+
head: res.head,
|
|
499
|
+
...(res.warnings ? { warnings: res.warnings } : {}),
|
|
500
|
+
...(res.receipts ? { receipts: res.receipts } : {}),
|
|
501
|
+
event: res.event,
|
|
502
|
+
recoverySheet: res.recoverySheet,
|
|
503
|
+
})}\n`;
|
|
504
|
+
}
|
|
505
|
+
return [
|
|
506
|
+
`rotated lineage ${res.lineage} (seq ${res.seq})`,
|
|
507
|
+
`uuaid: ${res.uuaid}`,
|
|
508
|
+
`publicKey: ${res.publicKey}`,
|
|
509
|
+
`head: ${res.head}`,
|
|
510
|
+
`status: ${res.status}`,
|
|
511
|
+
`recovery sheet (save offline — shown once, never stored in ${home}):`,
|
|
512
|
+
` ${res.recoverySheet.join(" ")}`,
|
|
513
|
+
"",
|
|
514
|
+
].join("\n");
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
function canDigestTip(tip) {
|
|
518
|
+
if (!tip || typeof tip !== "object" || Array.isArray(tip)) return false;
|
|
519
|
+
try { eventDigest(tip); return true; } catch { return false; }
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/**
|
|
523
|
+
* Execute `pillar lineage <subcommand>` with injectable streams.
|
|
524
|
+
* Returns `{ exitCode }` synchronously for local operations and a Promise when async HTTP home calls are used.
|
|
525
|
+
*/
|
|
526
|
+
export function runLineageCli(rawArgs, io = {}) {
|
|
527
|
+
const out = io.stdout ?? ((s) => process.stdout.write(s));
|
|
528
|
+
const errOut = io.stderr ?? ((s) => process.stderr.write(s));
|
|
529
|
+
const passphrase = io.passphrase ?? process.env.PILLAR_PASSPHRASE ?? "";
|
|
530
|
+
|
|
531
|
+
const { sub, rest, opts, unknownFlags, flagErrors } = parseLineageArgs(rawArgs);
|
|
532
|
+
const home = resolveHome(opts);
|
|
533
|
+
|
|
534
|
+
if (sub === "tombstone" && !opts.confirm) {
|
|
535
|
+
return failLineage(errOut, "lineage tombstone: --confirm <lineage> is required", 1); // @rule vnext.lineage-tombstone-confirm
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
if (sub === "show") {
|
|
539
|
+
if (unknownFlags.length > 0) return failLineage(errOut, `lineage show: unknown flag ${unknownFlags[0]}`, 64); // @rule vnext.lineage-show-unknown-flag
|
|
540
|
+
if (flagErrors.length > 0) return failLineage(errOut, flagErrors[0], 64);
|
|
541
|
+
if (rest.length > 0) return failLineage(errOut, `lineage show: unexpected argument "${rest[0]}"`, 64); // @rule vnext.lineage-show-extra-arg
|
|
542
|
+
const ts = opts.now !== undefined ? opts.now : nowIsoSeconds();
|
|
543
|
+
if (!isStrictIsoDateTime(ts)) return failLineage(errOut, "lineage show: --now must be a valid ISO-8601 timestamp", 64); // @rule vnext.lineage-show-now-valid
|
|
544
|
+
const logPath = join(home, LINEAGE_LOG_KEY);
|
|
545
|
+
if (!existsSync(logPath)) return failLineage(errOut, `lineage show: no lineage log found at ${logPath}`, 1);
|
|
546
|
+
let log;
|
|
547
|
+
try { log = JSON.parse(readFileSync(logPath, "utf8")); } catch (e) {
|
|
548
|
+
return failLineage(errOut, `lineage show: ${logPath} is not valid JSON (${e.message})`, 1);
|
|
549
|
+
}
|
|
550
|
+
const receipts = loadHomeReceipts(home);
|
|
551
|
+
const pres = Array.isArray(log) && receipts.length > 0 ? { v: "uuaid-lineage-log/1", events: log, receipts } : log;
|
|
552
|
+
const verdict = verifyLineage(pres, { now: ts });
|
|
553
|
+
const rawTip = Array.isArray(log) && log.length > 0 ? log[log.length - 1] : null;
|
|
554
|
+
let tipForDigest = rawTip;
|
|
555
|
+
if (tipForDigest && !canDigestTip(tipForDigest)) tipForDigest = null; // @rule vnext.lineage-show-tip-digest-guard
|
|
556
|
+
const tip = rawTip && typeof rawTip === "object" && !Array.isArray(rawTip) ? rawTip : null;
|
|
557
|
+
const summary = {
|
|
558
|
+
lineage: typeof log?.[0]?.lineage === "string" ? log[0].lineage : null,
|
|
559
|
+
current: verdict.facts?.current ?? (typeof tip?.key?.uuaid === "string" ? tip.key.uuaid : null),
|
|
560
|
+
seq: typeof tip?.seq === "number" ? tip.seq : null,
|
|
561
|
+
head: verdict.facts?.head ?? (tipForDigest ? `sha256:${eventDigest(tipForDigest)}` : null),
|
|
562
|
+
verdict: verdict.verdict,
|
|
563
|
+
reasons: verdict.reasons,
|
|
564
|
+
events: Array.isArray(log) ? log.length : 0,
|
|
565
|
+
keyPath: verdict.facts?.keyPath ?? [],
|
|
566
|
+
doors: verdict.facts?.doors ?? [],
|
|
567
|
+
tombstoned: Boolean(verdict.facts?.tombstoned),
|
|
568
|
+
boundLegacy: verdict.facts?.boundLegacy ?? [],
|
|
569
|
+
};
|
|
570
|
+
if (opts.json) {
|
|
571
|
+
out(`${JSON.stringify({ ...summary, log, ...(receipts.length ? { receipts } : {}) })}\n`);
|
|
572
|
+
} else {
|
|
573
|
+
out([
|
|
574
|
+
`lineage: ${summary.lineage}`,
|
|
575
|
+
`current: ${summary.current}`,
|
|
576
|
+
`seq: ${summary.seq}`,
|
|
577
|
+
`head: ${summary.head}`,
|
|
578
|
+
`verdict: ${summary.verdict}${summary.reasons.length ? ` (${summary.reasons.join(", ")})` : ""}`,
|
|
579
|
+
`events: ${summary.events}`,
|
|
580
|
+
"",
|
|
581
|
+
].join("\n"));
|
|
582
|
+
}
|
|
583
|
+
return { exitCode: verdict.verdict === "valid" || verdict.verdict === "recovered" ? 0 : 1 };
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
if (sub === "rotate") {
|
|
587
|
+
const subRawArgs = Array.isArray(rawArgs) ? rawArgs : [];
|
|
588
|
+
const handleErr = (e) => {
|
|
589
|
+
if (e instanceof WaveARefusalError) {
|
|
590
|
+
errOut(`${e.message}\n`);
|
|
591
|
+
return { exitCode: 1, error: e };
|
|
592
|
+
}
|
|
593
|
+
const code = Number.isInteger(e?.exitCode) ? e.exitCode : 1;
|
|
594
|
+
errOut(`${e instanceof Error ? e.message : String(e)}\n`);
|
|
595
|
+
return { exitCode: code, error: e };
|
|
596
|
+
};
|
|
597
|
+
try {
|
|
598
|
+
const words = readRecoverySheetWords(opts);
|
|
599
|
+
const resOrPromise = rotateLineageHome({
|
|
600
|
+
home,
|
|
601
|
+
rawArgs: subRawArgs,
|
|
602
|
+
recoverySheetWords: words,
|
|
603
|
+
now: opts.now,
|
|
604
|
+
contestWindow: opts.contestWindow,
|
|
605
|
+
reason: opts.reason,
|
|
606
|
+
passphrase,
|
|
607
|
+
noWitnesses: opts.noWitnesses,
|
|
608
|
+
preset: opts.preset,
|
|
609
|
+
switchGate: io.switchGate,
|
|
610
|
+
requireDefaultSwitch: io.requireDefaultSwitch,
|
|
611
|
+
allowWitnessed: io.allowWitnessed,
|
|
612
|
+
witnessFile: opts.witnessFile,
|
|
613
|
+
homesFile: opts.homesFile,
|
|
614
|
+
witnessCandidates: io.witnessCandidates,
|
|
615
|
+
homeRecords: io.homeRecords,
|
|
616
|
+
witnessThreshold: opts.witnessThreshold ?? opts.m,
|
|
617
|
+
localHostPublicKeys: io.localHostPublicKeys,
|
|
618
|
+
agentDeviceId: io.agentDeviceId,
|
|
619
|
+
recentKnockUuaids: io.recentKnockUuaids,
|
|
620
|
+
fetch: io.fetch,
|
|
621
|
+
urlMap: io.urlMap,
|
|
622
|
+
allowInsecureLoopback: opts.allowInsecureLoopback || Boolean(io.allowInsecureLoopback),
|
|
623
|
+
unknownFlags,
|
|
624
|
+
flagErrors,
|
|
625
|
+
extraArgs: rest,
|
|
626
|
+
});
|
|
627
|
+
if (resOrPromise && typeof resOrPromise.then === "function") {
|
|
628
|
+
return resOrPromise.then((res) => {
|
|
629
|
+
for (const w of res.warnings ?? []) errOut(`warning: ${w}\n`);
|
|
630
|
+
out(formatRotationOutput(res, home, opts.json));
|
|
631
|
+
return { exitCode: 0, result: res };
|
|
632
|
+
}, handleErr);
|
|
633
|
+
}
|
|
634
|
+
for (const w of resOrPromise.warnings ?? []) errOut(`warning: ${w}\n`);
|
|
635
|
+
out(formatRotationOutput(resOrPromise, home, opts.json));
|
|
636
|
+
return { exitCode: 0, result: resOrPromise };
|
|
637
|
+
} catch (e) {
|
|
638
|
+
return handleErr(e);
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
if (unknownFlags.length > 0) return failLineage(errOut, `lineage: unknown flag ${unknownFlags[0]}`, 64);
|
|
643
|
+
if (flagErrors.length > 0) return failLineage(errOut, flagErrors[0], 64);
|
|
644
|
+
|
|
645
|
+
if (sub === "door") return runDoorCli(rest[0], rest.slice(1), opts, home, passphrase, io, out, errOut);
|
|
646
|
+
if (sub === "bind") return runBindCli(rest, opts, home, passphrase, io, out, errOut);
|
|
647
|
+
if (sub === "tombstone") return runTombstoneCli(rest, opts, home, passphrase, io, out, errOut);
|
|
648
|
+
if (sub === "export-recovery-sheet") return runExportRecoverySheetCli(rest, opts, home, out, errOut);
|
|
649
|
+
if (sub === "recover") return runRecoverCli(rest[0], rest.slice(1), opts, home, passphrase, io, out, errOut);
|
|
650
|
+
if (sub === "witness") return runWitnessCli(rest[0], rest.slice(1), opts, home, passphrase, io, out, errOut);
|
|
651
|
+
|
|
652
|
+
return failLineage(errOut, "usage: pillar lineage <show|rotate|door|recover|witness|bind|tombstone|export-recovery-sheet> [--home DIR] [--json]", 64);
|
|
653
|
+
}
|