@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.
@@ -31,25 +31,17 @@ 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";
38
- import {
39
- DEFAULT_MAX_RESOLVE_MISSES_PER_IP_PER_MINUTE,
40
- DEFAULT_MAX_STRIKES,
41
- DEFAULT_NEGATIVE_CACHE_TTL_MS,
42
- DEFAULT_PULL_INTERVAL_MS,
43
- DEFAULT_QUARANTINE_COOLDOWN_MS,
44
- DEFAULT_RESOLVE_TIMEOUT_MS,
45
- FederationCoordinator,
46
- makeResolveMissRateLimiter,
47
- openRegistryDb,
48
- } from "../src/registry/federation.mjs";
39
+ import { FederationCoordinator, makeResolveMissRateLimiter, openRegistryDb } from "../src/registry/federation.mjs";
40
+ import { formatDirectoryLimits, parseDirectoryArgs } from "../src/registry/directory-flags.mjs";
49
41
  import { GossipCoordinator } from "../src/registry/gossip.mjs";
50
42
  import { HeartbeatStore } from "../src/registry/heartbeats.mjs";
51
43
  import { LineageStore, isStrictDateTime } from "../src/registry/lineage.mjs";
52
- import { ListingStore, isStrictHttpsUri, MAX_NEW_LINEAGES_PER_HOUR, startTombstonePruning } from "../src/registry/listings.mjs";
44
+ import { ListingStore, isStrictHttpsUri, startTombstonePruning } from "../src/registry/listings.mjs";
53
45
  import { handleRegistryRoute } from "../src/registry/resolve.mjs";
54
46
  import {
55
47
  buildRegistryStats,
@@ -60,32 +52,6 @@ import {
60
52
  } from "../src/registry/stats.mjs";
61
53
  import { exitWithHelp, wantsHelp } from "../src/cli-help.mjs";
62
54
 
63
- function parsePeersArg(raw) {
64
- if (!raw || typeof raw !== "string") return [];
65
- const trimmed = raw.trim();
66
- if (!trimmed) return [];
67
- if (trimmed.startsWith("[")) {
68
- const parsed = JSON.parse(trimmed);
69
- return Array.isArray(parsed) ? parsed : [];
70
- }
71
- return trimmed
72
- .split(",")
73
- .map((s) => s.trim())
74
- .filter(Boolean);
75
- }
76
-
77
- function parseArgs(argv) {
78
- const args = {};
79
- for (let i = 0; i < argv.length; i++) {
80
- const a = argv[i];
81
- if (a.startsWith("--")) {
82
- const k = a.slice(2);
83
- args[k] = (argv[i + 1] && !argv[i + 1].startsWith("--")) ? argv[++i] : true;
84
- }
85
- }
86
- return args;
87
- }
88
-
89
55
  const USAGE = `usage: pillar-directory [flags]
90
56
 
91
57
  Serves directory.json and the seed registry. Listens on 127.0.0.1 by default.
@@ -101,75 +67,82 @@ The first start mints the registry key in --home.
101
67
  --peers <url,...> peer registries (DIRECTORY_PEERS)
102
68
  --trusted-proxy <ips> whose X-Forwarded-For counts (DIRECTORY_TRUSTED_PROXIES)
103
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 listed while relayed
72
+ (DIRECTORY_FLEET_RELAYS; default none)
104
73
  -h, --help print this help and exit
105
74
 
106
75
  More flags (limits, federation timers, test hooks): --protocol, --allow-private-urls,
107
- --url-map, --clock-file, --stamp-bits, --max-new-lineages-per-hour,
76
+ --url-map, --clock-file, --stamp-bits, --probe-interval-ms, --max-new-lineages-per-hour,
108
77
  --max-listings-per-ip-per-hour, --max-lineage-posts-per-ip-per-hour,
109
78
  --max-heartbeats-per-ip-per-hour, --pull-interval-ms, --max-strikes,
110
79
  --quarantine-cooldown-ms, --resolve-timeout-ms, --resolve-negative-ttl-ms,
111
- --max-resolve-misses-per-ip-per-minute. Routes: see the header of bin/pillar-directory.mjs.`;
80
+ --max-resolve-misses-per-ip-per-minute. Routes: see the header of bin/pillar-directory.mjs.
81
+
82
+ --flag value and --flag=value are the same. An unknown flag, a flag with no value,
83
+ a number that is not a whole number in range (digits only) or an empty DIRECTORY_*
84
+ variable exits 2 before anything is written. After "listening on" a line shows
85
+ the limits in effect.`;
112
86
  if (wantsHelp(process.argv.slice(2))) await exitWithHelp(USAGE); // R2: before the registry key is minted or the db is opened
113
- const args = parseArgs(process.argv.slice(2));
114
- const home = args.home ?? process.env.DIRECTORY_HOME ?? join(homedir(), ".pillar-directory");
115
- const port = Number(args.port ?? process.env.DIRECTORY_PORT ?? 8800);
116
- const host = args.host ?? process.env.DIRECTORY_HOST ?? "127.0.0.1";
117
- const dbPath = args.db ?? process.env.DIRECTORY_DB ?? join(home, "registry.db");
118
- const carrier = args.carrier ?? process.env.DIRECTORY_CARRIER ?? null;
119
- const agentsPath = args.agents ?? process.env.DIRECTORY_AGENTS ?? null;
120
- const protocol = args.protocol ?? process.env.DIRECTORY_PROTOCOL ?? "uacp/1.0-draft";
121
- const probeMinutes = Number(args["probe-minutes"] ?? process.env.DIRECTORY_PROBE_MINUTES ?? 10);
122
- const allowPrivateUrls = Boolean(args["allow-private-urls"]);
123
- const publicUrlArg = args["public-url"] ?? process.env.DIRECTORY_PUBLIC_URL ?? null;
124
- const rawUrlMap = args["url-map"] ?? process.env.DIRECTORY_URL_MAP ?? null;
125
- const urlMap = rawUrlMap ? JSON.parse(rawUrlMap) : null;
126
- const clockFile = typeof args["clock-file"] === "string" ? args["clock-file"] : null;
87
+ // 2.7.3 (V1 c9da71 P3): every flag and DIRECTORY_* value is checked here, before
88
+ // the registry key is minted or the db is opened; one it cannot use exits 2.
89
+ const parsed = parseDirectoryArgs(process.argv.slice(2), process.env);
90
+ if (!parsed.ok) {
91
+ console.error(`pillar-directory: ${parsed.error.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`)}. See pillar-directory --help.`);
92
+ process.exit(2);
93
+ }
94
+ const opts = parsed.values;
95
+ const home = opts.home ?? join(homedir(), ".pillar-directory");
96
+ const port = opts.port;
97
+ const host = opts.host ?? "127.0.0.1";
98
+ const dbPath = opts.db ?? join(home, "registry.db");
99
+ const carrier = opts.carrier ?? null;
100
+ // 2.8.0 (RedTeam 22f6c3 Q2): directory.json never names a relayed seed URL
101
+ // (<relay origin>/e/<id>) as its bootstrap carrier.
102
+ if (typeof carrier === "string" && isRelayedSeedUrl(carrier)) {
103
+ console.error("pillar-directory: --carrier/DIRECTORY_CARRIER is a relayed seed URL (<origin>/e/<id>); 2.8.0 keeps relayed seeds out of directory.json. Name a direct carrier; clients reach a relayed seed with pillar init --carriers <url>.");
104
+ process.exit(2);
105
+ }
106
+ const agentsPath = opts.agents ?? null;
107
+ const protocol = opts.protocol ?? "uacp/1.0-draft";
108
+ const probeMinutes = opts["probe-minutes"];
109
+ // Test hook (2.8.0, like --pull-interval-ms): the probe interval in milliseconds
110
+ // (100 or more), overriding --probe-minutes, so tests can watch probes, demotion
111
+ // and recovery. Unset: --probe-minutes.
112
+ const probeIntervalMs = opts["probe-interval-ms"];
113
+ // The interval the probe loop really runs at. The registry sizes a relayed
114
+ // seed's vetting lease from it: min(3 x interval, 30 min) (RedTeam 22f6c3 Q1).
115
+ const effectiveProbeMs = probeIntervalMs ?? probeMinutes * 60_000;
116
+ const allowPrivateUrls = opts["allow-private-urls"];
117
+ // Fleet relays (2.8.0): the relay origins and attestation keys this registry pins.
118
+ // A relayed seed is listed, vetted and granted only on one of these. None by
119
+ // default: without this flag the registry pins no relay and lists no relayed seed.
120
+ const fleetRelaysPath = opts["fleet-relays"] ?? null;
121
+ let fleetRelays = new Map();
122
+ if (fleetRelaysPath !== null) {
123
+ try { fleetRelays = parseFleetRelays(readFileSync(fleetRelaysPath, "utf-8")); }
124
+ catch (e) { console.error(`pillar-directory: --fleet-relays ${fleetRelaysPath}: ${e.code ?? e.message}`); process.exit(2); }
125
+ }
126
+ const publicUrlArg = opts["public-url"] ?? null;
127
+ const urlMap = opts.urlMap;
128
+ const clockFile = opts["clock-file"] ?? null;
127
129
  const getNow = () => {
128
130
  if (!clockFile || !existsSync(clockFile)) return undefined;
129
131
  const raw = readFileSync(clockFile, "utf-8").trim();
130
132
  return isStrictDateTime(raw) ? raw : undefined;
131
133
  };
132
- const stampBits = Number(args["stamp-bits"] ?? process.env.DIRECTORY_STAMP_BITS ?? 18);
133
- const maxNewLineagesPerHour = Number(
134
- args["max-new-lineages-per-hour"] ?? process.env.DIRECTORY_MAX_NEW_LINEAGES_PER_HOUR ?? MAX_NEW_LINEAGES_PER_HOUR,
135
- );
136
- const DEFAULT_MAX_LISTINGS_PER_IP_PER_HOUR = 60;
137
- const DEFAULT_MAX_LINEAGE_POSTS_PER_IP_PER_HOUR = 300;
138
- const DEFAULT_MAX_HEARTBEATS_PER_IP_PER_HOUR = 120;
139
- const maxListingsPerIpPerHour = Number(
140
- args["max-listings-per-ip-per-hour"] ??
141
- process.env.DIRECTORY_MAX_LISTINGS_PER_IP_PER_HOUR ??
142
- DEFAULT_MAX_LISTINGS_PER_IP_PER_HOUR,
143
- );
144
- const maxLineagePostsPerIpPerHour = Number(
145
- args["max-lineage-posts-per-ip-per-hour"] ??
146
- process.env.DIRECTORY_MAX_LINEAGE_POSTS_PER_IP_PER_HOUR ??
147
- DEFAULT_MAX_LINEAGE_POSTS_PER_IP_PER_HOUR,
148
- );
149
- const maxHeartbeatsPerIpPerHour = Number(
150
- args["max-heartbeats-per-ip-per-hour"] ??
151
- process.env.DIRECTORY_MAX_HEARTBEATS_PER_IP_PER_HOUR ??
152
- DEFAULT_MAX_HEARTBEATS_PER_IP_PER_HOUR,
153
- );
154
- const configuredPeers = parsePeersArg(args.peers ?? args.peer ?? process.env.DIRECTORY_PEERS ?? "");
155
- const pullIntervalMs = Number(
156
- args["pull-interval-ms"] ?? process.env.DIRECTORY_PULL_INTERVAL_MS ?? DEFAULT_PULL_INTERVAL_MS,
157
- );
158
- const maxStrikes = Number(args["max-strikes"] ?? process.env.DIRECTORY_MAX_STRIKES ?? DEFAULT_MAX_STRIKES);
159
- const quarantineCooldownMs = Number(
160
- args["quarantine-cooldown-ms"] ?? process.env.DIRECTORY_QUARANTINE_COOLDOWN_MS ?? DEFAULT_QUARANTINE_COOLDOWN_MS,
161
- );
162
- const resolveTimeoutMs = Number(
163
- args["resolve-timeout-ms"] ?? process.env.DIRECTORY_RESOLVE_TIMEOUT_MS ?? DEFAULT_RESOLVE_TIMEOUT_MS,
164
- );
165
- const negativeCacheTtlMs = Number(
166
- args["resolve-negative-ttl-ms"] ?? process.env.DIRECTORY_RESOLVE_NEGATIVE_TTL_MS ?? DEFAULT_NEGATIVE_CACHE_TTL_MS,
167
- );
168
- const maxResolveMissesPerIpPerMinute = Number(
169
- args["max-resolve-misses-per-ip-per-minute"] ??
170
- process.env.DIRECTORY_MAX_RESOLVE_MISSES_PER_IP_PER_MINUTE ??
171
- DEFAULT_MAX_RESOLVE_MISSES_PER_IP_PER_MINUTE,
172
- );
134
+ const stampBits = opts["stamp-bits"];
135
+ const maxNewLineagesPerHour = opts["max-new-lineages-per-hour"];
136
+ const maxListingsPerIpPerHour = opts["max-listings-per-ip-per-hour"];
137
+ const maxLineagePostsPerIpPerHour = opts["max-lineage-posts-per-ip-per-hour"];
138
+ const maxHeartbeatsPerIpPerHour = opts["max-heartbeats-per-ip-per-hour"];
139
+ const configuredPeers = opts.peerList;
140
+ const pullIntervalMs = opts["pull-interval-ms"];
141
+ const maxStrikes = opts["max-strikes"];
142
+ const quarantineCooldownMs = opts["quarantine-cooldown-ms"];
143
+ const resolveTimeoutMs = opts["resolve-timeout-ms"];
144
+ const negativeCacheTtlMs = opts["resolve-negative-ttl-ms"];
145
+ const maxResolveMissesPerIpPerMinute = opts["max-resolve-misses-per-ip-per-minute"];
173
146
 
174
147
  const MAX_ENROLLMENTS_PER_HOUR = 10; // per client IP
175
148
  const MAX_BODY = 8 * 1024;
@@ -190,7 +163,7 @@ const statsAggregates = new Map();
190
163
 
191
164
  const hasSqlite = Boolean(tryLoadBetterSqlite3());
192
165
  const registry = hasSqlite
193
- ? new SeedRegistry({ keychain, carrierUrl: carrier, dbPath, protocol, allowPrivateUrls })
166
+ ? new SeedRegistry({ keychain, carrierUrl: carrier, dbPath, protocol, allowPrivateUrls, fleetRelays, probeIntervalMs: effectiveProbeMs })
194
167
  : (() => {
195
168
  const fallbackDb = openRegistryDb(dbPath, { forcePureJs: true });
196
169
  const normCarrier = carrier ? String(carrier).replace(/\/+$/, "") : null;
@@ -334,7 +307,7 @@ function readBody(req) {
334
307
 
335
308
  // X-Forwarded-For counts only from a trusted proxy (2.5.3; src/net/client-ip.mjs).
336
309
  let trustedProxies;
337
- try { trustedProxies = parseTrustedProxies(args["trusted-proxy"] ?? process.env.DIRECTORY_TRUSTED_PROXIES); }
310
+ try { trustedProxies = parseTrustedProxies(opts["trusted-proxy"]); }
338
311
  catch (e) { console.error(`pillar-directory: ${e.message}`); process.exit(2); }
339
312
  const clientIp = (req) => clientIpOf(req, trustedProxies);
340
313
 
@@ -425,7 +398,8 @@ const server = createServer(async (req, res) => {
425
398
  if (!grant) {
426
399
  const known = registry.get(uuaid);
427
400
  return send(res, known ? 200 : 404,
428
- known ? { ok: true, grant: null, reason: "tier-earns-no-grant", tier: known.tier }
401
+ // The evaluated tier (topology cap, vetting), as /v1/seeds/<uuaid> reports it (2.8.0).
402
+ known ? { ok: true, grant: null, reason: "tier-earns-no-grant", tier: registry.status(uuaid).tier }
429
403
  : { ok: false, reason: "unknown-seed" });
430
404
  }
431
405
  return send(res, 200, { ok: true, grant });
@@ -461,6 +435,7 @@ if (configuredPeers.length > 0 && pullIntervalMs > 0) {
461
435
  federationCoordinator.start();
462
436
  }
463
437
  console.log(`pillar-directory listening on http://${formatHostForUrl(host)}:${boundPort}`);
438
+ console.log(` limits: ${formatDirectoryLimits(opts)}`);
464
439
  console.log(` uuaid: ${registry.uuaid}`);
465
440
  console.log(` issuer: ${registry.issuerKey}`);
466
441
  console.log(` carrier: ${carrier ?? "(none — set --carrier)"}`);
@@ -488,7 +463,7 @@ const probeTimer = setInterval(async () => {
488
463
  } finally {
489
464
  probing = false;
490
465
  }
491
- }, Math.max(1, probeMinutes) * 60_000);
466
+ }, effectiveProbeMs);
492
467
 
493
468
  const shutdown = async () => {
494
469
  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,25 @@
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
+ * See src/net/tunnel-client.mjs and the README "Egress seed" section.
42
51
  */
43
52
  import "../src/node-check.mjs"; // must stay the first import: refuses Node < 22 before any dependency loads
44
53
  import { chmodSync, closeSync, constants as fsConstants, existsSync, fstatSync, mkdirSync, openSync, readSync, statSync } from "node:fs";
45
- import { createServer } from "node:net";
54
+ import { createServer, isIP } from "node:net";
46
55
  import { homedir } from "node:os";
47
56
  import { join, resolve } from "node:path";
48
- import { CarrierServer, parseSecureDelete, parseCommunityWaits, MAX_TTL_DAYS } from "../src/net/carrier-server.mjs";
57
+ import { CarrierServer, ResponseBudget, parseSecureDelete, parseCommunityWaits, MAX_TTL_DAYS } from "../src/net/carrier-server.mjs";
49
58
  import { parseTrustedProxies } from "../src/net/client-ip.mjs";
50
59
  import { Keychain, keyDerivesUuaid, mintNamespace, SERVICE_IDENTITY_NAMESPACE } from "../src/identity/keychain.mjs";
60
+ import { canonicalOrigin, relayedUrlFor, relayShapeOrigin } from "../src/net/tunnel.mjs";
61
+ import { TunnelClient } from "../src/net/tunnel-client.mjs";
51
62
 
52
63
  const USAGE = `usage: pillar-seed [flags]
53
64
 
@@ -66,6 +77,19 @@ and pass the proxy's address as --public-url.
66
77
  --port <n> listen port (SEED_PORT, default 8799)
67
78
  --ttl <days> envelope lifetime (SEED_TTL_DAYS, default 14, at most 36500)
68
79
  --public-url <https://> the URL your proxy serves (SEED_PUBLIC_URL)
80
+ --relay <https://origin> serve this seed through a relay carrier instead of a
81
+ public URL: one outbound tunnel, served at
82
+ <origin>/e/<id> (SEED_RELAY). Not with --public-url;
83
+ --host stays 127.0.0.1 or ::1
84
+ --takeover-wait <s> with --relay: how long to wait for another process
85
+ serving this seed key at the relay to stop, then
86
+ exit 2, at start or later (after a relay restart)
87
+ (SEED_TAKEOVER_WAIT, default 45, 0 to 3600)
88
+ --response-budget <MiB> with --relay: the most inbox-page bytes this seed
89
+ holds for clients at once; a read past it gets 503
90
+ seed-busy (SEED_RESPONSE_BUDGET, default 32, 4 to 4096)
91
+ --tunnel-retry-ms <n> test hook, with --relay: first reconnect delay in ms
92
+ (the backoff doubles to at most 8 x n), 50 to 1000
69
93
  --secure-delete <on|off> zero expired envelopes (SEED_SECURE_DELETE, default on)
70
94
  --community-waits <n> long-poll slots (SEED_COMMUNITY_WAITS, default 48)
71
95
  --trusted-proxy <ips> whose X-Forwarded-For counts for per-IP budgets
@@ -95,10 +119,10 @@ key. Every refusal is one line on stderr, with exit code 2.`;
95
119
  // Every flag this command reads. Every other token is refused before the seed
96
120
  // key or the database is touched, so a typo, a bare word or `--help` never
97
121
  // 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"]);
122
+ 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
123
  // Flags that only mean something with a value. Given bare, 2.4 fell through to a
100
124
  // 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"];
125
+ 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
126
  // Flags that take no value in either form. `--help=` would otherwise set help to
103
127
  // "" (falsy) and start a seed; `--status help` would swallow the word.
104
128
  const BOOL_FLAGS = new Set(["help", "status"]);
@@ -106,7 +130,7 @@ const BOOL_FLAGS = new Set(["help", "status"]);
106
130
  // refused like a bare flag: in 2.4 an empty SEED_HOST listened on every
107
131
  // interface, an empty SEED_PORT took a random port, and an empty SEED_DB kept
108
132
  // 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"];
133
+ 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
134
 
111
135
  const VALUE_SET = new Set(VALUE_FLAGS);
112
136
  // The longest envelope lifetime accepted, MAX_TTL_DAYS (36500, 100 years), comes
@@ -207,7 +231,7 @@ const ttlDays = Number(ttlText);
207
231
  // Digits with an optional decimal part: Number() alone also took "0x10", "1e3", "+14" and " 14".
208
232
  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
233
  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;
234
+ let publicUrl = args["public-url"] ?? process.env.SEED_PUBLIC_URL ?? null;
211
235
  const registryUrl = typeof args.announce === "string" ? args.announce.replace(/\/+$/, "") : null;
212
236
  const operator = args.operator ?? process.env.SEED_OPERATOR ?? null;
213
237
  const region = args.region ?? process.env.SEED_REGION ?? null;
@@ -231,6 +255,49 @@ try {
231
255
  } catch (e) {
232
256
  refuse(e.message);
233
257
  }
258
+ // --relay (2.8.0): served through a relay's tunnel, so this seed never listens
259
+ // beyond this machine, and its own carrier must trust the tunnel's loopback
260
+ // replay for X-Forwarded-For or every client would share one per-IP budget.
261
+ let relayOrigin = null;
262
+ const relayText = args.relay ?? process.env.SEED_RELAY ?? null;
263
+ if (relayText !== null) {
264
+ 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");
265
+ const c = canonicalOrigin(relayText);
266
+ // The value is never echoed: a refused origin may carry credentials (as --public-url, AC2 fa0be869 P2).
267
+ if (!c.ok) refuse(`--relay must be a relay origin such as https://relay.example.org (${c.reason}); the value is not shown`);
268
+ relayOrigin = c.origin;
269
+ const loopHost = host === "::1" || (/^127\.\d+\.\d+\.\d+$/.test(host));
270
+ if (!loopHost) refuse(`--relay keeps the seed on this machine: --host must be 127.0.0.1 or ::1, not ${JSON.stringify(host)}`);
271
+ if (!trustedProxies.includes(host)) refuse(`--relay replays each request to this seed from ${host}: --trusted-proxy must include ${host}`);
272
+ }
273
+ // --takeover-wait (2.8.0, V1 2b5070): another process with this seed key holds
274
+ // the relay; wait this long for it to go, then exit rather than fight it.
275
+ const takeoverText = args["takeover-wait"] ?? process.env.SEED_TAKEOVER_WAIT ?? null;
276
+ let takeoverWaitMs;
277
+ if (takeoverText !== null) {
278
+ if (relayOrigin === null) refuse("--takeover-wait applies only with --relay");
279
+ 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))}`);
280
+ takeoverWaitMs = Number(takeoverText) * 1000;
281
+ }
282
+ // --tunnel-retry-ms (2.8.0, test hook like pillar-directory's --probe-interval-ms):
283
+ // short reconnect delays so tests can restart a relay many times quickly.
284
+ // --response-budget (2.8.0, RedTeam 82902d): a relayed seed reserves every
285
+ // inbox page against this many MiB before it reads or builds it, so the mail
286
+ // it holds while clients read stays bounded; past it a read gets 503.
287
+ const budgetText = args["response-budget"] ?? process.env.SEED_RESPONSE_BUDGET ?? null;
288
+ let responseBudget = null;
289
+ if (budgetText !== null) {
290
+ if (relayOrigin === null) refuse("--response-budget applies only with --relay");
291
+ 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))}`);
292
+ }
293
+ if (relayOrigin !== null) responseBudget = new ResponseBudget(Number(budgetText ?? 32) * 1024 * 1024);
294
+ let tunnelBackoff;
295
+ if (args["tunnel-retry-ms"] !== undefined) {
296
+ const text = String(args["tunnel-retry-ms"]);
297
+ if (relayOrigin === null) refuse("--tunnel-retry-ms applies only with --relay");
298
+ 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)}`);
299
+ tunnelBackoff = { minMs: Number(text), maxMs: 8 * Number(text) };
300
+ }
234
301
 
235
302
  // The seed key's passphrase: a file (preferred: a systemd credential) or an
236
303
  // environment variable, never a flag value, so it is never in argv or ps. It is
@@ -313,7 +380,7 @@ if (args.status) {
313
380
  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
381
  }
315
382
  console.log(`seed ${savedUuaid}`);
316
- await printStanding(registryUrl, savedUuaid);
383
+ await printStanding(registryUrl, savedUuaid, keychain.publicView().publicKeyHex);
317
384
  process.exit(0);
318
385
  }
319
386
  // Bind the host and port once, before the key or database exists, and keep the
@@ -357,7 +424,7 @@ try {
357
424
  }
358
425
 
359
426
  /** Ask a registry where we stand and print the ladder position. */
360
- async function printStanding(registry, uuaid) {
427
+ async function printStanding(registry, uuaid, publicKeyHex) {
361
428
  try {
362
429
  const res = await fetch(`${registry}/v1/seeds/${encodeURIComponent(uuaid)}`);
363
430
  if (res.status === 404) {
@@ -372,6 +439,13 @@ async function printStanding(registry, uuaid) {
372
439
  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
440
  if (s.next) console.log(` next: ${s.next} — needs ${s.missing.join(", ")}`);
374
441
  else if (!s.demoted) console.log(` next: top of the ladder`);
442
+ // 2.8.0: the topology this registry has pinned for the seed.
443
+ if (s.topology) {
444
+ 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: clients reach a relayed seed only by explicit config, pillar init --carriers <url>)" : " (not listed in directory.json)") : ""}`);
445
+ } else {
446
+ const via = relayShapeOrigin(s.url, publicKeyHex);
447
+ if (via) console.log(` topology: relayed via ${via}; this registry predates 2.8.0, so its liveness checks are relay-attested`);
448
+ }
375
449
  } catch (e) {
376
450
  console.log(` standing: unreachable — ${e.message}`);
377
451
  }
@@ -396,25 +470,64 @@ if (dbPath === undefined) {
396
470
  }
397
471
  }
398
472
 
399
- const server = new CarrierServer({ dbPath, ttlDays, keychain, publicUrl, secureDelete, communityInboxWaits, trustedProxies });
473
+ if (relayOrigin) publicUrl = relayedUrlFor(relayOrigin, keychain._identity.publicKeyHex);
474
+ const server = new CarrierServer({ dbPath, ttlDays, keychain, publicUrl, relayOrigin, secureDelete, communityInboxWaits, trustedProxies, responseBudget });
400
475
  const addr = await server.listen(listener);
401
- console.log(`pillar-seed listening on http://${addr.address}:${addr.port}`);
476
+ console.log(`pillar-seed listening on http://${isIP(addr.address) === 6 ? `[${addr.address}]` : addr.address}:${addr.port}`);
402
477
  console.log(` uuaid: ${keychain._identity.uuaid}`);
403
478
  console.log(` db: ${dbPath}`);
404
479
  console.log(` ttl: ${ttlDays} days`);
405
480
  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
481
  if (publicUrl) console.log(` public url: ${publicUrl}`);
482
+ // The tunnel starts after the health check, so the first request it carries
483
+ // finds the seed serving. Announcing waits for the relay's first "ready".
484
+ let tunnel = null;
485
+ if (relayOrigin) {
486
+ tunnel = new TunnelClient({
487
+ relayOrigin, keychain, localPort: addr.port, localHost: addr.address, log: (line) => console.log(` ${line}`),
488
+ // An inbox page stays reserved until this tunnel has sent it to the relay.
489
+ responseBudget,
490
+ ...(takeoverWaitMs !== undefined ? { takeoverWaitMs } : {}),
491
+ ...(tunnelBackoff ? { backoff: tunnelBackoff } : {}),
492
+ // A seed that served, then found another process holding its key at the
493
+ // relay past --takeover-wait (V1 0a3350: after a relay restart), exits 2
494
+ // rather than wait for ever while its mail sits unreadable.
495
+ onGiveUp: async () => {
496
+ await server.close();
497
+ 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.`);
498
+ },
499
+ });
500
+ }
407
501
 
408
502
  // Boot self-check on the address we actually serve — verify before claim.
409
503
  try {
410
504
  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`);
505
+ // An IPv6 address goes in brackets in a URL (V1 2b5070: --host ::1).
506
+ const urlHost = isIP(probeHost) === 6 ? `[${probeHost}]` : probeHost;
507
+ const res = await fetch(`http://${urlHost}:${addr.port}/v1/health`);
412
508
  if (res.ok) console.log(` health: ok (${res.status})`);
413
509
  else console.log(` health: WARN ${res.status}`);
414
510
  } catch (e) {
415
511
  console.log(` health: unreachable — ${e.message}`);
416
512
  }
417
513
 
514
+ if (tunnel) {
515
+ console.log(` relay: ${relayOrigin} (one outbound tunnel; nothing listens beyond ${addr.address})`);
516
+ console.log(` response budget: ${responseBudget.limit / 1024 / 1024} MiB of inbox pages held for clients at once (--response-budget)`);
517
+ try {
518
+ await tunnel.start();
519
+ } catch (e) {
520
+ tunnel.stop();
521
+ await server.close();
522
+ const why = {
523
+ "not-allowed": ` Ask the relay operator to add ${keychain._identity.uuaid} to its allow-file.`,
524
+ "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).`,
525
+ "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).",
526
+ }[e.reason] ?? "";
527
+ refuse(`--relay: ${relayOrigin} refused this seed (${e.reason ?? e.message}). Nothing was announced.${why}`);
528
+ }
529
+ }
530
+
418
531
  if (registryUrl) {
419
532
  if (!publicUrl) {
420
533
  console.log(`\n --announce needs --public-url <https://your-host>: the registry enrolls a URL,`);
@@ -445,6 +558,8 @@ if (registryUrl) {
445
558
  console.log(` enrollment failed: ${e.message}`);
446
559
  }
447
560
  }
561
+ } else if (relayOrigin) {
562
+ console.log(`\n serving ${publicUrl} through the relay; not announced to any registry.`);
448
563
  } else if (publicUrl) {
449
564
  console.log(`\n serving ${publicUrl} through your proxy; not announced to any registry.`);
450
565
  } else if (host === "127.0.0.1") {
@@ -464,6 +579,7 @@ const vacuumTimer = setInterval(() => {
464
579
 
465
580
  const shutdown = async () => {
466
581
  clearInterval(vacuumTimer);
582
+ tunnel?.stop();
467
583
  await server.close();
468
584
  process.exit(0);
469
585
  };
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.2",
3
+ "version": "2.8.0",
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}`;