@uuaid/pillar 2.7.3 → 2.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -31,7 +31,8 @@ import { createServer } from "node:http";
31
31
  import { readFileSync, existsSync, mkdirSync } from "node:fs";
32
32
  import { homedir } from "node:os";
33
33
  import { join } from "node:path";
34
- import { SeedRegistry } from "../src/net/seed-registry.mjs";
34
+ import { SeedRegistry, parseFleetRelays } from "../src/net/seed-registry.mjs";
35
+ import { isRelayedSeedUrl } from "../src/net/tunnel.mjs";
35
36
  import { clientIpOf, parseTrustedProxies } from "../src/net/client-ip.mjs";
36
37
  import { Keychain, mintNamespace, SERVICE_IDENTITY_NAMESPACE } from "../src/identity/keychain.mjs";
37
38
  import { tryLoadBetterSqlite3 } from "../src/sqlite-loader.mjs";
@@ -66,10 +67,14 @@ The first start mints the registry key in --home.
66
67
  --peers <url,...> peer registries (DIRECTORY_PEERS)
67
68
  --trusted-proxy <ips> whose X-Forwarded-For counts (DIRECTORY_TRUSTED_PROXIES)
68
69
  --probe-minutes <n> seed probe interval (DIRECTORY_PROBE_MINUTES, default 10)
70
+ --fleet-relays <file> relay origins and keys this registry pins, one "<origin> <key hex>"
71
+ per line; only seeds on these are vetted and granted (2.8.1 lists
72
+ a relayed seed on any relay for reach, after a v2 round trip)
73
+ (DIRECTORY_FLEET_RELAYS; default none)
69
74
  -h, --help print this help and exit
70
75
 
71
76
  More flags (limits, federation timers, test hooks): --protocol, --allow-private-urls,
72
- --url-map, --clock-file, --stamp-bits, --max-new-lineages-per-hour,
77
+ --url-map, --clock-file, --stamp-bits, --probe-interval-ms, --max-new-lineages-per-hour,
73
78
  --max-listings-per-ip-per-hour, --max-lineage-posts-per-ip-per-hour,
74
79
  --max-heartbeats-per-ip-per-hour, --pull-interval-ms, --max-strikes,
75
80
  --quarantine-cooldown-ms, --resolve-timeout-ms, --resolve-negative-ttl-ms,
@@ -93,10 +98,33 @@ const port = opts.port;
93
98
  const host = opts.host ?? "127.0.0.1";
94
99
  const dbPath = opts.db ?? join(home, "registry.db");
95
100
  const carrier = opts.carrier ?? null;
101
+ // 2.8.0 (RedTeam 22f6c3 Q2): directory.json never names a relayed seed URL
102
+ // (<relay origin>/e/<id>) as its bootstrap carrier.
103
+ if (typeof carrier === "string" && isRelayedSeedUrl(carrier)) {
104
+ console.error("pillar-directory: --carrier/DIRECTORY_CARRIER is a relayed seed URL (<origin>/e/<id>); the bootstrap carrier is never a relayed seed (2.8.1 lists relayed seeds in seeds[] with their relay, for reach only). Name a direct carrier; clients reach a relayed seed with pillar init --carriers <url>.");
105
+ process.exit(2);
106
+ }
96
107
  const agentsPath = opts.agents ?? null;
97
108
  const protocol = opts.protocol ?? "uacp/1.0-draft";
98
109
  const probeMinutes = opts["probe-minutes"];
110
+ // Test hook (2.8.0, like --pull-interval-ms): the probe interval in milliseconds
111
+ // (100 or more), overriding --probe-minutes, so tests can watch probes, demotion
112
+ // and recovery. Unset: --probe-minutes.
113
+ const probeIntervalMs = opts["probe-interval-ms"];
114
+ // The interval the probe loop really runs at. The registry sizes a relayed
115
+ // seed's vetting lease from it: min(3 x interval, 30 min) (RedTeam 22f6c3 Q1).
116
+ const effectiveProbeMs = probeIntervalMs ?? probeMinutes * 60_000;
99
117
  const allowPrivateUrls = opts["allow-private-urls"];
118
+ // Fleet relays (2.8.0): the relay origins and attestation keys this registry pins.
119
+ // A relayed seed is vetted and granted only on one of these. None by default.
120
+ // 2.8.1: a relayed seed on any relay is listed for reach (no vetting, no grant)
121
+ // once a round trip with inbox auth v2 passed for its current pin.
122
+ const fleetRelaysPath = opts["fleet-relays"] ?? null;
123
+ let fleetRelays = new Map();
124
+ if (fleetRelaysPath !== null) {
125
+ try { fleetRelays = parseFleetRelays(readFileSync(fleetRelaysPath, "utf-8")); }
126
+ catch (e) { console.error(`pillar-directory: --fleet-relays ${fleetRelaysPath}: ${e.code ?? e.message}`); process.exit(2); }
127
+ }
100
128
  const publicUrlArg = opts["public-url"] ?? null;
101
129
  const urlMap = opts.urlMap;
102
130
  const clockFile = opts["clock-file"] ?? null;
@@ -137,7 +165,7 @@ const statsAggregates = new Map();
137
165
 
138
166
  const hasSqlite = Boolean(tryLoadBetterSqlite3());
139
167
  const registry = hasSqlite
140
- ? new SeedRegistry({ keychain, carrierUrl: carrier, dbPath, protocol, allowPrivateUrls })
168
+ ? new SeedRegistry({ keychain, carrierUrl: carrier, dbPath, protocol, allowPrivateUrls, fleetRelays, probeIntervalMs: effectiveProbeMs })
141
169
  : (() => {
142
170
  const fallbackDb = openRegistryDb(dbPath, { forcePureJs: true });
143
171
  const normCarrier = carrier ? String(carrier).replace(/\/+$/, "") : null;
@@ -372,7 +400,8 @@ const server = createServer(async (req, res) => {
372
400
  if (!grant) {
373
401
  const known = registry.get(uuaid);
374
402
  return send(res, known ? 200 : 404,
375
- known ? { ok: true, grant: null, reason: "tier-earns-no-grant", tier: known.tier }
403
+ // The evaluated tier (topology cap, vetting), as /v1/seeds/<uuaid> reports it (2.8.0).
404
+ known ? { ok: true, grant: null, reason: "tier-earns-no-grant", tier: registry.status(uuaid).tier }
376
405
  : { ok: false, reason: "unknown-seed" });
377
406
  }
378
407
  return send(res, 200, { ok: true, grant });
@@ -436,7 +465,7 @@ const probeTimer = setInterval(async () => {
436
465
  } finally {
437
466
  probing = false;
438
467
  }
439
- }, Math.max(1, probeMinutes) * 60_000);
468
+ }, effectiveProbeMs);
440
469
 
441
470
  const shutdown = async () => {
442
471
  clearInterval(probeTimer);
@@ -5,6 +5,7 @@
5
5
  *
6
6
  * pillar-seed --port 8799 --db /opt/pillar-seed/seed.db
7
7
  * pillar-seed --public-url https://seed.example.org --announce https://<registry>
8
+ * pillar-seed --relay https://<relay> --announce https://<registry>
8
9
  * pillar-seed --status --announce https://<registry>
9
10
  * pillar-seed --help
10
11
  *
@@ -39,15 +40,27 @@
39
40
  * Defaults to loopback (RedTeam F5). To become a real seed, put it behind a
40
41
  * TLS-terminating proxy (nginx/Caddy) and pass the PUBLIC https:// URL as
41
42
  * --public-url — never the loopback one.
43
+ *
44
+ * SEED OVER EGRESS (2.8.0)
45
+ *
46
+ * A machine with outbound-only network (a cloud VM, a laptop behind NAT) runs
47
+ * a seed with --relay <origin> instead: the seed stays on 127.0.0.1, opens one
48
+ * outbound WebSocket to that relay carrier, and is served at
49
+ * <origin>/e/<id>. The relay must list this seed's uuaid on its allow-file
50
+ * (2.8.1: an open relay, --accept-tunnels open, admits any seed that proves
51
+ * its uuaid key).
52
+ * See src/net/tunnel-client.mjs and the README "Egress seed" section.
42
53
  */
43
54
  import "../src/node-check.mjs"; // must stay the first import: refuses Node < 22 before any dependency loads
44
55
  import { chmodSync, closeSync, constants as fsConstants, existsSync, fstatSync, mkdirSync, openSync, readSync, statSync } from "node:fs";
45
- import { createServer } from "node:net";
56
+ import { createServer, isIP } from "node:net";
46
57
  import { homedir } from "node:os";
47
58
  import { join, resolve } from "node:path";
48
- import { CarrierServer, parseSecureDelete, parseCommunityWaits, MAX_TTL_DAYS } from "../src/net/carrier-server.mjs";
59
+ import { CarrierServer, ResponseBudget, parseSecureDelete, parseCommunityWaits, MAX_TTL_DAYS } from "../src/net/carrier-server.mjs";
49
60
  import { parseTrustedProxies } from "../src/net/client-ip.mjs";
50
61
  import { Keychain, keyDerivesUuaid, mintNamespace, SERVICE_IDENTITY_NAMESPACE } from "../src/identity/keychain.mjs";
62
+ import { canonicalOrigin, relayedUrlFor, relayShapeOrigin } from "../src/net/tunnel.mjs";
63
+ import { TunnelClient } from "../src/net/tunnel-client.mjs";
51
64
 
52
65
  const USAGE = `usage: pillar-seed [flags]
53
66
 
@@ -66,6 +79,19 @@ and pass the proxy's address as --public-url.
66
79
  --port <n> listen port (SEED_PORT, default 8799)
67
80
  --ttl <days> envelope lifetime (SEED_TTL_DAYS, default 14, at most 36500)
68
81
  --public-url <https://> the URL your proxy serves (SEED_PUBLIC_URL)
82
+ --relay <https://origin> serve this seed through a relay carrier instead of a
83
+ public URL: one outbound tunnel, served at
84
+ <origin>/e/<id> (SEED_RELAY). Not with --public-url;
85
+ --host stays 127.0.0.1 or ::1
86
+ --takeover-wait <s> with --relay: how long to wait for another process
87
+ serving this seed key at the relay to stop, then
88
+ exit 2, at start or later (after a relay restart)
89
+ (SEED_TAKEOVER_WAIT, default 45, 0 to 3600)
90
+ --response-budget <MiB> with --relay: the most inbox-page bytes this seed
91
+ holds for clients at once; a read past it gets 503
92
+ seed-busy (SEED_RESPONSE_BUDGET, default 32, 4 to 4096)
93
+ --tunnel-retry-ms <n> test hook, with --relay: first reconnect delay in ms
94
+ (the backoff doubles to at most 8 x n), 50 to 1000
69
95
  --secure-delete <on|off> zero expired envelopes (SEED_SECURE_DELETE, default on)
70
96
  --community-waits <n> long-poll slots (SEED_COMMUNITY_WAITS, default 48)
71
97
  --trusted-proxy <ips> whose X-Forwarded-For counts for per-IP budgets
@@ -95,10 +121,10 @@ key. Every refusal is one line on stderr, with exit code 2.`;
95
121
  // Every flag this command reads. Every other token is refused before the seed
96
122
  // key or the database is touched, so a typo, a bare word or `--help` never
97
123
  // starts a seed.
98
- const FLAGS = new Set(["announce", "community-waits", "db", "help", "home", "host", "namespace", "operator", "passphrase-file", "port", "public-url", "region", "secure-delete", "status", "trusted-proxy", "ttl"]);
124
+ const FLAGS = new Set(["announce", "community-waits", "db", "help", "home", "host", "namespace", "operator", "passphrase-file", "port", "public-url", "region", "relay", "response-budget", "secure-delete", "status", "takeover-wait", "trusted-proxy", "ttl", "tunnel-retry-ms"]);
99
125
  // Flags that only mean something with a value. Given bare, 2.4 fell through to a
100
126
  // later crash (--home, --db) or a wrong value (--port meant port 1).
101
- const VALUE_FLAGS = ["announce", "community-waits", "db", "home", "host", "namespace", "operator", "passphrase-file", "port", "public-url", "region", "trusted-proxy", "ttl"];
127
+ const VALUE_FLAGS = ["announce", "community-waits", "db", "home", "host", "namespace", "operator", "passphrase-file", "port", "public-url", "region", "relay", "response-budget", "takeover-wait", "trusted-proxy", "ttl", "tunnel-retry-ms"];
102
128
  // Flags that take no value in either form. `--help=` would otherwise set help to
103
129
  // "" (falsy) and start a seed; `--status help` would swallow the word.
104
130
  const BOOL_FLAGS = new Set(["help", "status"]);
@@ -106,7 +132,7 @@ const BOOL_FLAGS = new Set(["help", "status"]);
106
132
  // refused like a bare flag: in 2.4 an empty SEED_HOST listened on every
107
133
  // interface, an empty SEED_PORT took a random port, and an empty SEED_DB kept
108
134
  // mail only in memory.
109
- const SEED_ENV = ["SEED_COMMUNITY_WAITS", "SEED_DB", "SEED_HOME", "SEED_HOST", "SEED_KEYCHAIN_PASSPHRASE", "SEED_NAMESPACE", "SEED_OPERATOR", "SEED_PORT", "SEED_PUBLIC_URL", "SEED_REGION", "SEED_SECURE_DELETE", "SEED_TRUSTED_PROXIES", "SEED_TTL_DAYS"];
135
+ const SEED_ENV = ["SEED_COMMUNITY_WAITS", "SEED_DB", "SEED_HOME", "SEED_HOST", "SEED_KEYCHAIN_PASSPHRASE", "SEED_NAMESPACE", "SEED_OPERATOR", "SEED_PORT", "SEED_PUBLIC_URL", "SEED_REGION", "SEED_RELAY", "SEED_RESPONSE_BUDGET", "SEED_SECURE_DELETE", "SEED_TAKEOVER_WAIT", "SEED_TRUSTED_PROXIES", "SEED_TTL_DAYS"];
110
136
 
111
137
  const VALUE_SET = new Set(VALUE_FLAGS);
112
138
  // The longest envelope lifetime accepted, MAX_TTL_DAYS (36500, 100 years), comes
@@ -207,7 +233,7 @@ const ttlDays = Number(ttlText);
207
233
  // Digits with an optional decimal part: Number() alone also took "0x10", "1e3", "+14" and " 14".
208
234
  if (!/^[0-9]+(\.[0-9]+)?$/.test(ttlText) || !(ttlDays > 0)) refuse(`--ttl must be a positive number of days written as digits (14, 7.5), not ${JSON.stringify(ttlText)}`);
209
235
  if (ttlDays > MAX_TTL_DAYS) refuse(`--ttl must be at most ${MAX_TTL_DAYS} days (100 years), not ${JSON.stringify(ttlText)}`);
210
- const publicUrl = args["public-url"] ?? process.env.SEED_PUBLIC_URL ?? null;
236
+ let publicUrl = args["public-url"] ?? process.env.SEED_PUBLIC_URL ?? null;
211
237
  const registryUrl = typeof args.announce === "string" ? args.announce.replace(/\/+$/, "") : null;
212
238
  const operator = args.operator ?? process.env.SEED_OPERATOR ?? null;
213
239
  const region = args.region ?? process.env.SEED_REGION ?? null;
@@ -231,6 +257,49 @@ try {
231
257
  } catch (e) {
232
258
  refuse(e.message);
233
259
  }
260
+ // --relay (2.8.0): served through a relay's tunnel, so this seed never listens
261
+ // beyond this machine, and its own carrier must trust the tunnel's loopback
262
+ // replay for X-Forwarded-For or every client would share one per-IP budget.
263
+ let relayOrigin = null;
264
+ const relayText = args.relay ?? process.env.SEED_RELAY ?? null;
265
+ if (relayText !== null) {
266
+ if (publicUrl !== null) refuse("--relay and --public-url do not go together: a relayed seed is served at <relay>/e/<id>, which pillar-seed sets itself");
267
+ const c = canonicalOrigin(relayText);
268
+ // The value is never echoed: a refused origin may carry credentials (as --public-url, AC2 fa0be869 P2).
269
+ if (!c.ok) refuse(`--relay must be a relay origin such as https://relay.example.org (${c.reason}); the value is not shown`);
270
+ relayOrigin = c.origin;
271
+ const loopHost = host === "::1" || (/^127\.\d+\.\d+\.\d+$/.test(host));
272
+ if (!loopHost) refuse(`--relay keeps the seed on this machine: --host must be 127.0.0.1 or ::1, not ${JSON.stringify(host)}`);
273
+ if (!trustedProxies.includes(host)) refuse(`--relay replays each request to this seed from ${host}: --trusted-proxy must include ${host}`);
274
+ }
275
+ // --takeover-wait (2.8.0, V1 2b5070): another process with this seed key holds
276
+ // the relay; wait this long for it to go, then exit rather than fight it.
277
+ const takeoverText = args["takeover-wait"] ?? process.env.SEED_TAKEOVER_WAIT ?? null;
278
+ let takeoverWaitMs;
279
+ if (takeoverText !== null) {
280
+ if (relayOrigin === null) refuse("--takeover-wait applies only with --relay");
281
+ if (!/^[0-9]+$/.test(String(takeoverText)) || Number(takeoverText) > 3600) refuse(`--takeover-wait must be a whole number of seconds from 0 to 3600, not ${JSON.stringify(String(takeoverText))}`);
282
+ takeoverWaitMs = Number(takeoverText) * 1000;
283
+ }
284
+ // --tunnel-retry-ms (2.8.0, test hook like pillar-directory's --probe-interval-ms):
285
+ // short reconnect delays so tests can restart a relay many times quickly.
286
+ // --response-budget (2.8.0, RedTeam 82902d): a relayed seed reserves every
287
+ // inbox page against this many MiB before it reads or builds it, so the mail
288
+ // it holds while clients read stays bounded; past it a read gets 503.
289
+ const budgetText = args["response-budget"] ?? process.env.SEED_RESPONSE_BUDGET ?? null;
290
+ let responseBudget = null;
291
+ if (budgetText !== null) {
292
+ if (relayOrigin === null) refuse("--response-budget applies only with --relay");
293
+ if (!/^[0-9]+$/.test(String(budgetText)) || Number(budgetText) < 4 || Number(budgetText) > 4096) refuse(`--response-budget must be a whole number of MiB from 4 to 4096, not ${JSON.stringify(String(budgetText))}`);
294
+ }
295
+ if (relayOrigin !== null) responseBudget = new ResponseBudget(Number(budgetText ?? 32) * 1024 * 1024);
296
+ let tunnelBackoff;
297
+ if (args["tunnel-retry-ms"] !== undefined) {
298
+ const text = String(args["tunnel-retry-ms"]);
299
+ if (relayOrigin === null) refuse("--tunnel-retry-ms applies only with --relay");
300
+ if (!/^[0-9]+$/.test(text) || Number(text) < 50 || Number(text) > 1000) refuse(`--tunnel-retry-ms must be a whole number from 50 to 1000, not ${JSON.stringify(text)}`);
301
+ tunnelBackoff = { minMs: Number(text), maxMs: 8 * Number(text) };
302
+ }
234
303
 
235
304
  // The seed key's passphrase: a file (preferred: a systemd credential) or an
236
305
  // environment variable, never a flag value, so it is never in argv or ps. It is
@@ -313,7 +382,7 @@ if (args.status) {
313
382
  refuse(`no seed key at ${keyPath}: --status reports on an existing seed. ${homeGiven ? "Check that --home/SEED_HOME names the seed's key directory, or start the seed once." : "Start the seed once, or pass its --home."}`);
314
383
  }
315
384
  console.log(`seed ${savedUuaid}`);
316
- await printStanding(registryUrl, savedUuaid);
385
+ await printStanding(registryUrl, savedUuaid, keychain.publicView().publicKeyHex);
317
386
  process.exit(0);
318
387
  }
319
388
  // Bind the host and port once, before the key or database exists, and keep the
@@ -357,7 +426,7 @@ try {
357
426
  }
358
427
 
359
428
  /** Ask a registry where we stand and print the ladder position. */
360
- async function printStanding(registry, uuaid) {
429
+ async function printStanding(registry, uuaid, publicKeyHex) {
361
430
  try {
362
431
  const res = await fetch(`${registry}/v1/seeds/${encodeURIComponent(uuaid)}`);
363
432
  if (res.status === 404) {
@@ -372,6 +441,13 @@ async function printStanding(registry, uuaid) {
372
441
  console.log(` observed: ${o.probes?.passed ?? 0}/${o.probes?.total ?? 0} probes (${((o.uptime ?? 0) * 100).toFixed(1)}% uptime), ${o.roundTrips?.passed ?? 0} relay round-trips`);
373
442
  if (s.next) console.log(` next: ${s.next} — needs ${s.missing.join(", ")}`);
374
443
  else if (!s.demoted) console.log(` next: top of the ladder`);
444
+ // 2.8.0: the topology this registry has pinned for the seed.
445
+ if (s.topology) {
446
+ console.log(` topology: ${s.topology}${s.relay ? ` via ${s.relay}` : ""}${s.vettedUntil ? `, vetted until ${s.vettedUntil}` : ""}${s.listed === false ? (s.relay ? " (not in directory.json yet: a relayed seed is listed once a round trip with inbox auth v2 passes through its relay; until then clients reach it only by pillar init --carriers <url>)" : " (not listed in directory.json)") : ""}`);
447
+ } else {
448
+ const via = relayShapeOrigin(s.url, publicKeyHex);
449
+ if (via) console.log(` topology: relayed via ${via}; this registry predates 2.8.0, so its liveness checks are relay-attested`);
450
+ }
375
451
  } catch (e) {
376
452
  console.log(` standing: unreachable — ${e.message}`);
377
453
  }
@@ -396,25 +472,64 @@ if (dbPath === undefined) {
396
472
  }
397
473
  }
398
474
 
399
- const server = new CarrierServer({ dbPath, ttlDays, keychain, publicUrl, secureDelete, communityInboxWaits, trustedProxies });
475
+ if (relayOrigin) publicUrl = relayedUrlFor(relayOrigin, keychain._identity.publicKeyHex);
476
+ const server = new CarrierServer({ dbPath, ttlDays, keychain, publicUrl, relayOrigin, secureDelete, communityInboxWaits, trustedProxies, responseBudget });
400
477
  const addr = await server.listen(listener);
401
- console.log(`pillar-seed listening on http://${addr.address}:${addr.port}`);
478
+ console.log(`pillar-seed listening on http://${isIP(addr.address) === 6 ? `[${addr.address}]` : addr.address}:${addr.port}`);
402
479
  console.log(` uuaid: ${keychain._identity.uuaid}`);
403
480
  console.log(` db: ${dbPath}`);
404
481
  console.log(` ttl: ${ttlDays} days`);
405
482
  console.log(` secure-delete: ${secureDelete ? "on (expired envelopes are zeroed; WAL truncated after each expiry pass)" : "off (expired envelope bytes stay on disk until reused)"}`);
406
483
  if (publicUrl) console.log(` public url: ${publicUrl}`);
484
+ // The tunnel starts after the health check, so the first request it carries
485
+ // finds the seed serving. Announcing waits for the relay's first "ready".
486
+ let tunnel = null;
487
+ if (relayOrigin) {
488
+ tunnel = new TunnelClient({
489
+ relayOrigin, keychain, localPort: addr.port, localHost: addr.address, log: (line) => console.log(` ${line}`),
490
+ // An inbox page stays reserved until this tunnel has sent it to the relay.
491
+ responseBudget,
492
+ ...(takeoverWaitMs !== undefined ? { takeoverWaitMs } : {}),
493
+ ...(tunnelBackoff ? { backoff: tunnelBackoff } : {}),
494
+ // A seed that served, then found another process holding its key at the
495
+ // relay past --takeover-wait (V1 0a3350: after a relay restart), exits 2
496
+ // rather than wait for ever while its mail sits unreadable.
497
+ onGiveUp: async () => {
498
+ await server.close();
499
+ refuse(`--relay: another process took this seed key at ${relayOrigin} (after the relay restarted, or while this one was reconnecting) and kept it past the --takeover-wait. Mail this process accepted before is still in ${dbPath}: stop the other process, then start this one again to serve it. Run one process per seed key.`);
500
+ },
501
+ });
502
+ }
407
503
 
408
504
  // Boot self-check on the address we actually serve — verify before claim.
409
505
  try {
410
506
  const probeHost = addr.address === "0.0.0.0" || addr.address === "::" ? "127.0.0.1" : addr.address;
411
- const res = await fetch(`http://${probeHost}:${addr.port}/v1/health`);
507
+ // An IPv6 address goes in brackets in a URL (V1 2b5070: --host ::1).
508
+ const urlHost = isIP(probeHost) === 6 ? `[${probeHost}]` : probeHost;
509
+ const res = await fetch(`http://${urlHost}:${addr.port}/v1/health`);
412
510
  if (res.ok) console.log(` health: ok (${res.status})`);
413
511
  else console.log(` health: WARN ${res.status}`);
414
512
  } catch (e) {
415
513
  console.log(` health: unreachable — ${e.message}`);
416
514
  }
417
515
 
516
+ if (tunnel) {
517
+ console.log(` relay: ${relayOrigin} (one outbound tunnel; nothing listens beyond ${addr.address})`);
518
+ console.log(` response budget: ${responseBudget.limit / 1024 / 1024} MiB of inbox pages held for clients at once (--response-budget)`);
519
+ try {
520
+ await tunnel.start();
521
+ } catch (e) {
522
+ tunnel.stop();
523
+ await server.close();
524
+ const why = {
525
+ "not-allowed": ` Ask the relay operator to add ${keychain._identity.uuaid} to its allow-file.`,
526
+ "seed-already-connected": ` Another process is serving this seed key through ${relayOrigin} and did not stop within the --takeover-wait. Stop it, or give this seed its own key (a new --home).`,
527
+ "upgrade-blocked": " The relay accepts tunnels, but the WebSocket upgrade did not reach it: check that the proxy in front of it passes the Upgrade and Connection headers for /v1/tunnel (HOSTING-LIMITS.md section 5).",
528
+ }[e.reason] ?? "";
529
+ refuse(`--relay: ${relayOrigin} refused this seed (${e.reason ?? e.message}). Nothing was announced.${why}`);
530
+ }
531
+ }
532
+
418
533
  if (registryUrl) {
419
534
  if (!publicUrl) {
420
535
  console.log(`\n --announce needs --public-url <https://your-host>: the registry enrolls a URL,`);
@@ -445,6 +560,8 @@ if (registryUrl) {
445
560
  console.log(` enrollment failed: ${e.message}`);
446
561
  }
447
562
  }
563
+ } else if (relayOrigin) {
564
+ console.log(`\n serving ${publicUrl} through the relay; not announced to any registry.`);
448
565
  } else if (publicUrl) {
449
566
  console.log(`\n serving ${publicUrl} through your proxy; not announced to any registry.`);
450
567
  } else if (host === "127.0.0.1") {
@@ -464,6 +581,7 @@ const vacuumTimer = setInterval(() => {
464
581
 
465
582
  const shutdown = async () => {
466
583
  clearInterval(vacuumTimer);
584
+ tunnel?.stop();
467
585
  await server.close();
468
586
  process.exit(0);
469
587
  };
package/bin/pillar.mjs CHANGED
@@ -59,6 +59,7 @@ import { Mailbox, isErasedRow } from "../src/mailbox/mailbox.mjs";
59
59
  import { runVerifyCommand, VERIFY_USAGE } from "../src/vnext/verify-cli.mjs";
60
60
  import { runInitCli } from "../src/vnext/init-cli.mjs";
61
61
  import { runLineageCli } from "../src/vnext/lineage-cli.mjs";
62
+ import { runContinuityCli, runLineageContinuityCli } from "../src/vnext/continuity-cli.mjs";
62
63
  import { runCardCli } from "../src/vnext/card-cli.mjs";
63
64
  import { runIntroCli } from "../src/vnext/intro-cli.mjs";
64
65
  import { runResolveCli } from "../src/vnext/resolve-cli.mjs";
@@ -385,7 +386,8 @@ async function cmdSend(args) {
385
386
  const { envelope, delivery } = sent;
386
387
  const effRecipient = sent.redirectedTo ?? recipient;
387
388
  console.log(`sent envelope ${envelope.id}`);
388
- if (sent.redirectedFrom) console.log(` redirected (W-4): ${sent.redirectedFrom} -> ${sent.redirectedTo} (mapping persisted in ${join(homePath(args), "w4-redirect.json")})`);
389
+ if (sent.redirectedFrom && sent.continuity) console.log(` redirected (continuity, ${sent.continuity}): ${sent.redirectedFrom} -> ${sent.redirectedTo}`);
390
+ else if (sent.redirectedFrom) console.log(` redirected (W-4): ${sent.redirectedFrom} -> ${sent.redirectedTo} (mapping persisted in ${join(homePath(args), "w4-redirect.json")})`);
389
391
  console.log(` to: ${effRecipient}${effRecipient !== recipientArg ? ` (${recipientArg})` : ""}`);
390
392
  console.log(` kind: ${kind}`);
391
393
  if (sent.direct?.peerId) console.log(` via peerId: ${sent.direct.peerId}${sent.confirmed === false ? " (a direct stream only: nothing confirms it arrived)" : ""}`);
@@ -1685,7 +1687,7 @@ function findCommandIndex(raw) {
1685
1687
  return -1;
1686
1688
  }
1687
1689
 
1688
- const USAGE = `usage: pillar <init|verify|lineage|card|knock|knocks|answer|intro|resolve|listing|id|send|send-group|group|groups|recv|inbox|wait|notify|readers|status|receipts|trust|tier|peers|delegate> [--home DIR]
1690
+ const USAGE = `usage: pillar <init|verify|lineage|continuity|card|knock|knocks|answer|intro|resolve|listing|id|send|send-group|group|groups|recv|inbox|wait|notify|readers|status|receipts|trust|tier|peers|delegate> [--home DIR]
1689
1691
  pillar verify <file|-> verify a saved artifact offline (card, listing, lineage log, intro, ...)
1690
1692
  pillar verify <uuaid> verify an agent live: its registry listing, card and lineage
1691
1693
  pillar <command> --help usage of one command (verify, group, notify)`;
@@ -1710,7 +1712,7 @@ async function main() {
1710
1712
  if (wantsHelp(raw)) await exitWithHelp(helpText(raw)); // R2: before any home, key, file or carrier is touched
1711
1713
  const cmdIdx = findCommandIndex(raw);
1712
1714
  const directCmd = cmdIdx === -1 ? undefined : raw[cmdIdx];
1713
- const VNEXT_DIRECT_CMDS = new Set(["verify", "lineage", "init", "card", "knock", "knocks", "answer", "intro", "resolve", "listing", "soul"]);
1715
+ const VNEXT_DIRECT_CMDS = new Set(["verify", "lineage", "init", "card", "knock", "knocks", "answer", "intro", "resolve", "listing", "soul", "continuity"]);
1714
1716
  if (VNEXT_DIRECT_CMDS.has(directCmd)) {
1715
1717
  const subRaw = [...raw.slice(0, cmdIdx), ...raw.slice(cmdIdx + 1)];
1716
1718
  if (directCmd === "soul") {
@@ -1722,7 +1724,12 @@ async function main() {
1722
1724
  exit(exitCode);
1723
1725
  }
1724
1726
  if (directCmd === "lineage") {
1725
- const { exitCode } = await runLineageCli(subRaw);
1727
+ const wrapped = await runLineageContinuityCli(subRaw); // rotate (+ notices, retired inbox), notify, successor
1728
+ const { exitCode } = wrapped ?? await runLineageCli(subRaw);
1729
+ exit(exitCode);
1730
+ }
1731
+ if (directCmd === "continuity") {
1732
+ const { exitCode } = await runContinuityCli(subRaw);
1726
1733
  exit(exitCode);
1727
1734
  }
1728
1735
  if (directCmd === "init") {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uuaid/pillar",
3
- "version": "2.7.3",
3
+ "version": "2.8.1",
4
4
  "description": "Pillar (Protocol for Inter-agent Linked Ledger And Relay) — the secure delivery layer of UACP, the Universal Agent Communication Protocol. UACP = UUAID (identity) + Envelope (signed, encrypted container) + Pillar (relay, mailbox, routing, store-and-forward). Reference implementation of the UACP delivery layer; includes VDA-1 (IAASO-3901, in ballot) delivery attestation and a blind escrow for the Zilligon ZGN / EVM rails.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -505,6 +505,18 @@ export class Mailbox {
505
505
  if (this._jsonDir) return this._jsonDir.inboxSince(seq, limit);
506
506
  return this.db.prepare(`select * from inbox where seq > ? and ${LIVE_ENVELOPE_SQL} order by seq asc limit ?`).all(seq, limit);
507
507
  }
508
+ inboxAtSeqs(seqs = []) {
509
+ if (this._jsonDir) return this._jsonDir.inboxAtSeqs(seqs);
510
+ const wanted = [...new Set(seqs.filter((n) => Number.isSafeInteger(n) && n > 0))].sort((a, b) => a - b);
511
+ if (wanted.length === 0) return [];
512
+ const out = [];
513
+ for (let i = 0; i < wanted.length; i += 500) {
514
+ const chunk = wanted.slice(i, i + 500);
515
+ const ph = chunk.map(() => "?").join(",");
516
+ out.push(...this.db.prepare(`select * from inbox where seq in (${ph}) and ${LIVE_ENVELOPE_SQL} order by seq asc`).all(...chunk));
517
+ }
518
+ return out;
519
+ }
508
520
 
509
521
  _regularInboxWhere() {
510
522
  let clause = `quarantined is null and ${LIVE_ENVELOPE_SQL}`;
@@ -8,6 +8,17 @@
8
8
  import { envelopeBodyBytes, preflightBodyBytes } from "../blob/blob.mjs";
9
9
  import { seedTier } from "./seed-tier.mjs";
10
10
  import { carrierFix, REFUSAL_FIXES } from "./refusals.mjs";
11
+ import { isRelayedSeedUrl } from "./tunnel.mjs";
12
+ import { signInboxAuthV1, signInboxAuthV2 } from "./inbox-auth.mjs";
13
+
14
+ /**
15
+ * A 3xx answer under `redirect: "manual"` (2.8.1). Node's fetch hands back the
16
+ * 3xx itself; a browser-style runtime hands back an opaque redirect (status 0).
17
+ * Either way the client stops here and sends nothing to the target.
18
+ */
19
+ function isRedirect(res) {
20
+ return res.type === "opaqueredirect" || (res.status >= 300 && res.status < 400);
21
+ }
11
22
  import { setTimeout as sleepTimer } from "node:timers/promises";
12
23
 
13
24
  /**
@@ -115,6 +126,9 @@ export class CarrierClient {
115
126
  try {
116
127
  const res = await fetch(`${base}/v1/envelopes`, {
117
128
  method: "POST",
129
+ // 2.8.1: never follow a redirect. A 307/308 would replay the body and
130
+ // the x-pillar-* headers to whatever host the answer names.
131
+ redirect: "manual",
118
132
  headers: {
119
133
  "content-type": "application/json",
120
134
  ...(this.tierGrantB64 ? { "x-pillar-tier-grant": this.tierGrantB64 } : {}),
@@ -122,6 +136,10 @@ export class CarrierClient {
122
136
  body: JSON.stringify(envelope),
123
137
  signal: AbortSignal.timeout(timeoutMs),
124
138
  });
139
+ if (isRedirect(res)) {
140
+ await res.body?.cancel().catch(() => {});
141
+ return { carrier: base, ok: false, status: res.status, error: `${res.status} carrier-redirect-refused`, reason: "carrier-redirect-refused", fix: carrierFix("carrier-redirect-refused") };
142
+ }
125
143
  const raw = await res.text();
126
144
  let body = {};
127
145
  try { body = raw ? JSON.parse(raw) : {}; } catch (_error) {}
@@ -162,19 +180,29 @@ export class CarrierClient {
162
180
  * Signed request; carrier verifies our key before serving.
163
181
  */
164
182
  async fetchInbox(base, { since = 0, waitS = 0, timeoutMs = 40000, signal = null } = {}) {
165
- const path = `GET /v1/inbox/${this.uuaid}?since=${since}`;
166
- const ts = String(Date.now());
167
- const sig = this.keychain.sign(Buffer.from(`${path}\n${ts}`, "utf-8")).toString("hex");
168
- const res = await fetch(`${base}/v1/inbox/${encodeURIComponent(this.uuaid)}?since=${since}&wait=${waitS}`, {
169
- headers: {
170
- "x-pillar-pubkey": this.publicKeyHex,
171
- "x-pillar-ts": ts,
172
- "x-pillar-sig": sig,
173
- },
183
+ // 2.8.1 (Lead 5e8cf6): a relayed seed URL gets inbox auth v2, bound to
184
+ // that URL and single-use, so neither the seed nor its relay can replay it
185
+ // to another carrier. A direct carrier gets v1, as in 2.8.0.
186
+ const headers = isRelayedSeedUrl(base)
187
+ ? signInboxAuthV2(this.keychain, { audience: base, uuaid: this.uuaid, since, wait: waitS })
188
+ : signInboxAuthV1(this.keychain, { uuaid: this.uuaid, since });
189
+ const res = await fetch(`${String(base).replace(/\/+$/, "")}/v1/inbox/${encodeURIComponent(this.uuaid)}?since=${since}&wait=${waitS}`, {
190
+ headers,
174
191
  // `signal` lets a caller cancel a long-poll early (peekCarrierInbox stops
175
192
  // the other carriers once one has mail).
176
193
  signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs),
194
+ // 2.8.1: never follow a redirect; the signed inbox headers would go to
195
+ // the host the answer names, and stay replayable there for 5 minutes.
196
+ redirect: "manual",
177
197
  });
198
+ if (isRedirect(res)) {
199
+ await res.body?.cancel().catch(() => {});
200
+ const e = new Error(`inbox fetch ${base}: ${res.status} carrier-redirect-refused`);
201
+ e.code = "carrier-redirect-refused";
202
+ e.fix = carrierFix(e.code);
203
+ e.status = res.status; e.carrier = base;
204
+ throw e;
205
+ }
178
206
  if (res.status !== 200) {
179
207
  const body = await res.json().catch(() => ({}));
180
208
  const e = new Error(`inbox fetch ${base}: ${res.status} ${body.error ?? ""}`);