@uuaid/pillar 2.7.2 → 2.8.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 +95 -0
- package/README.md +251 -1
- package/bin/carrier.mjs +97 -1
- package/bin/pillar-directory.mjs +75 -100
- package/bin/pillar-seed.mjs +127 -11
- package/bin/pillar.mjs +11 -4
- package/package.json +1 -1
- package/src/mailbox/mailbox.mjs +12 -0
- package/src/net/carrier-server.mjs +191 -17
- package/src/net/discovery.mjs +72 -0
- package/src/net/refusals.mjs +15 -0
- package/src/net/seed-registry.mjs +334 -35
- package/src/net/seed-tier.mjs +35 -1
- package/src/net/tunnel-client.mjs +456 -0
- package/src/net/tunnel-relay.mjs +776 -0
- package/src/net/tunnel.mjs +288 -0
- package/src/notify-store.mjs +4 -1
- package/src/pillar.mjs +541 -9
- package/src/registry/directory-flags.mjs +189 -0
- package/src/registry/stats.mjs +1 -1
- package/src/vnext/continuity-cli.mjs +399 -0
- package/src/vnext/continuity.mjs +1801 -0
- package/src/vnext/init-cli.mjs +23 -7
- package/src/vnext/json-dir-mailbox.mjs +6 -0
- package/src/vnext/jsonl-mailbox.mjs +177 -23
- package/src/vnext/knock-cli.mjs +18 -0
- package/src/vnext/retired-import.mjs +556 -0
- package/src/vnext/verify-cli.mjs +1 -1
|
@@ -0,0 +1,556 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Retired-inbox import (2.8.0 Track B, B-1 / B6; DESIGN-continuity §4, §10).
|
|
3
|
+
*
|
|
4
|
+
* After `pillar lineage rotate`, mail that senders still address to the old
|
|
5
|
+
* UUAID waits on the carriers under that UUAID. For a bounded grace window
|
|
6
|
+
* this module pulls it, and nothing else:
|
|
7
|
+
* - The archived key is loaded only here, only while now < until, and only
|
|
8
|
+
* to sign `GET /v1/inbox/<old>` and to decrypt. It never signs a send, an
|
|
9
|
+
* ack, a receipt or a notice.
|
|
10
|
+
* - Each import keeps the signed original envelope verbatim and a copy of
|
|
11
|
+
* the payload sealed to the home's import vault (B6): a random identity in
|
|
12
|
+
* <home>/continuity/vault.json, saved with the home passphrase, that never
|
|
13
|
+
* rotates. Readers open the vault, never an archive.
|
|
14
|
+
* - Cursors are per carrier AND recipient (`<carrier>#<uuaid>`): the
|
|
15
|
+
* carrier's seq is one global counter.
|
|
16
|
+
* - Imports never reach the mailbox inbox, handlers, notify wakes, the recv
|
|
17
|
+
* bridge, receipts, group rosters or continuity processing.
|
|
18
|
+
*/
|
|
19
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
20
|
+
import { closeSync, existsSync, fstatSync, fsyncSync, ftruncateSync, lstatSync, openSync, readFileSync, readSync, readdirSync, renameSync, statSync, unlinkSync, writeSync, constants as C } from "node:fs";
|
|
21
|
+
import { basename, dirname, join } from "node:path";
|
|
22
|
+
import { durMs } from "../vendor/pillar-core.mjs";
|
|
23
|
+
import { sealPayload, openPayload } from "../crypto/e2e.mjs";
|
|
24
|
+
import { Keychain } from "../identity/keychain.mjs";
|
|
25
|
+
import { CarrierClient } from "../net/carrier-client.mjs";
|
|
26
|
+
import { decrypt, keychainSeed, open } from "../net/envelope.mjs";
|
|
27
|
+
import {
|
|
28
|
+
WRITER_STALE_MS,
|
|
29
|
+
WRITER_WAIT_MS,
|
|
30
|
+
acquireLockSync,
|
|
31
|
+
assertSafeFile,
|
|
32
|
+
currentUid,
|
|
33
|
+
ensurePrivateDir,
|
|
34
|
+
readPrivateFile,
|
|
35
|
+
releaseLock,
|
|
36
|
+
stillHoldsLock,
|
|
37
|
+
writePrivateAtomic,
|
|
38
|
+
} from "../notify-store.mjs";
|
|
39
|
+
import { CONTINUITY_DIR } from "./continuity.mjs";
|
|
40
|
+
import { isValidUuaid } from "./knock-lane.mjs";
|
|
41
|
+
import { keychainIdentityFromSeedHex } from "./wave-a.mjs";
|
|
42
|
+
|
|
43
|
+
export const RETIRED_V = "pillar-retired/1";
|
|
44
|
+
export const IMPORT_V = "pillar-import/1";
|
|
45
|
+
export const DEFAULT_GRACE = "P14D";
|
|
46
|
+
export const MAX_GRACE_MS = 90 * 86_400_000;
|
|
47
|
+
export const MAX_RETIRED = 8;
|
|
48
|
+
export const MAX_IMPORT_ROWS = 10_000;
|
|
49
|
+
export const MAX_IMPORT_BYTES = 256 * 1024 * 1024; // imports.jsonl; past it, mail stays on the carrier until its TTL
|
|
50
|
+
export const IMPORT_PERIOD_MS = 60_000;
|
|
51
|
+
export const MAX_IMPORT_PAGES = 25; // per carrier and retired key, per run
|
|
52
|
+
export const IMPORT_RUN_MS = 15_000; // total time a run may take, whatever the carriers do
|
|
53
|
+
export const INTENT_V = "pillar-rotation-intent/1";
|
|
54
|
+
const STAMP_RE = /^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})(?:-(\d{1,3}))?Z-/;
|
|
55
|
+
|
|
56
|
+
/** Grace window in ms from an ISO-8601 duration. P0D turns the import off. */
|
|
57
|
+
export function parseGrace(value = DEFAULT_GRACE) {
|
|
58
|
+
if (value === "P0D" || value === "PT0S") return 0;
|
|
59
|
+
const ms = durMs(String(value));
|
|
60
|
+
if (ms === null || !Number.isFinite(ms) || ms < 0) throw new Error(`--retired-grace must be an ISO-8601 duration such as P14D, not ${value}`);
|
|
61
|
+
if (ms > MAX_GRACE_MS) throw new Error(`--retired-grace is at most P90D, not ${value}`); // @rule retired.grace-max
|
|
62
|
+
return ms;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function archiveUuaid(dir) {
|
|
66
|
+
const kc = join(dir, "keychain.json");
|
|
67
|
+
if (existsSync(kc)) {
|
|
68
|
+
try { return new Keychain(kc).publicView(); } catch { return null; }
|
|
69
|
+
}
|
|
70
|
+
const meta = join(dir, "agent-meta.json");
|
|
71
|
+
if (existsSync(meta)) {
|
|
72
|
+
try { const m = JSON.parse(readFileSync(meta, "utf8")); return { uuaid: m.uuaid, publicKeyHex: m.publicKeyHex }; } catch { return null; }
|
|
73
|
+
}
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** The archive directory that holds the retired key `uuaid`, or null. */
|
|
78
|
+
export function findArchive(home, uuaid) {
|
|
79
|
+
const root = join(home, "rotated");
|
|
80
|
+
if (!existsSync(root)) return null;
|
|
81
|
+
for (const name of readdirSync(root).sort().reverse()) {
|
|
82
|
+
const dir = join(root, name);
|
|
83
|
+
try { if (!statSync(dir).isDirectory()) continue; } catch { continue; }
|
|
84
|
+
if (archiveUuaid(dir)?.uuaid === uuaid) return dir;
|
|
85
|
+
}
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Write `<archive>/retired.json` for the key `rotate` just retired. */
|
|
90
|
+
export function writeRetiredRecord(dir, { uuaid, publicKey, retiredAt, graceMs, cursors = {} }) {
|
|
91
|
+
const until = new Date(Date.parse(retiredAt) + graceMs).toISOString().replace(/\.\d{3}Z$/, "Z");
|
|
92
|
+
const rec = { v: RETIRED_V, uuaid, publicKey, retiredAt, until, cursors };
|
|
93
|
+
// Durable before anything relies on it (RedTeam 5402b7, a97f59): both the temp file and the archive
|
|
94
|
+
// directory entry must fsync cleanly before a pending intent is removed; sync errors surface to the caller.
|
|
95
|
+
writeDurablePrivate(join(dir, "retired.json"), `${JSON.stringify(rec, null, 2)}\n`); // @rule retired.record-durable
|
|
96
|
+
return rec;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function stampToIso(name) {
|
|
100
|
+
const m = STAMP_RE.exec(name);
|
|
101
|
+
if (!m) return null;
|
|
102
|
+
const iso = `${m[1]}T${m[2]}:${m[3]}:${m[4]}${m[5] ? `.${m[5]}` : ""}Z`;
|
|
103
|
+
return Number.isNaN(Date.parse(iso)) ? null : iso;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const isPlainObj = (x) => x !== null && typeof x === "object" && !Array.isArray(x);
|
|
107
|
+
const isIso = (x) => typeof x === "string" && !Number.isNaN(Date.parse(x));
|
|
108
|
+
const validCursors = (c) => isPlainObj(c) && Object.values(c).every((n) => Number.isSafeInteger(n) && n >= 0);
|
|
109
|
+
|
|
110
|
+
/** A modern retired record, checked in full: anything else is refused, never read as a legacy archive (RedTeam b5cbee P2). */
|
|
111
|
+
function validRetiredRecord(rec, uuaid) {
|
|
112
|
+
if (!isPlainObj(rec) || rec.v !== RETIRED_V || rec.uuaid !== uuaid) return false;
|
|
113
|
+
if (!isIso(rec.retiredAt) || !isIso(rec.until) || !validCursors(rec.cursors ?? {})) return false;
|
|
114
|
+
const span = Date.parse(rec.until) - Date.parse(rec.retiredAt);
|
|
115
|
+
return span >= 0 && span <= MAX_GRACE_MS;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function intentPath(home) { return join(home, "continuity", "rotation-intent.json"); }
|
|
119
|
+
function asideDir(home) { return join(home, "continuity", "rotation-intents"); }
|
|
120
|
+
function asidePath(home, uuaid) { return join(asideDir(home), `${createHash("sha256").update(uuaid).digest("hex").slice(0, 32)}.json`); }
|
|
121
|
+
|
|
122
|
+
/** Strictly fsync a directory fd, surfacing any sync failure so callers never clear a prior intent prematurely. */
|
|
123
|
+
function fsyncDirStrict(dir) {
|
|
124
|
+
const fd = openSync(dir, C.O_RDONLY);
|
|
125
|
+
try {
|
|
126
|
+
fsyncSync(fd); // @rule retired.dir-sync-strict
|
|
127
|
+
} finally {
|
|
128
|
+
closeSync(fd);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Write `data` to `path` (exclusive 0600 temp file, strict file fsync, rename, strict parent-dir fsync). */
|
|
133
|
+
function writeDurablePrivate(path, data, { uid = currentUid() } = {}) {
|
|
134
|
+
try { assertSafeFile(lstatSync(path), path, uid); }
|
|
135
|
+
catch (e) { if (e.code !== "ENOENT") throw e; }
|
|
136
|
+
const tmp = `${path}.tmp-${process.pid}-${randomBytes(6).toString("hex")}`;
|
|
137
|
+
const fd = openSync(tmp, C.O_WRONLY | C.O_CREAT | C.O_EXCL | C.O_NOFOLLOW, 0o600);
|
|
138
|
+
let closed = false;
|
|
139
|
+
try {
|
|
140
|
+
const buf = Buffer.from(data, "utf-8");
|
|
141
|
+
let off = 0;
|
|
142
|
+
while (off < buf.length) off += writeSync(fd, buf, off, buf.length - off);
|
|
143
|
+
fsyncSync(fd); // @rule retired.file-sync-strict
|
|
144
|
+
closed = true;
|
|
145
|
+
closeSync(fd);
|
|
146
|
+
renameSync(tmp, path);
|
|
147
|
+
} catch (e) {
|
|
148
|
+
if (!closed) closeSync(fd);
|
|
149
|
+
try { unlinkSync(tmp); } catch (_e) {}
|
|
150
|
+
throw e;
|
|
151
|
+
}
|
|
152
|
+
fsyncDirStrict(dirname(path));
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function syncExistingRecord(dir) {
|
|
156
|
+
const fd = openSync(join(dir, "retired.json"), C.O_RDONLY | C.O_NOFOLLOW);
|
|
157
|
+
try { fsyncSync(fd); } finally { closeSync(fd); }
|
|
158
|
+
fsyncDirStrict(dir);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** One intent file: null (absent), the intent, or { invalid }. */
|
|
162
|
+
function readIntentFile(path) {
|
|
163
|
+
let raw = null;
|
|
164
|
+
try { raw = readPrivateFile(path, { maxBytes: 64 * 1024 }); }
|
|
165
|
+
catch (e) { if (e?.code === "ENOENT") return null; return { invalid: `rotation intent unreadable (${String(e?.message ?? e).slice(0, 120)})` }; }
|
|
166
|
+
if (raw === null) return null;
|
|
167
|
+
let it;
|
|
168
|
+
try { it = JSON.parse(raw); } catch { return { invalid: "rotation intent is not JSON" }; }
|
|
169
|
+
if (!isPlainObj(it) || it.v !== INTENT_V || !isValidUuaid(it.previousUuaid) || !Number.isSafeInteger(it.graceMs) || it.graceMs < 0 || it.graceMs > MAX_GRACE_MS || !isIso(it.at) || !validCursors(it.cursors ?? {})) return { invalid: "rotation intent is malformed" };
|
|
170
|
+
return it;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* The rotation intent `pillar lineage rotate` writes before it rotates, so the
|
|
175
|
+
* policy survives a crash between the rotation and its retired.json
|
|
176
|
+
* (RedTeam b5cbee P2). Returns null (none), the intent, or { invalid }.
|
|
177
|
+
*/
|
|
178
|
+
export function readRotationIntent(home) {
|
|
179
|
+
return readIntentFile(intentPath(home));
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Intents set aside because their archive was not found when a later rotation
|
|
184
|
+
* started (RedTeam 5402b7): each keeps its key's policy until the archive is
|
|
185
|
+
* accounted for. Returns { intents: [{ ...intent, path }], invalid }.
|
|
186
|
+
*/
|
|
187
|
+
export function readSetAsideIntents(home) {
|
|
188
|
+
const dir = asideDir(home);
|
|
189
|
+
let st;
|
|
190
|
+
try { st = lstatSync(dir); } catch (e) { if (e?.code === "ENOENT") return { intents: [], invalid: null }; return { intents: [], invalid: `rotation intents unreadable (${String(e?.message ?? e).slice(0, 120)})` }; }
|
|
191
|
+
if (st.isSymbolicLink() || !st.isDirectory()) return { intents: [], invalid: "rotation-intents is not a private directory" };
|
|
192
|
+
let names = [];
|
|
193
|
+
try { names = readdirSync(dir); } catch (e) { return { intents: [], invalid: `rotation intents unreadable (${String(e?.message ?? e).slice(0, 120)})` }; }
|
|
194
|
+
const intents = [];
|
|
195
|
+
for (const name of names.filter((n) => n.endsWith(".json")).sort()) {
|
|
196
|
+
const full = join(dir, name);
|
|
197
|
+
const it = readIntentFile(full);
|
|
198
|
+
if (it?.invalid) return { intents: [], invalid: it.invalid };
|
|
199
|
+
if (!it) continue;
|
|
200
|
+
if (asidePath(home, it.previousUuaid) !== full) return { intents: [], invalid: "rotation intent name mismatch" };
|
|
201
|
+
intents.push({ ...it, path: full });
|
|
202
|
+
}
|
|
203
|
+
return { intents, invalid: null };
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** Write the rotation intent durably (0600, fsync, rename, strict folder fsync) in <home>/continuity. */
|
|
207
|
+
export function writeRotationIntent(home, { previousUuaid, graceMs, cursors = {}, at }) {
|
|
208
|
+
ensurePrivateDir(join(home, "continuity"));
|
|
209
|
+
fsyncDirStrict(home);
|
|
210
|
+
writeDurablePrivate(intentPath(home), JSON.stringify({ v: INTENT_V, previousUuaid, graceMs, cursors, at }));
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function validRecordAt(dir, uuaid) {
|
|
214
|
+
let rec = null;
|
|
215
|
+
try { rec = JSON.parse(readFileSync(join(dir, "retired.json"), "utf8")); } catch { rec = null; }
|
|
216
|
+
return validRetiredRecord(rec, uuaid);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* The archive of the key an intent names, with a valid retired.json made
|
|
221
|
+
* durable: true. A missing or torn record is written from the intent first.
|
|
222
|
+
* false when the archive is not found: the intent must be kept.
|
|
223
|
+
*/
|
|
224
|
+
function accountFor(home, it) {
|
|
225
|
+
const dir = findArchive(home, it.previousUuaid);
|
|
226
|
+
if (!dir) return false;
|
|
227
|
+
if (validRecordAt(dir, it.previousUuaid)) { syncExistingRecord(dir); return true; }
|
|
228
|
+
const id = archiveUuaid(dir);
|
|
229
|
+
writeRetiredRecord(dir, { uuaid: it.previousUuaid, publicKey: id?.publicKeyHex ?? null, retiredAt: stampToIso(basename(dir)) ?? it.at, graceMs: it.graceMs, cursors: it.cursors ?? {} }); // @rule retired.finish-pending-record
|
|
230
|
+
return true;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* Run before another rotation writes its intent (RedTeam 1c5e7a, 5402b7). An
|
|
235
|
+
* intent that names a key which is no longer current belongs to a rotation
|
|
236
|
+
* that happened but never wrote a valid retired.json (a crash). When its
|
|
237
|
+
* archive is found, the record is written from the intent and made durable,
|
|
238
|
+
* and only then is the intent removed. When the archive is not found, the
|
|
239
|
+
* intent is set aside (durably) and kept until the archive is accounted for.
|
|
240
|
+
* An intent for the current key is from a rotation that never happened, and
|
|
241
|
+
* the new one replaces it. Throws if an intent cannot be read: the caller must
|
|
242
|
+
* not rotate. Returns { finished: [keys], kept: [keys], stale }.
|
|
243
|
+
*/
|
|
244
|
+
export function finishPendingRetirement(home, currentUuaid) {
|
|
245
|
+
const it = readRotationIntent(home);
|
|
246
|
+
if (it?.invalid) throw new Error(it.invalid);
|
|
247
|
+
const aside = readSetAsideIntents(home);
|
|
248
|
+
if (aside.invalid) throw new Error(aside.invalid);
|
|
249
|
+
const out = { finished: [], kept: [], stale: null };
|
|
250
|
+
for (const a of aside.intents) {
|
|
251
|
+
if (!accountFor(home, a)) { out.kept.push(a.previousUuaid); continue; }
|
|
252
|
+
unlinkSync(a.path);
|
|
253
|
+
fsyncDirStrict(asideDir(home));
|
|
254
|
+
out.finished.push(a.previousUuaid);
|
|
255
|
+
}
|
|
256
|
+
if (!it) return out;
|
|
257
|
+
if (it.previousUuaid === currentUuaid) { out.stale = it.previousUuaid; return out; }
|
|
258
|
+
const accounted = accountFor(home, it);
|
|
259
|
+
if (!accounted) setAside(home, it); // @rule retired.keep-intent-without-archive
|
|
260
|
+
(accounted ? out.finished : out.kept).push(it.previousUuaid);
|
|
261
|
+
clearRotationIntent(home);
|
|
262
|
+
return out;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/** Keep an intent whose archive is not found, durably, under its own name. */
|
|
266
|
+
function setAside(home, it) {
|
|
267
|
+
ensurePrivateDir(asideDir(home));
|
|
268
|
+
fsyncDirStrict(join(home, "continuity"));
|
|
269
|
+
writeDurablePrivate(asidePath(home, it.previousUuaid), JSON.stringify({ v: INTENT_V, previousUuaid: it.previousUuaid, graceMs: it.graceMs, cursors: it.cursors ?? {}, at: it.at }));
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** Remove the rotation intent (after its retired.json is durable, or after a failed rotation). */
|
|
273
|
+
export function clearRotationIntent(home) {
|
|
274
|
+
try { unlinkSync(intentPath(home)); } catch (e) { if (e?.code !== "ENOENT") throw e; return; }
|
|
275
|
+
fsyncDirStrict(join(home, "continuity"));
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* Every retired key under `<home>/rotated/`, newest first.
|
|
280
|
+
* - a valid retired.json: its policy.
|
|
281
|
+
* - otherwise, a rotation intent (current or set aside) names this key: the
|
|
282
|
+
* intent's policy, also over a torn retired.json a crash left.
|
|
283
|
+
* - a retired.json that is not valid and no intent: listed as { invalid } and
|
|
284
|
+
* never imported (fail closed).
|
|
285
|
+
* - none: a 2.7.x archive, the default window and cursor 0. If an intent
|
|
286
|
+
* exists but is malformed, an archive without a valid record is refused too.
|
|
287
|
+
*/
|
|
288
|
+
export function listRetired(home) {
|
|
289
|
+
const root = join(home, "rotated");
|
|
290
|
+
if (!existsSync(root)) return [];
|
|
291
|
+
const single = readRotationIntent(home);
|
|
292
|
+
const aside = readSetAsideIntents(home);
|
|
293
|
+
const intentInvalid = single?.invalid ?? aside.invalid ?? null;
|
|
294
|
+
const intentOf = (uuaid) => (single && !single.invalid && single.previousUuaid === uuaid ? single : aside.intents.find((a) => a.previousUuaid === uuaid) ?? null);
|
|
295
|
+
const out = [];
|
|
296
|
+
for (const name of readdirSync(root)) {
|
|
297
|
+
const dir = join(root, name);
|
|
298
|
+
try { if (!statSync(dir).isDirectory()) continue; } catch { continue; }
|
|
299
|
+
const id = archiveUuaid(dir);
|
|
300
|
+
if (!id || !isValidUuaid(id.uuaid)) continue;
|
|
301
|
+
const recPath = join(dir, "retired.json");
|
|
302
|
+
let present = true;
|
|
303
|
+
try { lstatSync(recPath); } catch (e) { present = e?.code !== "ENOENT"; }
|
|
304
|
+
const stamp = stampToIso(name);
|
|
305
|
+
let rec = null;
|
|
306
|
+
if (present) { try { rec = JSON.parse(readFileSync(recPath, "utf8")); } catch { rec = null; } }
|
|
307
|
+
if (present && validRetiredRecord(rec, id.uuaid)) {
|
|
308
|
+
out.push({ dir, uuaid: rec.uuaid, publicKey: rec.publicKey, retiredAt: rec.retiredAt, until: rec.until, cursors: rec.cursors ?? {}, legacy: false });
|
|
309
|
+
continue;
|
|
310
|
+
}
|
|
311
|
+
const intent = intentOf(id.uuaid);
|
|
312
|
+
if (present && !intent) { out.push({ dir, uuaid: id.uuaid, retiredAt: stamp ?? "", invalid: "retired.json is malformed" }); continue; } // @rule retired.modern-record-fail-closed
|
|
313
|
+
if (!intent && intentInvalid) { out.push({ dir, uuaid: id.uuaid, retiredAt: stamp ?? "", invalid: intentInvalid }); continue; } // @rule retired.intent-fail-closed
|
|
314
|
+
if (intent) {
|
|
315
|
+
const retiredAt = stamp ?? intent.at;
|
|
316
|
+
const until = new Date(Date.parse(retiredAt) + intent.graceMs).toISOString().replace(/\.\d{3}Z$/, "Z");
|
|
317
|
+
out.push({ dir, uuaid: id.uuaid, publicKey: id.publicKeyHex, retiredAt, until, cursors: intent.cursors ?? {}, legacy: false, fromIntent: true }); // @rule retired.intent-policy
|
|
318
|
+
continue;
|
|
319
|
+
}
|
|
320
|
+
if (!stamp) continue;
|
|
321
|
+
const until = new Date(Date.parse(stamp) + parseGrace(DEFAULT_GRACE)).toISOString().replace(/\.\d{3}Z$/, "Z");
|
|
322
|
+
out.push({ dir, uuaid: id.uuaid, publicKey: id.publicKeyHex, retiredAt: stamp, until, cursors: {}, legacy: true });
|
|
323
|
+
}
|
|
324
|
+
return out.sort((a, b) => String(b.retiredAt).localeCompare(String(a.retiredAt)));
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** Load an archived key. Only importRetiredMail calls this. */
|
|
328
|
+
function loadArchivedKey(r, passphrase) {
|
|
329
|
+
const kcPath = join(r.dir, "keychain.json");
|
|
330
|
+
if (existsSync(kcPath)) {
|
|
331
|
+
const kc = new Keychain(kcPath);
|
|
332
|
+
kc.load({ passphrase });
|
|
333
|
+
return kc;
|
|
334
|
+
}
|
|
335
|
+
const seedHex = readFileSync(join(r.dir, "agent.seed"), "utf8").trim().toLowerCase();
|
|
336
|
+
if (!/^[0-9a-f]{64}$/.test(seedHex)) throw new Error(`retired import: ${r.dir}/agent.seed is not a 64-hex seed`);
|
|
337
|
+
const kc = new Keychain(join(r.dir, "agent.seed.keychain"));
|
|
338
|
+
kc._identity = keychainIdentityFromSeedHex(seedHex, r.uuaid, r.retiredAt);
|
|
339
|
+
return kc;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
// ── the import store ─────────────────────────────────────────────────────────
|
|
343
|
+
|
|
344
|
+
const NOT_LOCKED = Object.freeze({ path: null });
|
|
345
|
+
|
|
346
|
+
export class ImportStore {
|
|
347
|
+
constructor(home, { lockWaitMs = WRITER_WAIT_MS, lockStaleMs = WRITER_STALE_MS, maxRows = MAX_IMPORT_ROWS, maxBytes = MAX_IMPORT_BYTES } = {}) {
|
|
348
|
+
this.home = home;
|
|
349
|
+
this.maxRows = maxRows;
|
|
350
|
+
this.maxBytes = maxBytes;
|
|
351
|
+
this.dir = join(home, CONTINUITY_DIR);
|
|
352
|
+
this.rowsPath = join(this.dir, "imports.jsonl");
|
|
353
|
+
this.cursorsPath = join(this.dir, "import-cursors.json");
|
|
354
|
+
this.vaultPath = join(this.dir, "vault.json");
|
|
355
|
+
this.lockPath = join(this.dir, "writer.lock");
|
|
356
|
+
this.lockWaitMs = lockWaitMs;
|
|
357
|
+
this.lockStaleMs = lockStaleMs;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/** Committed rows (an unterminated tail is an append in flight and is dropped). */
|
|
361
|
+
rows() {
|
|
362
|
+
let raw = null;
|
|
363
|
+
try { raw = readPrivateFile(this.rowsPath, { maxBytes: MAX_IMPORT_BYTES + 4 * 1024 * 1024 }); } catch (e) { if (e?.code === "ENOENT") return []; throw e; }
|
|
364
|
+
if (!raw) return [];
|
|
365
|
+
const text = raw.slice(0, raw.lastIndexOf("\n") + 1);
|
|
366
|
+
const out = [];
|
|
367
|
+
for (const line of text.split("\n")) {
|
|
368
|
+
if (!line) continue;
|
|
369
|
+
try { const r = JSON.parse(line); if (r?.v === IMPORT_V) out.push(r); } catch { /* a damaged line is skipped */ }
|
|
370
|
+
}
|
|
371
|
+
return out;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
cursors() {
|
|
375
|
+
const raw = readPrivateFile(this.cursorsPath, { maxBytes: 1024 * 1024 });
|
|
376
|
+
if (!raw) return {};
|
|
377
|
+
try { const c = JSON.parse(raw); return c && typeof c === "object" && !Array.isArray(c) ? c : {}; } catch { return {}; }
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* The import vault: load it, or (create = true) make it. Saved with the
|
|
382
|
+
* home passphrase. Creation happens under the writer lock and lands by an
|
|
383
|
+
* atomic rename, so two processes doing their first import at once end up
|
|
384
|
+
* with the same vault, and a reader never sees a half-written file (B-P2b).
|
|
385
|
+
*/
|
|
386
|
+
vault(passphrase, { create = false } = {}) {
|
|
387
|
+
const load = () => { const kc = new Keychain(this.vaultPath); kc.load({ passphrase }); return kc; };
|
|
388
|
+
if (!create) return existsSync(this.vaultPath) ? load() : null;
|
|
389
|
+
return this._withLock(() => {
|
|
390
|
+
if (existsSync(this.vaultPath)) return load(); // @rule retired.vault-recheck-under-lock
|
|
391
|
+
const tmp = `${this.vaultPath}.${process.pid}-${randomBytes(6).toString("hex")}`;
|
|
392
|
+
new Keychain(tmp).save(Keychain.generate({ uuaidNamespace: "pillar", objectType: "agent" }), { passphrase });
|
|
393
|
+
renameSync(tmp, this.vaultPath);
|
|
394
|
+
return load();
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
_withLock(fn) {
|
|
399
|
+
ensurePrivateDir(this.dir);
|
|
400
|
+
let handle = NOT_LOCKED;
|
|
401
|
+
handle = acquireLockSync(this.lockPath, { staleMs: this.lockStaleMs, waitMs: this.lockWaitMs });
|
|
402
|
+
if (!handle) throw Object.assign(new Error(`continuity-locked: another process holds ${this.lockPath}`), { code: "continuity-locked" });
|
|
403
|
+
try { return fn(handle); } finally { releaseLock(handle); }
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/**
|
|
407
|
+
* Cut an unterminated tail (an append that crashed) back to the last full
|
|
408
|
+
* row, under the lock (RedTeam b5cbee P1). A row appended after torn bytes
|
|
409
|
+
* would be joined to them and lost while its cursor moved on.
|
|
410
|
+
* Returns the bytes removed.
|
|
411
|
+
*/
|
|
412
|
+
_repairTornTail() {
|
|
413
|
+
let fd;
|
|
414
|
+
try { fd = openSync(this.rowsPath, C.O_RDWR | C.O_NOFOLLOW); }
|
|
415
|
+
catch (e) { if (e?.code === "ENOENT") return 0; throw e; }
|
|
416
|
+
try {
|
|
417
|
+
const size = fstatSync(fd).size;
|
|
418
|
+
if (size === 0) return 0;
|
|
419
|
+
const last = Buffer.alloc(1);
|
|
420
|
+
readSync(fd, last, 0, 1, size - 1);
|
|
421
|
+
if (last[0] === 0x0a) return 0;
|
|
422
|
+
let cut = 0;
|
|
423
|
+
for (let pos = size; pos > 0;) {
|
|
424
|
+
const n = Math.min(64 * 1024, pos);
|
|
425
|
+
pos -= n;
|
|
426
|
+
const buf = Buffer.alloc(n);
|
|
427
|
+
readSync(fd, buf, 0, n, pos);
|
|
428
|
+
const i = buf.lastIndexOf(0x0a);
|
|
429
|
+
if (i !== -1) { cut = pos + i + 1; break; }
|
|
430
|
+
}
|
|
431
|
+
ftruncateSync(fd, cut);
|
|
432
|
+
fsyncSync(fd);
|
|
433
|
+
return size - cut;
|
|
434
|
+
} finally { closeSync(fd); }
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/**
|
|
438
|
+
* Append new rows (deduped on recipient, sender, id), then move the cursors.
|
|
439
|
+
* Rows first: a crash before the cursor write re-fetches, and dedup drops the copies.
|
|
440
|
+
*/
|
|
441
|
+
commit(newRows, cursorUpdates) {
|
|
442
|
+
return this._withLock((handle) => {
|
|
443
|
+
this._repairTornTail(); // @rule retired.torn-tail-repaired
|
|
444
|
+
const have = new Set(this.rows().map((r) => `${r.recipient}|${r.sender}|${r.id}`));
|
|
445
|
+
const fresh = [];
|
|
446
|
+
for (const r of newRows) {
|
|
447
|
+
const k = `${r.recipient}|${r.sender}|${r.id}`;
|
|
448
|
+
if (have.has(k)) continue; // @rule retired.dedup
|
|
449
|
+
have.add(k);
|
|
450
|
+
fresh.push(r);
|
|
451
|
+
}
|
|
452
|
+
const add = Buffer.byteLength(fresh.map((r) => `${JSON.stringify(r)}\n`).join(""), "utf8");
|
|
453
|
+
let size = 0;
|
|
454
|
+
try { size = statSync(this.rowsPath).size; } catch { size = 0; }
|
|
455
|
+
if (have.size > this.maxRows || size + add > this.maxBytes) throw Object.assign(new Error(`retired import: the cap (${this.maxRows} rows, ${this.maxBytes} bytes) is reached; the rest stays on the carrier until its TTL`), { code: "import-cap" }); // @rule retired.import-cap
|
|
456
|
+
if (!stillHoldsLock(handle)) throw Object.assign(new Error("continuity-locked: the writer lock was lost"), { code: "continuity-locked" });
|
|
457
|
+
if (fresh.length) {
|
|
458
|
+
const fd = openSync(this.rowsPath, C.O_WRONLY | C.O_APPEND | C.O_CREAT | C.O_NOFOLLOW, 0o600);
|
|
459
|
+
try {
|
|
460
|
+
const buf = Buffer.from(fresh.map((r) => `${JSON.stringify(r)}\n`).join(""), "utf8");
|
|
461
|
+
let off = 0;
|
|
462
|
+
while (off < buf.length) off += writeSync(fd, buf, off, buf.length - off);
|
|
463
|
+
fsyncSync(fd);
|
|
464
|
+
} finally { closeSync(fd); }
|
|
465
|
+
}
|
|
466
|
+
const cur = { ...this.cursors() };
|
|
467
|
+
for (const [k, seq] of Object.entries(cursorUpdates)) cur[k] = Math.max(cur[k] ?? 0, seq);
|
|
468
|
+
writePrivateAtomic(this.cursorsPath, JSON.stringify(cur)); // @rule retired.cursor-after-rows
|
|
469
|
+
return fresh.length;
|
|
470
|
+
});
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
/**
|
|
475
|
+
* Pull each retired inbox inside its window and store what verifies.
|
|
476
|
+
* pillar: a Pillar (home, carriers, cryptoInventory, metrics).
|
|
477
|
+
* Returns { imported, rejected, keys, errors }.
|
|
478
|
+
*/
|
|
479
|
+
export async function importRetiredMail(pillar, { now = new Date().toISOString(), passphrase = "", timeoutMs = 20_000, store = null, signal = null, runMs = IMPORT_RUN_MS, maxPages = MAX_IMPORT_PAGES } = {}) {
|
|
480
|
+
const out = { imported: 0, rejected: 0, keys: 0, pages: 0, errors: [] };
|
|
481
|
+
const home = pillar?._continuityHome ?? null;
|
|
482
|
+
if (!home || !Array.isArray(pillar.carriers) || pillar.carriers.length === 0) return out;
|
|
483
|
+
const nowMs = Date.parse(now);
|
|
484
|
+
const deadline = Date.now() + runMs;
|
|
485
|
+
let retired = listRetired(home);
|
|
486
|
+
for (const r of retired.filter((x) => x.invalid)) out.errors.push({ uuaid: r.uuaid, error: `not imported: ${r.invalid}` });
|
|
487
|
+
retired = retired.filter((r) => !r.invalid);
|
|
488
|
+
retired = retired.filter((r) => nowMs < Date.parse(r.until)); // @rule retired.window
|
|
489
|
+
retired = retired.slice(0, MAX_RETIRED); // @rule retired.max-keys
|
|
490
|
+
if (retired.length === 0) return out;
|
|
491
|
+
const st = store ?? new ImportStore(home);
|
|
492
|
+
let vault = null;
|
|
493
|
+
for (const r of retired) {
|
|
494
|
+
if (signal?.aborted || Date.now() >= deadline) { out.errors.push({ uuaid: r.uuaid, error: signal?.aborted ? "aborted" : "run time limit reached" }); continue; }
|
|
495
|
+
let kc;
|
|
496
|
+
try { kc = loadArchivedKey(r, passphrase); }
|
|
497
|
+
catch (e) { out.errors.push({ uuaid: r.uuaid, error: `archive key: ${e.message}` }); continue; }
|
|
498
|
+
pillar.metrics?.inc?.("continuity.import.archive-key-load");
|
|
499
|
+
out.keys++;
|
|
500
|
+
const client = new CarrierClient({ keychain: kc, carriers: pillar.carriers });
|
|
501
|
+
for (const base of pillar.carriers) {
|
|
502
|
+
const key = `${base}#${r.uuaid}`;
|
|
503
|
+
let since = r.cursors?.[base] ?? 0;
|
|
504
|
+
since = st.cursors()[key] ?? since; // @rule retired.cursor-per-recipient
|
|
505
|
+
try {
|
|
506
|
+
for (let page = 0; ; page++) {
|
|
507
|
+
if (page >= maxPages) { out.errors.push({ uuaid: r.uuaid, carrier: base, error: `page limit (${maxPages}) reached; the rest is pulled next run` }); break; } // @rule retired.page-cap
|
|
508
|
+
if (signal?.aborted) { out.errors.push({ uuaid: r.uuaid, carrier: base, error: "aborted" }); break; } // @rule retired.abort
|
|
509
|
+
const left = deadline - Date.now();
|
|
510
|
+
if (left <= 0) { out.errors.push({ uuaid: r.uuaid, carrier: base, error: "run time limit reached" }); break; } // @rule retired.run-deadline
|
|
511
|
+
const res = await client.fetchInbox(base, { since, waitS: 0, timeoutMs: Math.min(timeoutMs, left), ...(signal ? { signal } : {}) });
|
|
512
|
+
out.pages++;
|
|
513
|
+
if (!res.envelopes.length) break;
|
|
514
|
+
const pageMax = Math.max(...res.envelopes.map((x) => (Number.isSafeInteger(x?.seq) ? x.seq : -1)));
|
|
515
|
+
if (!(pageMax > since)) { out.errors.push({ uuaid: r.uuaid, carrier: base, error: "the carrier's cursor did not move; stopped" }); break; } // @rule retired.cursor-progress
|
|
516
|
+
const rows = [];
|
|
517
|
+
const from = since;
|
|
518
|
+
for (const { seq, envelope } of res.envelopes) {
|
|
519
|
+
if (!Number.isSafeInteger(seq) || seq <= from) continue;
|
|
520
|
+
const v = open(envelope, { cryptoInventory: pillar.cryptoInventory });
|
|
521
|
+
if (!v.ok) { out.rejected++; continue; }
|
|
522
|
+
// The original recipient must be this retired key. decrypt() refuses another recipient too;
|
|
523
|
+
// this check says so first and keeps the reason in `rejected` (defence in depth, no @rule:
|
|
524
|
+
// deleting it changes no outcome, so no probe could kill it).
|
|
525
|
+
if (envelope.recipient !== r.uuaid) { out.rejected++; continue; }
|
|
526
|
+
let payload;
|
|
527
|
+
try { payload = decrypt(kc, envelope); } catch { out.rejected++; continue; }
|
|
528
|
+
vault ??= st.vault(passphrase, { create: true });
|
|
529
|
+
const local = sealPayload(vault._identity.publicKeyHex, payload, { aad: `import:${r.uuaid}:${envelope.id}` });
|
|
530
|
+
rows.push({ v: IMPORT_V, recipient: r.uuaid, sender: envelope.sender, id: envelope.id, kind: envelope.kind, carrier: base, seq, importedAt: now, envelope, local });
|
|
531
|
+
}
|
|
532
|
+
since = pageMax;
|
|
533
|
+
out.imported += st.commit(rows, { [key]: since });
|
|
534
|
+
}
|
|
535
|
+
} catch (e) {
|
|
536
|
+
out.errors.push({ uuaid: r.uuaid, carrier: base, error: e.message });
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
if (out.imported) pillar.metrics?.inc?.("continuity.import.rows", out.imported);
|
|
541
|
+
return out;
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
/** Imported mail, decrypted with the vault (never an archived key). */
|
|
545
|
+
export function readImports(home, { passphrase = "" } = {}) {
|
|
546
|
+
const st = new ImportStore(home);
|
|
547
|
+
const rows = st.rows();
|
|
548
|
+
if (!rows.length) return [];
|
|
549
|
+
const vault = st.vault(passphrase);
|
|
550
|
+
const seed = vault ? keychainSeed(vault) : null;
|
|
551
|
+
return rows.map((r) => {
|
|
552
|
+
let payload = null;
|
|
553
|
+
try { payload = seed ? openPayload(seed, r.local, { aad: `import:${r.recipient}:${r.id}` }) : null; } catch { payload = null; }
|
|
554
|
+
return { id: r.id, sender: r.sender, recipient: r.recipient, kind: r.kind, at: r.envelope?.createdAt ?? null, importedAt: r.importedAt, carrier: r.carrier, payload, readable: payload !== null };
|
|
555
|
+
});
|
|
556
|
+
}
|
package/src/vnext/verify-cli.mjs
CHANGED
|
@@ -31,7 +31,7 @@ import {
|
|
|
31
31
|
verifyStatsArtifact,
|
|
32
32
|
} from "../registry/stats.mjs";
|
|
33
33
|
|
|
34
|
-
export const VERIFY_CLI_TOOL = "pillar/2.
|
|
34
|
+
export const VERIFY_CLI_TOOL = "pillar/2.8.0";
|
|
35
35
|
const TYPE_SET = new Set([...VERIFY_TYPES, TTFA_VERDICT_TYPE, REGISTRY_STATS_VERDICT_TYPE]);
|
|
36
36
|
|
|
37
37
|
const VALUE_FLAGS = new Set([
|