@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.
- package/HOSTING-LIMITS.md +12 -0
- package/README.md +201 -5
- package/bin/carrier.mjs +72 -2
- package/bin/pillar-ask.mjs +4 -1
- package/bin/pillar-blob.mjs +6 -0
- package/bin/pillar-directory.mjs +280 -16
- package/bin/pillar-escrow.mjs +4 -1
- package/bin/pillar-group-v2.mjs +6 -0
- package/bin/pillar-notify.mjs +13 -0
- package/bin/pillar-responder.mjs +266 -23
- package/bin/pillar.mjs +504 -255
- package/package.json +17 -25
- package/src/cli-help.mjs +23 -0
- package/src/group-v2-cli.mjs +1 -1
- package/src/identity/trust.mjs +72 -6
- package/src/mailbox/mailbox.mjs +308 -12
- package/src/net/carrier-server.mjs +34 -2
- package/src/net/refusals.mjs +2 -0
- package/src/net/seed-registry.mjs +2 -1
- package/src/net/transport.mjs +308 -92
- package/src/node-check.mjs +29 -8
- package/src/notify-events.mjs +148 -0
- package/src/notify-log.mjs +124 -0
- package/src/notify-runner.mjs +372 -0
- package/src/notify-store.mjs +725 -0
- package/src/notify.mjs +350 -0
- package/src/pillar.mjs +382 -27
- package/src/readers.mjs +2 -2
- package/src/registry/federation.mjs +3056 -0
- package/src/registry/gossip.mjs +294 -0
- package/src/registry/heartbeats.mjs +195 -0
- package/src/registry/lineage-verifier.mjs +972 -0
- package/src/registry/lineage.mjs +984 -0
- package/src/registry/listings.mjs +549 -0
- package/src/registry/resolve.mjs +376 -0
- package/src/registry/stats.mjs +508 -0
- package/src/sqlite-loader.mjs +40 -0
- package/src/vendor/pillar-core.mjs +22 -0
- package/src/vendor/uuaid-soul.mjs +2246 -0
- package/src/vnext/a6b-common.mjs +270 -0
- package/src/vnext/b1-cli.mjs +970 -0
- package/src/vnext/card-cli.mjs +370 -0
- package/src/vnext/greeter-operator.mjs +160 -0
- package/src/vnext/greeter-suggest.mjs +318 -0
- package/src/vnext/greeter.mjs +571 -0
- package/src/vnext/homes.mjs +48 -0
- package/src/vnext/init-cli.mjs +489 -0
- package/src/vnext/intro-cli.mjs +81 -0
- package/src/vnext/json-dir-mailbox.mjs +296 -0
- package/src/vnext/jsonl-mailbox.mjs +1066 -0
- package/src/vnext/knock-answer.mjs +162 -0
- package/src/vnext/knock-cli.mjs +520 -0
- package/src/vnext/knock-lane.mjs +312 -0
- package/src/vnext/knock-responder.mjs +344 -0
- package/src/vnext/lineage-cli.mjs +653 -0
- package/src/vnext/listing-cli.mjs +323 -0
- package/src/vnext/resolve-cli.mjs +86 -0
- package/src/vnext/soul-cli.mjs +666 -0
- package/src/vnext/verify-cli.mjs +251 -0
- package/src/vnext/w4-redirect.mjs +178 -0
- package/src/vnext/wave-a.mjs +193 -0
- package/src/vnext/witness-cli.mjs +547 -0
|
@@ -0,0 +1,970 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pillar vNext Wave B B1 — Extended `pillar lineage` verbs (`door add|retire`,
|
|
3
|
+
* `recover claim|veto|finalize`, `witness vouch`, `bind`, `tombstone`,
|
|
4
|
+
* `export-recovery-sheet`) and witnessed `init` / `rotate` helpers.
|
|
5
|
+
*/
|
|
6
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync } from "node:fs";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
import { Keychain } from "../identity/keychain.mjs";
|
|
9
|
+
import {
|
|
10
|
+
DOOR_SEED_KEY,
|
|
11
|
+
LINEAGE_RECEIPTS_KEY,
|
|
12
|
+
bind as buildBindEvent,
|
|
13
|
+
buildContinuityLegacy,
|
|
14
|
+
doorAdd,
|
|
15
|
+
doorRetire,
|
|
16
|
+
eligibleHomes,
|
|
17
|
+
encodeRecoverySheet,
|
|
18
|
+
eventDigest,
|
|
19
|
+
generateIdentity,
|
|
20
|
+
homeRecord,
|
|
21
|
+
identityFromSeed,
|
|
22
|
+
nextCommitment,
|
|
23
|
+
parseUuaid,
|
|
24
|
+
publishSeq0ToHomes,
|
|
25
|
+
recoveryClaim,
|
|
26
|
+
recoveryFinal,
|
|
27
|
+
recoveryVeto,
|
|
28
|
+
resignCardForLineage,
|
|
29
|
+
rotation,
|
|
30
|
+
tombstone,
|
|
31
|
+
tryDecodeRecoverySheet,
|
|
32
|
+
verifyCard,
|
|
33
|
+
verifyLineage,
|
|
34
|
+
verifyLineageFromHomes,
|
|
35
|
+
} from "../vendor/pillar-core.mjs";
|
|
36
|
+
import { isJsonDirHome } from "./json-dir-mailbox.mjs";
|
|
37
|
+
import {
|
|
38
|
+
CARD_KEY,
|
|
39
|
+
LINEAGE_LOG_KEY,
|
|
40
|
+
isStrictIsoDateTime,
|
|
41
|
+
keychainIdentityFromSeedHex,
|
|
42
|
+
nowIsoSeconds,
|
|
43
|
+
readRecoverySheetWords,
|
|
44
|
+
seedHexFromKeychainIdentity,
|
|
45
|
+
writeFileAtomic,
|
|
46
|
+
} from "./wave-a.mjs";
|
|
47
|
+
import {
|
|
48
|
+
chainActiveState,
|
|
49
|
+
exportRecoverySheetCheck,
|
|
50
|
+
formatFingerprint16,
|
|
51
|
+
postLineageEventToHomes,
|
|
52
|
+
pullLineageHomes,
|
|
53
|
+
stripShaPrefix,
|
|
54
|
+
validStampTimesForEvent,
|
|
55
|
+
validateWitnessSetD4,
|
|
56
|
+
witnessVouchHome,
|
|
57
|
+
} from "./witness-cli.mjs";
|
|
58
|
+
|
|
59
|
+
export const PENDING_CLAIM_KEY = "recovery/pending-claim.json";
|
|
60
|
+
|
|
61
|
+
export function loadJsonArrayFile(filePath, label) {
|
|
62
|
+
let parsed;
|
|
63
|
+
try { parsed = JSON.parse(readFileSync(filePath, "utf8")); } catch (e) {
|
|
64
|
+
throw new Error(`${label}: cannot read ${filePath} (${e.message})`);
|
|
65
|
+
}
|
|
66
|
+
if (!Array.isArray(parsed)) throw new Error(`${label}: ${filePath} must be a JSON array`);
|
|
67
|
+
return parsed;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function loadHomeReceipts(home) {
|
|
71
|
+
const p = join(home, LINEAGE_RECEIPTS_KEY);
|
|
72
|
+
if (!existsSync(p)) return [];
|
|
73
|
+
try {
|
|
74
|
+
const parsed = JSON.parse(readFileSync(p, "utf8"));
|
|
75
|
+
return Array.isArray(parsed) ? parsed : [];
|
|
76
|
+
} catch {
|
|
77
|
+
return [];
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function mergeAndSaveReceipts(home, existing, incoming) {
|
|
82
|
+
const map = new Map();
|
|
83
|
+
for (const r of [...(Array.isArray(existing) ? existing : []), ...(Array.isArray(incoming) ? incoming : [])]) {
|
|
84
|
+
if (!r || typeof r !== "object" || typeof r.registry !== "string" || typeof r.event !== "string") continue;
|
|
85
|
+
const k = `${r.registry}:${r.event}`;
|
|
86
|
+
const prev = map.get(k);
|
|
87
|
+
if (!prev || Date.parse(r.seenAt) < Date.parse(prev.seenAt)) map.set(k, r);
|
|
88
|
+
}
|
|
89
|
+
const merged = [...map.values()];
|
|
90
|
+
if (merged.length > 0) {
|
|
91
|
+
writeFileAtomic(join(home, LINEAGE_RECEIPTS_KEY), `${JSON.stringify(merged, null, 2)}\n`, 0o600);
|
|
92
|
+
}
|
|
93
|
+
return merged;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function loadSignerFromHomeOrSeed({ home, seedHex, namespace = "pillar", passphrase = "" }) {
|
|
97
|
+
if (typeof seedHex === "string" && seedHex.trim()) {
|
|
98
|
+
const clean = seedHex.trim().toLowerCase();
|
|
99
|
+
if (!/^[0-9a-f]{64}$/.test(clean)) throw new Error("invalid 64-hex seed");
|
|
100
|
+
const id = identityFromSeed(new Uint8Array(Buffer.from(clean, "hex")), { namespace });
|
|
101
|
+
return { seedHex: clean, publicKeyHex: id.publicKeyHex, uuaid: id.uuaid };
|
|
102
|
+
}
|
|
103
|
+
const kcPath = join(home, "keychain.json");
|
|
104
|
+
if (existsSync(kcPath)) {
|
|
105
|
+
const kc = new Keychain(kcPath);
|
|
106
|
+
const id = kc.load({ passphrase });
|
|
107
|
+
const parsedNs = parseUuaid(id.uuaid)?.namespace ?? namespace;
|
|
108
|
+
const sHex = seedHexFromKeychainIdentity(id);
|
|
109
|
+
const derived = identityFromSeed(new Uint8Array(Buffer.from(sHex, "hex")), { namespace: parsedNs });
|
|
110
|
+
return { seedHex: sHex, publicKeyHex: derived.publicKeyHex, uuaid: derived.uuaid };
|
|
111
|
+
}
|
|
112
|
+
const seedPath = join(home, "identity", "agent.seed");
|
|
113
|
+
if (existsSync(seedPath)) {
|
|
114
|
+
const clean = readFileSync(seedPath, "utf8").trim().toLowerCase();
|
|
115
|
+
if (/^[0-9a-f]{64}$/.test(clean)) {
|
|
116
|
+
const id = identityFromSeed(new Uint8Array(Buffer.from(clean, "hex")), { namespace });
|
|
117
|
+
return { seedHex: clean, publicKeyHex: id.publicKeyHex, uuaid: id.uuaid };
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return null;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export function canonicalChainToHead(log, headPrefixed) {
|
|
124
|
+
const byDigest = new Map();
|
|
125
|
+
for (const e of log) {
|
|
126
|
+
if (e && typeof e === "object") {
|
|
127
|
+
try { byDigest.set(eventDigest(e), e); } catch {}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
const headHex = stripShaPrefix(headPrefixed ?? "");
|
|
131
|
+
const chain = [];
|
|
132
|
+
for (let cur = byDigest.get(headHex); cur; cur = typeof cur.prev === "string" ? byDigest.get(cur.prev) : undefined) {
|
|
133
|
+
chain.unshift(cur);
|
|
134
|
+
}
|
|
135
|
+
return chain.length > 0 ? chain : log;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export function loadActiveSignerForLog(home, log, ts, passphrase = "") {
|
|
139
|
+
const receipts = loadHomeReceipts(home);
|
|
140
|
+
const pres = receipts.length ? { v: "uuaid-lineage-log/1", events: log, receipts } : log;
|
|
141
|
+
const verdict = verifyLineage(pres, { now: ts });
|
|
142
|
+
if (verdict.verdict !== "valid" && verdict.verdict !== "recovered") {
|
|
143
|
+
throw new Error(`stored lineage is ${verdict.verdict} (${verdict.reasons.join(", ")})`); // @rule pillar-b1.lineage-active-verdict
|
|
144
|
+
}
|
|
145
|
+
const ns = parseUuaid(log[0].lineage).namespace;
|
|
146
|
+
const signer = loadSignerFromHomeOrSeed({ home, namespace: ns, passphrase });
|
|
147
|
+
if (!signer || signer.uuaid !== verdict.facts.current) {
|
|
148
|
+
throw new Error(`local key (${signer?.uuaid ?? "missing"}) does not match active lineage key (${verdict.facts.current})`); // @rule pillar-b1.active-signer-match
|
|
149
|
+
}
|
|
150
|
+
const canonicalChain = canonicalChainToHead(log, verdict.facts.head);
|
|
151
|
+
return { signer, verdict, receipts, namespace: ns, canonicalChain };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export function persistWorkingKey(home, newWorking, oldUuaid, ts, passphrase = "") {
|
|
155
|
+
const kcPath = join(home, "keychain.json");
|
|
156
|
+
const seedPath = join(home, "identity", "agent.seed");
|
|
157
|
+
const metaPath = join(home, "identity", "agent-meta.json");
|
|
158
|
+
const jsonDirHome = isJsonDirHome(home);
|
|
159
|
+
const stamp = ts.replace(/[:.]/g, "-");
|
|
160
|
+
const oldShort = (String(oldUuaid ?? "unknown").split(":")[3] ?? "unknown").slice(0, 8);
|
|
161
|
+
const archiveDir = join(home, "rotated", `${stamp}-${oldShort}`);
|
|
162
|
+
|
|
163
|
+
if (jsonDirHome) {
|
|
164
|
+
if (existsSync(seedPath) || existsSync(metaPath)) {
|
|
165
|
+
mkdirSync(archiveDir, { recursive: true });
|
|
166
|
+
if (existsSync(seedPath)) {
|
|
167
|
+
const dst = join(archiveDir, "agent.seed");
|
|
168
|
+
renameSync(seedPath, dst);
|
|
169
|
+
chmodSync(dst, 0o600);
|
|
170
|
+
}
|
|
171
|
+
if (existsSync(metaPath)) {
|
|
172
|
+
const dst = join(archiveDir, "agent-meta.json");
|
|
173
|
+
renameSync(metaPath, dst);
|
|
174
|
+
chmodSync(dst, 0o600);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
writeFileAtomic(seedPath, newWorking.seedHex, 0o600);
|
|
178
|
+
writeFileAtomic(metaPath, JSON.stringify({
|
|
179
|
+
uuaid: newWorking.uuaid,
|
|
180
|
+
publicKeyHex: newWorking.publicKeyHex,
|
|
181
|
+
createdAt: ts,
|
|
182
|
+
}), 0o600);
|
|
183
|
+
} else {
|
|
184
|
+
if (existsSync(kcPath)) {
|
|
185
|
+
mkdirSync(archiveDir, { recursive: true });
|
|
186
|
+
renameSync(kcPath, join(archiveDir, "keychain.json"));
|
|
187
|
+
}
|
|
188
|
+
mkdirSync(home, { recursive: true });
|
|
189
|
+
const kc = new Keychain(kcPath);
|
|
190
|
+
kc.save(keychainIdentityFromSeedHex(newWorking.seedHex, newWorking.uuaid, ts), { passphrase });
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
export function resignHomeCardIfPresent(home, activeSigner, updatedLog, receipts, ts) {
|
|
195
|
+
const cardPath = join(home, CARD_KEY);
|
|
196
|
+
if (!existsSync(cardPath)) return null;
|
|
197
|
+
let oldCard;
|
|
198
|
+
try { oldCard = JSON.parse(readFileSync(cardPath, "utf8")); } catch (e) {
|
|
199
|
+
throw new Error(`${cardPath} is not valid JSON (${e.message})`);
|
|
200
|
+
}
|
|
201
|
+
const pres = Array.isArray(receipts) && receipts.length > 0
|
|
202
|
+
? { v: "uuaid-lineage-log/1", events: updatedLog, receipts }
|
|
203
|
+
: updatedLog;
|
|
204
|
+
const nextCard = resignCardForLineage(oldCard, activeSigner, updatedLog, { now: ts, receipts });
|
|
205
|
+
const cv = verifyCard(nextCard, { now: ts, lineage: pres });
|
|
206
|
+
if (cv.verdict !== "valid") {
|
|
207
|
+
throw new Error(`rebuilt card failed verification (${cv.verdict}: ${cv.reasons.join(", ")})`);
|
|
208
|
+
}
|
|
209
|
+
return nextCard;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
export function prepareWitnessedInit({
|
|
213
|
+
working,
|
|
214
|
+
nextKey,
|
|
215
|
+
uuaidNamespace,
|
|
216
|
+
witnessFile,
|
|
217
|
+
homesFile,
|
|
218
|
+
witnessCandidates,
|
|
219
|
+
homeRecords,
|
|
220
|
+
witnessThreshold,
|
|
221
|
+
localHostPublicKeys,
|
|
222
|
+
agentDeviceId,
|
|
223
|
+
}) {
|
|
224
|
+
const rawWits = Array.isArray(witnessCandidates)
|
|
225
|
+
? witnessCandidates
|
|
226
|
+
: witnessFile
|
|
227
|
+
? loadJsonArrayFile(witnessFile, "init --witness-file")
|
|
228
|
+
: [];
|
|
229
|
+
const rawHomes = Array.isArray(homeRecords)
|
|
230
|
+
? homeRecords
|
|
231
|
+
: homesFile
|
|
232
|
+
? loadJsonArrayFile(homesFile, "init --homes-file")
|
|
233
|
+
: [];
|
|
234
|
+
const parsedM = witnessThreshold !== undefined ? Number(witnessThreshold) : undefined;
|
|
235
|
+
const homeRecs = rawHomes.map((h) => homeRecord(h, "pillar"));
|
|
236
|
+
const d4 = validateWitnessSetD4(rawWits, {
|
|
237
|
+
phase: "init",
|
|
238
|
+
witnessThreshold: parsedM,
|
|
239
|
+
namespace: uuaidNamespace,
|
|
240
|
+
lineagePublicKeys: [working.publicKeyHex, nextKey.publicKeyHex],
|
|
241
|
+
nextCommitments: [nextCommitment(nextKey)],
|
|
242
|
+
homePublicKeys: homeRecs.map((h) => h.publicKey),
|
|
243
|
+
localHostPublicKeys,
|
|
244
|
+
agentDeviceId,
|
|
245
|
+
});
|
|
246
|
+
if (!d4.ok) throw new Error(`init: witness set refused (${d4.reason})`); // @rule pillar-init.d4-witness-set
|
|
247
|
+
if (homeRecs.length < 2) throw new Error("init: witnessed inception requires >= 2 home records"); // @rule pillar-init.min-two-homes
|
|
248
|
+
return {
|
|
249
|
+
witnessOpts: {
|
|
250
|
+
witnesses: d4.witnesses,
|
|
251
|
+
witnessThreshold: d4.witnessThreshold,
|
|
252
|
+
homes: homeRecs,
|
|
253
|
+
},
|
|
254
|
+
warnings: d4.warnings,
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
export async function publishWitnessedSeq0(inc, opts = {}) {
|
|
259
|
+
let receipts = [];
|
|
260
|
+
receipts = await publishSeq0ToHomes(inc, opts); // @rule pillar-init.seq0-home-receipts
|
|
261
|
+
if (receipts.length < 2) throw new Error("init: witnessed inception requires >= 2 live home receipts");
|
|
262
|
+
return receipts;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
export function prepareWitnessedRotationChanges({
|
|
266
|
+
log,
|
|
267
|
+
newWorking,
|
|
268
|
+
newNext,
|
|
269
|
+
uuaidNamespace,
|
|
270
|
+
witnessFile,
|
|
271
|
+
homesFile,
|
|
272
|
+
witnessCandidates,
|
|
273
|
+
homeRecords,
|
|
274
|
+
witnessThreshold,
|
|
275
|
+
localHostPublicKeys,
|
|
276
|
+
agentDeviceId,
|
|
277
|
+
recentKnockUuaids,
|
|
278
|
+
}) {
|
|
279
|
+
const st = chainActiveState(log);
|
|
280
|
+
const changes = {};
|
|
281
|
+
let warnings = [];
|
|
282
|
+
let homeRecs = st.homes;
|
|
283
|
+
|
|
284
|
+
if (Array.isArray(homeRecords) || homesFile) {
|
|
285
|
+
const rawHomes = Array.isArray(homeRecords) ? homeRecords : loadJsonArrayFile(homesFile, "lineage rotate --homes-file");
|
|
286
|
+
homeRecs = rawHomes.map((h) => homeRecord(h, "pillar"));
|
|
287
|
+
if (homeRecs.length < 2) throw new Error("lineage rotate: witnessed/homed lineage requires >= 2 home records"); // @rule pillar-rotate.min-two-homes
|
|
288
|
+
changes.homes = homeRecs;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
if (Array.isArray(witnessCandidates) || witnessFile) {
|
|
292
|
+
const rawWits = Array.isArray(witnessCandidates) ? witnessCandidates : loadJsonArrayFile(witnessFile, "lineage rotate --witness-file");
|
|
293
|
+
const parsedM = witnessThreshold !== undefined ? Number(witnessThreshold) : undefined;
|
|
294
|
+
const d4 = validateWitnessSetD4(rawWits, {
|
|
295
|
+
phase: "rotate",
|
|
296
|
+
witnessThreshold: parsedM,
|
|
297
|
+
namespace: uuaidNamespace,
|
|
298
|
+
lineagePublicKeys: [...st.lineagePublicKeys, newWorking.publicKeyHex, newNext.publicKeyHex],
|
|
299
|
+
nextCommitments: [...st.nextCommitments, nextCommitment(newNext)],
|
|
300
|
+
doorPublicKeys: st.doors.map((d) => d.publicKey),
|
|
301
|
+
homePublicKeys: homeRecs.map((h) => h.publicKey),
|
|
302
|
+
localHostPublicKeys,
|
|
303
|
+
agentDeviceId,
|
|
304
|
+
recentKnockUuaids,
|
|
305
|
+
});
|
|
306
|
+
if (!d4.ok) throw new Error(`lineage rotate: witness set refused (${d4.reason})`); // @rule pillar-rotate.d4-witness-set
|
|
307
|
+
changes.witnesses = d4.witnesses;
|
|
308
|
+
changes.witnessThreshold = d4.witnessThreshold;
|
|
309
|
+
warnings = d4.warnings;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
return { changes, warnings, activeHomes: homeRecs };
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function maybePublishLocalEvent(home, ev, lineage, activeHomes, existingReceipts, ts, io, opts, finishSync) {
|
|
316
|
+
if (!Array.isArray(activeHomes) || activeHomes.length === 0) {
|
|
317
|
+
return finishSync(existingReceipts, []);
|
|
318
|
+
}
|
|
319
|
+
return (async () => {
|
|
320
|
+
const posted = await postLineageEventToHomes(ev, lineage, activeHomes, {
|
|
321
|
+
now: ts,
|
|
322
|
+
fetch: io.fetch,
|
|
323
|
+
urlMap: io.urlMap,
|
|
324
|
+
allowInsecureLoopback: Boolean(opts.allowInsecureLoopback || io.allowInsecureLoopback),
|
|
325
|
+
});
|
|
326
|
+
const merged = mergeAndSaveReceipts(home, existingReceipts, posted.receipts);
|
|
327
|
+
return finishSync(merged, posted.refusals);
|
|
328
|
+
})();
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
function loadLocalLogOrThrow(home, cmdLabel) {
|
|
332
|
+
const logPath = join(home, LINEAGE_LOG_KEY);
|
|
333
|
+
if (!existsSync(logPath)) throw new Error(`${cmdLabel}: no lineage log found at ${logPath}`);
|
|
334
|
+
let log;
|
|
335
|
+
try { log = JSON.parse(readFileSync(logPath, "utf8")); } catch { log = null; }
|
|
336
|
+
if (!Array.isArray(log) || log.length === 0) throw new Error(`${cmdLabel}: ${logPath} is not a valid lineage event array`);
|
|
337
|
+
return { logPath, log };
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
export function runDoorCli(action, rest, opts, home, passphrase, io, out, errOut) {
|
|
341
|
+
const fail = (m, code = 1) => { errOut(`${m}\n`); return { exitCode: code }; };
|
|
342
|
+
const ts = opts.now !== undefined ? opts.now : nowIsoSeconds();
|
|
343
|
+
if (!isStrictIsoDateTime(ts)) return fail("lineage door: --now must be a valid ISO-8601 timestamp", 64);
|
|
344
|
+
|
|
345
|
+
if (action === "add") {
|
|
346
|
+
let logInfo;
|
|
347
|
+
try { logInfo = loadLocalLogOrThrow(home, "lineage door add"); } catch (e) { return fail(e.message, 1); }
|
|
348
|
+
let active;
|
|
349
|
+
try { active = loadActiveSignerForLog(home, logInfo.log, ts, passphrase); } catch (e) { return fail(`lineage door add: ${e.message}`, 1); }
|
|
350
|
+
|
|
351
|
+
let doorSigner = null;
|
|
352
|
+
if (opts.doorSeed) {
|
|
353
|
+
try { doorSigner = loadSignerFromHomeOrSeed({ seedHex: opts.doorSeed, namespace: active.namespace }); } catch (e) { return fail(`lineage door add: ${e.message}`, 1); }
|
|
354
|
+
} else if (opts.generate) {
|
|
355
|
+
doorSigner = generateIdentity({ namespace: active.namespace, objectType: "agent" });
|
|
356
|
+
} else if (opts.doorHome && existsSync(join(opts.doorHome, "keychain.json"))) {
|
|
357
|
+
doorSigner = loadSignerFromHomeOrSeed({ home: opts.doorHome, namespace: active.namespace, passphrase });
|
|
358
|
+
} else if (opts.doorHome) {
|
|
359
|
+
doorSigner = generateIdentity({ namespace: active.namespace, objectType: "agent" });
|
|
360
|
+
}
|
|
361
|
+
if (!doorSigner) return fail("lineage door add: pass --door-seed <64hex>, --door-home <dir>, or --generate", 1); // @rule pillar-door.add-requires-door-signer
|
|
362
|
+
|
|
363
|
+
let ev;
|
|
364
|
+
try {
|
|
365
|
+
ev = doorAdd(active.canonicalChain, active.signer, doorSigner, ts, {
|
|
366
|
+
...(opts.purpose !== undefined ? { purpose: opts.purpose } : {}),
|
|
367
|
+
...(opts.notAfter !== undefined ? { notAfter: opts.notAfter } : {}),
|
|
368
|
+
...(opts.reason !== undefined ? { reason: opts.reason } : {}),
|
|
369
|
+
});
|
|
370
|
+
} catch (e) {
|
|
371
|
+
return fail(`lineage door add: ${e.message}`, 1);
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
const updatedLog = [...logInfo.log, ev];
|
|
375
|
+
let nextCard = null;
|
|
376
|
+
try { nextCard = resignHomeCardIfPresent(home, active.signer, updatedLog, active.receipts, ts); } catch (e) { return fail(`lineage door add: ${e.message}`, 1); }
|
|
377
|
+
if (nextCard) writeFileAtomic(join(home, CARD_KEY), `${JSON.stringify(nextCard, null, 2)}\n`, 0o600);
|
|
378
|
+
writeFileAtomic(logInfo.logPath, `${JSON.stringify(updatedLog, null, 2)}\n`, 0o600);
|
|
379
|
+
|
|
380
|
+
const st = chainActiveState([...active.canonicalChain, ev]);
|
|
381
|
+
return maybePublishLocalEvent(home, ev, updatedLog[0].lineage, st.homes, active.receipts, ts, io, opts, (mergedReceipts, refusals) => {
|
|
382
|
+
if (opts.doorHome) {
|
|
383
|
+
writeFileAtomic(join(opts.doorHome, DOOR_SEED_KEY), doorSigner.seedHex, 0o600);
|
|
384
|
+
writeFileAtomic(join(opts.doorHome, LINEAGE_LOG_KEY), `${JSON.stringify(updatedLog, null, 2)}\n`, 0o600);
|
|
385
|
+
if (mergedReceipts.length > 0) writeFileAtomic(join(opts.doorHome, LINEAGE_RECEIPTS_KEY), `${JSON.stringify(mergedReceipts, null, 2)}\n`, 0o600);
|
|
386
|
+
if (nextCard) writeFileAtomic(join(opts.doorHome, CARD_KEY), `${JSON.stringify(nextCard, null, 2)}\n`, 0o600);
|
|
387
|
+
}
|
|
388
|
+
const res = {
|
|
389
|
+
ok: true,
|
|
390
|
+
lineage: updatedLog[0].lineage,
|
|
391
|
+
door: ev.door,
|
|
392
|
+
seq: ev.seq,
|
|
393
|
+
head: `sha256:${eventDigest(ev)}`,
|
|
394
|
+
event: ev,
|
|
395
|
+
refusals,
|
|
396
|
+
};
|
|
397
|
+
out(opts.json ? `${JSON.stringify(res)}\n` : `added door ${ev.door.uuaid} (seq ${ev.seq})\n`);
|
|
398
|
+
return { exitCode: 0, result: res };
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
if (action === "retire") {
|
|
403
|
+
const doorUuaid = opts.door ?? rest[0];
|
|
404
|
+
if (typeof doorUuaid !== "string" || !doorUuaid.trim()) {
|
|
405
|
+
return fail("lineage door retire: door UUAID is required (<door-uuaid> or --door <uuaid>)", 1); // @rule pillar-door.retire-requires-door
|
|
406
|
+
}
|
|
407
|
+
let logInfo;
|
|
408
|
+
try { logInfo = loadLocalLogOrThrow(home, "lineage door retire"); } catch (e) { return fail(e.message, 1); }
|
|
409
|
+
let active;
|
|
410
|
+
try { active = loadActiveSignerForLog(home, logInfo.log, ts, passphrase); } catch (e) { return fail(`lineage door retire: ${e.message}`, 1); }
|
|
411
|
+
|
|
412
|
+
const curState = chainActiveState(active.canonicalChain);
|
|
413
|
+
const doorRec = curState.doors.find((d) => d.uuaid === doorUuaid.trim());
|
|
414
|
+
if (!doorRec) return fail(`lineage door retire: active door ${doorUuaid.trim()} not found`, 1);
|
|
415
|
+
|
|
416
|
+
let ev;
|
|
417
|
+
try {
|
|
418
|
+
ev = doorRetire(active.canonicalChain, active.signer, doorRec, ts, {
|
|
419
|
+
...(opts.reason !== undefined ? { reason: opts.reason } : {}),
|
|
420
|
+
});
|
|
421
|
+
} catch (e) {
|
|
422
|
+
return fail(`lineage door retire: ${e.message}`, 1);
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
const updatedLog = [...logInfo.log, ev];
|
|
426
|
+
let nextCard = null;
|
|
427
|
+
try { nextCard = resignHomeCardIfPresent(home, active.signer, updatedLog, active.receipts, ts); } catch (e) { return fail(`lineage door retire: ${e.message}`, 1); }
|
|
428
|
+
if (nextCard) writeFileAtomic(join(home, CARD_KEY), `${JSON.stringify(nextCard, null, 2)}\n`, 0o600);
|
|
429
|
+
writeFileAtomic(logInfo.logPath, `${JSON.stringify(updatedLog, null, 2)}\n`, 0o600);
|
|
430
|
+
|
|
431
|
+
const st = chainActiveState([...active.canonicalChain, ev]);
|
|
432
|
+
return maybePublishLocalEvent(home, ev, updatedLog[0].lineage, st.homes, active.receipts, ts, io, opts, (_merged, refusals) => {
|
|
433
|
+
const res = {
|
|
434
|
+
ok: true,
|
|
435
|
+
lineage: updatedLog[0].lineage,
|
|
436
|
+
retiredDoor: ev.door.uuaid,
|
|
437
|
+
seq: ev.seq,
|
|
438
|
+
head: `sha256:${eventDigest(ev)}`,
|
|
439
|
+
event: ev,
|
|
440
|
+
refusals,
|
|
441
|
+
};
|
|
442
|
+
out(opts.json ? `${JSON.stringify(res)}\n` : `retired door ${ev.door.uuaid} (seq ${ev.seq})\n`);
|
|
443
|
+
return { exitCode: 0, result: res };
|
|
444
|
+
});
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
return fail("usage: pillar lineage door <add|retire> ...", 64);
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
export function runBindCli(rest, opts, home, passphrase, io, out, errOut) {
|
|
451
|
+
const fail = (m, code = 1) => { errOut(`${m}\n`); return { exitCode: code }; };
|
|
452
|
+
if (rest.length > 0) return fail(`lineage bind: unexpected argument "${rest[0]}"`, 64);
|
|
453
|
+
const ts = opts.now !== undefined ? opts.now : nowIsoSeconds();
|
|
454
|
+
if (!isStrictIsoDateTime(ts)) return fail("lineage bind: --now must be a valid ISO-8601 timestamp", 64);
|
|
455
|
+
|
|
456
|
+
let logInfo;
|
|
457
|
+
try { logInfo = loadLocalLogOrThrow(home, "lineage bind"); } catch (e) { return fail(e.message, 1); }
|
|
458
|
+
let active;
|
|
459
|
+
try { active = loadActiveSignerForLog(home, logInfo.log, ts, passphrase); } catch (e) { return fail(`lineage bind: ${e.message}`, 1); }
|
|
460
|
+
|
|
461
|
+
let legacyDoc = null;
|
|
462
|
+
if (opts.legacyFile) {
|
|
463
|
+
try { legacyDoc = JSON.parse(readFileSync(opts.legacyFile, "utf8")); } catch (e) {
|
|
464
|
+
return fail(`lineage bind: cannot read --legacy-file (${e.message})`, 1);
|
|
465
|
+
}
|
|
466
|
+
} else if (opts.oldSeed || opts.oldHome) {
|
|
467
|
+
let oldSigner;
|
|
468
|
+
try {
|
|
469
|
+
oldSigner = loadSignerFromHomeOrSeed({
|
|
470
|
+
home: opts.oldHome,
|
|
471
|
+
seedHex: opts.oldSeed,
|
|
472
|
+
namespace: active.namespace,
|
|
473
|
+
passphrase,
|
|
474
|
+
});
|
|
475
|
+
} catch (e) {
|
|
476
|
+
return fail(`lineage bind: ${e.message}`, 1);
|
|
477
|
+
}
|
|
478
|
+
if (!oldSigner) return fail("lineage bind: could not load old signer", 1);
|
|
479
|
+
legacyDoc = buildContinuityLegacy(oldSigner, active.signer, {
|
|
480
|
+
relation: opts.relation === "additional-door" ? "additional-door" : "rotation",
|
|
481
|
+
issuedAt: ts,
|
|
482
|
+
...(opts.reason !== undefined ? { statement: opts.reason } : {}),
|
|
483
|
+
});
|
|
484
|
+
}
|
|
485
|
+
if (!legacyDoc) return fail("lineage bind: pass --legacy-file <json>, --old-seed <64hex>, or --old-home <dir>", 1); // @rule pillar-bind.requires-legacy-or-old-key
|
|
486
|
+
|
|
487
|
+
let ev;
|
|
488
|
+
try {
|
|
489
|
+
ev = buildBindEvent(active.canonicalChain, active.signer, legacyDoc, ts, {
|
|
490
|
+
...(opts.reason !== undefined ? { reason: opts.reason } : {}),
|
|
491
|
+
});
|
|
492
|
+
} catch (e) {
|
|
493
|
+
return fail(`lineage bind: ${e.message}`, 1);
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
const updatedLog = [...logInfo.log, ev];
|
|
497
|
+
writeFileAtomic(logInfo.logPath, `${JSON.stringify(updatedLog, null, 2)}\n`, 0o600);
|
|
498
|
+
const st = chainActiveState([...active.canonicalChain, ev]);
|
|
499
|
+
return maybePublishLocalEvent(home, ev, updatedLog[0].lineage, st.homes, active.receipts, ts, io, opts, (_merged, refusals) => {
|
|
500
|
+
const res = {
|
|
501
|
+
ok: true,
|
|
502
|
+
lineage: updatedLog[0].lineage,
|
|
503
|
+
boundOld: ev.legacy.old.uuaid,
|
|
504
|
+
seq: ev.seq,
|
|
505
|
+
head: `sha256:${eventDigest(ev)}`,
|
|
506
|
+
event: ev,
|
|
507
|
+
refusals,
|
|
508
|
+
};
|
|
509
|
+
out(opts.json ? `${JSON.stringify(res)}\n` : `bound legacy identity ${ev.legacy.old.uuaid} -> ${updatedLog[0].lineage} (seq ${ev.seq})\n`);
|
|
510
|
+
return { exitCode: 0, result: res };
|
|
511
|
+
});
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
export function runTombstoneCli(rest, opts, home, passphrase, io, out, errOut) {
|
|
515
|
+
const fail = (m, code = 1) => { errOut(`${m}\n`); return { exitCode: code }; };
|
|
516
|
+
if (rest.length > 0) return fail(`lineage tombstone: unexpected argument "${rest[0]}"`, 64);
|
|
517
|
+
const ts = opts.now !== undefined ? opts.now : nowIsoSeconds();
|
|
518
|
+
if (!isStrictIsoDateTime(ts)) return fail("lineage tombstone: --now must be a valid ISO-8601 timestamp", 64);
|
|
519
|
+
|
|
520
|
+
let logInfo;
|
|
521
|
+
try { logInfo = loadLocalLogOrThrow(home, "lineage tombstone"); } catch (e) { return fail(e.message, 1); }
|
|
522
|
+
let active;
|
|
523
|
+
try { active = loadActiveSignerForLog(home, logInfo.log, ts, passphrase); } catch (e) { return fail(`lineage tombstone: ${e.message}`, 1); }
|
|
524
|
+
|
|
525
|
+
const lineageId = logInfo.log[0].lineage;
|
|
526
|
+
if (opts.confirm !== undefined && opts.confirm !== lineageId && opts.confirm !== active.signer.uuaid) {
|
|
527
|
+
return fail(`lineage tombstone: --confirm does not match lineage ${lineageId}`, 1); // @rule pillar-tombstone.confirm-match
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
let ev;
|
|
531
|
+
try { ev = tombstone(active.canonicalChain, active.signer, ts, opts.reason); } catch (e) { return fail(`lineage tombstone: ${e.message}`, 1); }
|
|
532
|
+
const updatedLog = [...logInfo.log, ev];
|
|
533
|
+
writeFileAtomic(logInfo.logPath, `${JSON.stringify(updatedLog, null, 2)}\n`, 0o600);
|
|
534
|
+
|
|
535
|
+
const st = chainActiveState([...active.canonicalChain, ev]);
|
|
536
|
+
return maybePublishLocalEvent(home, ev, lineageId, st.homes, active.receipts, ts, io, opts, (_merged, refusals) => {
|
|
537
|
+
const res = {
|
|
538
|
+
ok: true,
|
|
539
|
+
tombstoned: true,
|
|
540
|
+
lineage: lineageId,
|
|
541
|
+
seq: ev.seq,
|
|
542
|
+
head: `sha256:${eventDigest(ev)}`,
|
|
543
|
+
event: ev,
|
|
544
|
+
refusals,
|
|
545
|
+
};
|
|
546
|
+
out(opts.json ? `${JSON.stringify(res)}\n` : `tombstoned lineage ${lineageId} (seq ${ev.seq})\n`);
|
|
547
|
+
return { exitCode: 0, result: res };
|
|
548
|
+
});
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
export function runExportRecoverySheetCli(rest, opts, home, out, errOut) {
|
|
552
|
+
const fail = (m, code = 1) => { errOut(`${m}\n`); return { exitCode: code }; };
|
|
553
|
+
if (rest.length > 0) return fail(`lineage export-recovery-sheet: unexpected argument "${rest[0]}"`, 64);
|
|
554
|
+
const ts = opts.now !== undefined ? opts.now : nowIsoSeconds();
|
|
555
|
+
if (!isStrictIsoDateTime(ts)) return fail("lineage export-recovery-sheet: --now must be a valid ISO-8601 timestamp", 64);
|
|
556
|
+
|
|
557
|
+
let logInfo;
|
|
558
|
+
try { logInfo = loadLocalLogOrThrow(home, "lineage export-recovery-sheet"); } catch (e) { return fail(e.message, 1); }
|
|
559
|
+
const receipts = loadHomeReceipts(home);
|
|
560
|
+
const check = exportRecoverySheetCheck(logInfo.log, receipts, { now: ts });
|
|
561
|
+
if (!check.corroborated && check.warning) {
|
|
562
|
+
errOut(`rotation-uncorroborated: ${check.warning}\n`); // @rule pillar-sheet.cli-stderr-warning
|
|
563
|
+
}
|
|
564
|
+
const res = { ok: true, ...check };
|
|
565
|
+
out(opts.json ? `${JSON.stringify(res)}\n` : `${check.warning ?? `corroborated (${check.stampsFound}/${check.stampsRequired} home stamps)`}\n`);
|
|
566
|
+
return { exitCode: 0, result: res };
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
function resolveLineageAndHomesForRemote(home, opts, io) {
|
|
570
|
+
const logPath = join(home, LINEAGE_LOG_KEY);
|
|
571
|
+
let localLog = [];
|
|
572
|
+
if (existsSync(logPath)) {
|
|
573
|
+
try {
|
|
574
|
+
const parsed = JSON.parse(readFileSync(logPath, "utf8"));
|
|
575
|
+
if (Array.isArray(parsed)) localLog = parsed;
|
|
576
|
+
} catch {}
|
|
577
|
+
}
|
|
578
|
+
const st = chainActiveState(localLog);
|
|
579
|
+
let homes = st.homes;
|
|
580
|
+
if (Array.isArray(io.homeRecords)) homes = io.homeRecords.map((h) => homeRecord(h, "pillar"));
|
|
581
|
+
else if (opts.homesFile) homes = loadJsonArrayFile(opts.homesFile, "--homes-file").map((h) => homeRecord(h, "pillar"));
|
|
582
|
+
const lineage = opts.lineage ?? localLog[0]?.lineage ?? null;
|
|
583
|
+
return { lineage, homes, localLog, localReceipts: loadHomeReceipts(home) };
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
function chainFromByDigest(byDigest, headHex) {
|
|
587
|
+
const chain = [];
|
|
588
|
+
for (let cur = byDigest.get(headHex); cur; cur = typeof cur.prev === "string" ? byDigest.get(cur.prev) : undefined) {
|
|
589
|
+
chain.unshift(cur);
|
|
590
|
+
}
|
|
591
|
+
return chain;
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
export async function runRecoverCli(action, _rest, opts, home, passphrase, io, out, errOut) {
|
|
595
|
+
const fail = (m, code = 1) => { errOut(`${m}\n`); return { exitCode: code }; };
|
|
596
|
+
const ts = opts.now !== undefined ? opts.now : nowIsoSeconds();
|
|
597
|
+
if (!isStrictIsoDateTime(ts)) return fail("lineage recover: --now must be a valid ISO-8601 timestamp", 64);
|
|
598
|
+
const allowLoop = Boolean(opts.allowInsecureLoopback || io.allowInsecureLoopback);
|
|
599
|
+
|
|
600
|
+
let target;
|
|
601
|
+
try { target = resolveLineageAndHomesForRemote(home, opts, io); } catch (e) { return fail(`lineage recover: ${e.message}`, 1); }
|
|
602
|
+
if (!target.lineage) return fail("lineage recover: --lineage <uuaid> (or initialized --home) is required", 1);
|
|
603
|
+
if (!Array.isArray(target.homes) || target.homes.length < 2) {
|
|
604
|
+
return fail("lineage recover: >= 2 declared homes are required (--homes-file or initialized witnessed home)", 1); // @rule pillar-recover.homes-min2
|
|
605
|
+
}
|
|
606
|
+
const ns = parseUuaid(target.lineage).namespace;
|
|
607
|
+
|
|
608
|
+
if (action === "claim") {
|
|
609
|
+
const pulled = await pullLineageHomes(target.lineage, target.homes, {
|
|
610
|
+
localEvents: target.localLog,
|
|
611
|
+
localReceipts: target.localReceipts,
|
|
612
|
+
now: ts,
|
|
613
|
+
fetch: io.fetch,
|
|
614
|
+
urlMap: io.urlMap,
|
|
615
|
+
allowInsecureLoopback: allowLoop,
|
|
616
|
+
});
|
|
617
|
+
const parentDigests = new Set([...pulled.byDigest.values()].map((e) => e?.prev).filter((p) => typeof p === "string"));
|
|
618
|
+
const isLeafClaim = (e) => {
|
|
619
|
+
if (!e || typeof e !== "object" || e.type !== "recovery.claim") return false;
|
|
620
|
+
try { return !parentDigests.has(eventDigest(e)); } catch { return true; }
|
|
621
|
+
};
|
|
622
|
+
const baseResponses = pulled.responses.map((r) => ({
|
|
623
|
+
...r,
|
|
624
|
+
events: Array.isArray(r.events) ? r.events.filter((e) => !isLeafClaim(e)) : r.events,
|
|
625
|
+
}));
|
|
626
|
+
const baseV = verifyLineageFromHomes(target.lineage, baseResponses, { now: ts });
|
|
627
|
+
if (baseV.verdict !== "valid" && baseV.verdict !== "recovered") {
|
|
628
|
+
return fail(`lineage recover claim: base lineage on homes is ${baseV.verdict} (${baseV.reasons.join(", ")})`, 1); // @rule pillar-recover.claim-base-valid
|
|
629
|
+
}
|
|
630
|
+
const headHex = stripShaPrefix(baseV.facts.head ?? "");
|
|
631
|
+
const chain = chainFromByDigest(pulled.byDigest, headHex);
|
|
632
|
+
|
|
633
|
+
const newWorking = opts.newSeed
|
|
634
|
+
? loadSignerFromHomeOrSeed({ seedHex: opts.newSeed, namespace: ns })
|
|
635
|
+
: generateIdentity({ namespace: ns, objectType: "agent" });
|
|
636
|
+
const newNext = generateIdentity({ namespace: ns, objectType: "agent" });
|
|
637
|
+
const newRecoverySheet = encodeRecoverySheet(newNext.seedHex);
|
|
638
|
+
|
|
639
|
+
const witSigners = [];
|
|
640
|
+
for (const sHex of opts.witnessSeeds) {
|
|
641
|
+
witSigners.push(loadSignerFromHomeOrSeed({ seedHex: sHex, namespace: ns }));
|
|
642
|
+
}
|
|
643
|
+
for (const wHome of opts.witnessHomes) {
|
|
644
|
+
const ws = loadSignerFromHomeOrSeed({ home: wHome, namespace: ns, passphrase });
|
|
645
|
+
if (!ws) return fail(`lineage recover claim: no witness key in ${wHome}`, 1);
|
|
646
|
+
witSigners.push(ws);
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
let claimEv;
|
|
650
|
+
try {
|
|
651
|
+
claimEv = recoveryClaim(
|
|
652
|
+
chain,
|
|
653
|
+
witSigners,
|
|
654
|
+
newWorking,
|
|
655
|
+
{ uuaid: newNext.uuaid, publicKeyHex: newNext.publicKeyHex },
|
|
656
|
+
ts,
|
|
657
|
+
opts.reason,
|
|
658
|
+
opts.claimedAt ? { claimedAt: opts.claimedAt } : {},
|
|
659
|
+
);
|
|
660
|
+
} catch (e) {
|
|
661
|
+
return fail(`lineage recover claim: ${e.message}`, 1);
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
const claimDigest = eventDigest(claimEv);
|
|
665
|
+
const posted = await postLineageEventToHomes(claimEv, target.lineage, target.homes, {
|
|
666
|
+
now: ts,
|
|
667
|
+
fetch: io.fetch,
|
|
668
|
+
urlMap: io.urlMap,
|
|
669
|
+
allowInsecureLoopback: allowLoop,
|
|
670
|
+
});
|
|
671
|
+
const mergedReceipts = mergeAndSaveReceipts(home, [...pulled.recMap.values()], posted.receipts);
|
|
672
|
+
|
|
673
|
+
writeFileAtomic(
|
|
674
|
+
join(home, PENDING_CLAIM_KEY),
|
|
675
|
+
`${JSON.stringify({
|
|
676
|
+
lineage: target.lineage,
|
|
677
|
+
claimDigest,
|
|
678
|
+
newWorkingSeedHex: newWorking.seedHex,
|
|
679
|
+
newWorkingUuaid: newWorking.uuaid,
|
|
680
|
+
newWorkingPublicKey: newWorking.publicKeyHex,
|
|
681
|
+
nextCommitment: claimEv.next,
|
|
682
|
+
createdAt: ts,
|
|
683
|
+
}, null, 2)}\n`,
|
|
684
|
+
0o600,
|
|
685
|
+
);
|
|
686
|
+
|
|
687
|
+
const res = {
|
|
688
|
+
ok: true,
|
|
689
|
+
status: "pending-recovery",
|
|
690
|
+
lineage: target.lineage,
|
|
691
|
+
claimDigest,
|
|
692
|
+
uuaid: newWorking.uuaid,
|
|
693
|
+
publicKey: newWorking.publicKeyHex,
|
|
694
|
+
newKeyFingerprint: formatFingerprint16(newWorking.publicKeyHex),
|
|
695
|
+
nextFingerprint: formatFingerprint16(claimEv.next),
|
|
696
|
+
homesAccepted: posted.acceptedCount,
|
|
697
|
+
receipts: posted.receipts,
|
|
698
|
+
totalReceipts: mergedReceipts.length,
|
|
699
|
+
event: claimEv,
|
|
700
|
+
recoverySheet: newRecoverySheet,
|
|
701
|
+
};
|
|
702
|
+
out(
|
|
703
|
+
opts.json
|
|
704
|
+
? `${JSON.stringify(res)}\n`
|
|
705
|
+
: [
|
|
706
|
+
`submitted recovery.claim ${claimDigest} for ${target.lineage}`,
|
|
707
|
+
`new key: ${newWorking.uuaid} (${res.newKeyFingerprint})`,
|
|
708
|
+
`homes accepted: ${posted.acceptedCount}`,
|
|
709
|
+
`recovery sheet (save offline — shown once, never stored in ${home}):`,
|
|
710
|
+
` ${newRecoverySheet.join(" ")}`,
|
|
711
|
+
"",
|
|
712
|
+
].join("\n"),
|
|
713
|
+
);
|
|
714
|
+
return { exitCode: 0, result: res };
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
if (action === "veto") {
|
|
718
|
+
const pulled = await pullLineageHomes(target.lineage, target.homes, {
|
|
719
|
+
localEvents: target.localLog,
|
|
720
|
+
localReceipts: target.localReceipts,
|
|
721
|
+
now: ts,
|
|
722
|
+
fetch: io.fetch,
|
|
723
|
+
urlMap: io.urlMap,
|
|
724
|
+
allowInsecureLoopback: allowLoop,
|
|
725
|
+
});
|
|
726
|
+
const wanted = opts.claim ? stripShaPrefix(opts.claim) : "";
|
|
727
|
+
const hit = [...pulled.byDigest.entries()].find(([d, e]) => e?.type === "recovery.claim" && (!wanted || d === wanted));
|
|
728
|
+
if (!hit) return fail("lineage recover veto: target recovery.claim not found on homes", 1); // @rule pillar-recover.veto-claim-exists
|
|
729
|
+
const [claimDigest, claimEv] = hit;
|
|
730
|
+
const parentChain = chainFromByDigest(pulled.byDigest, String(claimEv.prev));
|
|
731
|
+
const fullForVeto = [...parentChain, claimEv];
|
|
732
|
+
|
|
733
|
+
let words = null;
|
|
734
|
+
try { words = readRecoverySheetWords(opts); } catch (e) { return fail(`lineage recover veto: ${e.message}`, 1); }
|
|
735
|
+
const asNextKey = Boolean(words && words.length > 0);
|
|
736
|
+
let vetoSigner = null;
|
|
737
|
+
if (asNextKey) {
|
|
738
|
+
const dec = tryDecodeRecoverySheet(words, { namespace: ns });
|
|
739
|
+
if (!dec.ok) return fail(`lineage recover veto: invalid recovery sheet (${dec.reason})`, 1);
|
|
740
|
+
vetoSigner = { seedHex: dec.seedHex, publicKeyHex: dec.publicKeyHex, uuaid: dec.uuaid };
|
|
741
|
+
} else {
|
|
742
|
+
vetoSigner = loadSignerFromHomeOrSeed({ home, namespace: ns, passphrase });
|
|
743
|
+
if (!vetoSigner) return fail("lineage recover veto: no local key found; pass --recovery-sheet to veto as pre-committed nextKey", 1);
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
let vetoEv;
|
|
747
|
+
try {
|
|
748
|
+
vetoEv = recoveryVeto(fullForVeto, vetoSigner, claimDigest, ts, {
|
|
749
|
+
asNextKey,
|
|
750
|
+
...(opts.reason !== undefined ? { reason: opts.reason } : {}),
|
|
751
|
+
});
|
|
752
|
+
} catch (e) {
|
|
753
|
+
return fail(`lineage recover veto: ${e.message}`, 1);
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
const vetoDigest = eventDigest(vetoEv);
|
|
757
|
+
const postedVeto = await postLineageEventToHomes(vetoEv, target.lineage, target.homes, {
|
|
758
|
+
now: ts,
|
|
759
|
+
fetch: io.fetch,
|
|
760
|
+
urlMap: io.urlMap,
|
|
761
|
+
allowInsecureLoopback: allowLoop,
|
|
762
|
+
});
|
|
763
|
+
const repulled = await pullLineageHomes(target.lineage, target.homes, {
|
|
764
|
+
localEvents: [...fullForVeto, vetoEv],
|
|
765
|
+
localReceipts: [...pulled.recMap.values(), ...postedVeto.receipts],
|
|
766
|
+
now: ts,
|
|
767
|
+
fetch: io.fetch,
|
|
768
|
+
urlMap: io.urlMap,
|
|
769
|
+
allowInsecureLoopback: allowLoop,
|
|
770
|
+
});
|
|
771
|
+
const st = chainActiveState(parentChain);
|
|
772
|
+
const elig = eligibleHomes(st.homes.length ? st.homes : target.homes, st.witnesses);
|
|
773
|
+
const vetoStamps = validStampTimesForEvent([...repulled.recMap.values()], target.lineage, vetoDigest, elig, ts).length;
|
|
774
|
+
if (vetoStamps < 2) {
|
|
775
|
+
return fail(`lineage recover veto: veto requires >= 2 eligible home stamps, got ${vetoStamps}`, 1); // @rule pillar-recover.veto-quorum
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
let rotated = null;
|
|
779
|
+
let newRecoverySheet = null;
|
|
780
|
+
const baseEvents = [...new Map([...target.localLog, ...parentChain, claimEv, vetoEv].map((e) => [eventDigest(e), e])).values()];
|
|
781
|
+
let finalLog = baseEvents;
|
|
782
|
+
let finalReceipts = [...repulled.recMap.values()];
|
|
783
|
+
|
|
784
|
+
if (asNextKey) {
|
|
785
|
+
const curTip = parentChain[parentChain.length - 1];
|
|
786
|
+
const curSigner = loadSignerFromHomeOrSeed({ home, namespace: ns, passphrase });
|
|
787
|
+
const optOutgoing = curSigner && curSigner.publicKeyHex === curTip?.key?.publicKey ? curSigner : null;
|
|
788
|
+
const newWorking = generateIdentity({ namespace: ns, objectType: "agent" });
|
|
789
|
+
const newNext = generateIdentity({ namespace: ns, objectType: "agent" });
|
|
790
|
+
newRecoverySheet = encodeRecoverySheet(newNext.seedHex);
|
|
791
|
+
const nextKeyRec = { uuaid: newNext.uuaid, publicKeyHex: newNext.publicKeyHex };
|
|
792
|
+
let rotEv = null;
|
|
793
|
+
rotEv = rotation(parentChain, optOutgoing, vetoSigner, newWorking, nextKeyRec, ts); // @rule pillar-recover.post-nextkey-rotation
|
|
794
|
+
if (rotEv) {
|
|
795
|
+
const postedRot = await postLineageEventToHomes(rotEv, target.lineage, target.homes, {
|
|
796
|
+
now: ts,
|
|
797
|
+
fetch: io.fetch,
|
|
798
|
+
urlMap: io.urlMap,
|
|
799
|
+
allowInsecureLoopback: allowLoop,
|
|
800
|
+
});
|
|
801
|
+
finalLog = [...parentChain, claimEv, vetoEv, rotEv];
|
|
802
|
+
finalReceipts = mergeAndSaveReceipts(home, finalReceipts, postedRot.receipts);
|
|
803
|
+
const nextCard = resignHomeCardIfPresent(home, newWorking, finalLog, finalReceipts, ts);
|
|
804
|
+
persistWorkingKey(home, newWorking, curTip?.key?.uuaid, ts, passphrase);
|
|
805
|
+
if (nextCard) writeFileAtomic(join(home, CARD_KEY), `${JSON.stringify(nextCard, null, 2)}\n`, 0o600);
|
|
806
|
+
rotated = rotEv;
|
|
807
|
+
}
|
|
808
|
+
} else {
|
|
809
|
+
finalReceipts = mergeAndSaveReceipts(home, finalReceipts, []);
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
writeFileAtomic(join(home, LINEAGE_LOG_KEY), `${JSON.stringify(finalLog, null, 2)}\n`, 0o600);
|
|
813
|
+
|
|
814
|
+
const res = {
|
|
815
|
+
ok: true,
|
|
816
|
+
lineage: target.lineage,
|
|
817
|
+
claimDigest,
|
|
818
|
+
vetoDigest,
|
|
819
|
+
asNextKey,
|
|
820
|
+
vetoStamps,
|
|
821
|
+
vetoEvent: vetoEv,
|
|
822
|
+
...(rotated ? { rotatedEvent: rotated, uuaid: rotated.key.uuaid, recoverySheet: newRecoverySheet } : {}),
|
|
823
|
+
};
|
|
824
|
+
out(opts.json ? `${JSON.stringify(res)}\n` : `vetoed claim ${claimDigest} (${vetoStamps} home stamps)${rotated ? ` and rotated to ${rotated.key.uuaid}` : ""}\n`);
|
|
825
|
+
return { exitCode: 0, result: res };
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
if (action === "finalize") {
|
|
829
|
+
const pendingPath = join(home, PENDING_CLAIM_KEY);
|
|
830
|
+
let pending = null;
|
|
831
|
+
if (existsSync(pendingPath)) {
|
|
832
|
+
try { pending = JSON.parse(readFileSync(pendingPath, "utf8")); } catch { pending = null; }
|
|
833
|
+
}
|
|
834
|
+
const seedHex = opts.newSeed ?? pending?.newWorkingSeedHex;
|
|
835
|
+
const wantedClaim = stripShaPrefix(opts.claim ?? pending?.claimDigest ?? "");
|
|
836
|
+
if (!seedHex || !wantedClaim) {
|
|
837
|
+
return fail("lineage recover finalize: no pending claim found (run `pillar lineage recover claim` first or pass --claim and --new-seed)", 1); // @rule pillar-recover.finalize-pending-claim
|
|
838
|
+
}
|
|
839
|
+
const newWorking = loadSignerFromHomeOrSeed({ seedHex, namespace: ns });
|
|
840
|
+
|
|
841
|
+
const pulled = await pullLineageHomes(target.lineage, target.homes, {
|
|
842
|
+
localEvents: target.localLog,
|
|
843
|
+
localReceipts: target.localReceipts,
|
|
844
|
+
now: ts,
|
|
845
|
+
fetch: io.fetch,
|
|
846
|
+
urlMap: io.urlMap,
|
|
847
|
+
allowInsecureLoopback: allowLoop,
|
|
848
|
+
});
|
|
849
|
+
const claimOnHome = pulled.byDigest.get(wantedClaim);
|
|
850
|
+
if (!claimOnHome || claimOnHome.type !== "recovery.claim") {
|
|
851
|
+
return fail(`lineage recover finalize: claim ${wantedClaim} not found on homes`, 1);
|
|
852
|
+
}
|
|
853
|
+
const parentChain = chainFromByDigest(pulled.byDigest, String(claimOnHome.prev));
|
|
854
|
+
const chainWithClaim = [...parentChain, claimOnHome];
|
|
855
|
+
|
|
856
|
+
let finEv;
|
|
857
|
+
try {
|
|
858
|
+
finEv = recoveryFinal(chainWithClaim, newWorking, claimOnHome, ts, opts.reason);
|
|
859
|
+
} catch (e) {
|
|
860
|
+
return fail(`lineage recover finalize: ${e.message}`, 1);
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
const testResponses = pulled.responses.map((r) =>
|
|
864
|
+
r.unreachable ? r : { ...r, events: [...(Array.isArray(r.events) ? r.events : []), finEv] },
|
|
865
|
+
);
|
|
866
|
+
const checkV = verifyLineageFromHomes(target.lineage, testResponses, { now: ts });
|
|
867
|
+
const notReadyMsg = `lineage recover finalize: claim is not ready to finalize (verdict=${checkV.verdict}${checkV.reasons.length ? `, reasons=${checkV.reasons.join(",")}` : ""})`;
|
|
868
|
+
if (checkV.verdict !== "recovered" || checkV.facts.current !== newWorking.uuaid) {
|
|
869
|
+
return fail(notReadyMsg, 1); // @rule pillar-recover.finalize-must-be-recovered
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
const postedFin = await postLineageEventToHomes(finEv, target.lineage, target.homes, {
|
|
873
|
+
now: ts,
|
|
874
|
+
fetch: io.fetch,
|
|
875
|
+
urlMap: io.urlMap,
|
|
876
|
+
allowInsecureLoopback: allowLoop,
|
|
877
|
+
});
|
|
878
|
+
const recoveredLog = [...chainWithClaim, finEv];
|
|
879
|
+
const mergedReceipts = mergeAndSaveReceipts(home, [...pulled.recMap.values()], postedFin.receipts);
|
|
880
|
+
|
|
881
|
+
let nextCard = null;
|
|
882
|
+
try {
|
|
883
|
+
nextCard = resignHomeCardIfPresent(home, newWorking, recoveredLog, mergedReceipts, ts); // @rule pillar-recover.finalize-resign-card
|
|
884
|
+
} catch (e) {
|
|
885
|
+
return fail(`lineage recover finalize: ${e.message}`, 1);
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
const oldUuaid = parentChain[parentChain.length - 1]?.key?.uuaid ?? target.lineage;
|
|
889
|
+
persistWorkingKey(home, newWorking, oldUuaid, ts, passphrase);
|
|
890
|
+
if (nextCard) writeFileAtomic(join(home, CARD_KEY), `${JSON.stringify(nextCard, null, 2)}\n`, 0o600);
|
|
891
|
+
writeFileAtomic(join(home, LINEAGE_LOG_KEY), `${JSON.stringify(recoveredLog, null, 2)}\n`, 0o600);
|
|
892
|
+
if (existsSync(pendingPath)) rmSync(pendingPath, { force: true });
|
|
893
|
+
|
|
894
|
+
const head = `sha256:${eventDigest(finEv)}`;
|
|
895
|
+
const res = {
|
|
896
|
+
ok: true,
|
|
897
|
+
status: "recovered",
|
|
898
|
+
lineage: target.lineage,
|
|
899
|
+
uuaid: newWorking.uuaid,
|
|
900
|
+
publicKey: newWorking.publicKeyHex,
|
|
901
|
+
seq: finEv.seq,
|
|
902
|
+
head,
|
|
903
|
+
claimDigest: wantedClaim,
|
|
904
|
+
event: finEv,
|
|
905
|
+
};
|
|
906
|
+
out(opts.json ? `${JSON.stringify(res)}\n` : `finalized recovery for ${target.lineage} -> ${newWorking.uuaid} (seq ${finEv.seq})\n`);
|
|
907
|
+
return { exitCode: 0, result: res };
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
return fail("usage: pillar lineage recover <claim|veto|finalize> ...", 64);
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
export async function runWitnessCli(action, _rest, opts, home, passphrase, io, out, errOut) {
|
|
914
|
+
const fail = (m, code = 1) => { errOut(`${m}\n`); return { exitCode: code }; };
|
|
915
|
+
if (action !== "vouch") return fail("usage: pillar lineage witness vouch ...", 64);
|
|
916
|
+
if (opts.claimFile !== undefined || opts.claimJson !== undefined) {
|
|
917
|
+
return fail("lineage witness vouch: claim-must-be-fetched-from-home (never pass a claimant file or JSON)", 1); // @rule pillar-witness.cli-no-claim-file
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
const ts = opts.now !== undefined ? opts.now : nowIsoSeconds();
|
|
921
|
+
if (!isStrictIsoDateTime(ts)) return fail("lineage witness vouch: --now must be a valid ISO-8601 timestamp", 64);
|
|
922
|
+
|
|
923
|
+
let target;
|
|
924
|
+
try { target = resolveLineageAndHomesForRemote(home, opts, io); } catch (e) { return fail(`lineage witness vouch: ${e.message}`, 1); }
|
|
925
|
+
if (!target.lineage) return fail("lineage witness vouch: --lineage <uuaid> is required", 1);
|
|
926
|
+
|
|
927
|
+
const ns = parseUuaid(target.lineage)?.namespace ?? "pillar";
|
|
928
|
+
const witnessSigner = loadSignerFromHomeOrSeed({
|
|
929
|
+
home: opts.witnessHome ?? home,
|
|
930
|
+
seedHex: opts.witnessSeed,
|
|
931
|
+
namespace: ns,
|
|
932
|
+
passphrase,
|
|
933
|
+
});
|
|
934
|
+
if (!witnessSigner) return fail("lineage witness vouch: no witness identity found (init witness home or pass --witness-seed)", 1);
|
|
935
|
+
|
|
936
|
+
const vouchRes = await witnessVouchHome({
|
|
937
|
+
witnessHome: opts.witnessHome ?? home,
|
|
938
|
+
witnessSigner,
|
|
939
|
+
lineage: target.lineage,
|
|
940
|
+
homes: target.homes,
|
|
941
|
+
claimDigest: opts.claim,
|
|
942
|
+
confirmedNewKeyFingerprint: opts.fingerprint ?? "",
|
|
943
|
+
confirmedMethod: opts.method ?? "",
|
|
944
|
+
cardName: opts.cardName,
|
|
945
|
+
now: ts,
|
|
946
|
+
fetch: io.fetch,
|
|
947
|
+
urlMap: io.urlMap,
|
|
948
|
+
allowInsecureLoopback: Boolean(opts.allowInsecureLoopback || io.allowInsecureLoopback),
|
|
949
|
+
namespace: ns,
|
|
950
|
+
});
|
|
951
|
+
|
|
952
|
+
if (!vouchRes.ok) {
|
|
953
|
+
return fail(`lineage witness vouch: ${vouchRes.reason}`, 1);
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
out(
|
|
957
|
+
opts.json
|
|
958
|
+
? `${JSON.stringify(vouchRes)}\n`
|
|
959
|
+
: [
|
|
960
|
+
`vouched recovery.claim ${vouchRes.claimDigest}`,
|
|
961
|
+
`lineage: ${vouchRes.display.lineage}${vouchRes.display.cardName ? ` (${vouchRes.display.cardName})` : ""}`,
|
|
962
|
+
`prev: ${vouchRes.display.prevFingerprint}`,
|
|
963
|
+
`newKey: ${vouchRes.display.newKey.uuaid} (${vouchRes.display.newKeyFingerprint})`,
|
|
964
|
+
`next: ${vouchRes.display.nextFingerprint}`,
|
|
965
|
+
`homes: ${vouchRes.homesUpdated}`,
|
|
966
|
+
"",
|
|
967
|
+
].join("\n"),
|
|
968
|
+
);
|
|
969
|
+
return { exitCode: 0, result: vouchRes };
|
|
970
|
+
}
|