@uuaid/pillar 2.5.2 → 2.5.4

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.
@@ -33,6 +33,9 @@
33
33
  * priority is to become infrastructure for everyone else.
34
34
  */
35
35
  import { createHash } from "node:crypto";
36
+ import dns from "node:dns";
37
+ import { request as httpRequest } from "node:http";
38
+ import { request as httpsRequest } from "node:https";
36
39
  import { isIP } from "node:net";
37
40
  import Database from "better-sqlite3";
38
41
  import { jcs } from "../identity/jcs.mjs";
@@ -43,29 +46,109 @@ import { evaluateSeedTier, seedTier, GRANT_TTL_DAYS, DEMOTE_AFTER_FAILURES } fro
43
46
 
44
47
  const PROBE_TIMEOUT_MS = 10_000;
45
48
  const ROUND_TRIP_WAIT_S = 5;
49
+ const MAX_RESPONSE_BYTES = 1024 * 1024;
46
50
  /** Keep the observation window bounded so uptime reflects recent behaviour. */
47
51
  export const PROBE_WINDOW = 1000;
48
52
 
53
+ function unwrapHost(host) {
54
+ const raw = String(host ?? "").trim().toLowerCase();
55
+ return raw.startsWith("[") && raw.endsWith("]") ? raw.slice(1, -1) : raw;
56
+ }
57
+
58
+ function isPrivateIpv4Octets(a, b, c, d) {
59
+ if ([a, b, c, d].some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return true;
60
+ if (a === 0 || a === 10 || a === 127) return true; // 0.0.0.0/8, 10.0.0.0/8, 127.0.0.0/8
61
+ if (a === 100 && b >= 64 && b <= 127) return true; // 100.64.0.0/10 (CGNAT)
62
+ if (a === 169 && b === 254) return true; // 169.254.0.0/16 (link-local / cloud metadata)
63
+ if (a === 172 && b >= 16 && b <= 31) return true; // 172.16.0.0/12 (RFC 1918)
64
+ if (a === 192 && b === 0 && c === 0) return true; // 192.0.0.0/24 (IETF protocol assignments)
65
+ if (a === 192 && b === 168) return true; // 192.168.0.0/16 (RFC 1918)
66
+ if (a === 198 && (b === 18 || b === 19)) return true; // 198.18.0.0/15 (benchmarking)
67
+ if (a >= 224) return true; // 224.0.0.0/4 (multicast) + 240.0.0.0/4 (reserved/broadcast)
68
+ return false;
69
+ }
70
+
71
+ function parseIpv6Words(addr) {
72
+ let s = addr;
73
+ const lastColon = s.lastIndexOf(":");
74
+ if (lastColon !== -1 && s.slice(lastColon + 1).includes(".")) {
75
+ const v4 = s.slice(lastColon + 1);
76
+ if (isIP(v4) !== 4) return null;
77
+ const [a, b, c, d] = v4.split(".").map(Number);
78
+ const hi = ((a << 8) | b).toString(16);
79
+ const lo = ((c << 8) | d).toString(16);
80
+ s = `${s.slice(0, lastColon + 1)}${hi}:${lo}`;
81
+ }
82
+ const halves = s.split("::");
83
+ if (halves.length > 2) return null;
84
+ let groups;
85
+ if (halves.length === 2) {
86
+ const left = halves[0] ? halves[0].split(":") : [];
87
+ const right = halves[1] ? halves[1].split(":") : [];
88
+ const fill = 8 - left.length - right.length;
89
+ if (fill < 1) return null;
90
+ groups = [...left, ...Array(fill).fill("0"), ...right];
91
+ } else {
92
+ groups = s.split(":");
93
+ }
94
+ if (groups.length !== 8) return null;
95
+ const words = groups.map((g) => (/^[0-9a-f]{1,4}$/i.test(g) ? parseInt(g, 16) : NaN));
96
+ return words.some(Number.isNaN) ? null : words;
97
+ }
98
+
49
99
  /**
50
- * Hostnames that must never be probed from a public registry. Enrollment
51
- * takes a URL from an unauthenticated stranger and makes the registry fetch
52
- * it, which is a server-side request forgery primitive unless it is fenced.
100
+ * Hostnames and IP literals that must never be probed from a public registry.
101
+ * Enrollment takes a URL from an unauthenticated stranger and makes the
102
+ * registry fetch it, which is a server-side request forgery primitive unless
103
+ * both literal addresses and resolved DNS answers are fenced.
53
104
  * Tests pass allowPrivateUrls to reach a loopback seed.
54
105
  */
55
- function isPrivateHost(host) {
56
- const h = host.toLowerCase();
57
- if (h === "localhost" || h.endsWith(".localhost") || h.endsWith(".local") || h.endsWith(".internal")) return true;
106
+ export function isPrivateHost(host) {
107
+ const raw = String(host ?? "").trim().toLowerCase();
108
+ const bracketed = raw.startsWith("[") || raw.endsWith("]");
109
+ let h = unwrapHost(raw);
110
+ if (!h || h.includes("%") || h.includes("[") || h.includes("]")) return true;
111
+ if (bracketed && isIP(h) !== 6) return true;
112
+ h = h.replace(/\.+$/, "");
113
+ if (!h || h === "localhost" || h.endsWith(".localhost") || h.endsWith(".local") || h.endsWith(".internal")) {
114
+ return true;
115
+ }
116
+ if (isIP(h) === 0) {
117
+ try {
118
+ const canonical = unwrapHost(new URL(`http://${h}`).hostname);
119
+ if (isIP(canonical) !== 0) h = canonical;
120
+ } catch (_e) { /* not an alternate IP literal */ }
121
+ }
58
122
  if (isIP(h) === 4) {
59
- const [a, b] = h.split(".").map(Number);
60
- if (a === 10 || a === 127 || a === 0) return true;
61
- if (a === 172 && b >= 16 && b <= 31) return true;
62
- if (a === 192 && b === 168) return true;
63
- if (a === 169 && b === 254) return true; // link-local / cloud metadata
64
- if (a === 100 && b >= 64 && b <= 127) return true; // CGNAT
65
- return false;
123
+ const [a, b, c, d] = h.split(".").map(Number);
124
+ return isPrivateIpv4Octets(a, b, c, d);
66
125
  }
67
126
  if (isIP(h) === 6) {
68
- return h === "::1" || h === "::" || h.startsWith("fc") || h.startsWith("fd") || h.startsWith("fe80");
127
+ const w = parseIpv6Words(h);
128
+ if (!w) return true;
129
+ const [w0, w1, w2, w3, w4, w5, w6, w7] = w;
130
+ // :: (unspecified) and ::1 (loopback)
131
+ if (w0 === 0 && w1 === 0 && w2 === 0 && w3 === 0 && w4 === 0 && w5 === 0 && w6 === 0 && (w7 === 0 || w7 === 1)) {
132
+ return true;
133
+ }
134
+ // fc00::/7 (unique local), fe80::/10 (link-local), ff00::/8 (multicast), 2001:db8::/32 (documentation)
135
+ if ((w0 & 0xfe00) === 0xfc00) return true;
136
+ if ((w0 & 0xffc0) === 0xfe80) return true;
137
+ if ((w0 & 0xff00) === 0xff00) return true;
138
+ if (w0 === 0x2001 && w1 === 0x0db8) return true;
139
+ // ::ffff:0:0/96 (IPv4-mapped) and ::/96 (IPv4-compatible)
140
+ if (w0 === 0 && w1 === 0 && w2 === 0 && w3 === 0 && w4 === 0 && (w5 === 0xffff || w5 === 0)) {
141
+ return isPrivateIpv4Octets(w6 >> 8, w6 & 0xff, w7 >> 8, w7 & 0xff);
142
+ }
143
+ // 64:ff9b::/96 (NAT64 well-known prefix)
144
+ if (w0 === 0x0064 && w1 === 0xff9b && w2 === 0 && w3 === 0 && w4 === 0 && w5 === 0) {
145
+ return isPrivateIpv4Octets(w6 >> 8, w6 & 0xff, w7 >> 8, w7 & 0xff);
146
+ }
147
+ // 2002::/16 (6to4: embedded IPv4 in bits 16..47 = w1, w2)
148
+ if (w0 === 0x2002) {
149
+ return isPrivateIpv4Octets(w1 >> 8, w1 & 0xff, w2 >> 8, w2 & 0xff);
150
+ }
151
+ return false;
69
152
  }
70
153
  return false;
71
154
  }
@@ -84,6 +167,200 @@ export function checkSeedUrl(raw, { allowPrivateUrls = false } = {}) {
84
167
  return { ok: true, url };
85
168
  }
86
169
 
170
+ function defaultLookup(hostname, options, callback) {
171
+ return dns.lookup(hostname, options, callback);
172
+ }
173
+
174
+ function callLookupAll(lookupFn, host, signal) {
175
+ if (signal?.aborted) {
176
+ return Promise.reject(signal.reason ?? new Error("DNS lookup timed out"));
177
+ }
178
+ let settled = false;
179
+ return new Promise((resolve, reject) => {
180
+ let onAbort;
181
+ const cleanup = () => {
182
+ if (signal && onAbort) signal.removeEventListener("abort", onAbort);
183
+ };
184
+ const done = (err, res) => {
185
+ if (settled) return;
186
+ settled = true;
187
+ cleanup();
188
+ if (err) reject(err);
189
+ else resolve(res);
190
+ };
191
+ if (signal) {
192
+ onAbort = () => {
193
+ done(signal.reason ?? new Error("DNS lookup timed out"));
194
+ };
195
+ signal.addEventListener("abort", onAbort, { once: true });
196
+ }
197
+ try {
198
+ const maybePromise = lookupFn(host, { all: true }, done);
199
+ if (maybePromise && typeof maybePromise.then === "function") {
200
+ maybePromise.then((res) => done(null, res), (err) => done(err));
201
+ }
202
+ } catch (e) {
203
+ done(e);
204
+ }
205
+ });
206
+ }
207
+
208
+ function makePinnedLookup(expectedHost, addresses) {
209
+ const frozen = addresses.map((a) => Object.freeze({ address: a.address, family: a.family }));
210
+ return function pinnedLookup(hostname, options, callback) {
211
+ if (typeof options === "function") {
212
+ callback = options;
213
+ options = {};
214
+ }
215
+ if (unwrapHost(hostname) !== expectedHost) {
216
+ const err = new Error(`refused lookup for unpinned host ${hostname} (expected ${expectedHost})`);
217
+ err.code = "ENOTFOUND";
218
+ return callback(err);
219
+ }
220
+ const wantFamily = typeof options === "number"
221
+ ? options
222
+ : (options?.family === 4 || options?.family === 6 ? options.family : 0);
223
+ const matches = wantFamily ? frozen.filter((a) => a.family === wantFamily) : frozen;
224
+ if (matches.length === 0) {
225
+ const err = new Error(`getaddrinfo ENOTFOUND ${hostname}`);
226
+ err.code = "ENOTFOUND";
227
+ return callback(err);
228
+ }
229
+ if (options && typeof options === "object" && options.all) {
230
+ return callback(null, matches.map((a) => ({ address: a.address, family: a.family })));
231
+ }
232
+ return callback(null, matches[0].address, matches[0].family);
233
+ };
234
+ }
235
+
236
+ /**
237
+ * Normalise a candidate seed URL, resolve its hostname with `{ all: true }`,
238
+ * refuse if any returned address is non-global, and return a `lookup` callback
239
+ * pinned to the validated addresses so a DNS rebind between check and connect
240
+ * cannot re-point the socket.
241
+ */
242
+ export async function resolveSeedUrl(
243
+ raw,
244
+ { allowPrivateUrls = false, lookup = defaultLookup, signal, timeoutMs = PROBE_TIMEOUT_MS } = {},
245
+ ) {
246
+ const checked = checkSeedUrl(raw, { allowPrivateUrls });
247
+ if (!checked.ok) return checked;
248
+ if (allowPrivateUrls) return { ok: true, url: checked.url, addresses: [], lookup: undefined };
249
+
250
+ const u = new URL(checked.url);
251
+ const host = unwrapHost(u.hostname);
252
+ const literalFamily = isIP(host);
253
+ if (literalFamily !== 0) {
254
+ const addresses = [{ address: host, family: literalFamily }];
255
+ return { ok: true, url: checked.url, addresses, lookup: makePinnedLookup(host, addresses) };
256
+ }
257
+
258
+ const lookupSignal = signal ?? (Number.isFinite(timeoutMs) && timeoutMs > 0 ? AbortSignal.timeout(timeoutMs) : undefined);
259
+ let rawAddrs;
260
+ try {
261
+ rawAddrs = await callLookupAll(lookup, host, lookupSignal);
262
+ } catch (e) {
263
+ return { ok: false, reason: `seed-unreachable: ${e?.message ?? e}` };
264
+ }
265
+ if (lookupSignal?.aborted) {
266
+ const err = lookupSignal.reason;
267
+ return { ok: false, reason: `seed-unreachable: ${err?.message ?? err ?? "DNS lookup timed out"}` };
268
+ }
269
+ const list = Array.isArray(rawAddrs) ? rawAddrs : (rawAddrs ? [rawAddrs] : []);
270
+ if (list.length === 0) {
271
+ return { ok: false, reason: "seed-unreachable: no addresses returned" };
272
+ }
273
+ const addresses = [];
274
+ for (const entry of list) {
275
+ const address = unwrapHost(typeof entry === "string" ? entry : entry?.address);
276
+ const family = isIP(address);
277
+ if (!family || isPrivateHost(address)) {
278
+ return { ok: false, reason: "private-address" };
279
+ }
280
+ addresses.push({ address, family });
281
+ }
282
+ return { ok: true, url: checked.url, addresses, lookup: makePinnedLookup(host, addresses) };
283
+ }
284
+
285
+ function raceSignal(promise, signal) {
286
+ if (!signal) return promise;
287
+ if (signal.aborted) return Promise.reject(signal.reason ?? new Error("probe timed out"));
288
+ return new Promise((resolve, reject) => {
289
+ const onAbort = () => reject(signal.reason ?? new Error("probe timed out"));
290
+ signal.addEventListener("abort", onAbort, { once: true });
291
+ Promise.resolve(promise).then(
292
+ (val) => {
293
+ signal.removeEventListener("abort", onAbort);
294
+ resolve(val);
295
+ },
296
+ (err) => {
297
+ signal.removeEventListener("abort", onAbort);
298
+ reject(err);
299
+ },
300
+ );
301
+ });
302
+ }
303
+
304
+ function defaultFetch(input, init = {}) {
305
+ const u = new URL(String(input));
306
+ const reqFn = u.protocol === "https:" ? httpsRequest : httpRequest;
307
+ const headers = { ...(init.headers ?? {}) };
308
+ const body = init.body !== undefined && init.body !== null ? Buffer.from(init.body) : null;
309
+ if (body && !Object.keys(headers).some((k) => k.toLowerCase() === "content-length")) {
310
+ headers["content-length"] = String(body.byteLength);
311
+ }
312
+ return new Promise((resolve, reject) => {
313
+ let settled = false;
314
+ const fail = (err) => {
315
+ if (settled) return;
316
+ settled = true;
317
+ reject(err);
318
+ };
319
+ const req = reqFn(
320
+ u,
321
+ {
322
+ method: init.method ?? "GET",
323
+ headers,
324
+ signal: init.signal,
325
+ lookup: init.lookup,
326
+ agent: false,
327
+ },
328
+ (res) => {
329
+ const chunks = [];
330
+ let bytes = 0;
331
+ res.on("data", (c) => {
332
+ bytes += c.length;
333
+ if (bytes > MAX_RESPONSE_BYTES) {
334
+ req.destroy(new Error("seed response too large"));
335
+ return;
336
+ }
337
+ chunks.push(c);
338
+ });
339
+ res.on("end", () => {
340
+ if (settled) return;
341
+ settled = true;
342
+ const buf = Buffer.concat(chunks);
343
+ const status = res.statusCode ?? 0;
344
+ resolve({
345
+ ok: status >= 200 && status < 300,
346
+ status,
347
+ headers: res.headers,
348
+ text: async () => buf.toString("utf-8"),
349
+ json: async () => JSON.parse(buf.toString("utf-8")),
350
+ });
351
+ });
352
+ res.on("error", fail);
353
+ },
354
+ );
355
+ req.on("error", fail);
356
+ req.on("close", () => {
357
+ if (!settled) fail(init.signal?.reason ?? new Error("request closed prematurely"));
358
+ });
359
+ if (body) req.write(body);
360
+ req.end();
361
+ });
362
+ }
363
+
87
364
  /** Verify a /v1/seed-info document: signature, key/uuaid binding, URL match. */
88
365
  export function verifySeedInfo(doc, expectedUrl) {
89
366
  if (doc?.v !== 1) return { ok: false, reason: "bad-version" };
@@ -116,15 +393,28 @@ export class SeedRegistry {
116
393
  * dbPath SQLite path
117
394
  * protocol directory.protocol string
118
395
  * fetchImpl injectable fetch (tests)
396
+ * lookup injectable dns.lookup (tests)
119
397
  * allowPrivateUrls permit loopback seeds (tests / local networks)
120
398
  */
121
- constructor({ keychain, carrierUrl, dbPath = "seed-registry.db", protocol = "uacp/1.0-draft", fetchImpl = globalThis.fetch, allowPrivateUrls = false } = {}) {
399
+ constructor({
400
+ keychain,
401
+ carrierUrl,
402
+ dbPath = "seed-registry.db",
403
+ protocol = "uacp/1.0-draft",
404
+ fetchImpl = defaultFetch,
405
+ lookup = defaultLookup,
406
+ lookupImpl,
407
+ allowPrivateUrls = false,
408
+ probeTimeoutMs = PROBE_TIMEOUT_MS,
409
+ } = {}) {
122
410
  if (!keychain?._identity) throw new Error("SeedRegistry needs a loaded keychain");
123
411
  this.keychain = keychain;
124
412
  this.carrierUrl = carrierUrl ? String(carrierUrl).replace(/\/+$/, "") : null;
125
413
  this.protocol = protocol;
126
414
  this.fetch = fetchImpl;
415
+ this.lookup = lookupImpl ?? lookup;
127
416
  this.allowPrivateUrls = allowPrivateUrls;
417
+ this.probeTimeoutMs = probeTimeoutMs;
128
418
  this.db = new Database(dbPath);
129
419
  this.db.pragma("journal_mode = WAL");
130
420
  this.db.exec(`
@@ -187,34 +477,50 @@ export class SeedRegistry {
187
477
  * have to care whether it enrolled before.
188
478
  */
189
479
  async enroll({ url, operator = null, region = null, now = Date.now() }) {
190
- const checked = checkSeedUrl(url, { allowPrivateUrls: this.allowPrivateUrls });
191
- if (!checked.ok) return { ok: false, reason: checked.reason };
480
+ const signal = AbortSignal.timeout(this.probeTimeoutMs);
481
+ const resolved = await resolveSeedUrl(url, {
482
+ allowPrivateUrls: this.allowPrivateUrls,
483
+ lookup: this.lookup,
484
+ signal,
485
+ });
486
+ if (!resolved.ok) return { ok: false, reason: resolved.reason };
487
+ if (signal.aborted) {
488
+ const err = signal.reason;
489
+ return { ok: false, reason: `seed-unreachable: ${err?.message ?? err ?? "probe timed out"}` };
490
+ }
192
491
 
193
492
  let doc;
194
493
  try {
195
- const res = await this.fetch(`${checked.url}/v1/seed-info`, { signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) });
494
+ const res = await raceSignal(
495
+ this.fetch(`${resolved.url}/v1/seed-info`, {
496
+ signal,
497
+ redirect: "manual",
498
+ ...(resolved.lookup ? { lookup: resolved.lookup } : {}),
499
+ }),
500
+ signal,
501
+ );
196
502
  if (!res.ok) return { ok: false, reason: `seed-info-${res.status}` };
197
- doc = await res.json();
503
+ doc = await raceSignal(res.json(), signal);
198
504
  } catch (e) {
199
- return { ok: false, reason: `seed-unreachable: ${e.message}` };
505
+ return { ok: false, reason: `seed-unreachable: ${e?.message ?? e}` };
200
506
  }
201
- const v = verifySeedInfo(doc, checked.url);
507
+ const v = verifySeedInfo(doc, resolved.url);
202
508
  if (!v.ok) return { ok: false, reason: `seed-info-invalid:${v.reason}` };
203
509
 
204
510
  const existing = this.get(doc.uuaid);
205
511
  if (existing) {
206
- if (existing.url !== checked.url) return { ok: false, reason: "uuaid-already-enrolled-at-other-url" };
512
+ if (existing.url !== resolved.url) return { ok: false, reason: "uuaid-already-enrolled-at-other-url" };
207
513
  return { ok: true, already: true, ...this.status(doc.uuaid) };
208
514
  }
209
515
  // A URL can only ever belong to one identity: otherwise a second key
210
516
  // could enroll the same host and inherit its observed history.
211
- const urlTaken = this.db.prepare("select uuaid from seeds where url = ?").get(checked.url);
517
+ const urlTaken = this.db.prepare("select uuaid from seeds where url = ?").get(resolved.url);
212
518
  if (urlTaken) return { ok: false, reason: "url-already-enrolled" };
213
519
 
214
520
  this.db.prepare(`
215
521
  insert into seeds (uuaid, url, public_key, operator, region, enrolled_at, tier, claimed)
216
522
  values (?,?,?,?,?,?,'probation',?)
217
- `).run(doc.uuaid, checked.url, doc.publicKey.toLowerCase(), operator, region,
523
+ `).run(doc.uuaid, resolved.url, doc.publicKey.toLowerCase(), operator, region,
218
524
  new Date(now).toISOString(), JSON.stringify(doc.stats ?? {}));
219
525
  return { ok: true, already: false, ...this.status(doc.uuaid) };
220
526
  }
@@ -263,9 +569,23 @@ export class SeedRegistry {
263
569
  /** GET <url>/v1/health — the liveness half of an observation. */
264
570
  async healthProbe(row) {
265
571
  try {
266
- const res = await this.fetch(`${row.url}/v1/health`, { signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) });
572
+ const signal = AbortSignal.timeout(this.probeTimeoutMs);
573
+ const resolved = await resolveSeedUrl(row.url, {
574
+ allowPrivateUrls: this.allowPrivateUrls,
575
+ lookup: this.lookup,
576
+ signal,
577
+ });
578
+ if (!resolved.ok || signal.aborted) return false;
579
+ const res = await raceSignal(
580
+ this.fetch(`${resolved.url}/v1/health`, {
581
+ signal,
582
+ redirect: "manual",
583
+ ...(resolved.lookup ? { lookup: resolved.lookup } : {}),
584
+ }),
585
+ signal,
586
+ );
267
587
  if (!res.ok) return false;
268
- const body = await res.json();
588
+ const body = await raceSignal(res.json(), signal);
269
589
  return body?.ok === true;
270
590
  } catch (_e) { return false; }
271
591
  }
@@ -279,6 +599,19 @@ export class SeedRegistry {
279
599
  * answers /v1/health and drops mail.
280
600
  */
281
601
  async roundTripProbe(row, { now = Date.now() } = {}) {
602
+ const postSignal = AbortSignal.timeout(this.probeTimeoutMs);
603
+ const resolved = await resolveSeedUrl(row.url, {
604
+ allowPrivateUrls: this.allowPrivateUrls,
605
+ lookup: this.lookup,
606
+ signal: postSignal,
607
+ });
608
+ if (!resolved.ok) return { ok: false, reason: resolved.reason };
609
+ if (postSignal.aborted) {
610
+ const err = postSignal.reason;
611
+ return { ok: false, reason: `seed-unreachable: ${err?.message ?? err ?? "probe timed out"}` };
612
+ }
613
+ const lookupOpt = resolved.lookup ? { lookup: resolved.lookup } : {};
614
+
282
615
  const me = this.keychain._identity;
283
616
  let envelope;
284
617
  try {
@@ -291,14 +624,19 @@ export class SeedRegistry {
291
624
  } catch (e) { return { ok: false, reason: `seal-failed: ${e.message}` }; }
292
625
 
293
626
  try {
294
- const post = await this.fetch(`${row.url}/v1/envelopes`, {
295
- method: "POST",
296
- headers: { "content-type": "application/json" },
297
- body: JSON.stringify(envelope),
298
- signal: AbortSignal.timeout(PROBE_TIMEOUT_MS),
299
- });
627
+ const post = await raceSignal(
628
+ this.fetch(`${resolved.url}/v1/envelopes`, {
629
+ method: "POST",
630
+ headers: { "content-type": "application/json" },
631
+ body: JSON.stringify(envelope),
632
+ signal: postSignal,
633
+ redirect: "manual",
634
+ ...lookupOpt,
635
+ }),
636
+ postSignal,
637
+ );
300
638
  if (post.status !== 202) return { ok: false, reason: `deliver-${post.status}` };
301
- const receipt = await post.json();
639
+ const receipt = await raceSignal(post.json(), postSignal);
302
640
  if (!receipt?.accepted) return { ok: false, reason: "deliver-not-accepted" };
303
641
 
304
642
  // Poll from just below the receipt seq so the probe envelope is in
@@ -307,19 +645,25 @@ export class SeedRegistry {
307
645
  const path = `GET /v1/inbox/${me.uuaid}?since=${since}`;
308
646
  const ts = String(Date.now());
309
647
  const sig = this.keychain.sign(Buffer.from(`${path}\n${ts}`, "utf-8")).toString("hex");
310
- const res = await this.fetch(
311
- `${row.url}/v1/inbox/${encodeURIComponent(me.uuaid)}?since=${since}&wait=${ROUND_TRIP_WAIT_S}`,
312
- {
313
- headers: { "x-pillar-pubkey": me.publicKeyHex, "x-pillar-ts": ts, "x-pillar-sig": sig },
314
- signal: AbortSignal.timeout(PROBE_TIMEOUT_MS + ROUND_TRIP_WAIT_S * 1000),
315
- },
648
+ const getSignal = AbortSignal.timeout(this.probeTimeoutMs + ROUND_TRIP_WAIT_S * 1000);
649
+ const res = await raceSignal(
650
+ this.fetch(
651
+ `${resolved.url}/v1/inbox/${encodeURIComponent(me.uuaid)}?since=${since}&wait=${ROUND_TRIP_WAIT_S}`,
652
+ {
653
+ headers: { "x-pillar-pubkey": me.publicKeyHex, "x-pillar-ts": ts, "x-pillar-sig": sig },
654
+ signal: getSignal,
655
+ redirect: "manual",
656
+ ...lookupOpt,
657
+ },
658
+ ),
659
+ getSignal,
316
660
  );
317
661
  if (res.status !== 200) return { ok: false, reason: `inbox-${res.status}` };
318
- const body = await res.json();
662
+ const body = await raceSignal(res.json(), getSignal);
319
663
  const found = (body?.envelopes ?? []).some(e => e?.envelope?.id === envelope.id);
320
664
  return found ? { ok: true } : { ok: false, reason: "envelope-not-returned" };
321
665
  } catch (e) {
322
- return { ok: false, reason: `probe-threw: ${e.message}` };
666
+ return { ok: false, reason: `probe-threw: ${e?.message ?? e}` };
323
667
  }
324
668
  }
325
669
 
@@ -31,7 +31,7 @@ import { dcutr } from "@libp2p/dcutr";
31
31
  import { autoNAT } from "@libp2p/autonat";
32
32
  import { ping } from "@libp2p/ping";
33
33
  import { privateKeyFromRaw, publicKeyFromRaw } from "@libp2p/crypto/keys";
34
- import { peerIdFromPublicKey } from "@libp2p/peer-id";
34
+ import { peerIdFromPublicKey, peerIdFromPrivateKey } from "@libp2p/peer-id";
35
35
  import { createHash } from "node:crypto";
36
36
 
37
37
  export const PILLAR_PROTOCOL = "/uuaid/pillar/1.0.0";
@@ -98,6 +98,18 @@ export function uuaidToDhtKey(uuaid) {
98
98
  return createHash("sha256").update(uuaid, "utf-8").digest();
99
99
  }
100
100
 
101
+ /**
102
+ * The libp2p PeerId of a node that createTransport starts with this 32-byte
103
+ * seed. privateKeyFromRaw reads 32 raw bytes as a secp256k1 key, so the PeerId
104
+ * cannot be derived from the identity's Ed25519 public key; `pillar id` uses
105
+ * this to print it without starting a node (2.5.3).
106
+ */
107
+ export function peerIdFromSeedHex(seedHex) {
108
+ const seed = Buffer.from(seedHex, "hex");
109
+ if (seed.length !== 32) throw new Error("seedHex must be 32 raw bytes hex");
110
+ return peerIdFromPrivateKey(privateKeyFromRaw(seed));
111
+ }
112
+
101
113
  /**
102
114
  * Convert a raw Ed25519 public key hex to a libp2p PeerId. This is how
103
115
  * a peer given only a UUAID's public key can dial that peer.
@@ -99,14 +99,14 @@ export class Observability {
99
99
  journal({ event, ...fields }) {
100
100
  if (!this.sinkPath) return;
101
101
  mkdirSync(dirname(this.sinkPath), { recursive: true });
102
- appendFileSync(this.sinkPath, JSON.stringify({ at: new Date().toISOString(), event, ...fields }) + "\n");
102
+ appendFileSync(this.sinkPath, JSON.stringify({ at: new Date().toISOString(), event, ...fields }) + "\n", { mode: 0o600 });
103
103
  }
104
104
 
105
105
  /** Append a full state snapshot line to the sink (no-op without a sinkPath). */
106
106
  flush() {
107
107
  if (!this.sinkPath) return;
108
108
  mkdirSync(dirname(this.sinkPath), { recursive: true });
109
- appendFileSync(this.sinkPath, JSON.stringify({ type: "snapshot", ...this.snapshot() }) + "\n");
109
+ appendFileSync(this.sinkPath, JSON.stringify({ type: "snapshot", ...this.snapshot() }) + "\n", { mode: 0o600 });
110
110
  }
111
111
 
112
112
  /* ------------------------------------------------ read paths --------- */
package/src/pillar.mjs CHANGED
@@ -314,18 +314,36 @@ export class Pillar {
314
314
  });
315
315
 
316
316
  // 1. Address book path: direct libp2p dial (lowest latency, no third party).
317
+ // A stream that closes is not a receipt: nothing tells us the recipient read
318
+ // it, and against throttled receivers most such sends were lost while marked
319
+ // delivered (2.5.3). So with carriers configured the envelope also goes to
320
+ // them, in parallel, and only a carrier's acceptance marks the row delivered
321
+ // (what status 'delivered' has always meant, mailbox.mjs). The recipient's
322
+ // mailbox keys on (sender, envelope id), so a copy that arrives both ways is
323
+ // stored and handled once.
317
324
  if (this.node && book?.peerId && book?.multiaddr) {
318
- try {
319
- const delivery = await this._deliverToPeer(envelope, book.peerId, book.multiaddr);
320
- this.metrics.inc("send.via.direct");
321
- this.metrics.observe("send.latencyMs.via.direct", Date.now() - t0);
322
- return { envelope, persisted, via: "direct", delivery };
323
- } catch (e) {
324
- if (!this.carrierClient) {
325
- this.metrics.inc("send.error.direct-delivery-failed");
326
- throw e;
327
- } // else fall through to carrier
325
+ const [direct, carrier] = await Promise.allSettled([
326
+ this._deliverToPeer(envelope, book.peerId, book.multiaddr),
327
+ this.carrierClient ? this.carrierClient.deliver(envelope) : Promise.resolve(null),
328
+ ]);
329
+ const sentDirect = direct.status === "fulfilled" ? direct.value : null;
330
+ if (carrier.status === "fulfilled" && carrier.value) {
331
+ this.mailbox.markOutboundDelivered(envelope.id, envelopeSha(envelope));
332
+ const via = sentDirect ? "direct+carrier" : "carrier";
333
+ this.metrics.inc(`send.via.${via}`);
334
+ this.metrics.observe(`send.latencyMs.via.${via}`, Date.now() - t0);
335
+ return { envelope, persisted, via, delivery: carrier.value, direct: sentDirect, confirmed: true };
336
+ }
337
+ if (sentDirect) {
338
+ // Written to a stream, and no carrier holds a copy: nothing confirms it
339
+ // arrived, so the row stays pending (the recipient's signed ack, if it
340
+ // sends one, is recorded when it comes).
341
+ this.metrics.inc("send.via.direct-unconfirmed");
342
+ return { envelope, persisted, via: "direct", delivery: sentDirect, direct: sentDirect, confirmed: false,
343
+ carrierError: carrier.status === "rejected" ? carrier.reason : null };
328
344
  }
345
+ this.metrics.inc("send.error.direct-delivery-failed");
346
+ throw carrier.status === "rejected" ? carrier.reason : direct.reason;
329
347
  }
330
348
 
331
349
  // 2. Carrier path: universal store-and-forward.
@@ -352,7 +370,8 @@ export class Pillar {
352
370
  const delivery = await this._deliverToPeer(envelope, dhtAdvert.peerId, dhtAdvert.addrs?.[0]);
353
371
  this.metrics.inc("send.via.dht");
354
372
  this.metrics.observe("send.latencyMs.via.dht", Date.now() - t0);
355
- return { envelope, persisted, via: "dht", delivery };
373
+ // No carrier: a closed stream confirms nothing, so the row stays pending.
374
+ return { envelope, persisted, via: "dht", delivery, direct: delivery, confirmed: false };
356
375
  }
357
376
 
358
377
  /**
@@ -585,7 +604,7 @@ export class Pillar {
585
604
  const line = JSON.stringify(envelope) + "\n";
586
605
  stream.send(u8FromString(line));
587
606
  await stream.close();
588
- this.mailbox.markOutboundDelivered(envelope.id, envelopeSha(envelope));
607
+ // Not marked delivered here: a closed stream is not a receipt (2.5.3).
589
608
  return { peerId: peerIdStr };
590
609
  }
591
610
 
@@ -633,7 +652,7 @@ export class Pillar {
633
652
  const line = JSON.stringify(envelope) + "\n";
634
653
  stream.send(u8FromString(line));
635
654
  await stream.close();
636
- this.mailbox.markOutboundDelivered(envelope.id, envelopeSha(envelope));
655
+ // Not marked delivered: a closed stream is not a receipt (2.5.3).
637
656
  return envelope;
638
657
  }
639
658
 
@@ -107,8 +107,9 @@ function staleBackupFiles(dbFile) {
107
107
  .map((f) => join(dirname(dbFile), f));
108
108
  }
109
109
 
110
- function removeBackup(backup) {
111
- for (const f of [backup, `${backup}-journal`]) rmSync(f, { force: true });
110
+ /** The backup and every file SQLite may leave beside it (2.5.3, AC7-Kimi d: -wal and -shm too). */
111
+ export function removeBackup(backup) {
112
+ for (const f of [backup, `${backup}-journal`, `${backup}-wal`, `${backup}-shm`]) rmSync(f, { force: true });
112
113
  }
113
114
 
114
115
  /**