@uuaid/pillar 2.4.1 → 2.5.3

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.
@@ -4,8 +4,9 @@
4
4
  * the p2p store-and-forward mesh, like a LimeWire/BitTorrent seed peer.
5
5
  *
6
6
  * pillar-seed --port 8799 --db /opt/pillar-seed/seed.db
7
- * pillar-seed --public-url https://seed.example.org --announce https://pillar.uuaid.org
8
- * pillar-seed --status --announce https://pillar.uuaid.org
7
+ * pillar-seed --public-url https://seed.example.org --announce https://<registry>
8
+ * pillar-seed --status --announce https://<registry>
9
+ * pillar-seed --help
9
10
  *
10
11
  * A seed IS a carrier server with a public URL — nothing else. Agents
11
12
  * anywhere list your URL in their carriers[] and then:
@@ -40,30 +41,172 @@
40
41
  * --public-url — never the loopback one.
41
42
  */
42
43
  import "../src/node-check.mjs"; // must stay the first import: refuses Node < 22 before any dependency loads
43
- import { mkdirSync } from "node:fs";
44
+ import { chmodSync, closeSync, constants as fsConstants, existsSync, fstatSync, mkdirSync, openSync, readSync, statSync } from "node:fs";
45
+ import { createServer } from "node:net";
44
46
  import { homedir } from "node:os";
45
- import { join } from "node:path";
46
- import { CarrierServer, parseSecureDelete, parseCommunityWaits } from "../src/net/carrier-server.mjs";
47
- import { Keychain, mintNamespace, SERVICE_IDENTITY_NAMESPACE } from "../src/identity/keychain.mjs";
47
+ import { join, resolve } from "node:path";
48
+ import { CarrierServer, parseSecureDelete, parseCommunityWaits, MAX_TTL_DAYS } from "../src/net/carrier-server.mjs";
49
+ import { parseTrustedProxies } from "../src/net/client-ip.mjs";
50
+ import { Keychain, keyDerivesUuaid, mintNamespace, SERVICE_IDENTITY_NAMESPACE } from "../src/identity/keychain.mjs";
51
+
52
+ const USAGE = `usage: pillar-seed [flags]
53
+
54
+ Runs a pillar seed: a carrier server that stores and forwards sealed envelopes.
55
+ It listens on 127.0.0.1 by default; put a TLS-terminating proxy in front of it
56
+ and pass the proxy's address as --public-url.
57
+
58
+ --home <dir> seed key directory (SEED_HOME, default ~/.pillar-seed)
59
+ --db <file> SQLite database (SEED_DB, default <home>/seed.db; a
60
+ ./pillar-seed.db left by 2.4 or earlier is still used)
61
+ --namespace <ns> foundation, pillar or agentnet, for a NEW key only
62
+ (SEED_NAMESPACE, default foundation)
63
+ --passphrase-file <f> file holding the seed key's passphrase; or set
64
+ SEED_KEYCHAIN_PASSPHRASE. Default: no passphrase
65
+ --host <addr> listen address (SEED_HOST, default 127.0.0.1)
66
+ --port <n> listen port (SEED_PORT, default 8799)
67
+ --ttl <days> envelope lifetime (SEED_TTL_DAYS, default 14, at most 36500)
68
+ --public-url <https://> the URL your proxy serves (SEED_PUBLIC_URL)
69
+ --secure-delete <on|off> zero expired envelopes (SEED_SECURE_DELETE, default on)
70
+ --community-waits <n> long-poll slots (SEED_COMMUNITY_WAITS, default 48)
71
+ --trusted-proxy <ips> whose X-Forwarded-For counts for per-IP budgets
72
+ (SEED_TRUSTED_PROXIES, default 127.0.0.1,::1)
73
+ --announce <registry> enroll --public-url in a seed registry
74
+ --operator <name> operator label sent with --announce (SEED_OPERATOR)
75
+ --region <name> region label sent with --announce (SEED_REGION)
76
+ --status with --announce: print this seed's standing, then exit
77
+ -h, --help print this help and exit
78
+
79
+ Write a value as --flag value or --flag=value. A value that starts with "-"
80
+ must be written --flag=<value>: a separate token starting with "-" is never
81
+ taken as a value. The first start creates the seed key in --home (mode 0700 if
82
+ pillar-seed creates it), with --namespace and the passphrase given then; an
83
+ existing key keeps its namespace and passphrase. --status reads only the key's
84
+ public part, so it needs no passphrase.
85
+
86
+ Refused before anything is written: an unknown flag; a bare word (such as
87
+ "help"); a value flag with no value; a value given to --help or --status; a
88
+ SEED_* variable set to an empty string; an invalid --port, --ttl (digits with
89
+ an optional decimal part, above 0, at most 36500) or --community-waits; a
90
+ --host with spaces; a host and port that cannot be listened on (unresolvable,
91
+ not on this machine, or in use); a --passphrase-file that is not a regular
92
+ file; and a damaged key file, including one whose uuaid does not belong to its
93
+ key. Every refusal is one line on stderr, with exit code 2.`;
94
+
95
+ // Every flag this command reads. Every other token is refused before the seed
96
+ // key or the database is touched, so a typo, a bare word or `--help` never
97
+ // 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"]);
99
+ // Flags that only mean something with a value. Given bare, 2.4 fell through to a
100
+ // 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"];
102
+ // Flags that take no value in either form. `--help=` would otherwise set help to
103
+ // "" (falsy) and start a seed; `--status help` would swallow the word.
104
+ const BOOL_FLAGS = new Set(["help", "status"]);
105
+ // Every environment variable this command reads as a setting. One set to "" is
106
+ // refused like a bare flag: in 2.4 an empty SEED_HOST listened on every
107
+ // interface, an empty SEED_PORT took a random port, and an empty SEED_DB kept
108
+ // 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"];
110
+
111
+ const VALUE_SET = new Set(VALUE_FLAGS);
112
+ // The longest envelope lifetime accepted, MAX_TTL_DAYS (36500, 100 years), comes
113
+ // from carrier-server.mjs, which enforces it too (2.5.3): past year 9999 a stored
114
+ // deadline sorted before today and the hourly vacuum deleted fresh mail.
48
115
 
49
116
  function parseArgs(argv) {
50
117
  const args = {};
118
+ const unknown = [];
119
+ const dashed = []; // value flags followed by a token starting with "-", which is never a value
51
120
  for (let i = 0; i < argv.length; i++) {
52
121
  const a = argv[i];
53
- if (a.startsWith("--")) {
54
- const k = a.slice(2);
55
- args[k] = (argv[i + 1] && !argv[i + 1].startsWith("--")) ? argv[++i] : true;
122
+ if (a === "-h") {
123
+ args.help = true;
124
+ } else if (a.startsWith("--") && a.length > 2) {
125
+ // --flag=value, as `pillar` takes it, or --flag followed by its value.
126
+ const eq = a.indexOf("=");
127
+ const k = eq === -1 ? a.slice(2) : a.slice(2, eq);
128
+ if (!FLAGS.has(k)) unknown.push(eq === -1 ? a : `--${k}`);
129
+ else if (BOOL_FLAGS.has(k)) {
130
+ if (eq === -1) args[k] = true; else unknown.push(`--${k}=`);
131
+ continue; // never takes the next token as its value
132
+ }
133
+ if (eq !== -1) {
134
+ args[k] = a.slice(eq + 1);
135
+ } else if (argv[i + 1] && !argv[i + 1].startsWith("-")) {
136
+ args[k] = argv[++i];
137
+ } else {
138
+ args[k] = true;
139
+ if (argv[i + 1]?.startsWith("-") && VALUE_SET.has(k)) dashed.push(k);
140
+ }
141
+ } else {
142
+ // A bare word ("help"), a single-dash token ("-9", "-"), "--" or "":
143
+ // 2.4 ignored all of these and started a seed.
144
+ unknown.push(a);
56
145
  }
57
146
  }
58
- return args;
147
+ return { args, unknown, dashed };
59
148
  }
60
149
 
61
- const args = parseArgs(process.argv.slice(2));
150
+ /**
151
+ * Refuse to start: one line to stderr, exit 2, and nothing has been written.
152
+ * A control character in the message (a newline in an echoed --home path, a
153
+ * --namespace value or a key file's contents) is shown escaped, so a refusal is
154
+ * always exactly one line.
155
+ */
156
+ function refuse(message) {
157
+ console.error(`pillar-seed: ${oneLine(message)}`);
158
+ process.exit(2);
159
+ }
160
+ const ESCAPES = { "\n": "\\n", "\r": "\\r", "\t": "\\t" };
161
+ // U+2028 and U+2029 too: JSON.stringify leaves them as they are, and some
162
+ // terminals and log viewers break the line on them (2.5.3).
163
+ function oneLine(text) {
164
+ return String(text).replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g, (c) => ESCAPES[c] ?? `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
165
+ }
166
+ /** An operator's token as a message shows it: as typed when it is plain, else JSON-quoted. */
167
+ const shown = (token) => (/^[\x21-\x7e]+$/.test(token) ? token : JSON.stringify(token));
168
+
169
+ const { args, unknown, dashed } = parseArgs(process.argv.slice(2));
170
+ // Checked before --help: in `--home -h` the "-h" may have been meant as the value.
171
+ // The names come from `dashed` as well as from `args`: a repeated flag
172
+ // (`--port -1 --port 0`) has a value in `args` by now, and is still refused.
173
+ if (dashed.length) {
174
+ const missing = VALUE_FLAGS.filter((k) => dashed.includes(k) || args[k] === true || args[k] === "").map((k) => `--${k}`);
175
+ refuse(`${missing.join(", ")} need${missing.length > 1 ? "" : "s"} a value; a value that starts with "-" is written --${dashed[0]}=<value>. See pillar-seed --help.`);
176
+ }
177
+ if (args.help) {
178
+ console.log(USAGE);
179
+ process.exit(0);
180
+ }
181
+ if (unknown.length) {
182
+ const flags = unknown.filter((t) => /^-./.test(t) && t !== "--");
183
+ const words = unknown.filter((t) => !flags.includes(t));
184
+ const parts = [];
185
+ const valued = flags.filter((t) => t.endsWith("="));
186
+ const unknownFlags = flags.filter((t) => !t.endsWith("="));
187
+ if (unknownFlags.length) parts.push(`unknown flag${unknownFlags.length > 1 ? "s" : ""} ${unknownFlags.map(shown).join(", ")}`);
188
+ if (valued.length) parts.push(`${valued.map((t) => t.slice(0, -1)).join(", ")} take${valued.length > 1 ? "" : "s"} no value`);
189
+ if (words.length) parts.push(`unexpected argument${words.length > 1 ? "s" : ""} ${words.map((w) => JSON.stringify(w)).join(", ")} (pillar-seed takes only flags)`);
190
+ refuse(`${parts.join("; ")}. See pillar-seed --help.`);
191
+ }
192
+ const bare = VALUE_FLAGS.filter((k) => args[k] === true || args[k] === "").map((k) => `--${k}`);
193
+ if (bare.length) refuse(`${bare.join(", ")} need${bare.length > 1 ? "" : "s"} a value. See pillar-seed --help.`);
194
+ const emptyEnv = SEED_ENV.filter((n) => process.env[n] === "");
195
+ if (emptyEnv.length) refuse(`${emptyEnv.join(", ")} ${emptyEnv.length > 1 ? "are" : "is"} set but empty: unset ${emptyEnv.length > 1 ? "them" : "it"} or give a value`);
62
196
  const home = args.home ?? process.env.SEED_HOME ?? join(homedir(), ".pillar-seed");
63
- const port = Number(args.port ?? process.env.SEED_PORT ?? 8799);
197
+ const portText = String(args.port ?? process.env.SEED_PORT ?? 8799);
198
+ const port = Number(portText);
199
+ // The rule Node's listen() applies anyway, checked here so a bad value is refused
200
+ // before the key is minted rather than after. Digits only, so " " or "0x10" is not
201
+ // read as a port (Number(" ") is 0, a random port).
202
+ if (!/^[0-9]+$/.test(portText) || port > 65535) refuse(`--port must be a whole number from 0 to 65535, not ${JSON.stringify(portText)}`);
64
203
  const host = args.host ?? process.env.SEED_HOST ?? "127.0.0.1";
65
- const dbPath = args.db ?? process.env.SEED_DB ?? "pillar-seed.db";
66
- const ttlDays = Number(args.ttl ?? process.env.SEED_TTL_DAYS ?? 14);
204
+ if (/\s/.test(host)) refuse(`--host must not contain spaces, not ${JSON.stringify(host)}`);
205
+ const ttlText = String(args.ttl ?? process.env.SEED_TTL_DAYS ?? 14);
206
+ const ttlDays = Number(ttlText);
207
+ // Digits with an optional decimal part: Number() alone also took "0x10", "1e3", "+14" and " 14".
208
+ 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
+ if (ttlDays > MAX_TTL_DAYS) refuse(`--ttl must be at most ${MAX_TTL_DAYS} days (100 years), not ${JSON.stringify(ttlText)}`);
67
210
  const publicUrl = args["public-url"] ?? process.env.SEED_PUBLIC_URL ?? null;
68
211
  const registryUrl = typeof args.announce === "string" ? args.announce.replace(/\/+$/, "") : null;
69
212
  const operator = args.operator ?? process.env.SEED_OPERATOR ?? null;
@@ -73,22 +216,145 @@ let secureDelete;
73
216
  try {
74
217
  secureDelete = parseSecureDelete(args["secure-delete"] ?? process.env.SEED_SECURE_DELETE);
75
218
  } catch (e) {
76
- console.error(`pillar-seed: ${e.message}`);
77
- process.exit(2);
219
+ refuse(e.message);
220
+ }
221
+ let communityInboxWaits;
222
+ try {
223
+ communityInboxWaits = parseCommunityWaits(args["community-waits"] ?? process.env.SEED_COMMUNITY_WAITS ?? process.env.CARRIER_COMMUNITY_WAITS);
224
+ } catch (e) {
225
+ refuse(e.message);
226
+ }
227
+ // Whose X-Forwarded-For counts for the per-IP budgets (2.5.3): this machine by default.
228
+ let trustedProxies;
229
+ try {
230
+ trustedProxies = parseTrustedProxies(args["trusted-proxy"] ?? process.env.SEED_TRUSTED_PROXIES);
231
+ } catch (e) {
232
+ refuse(e.message);
233
+ }
234
+
235
+ // The seed key's passphrase: a file (preferred: a systemd credential) or an
236
+ // environment variable, never a flag value, so it is never in argv or ps. It is
237
+ // used to save a new key and to open an existing one. Without either, the key
238
+ // is saved and opened with no passphrase, as in 2.4. It is never printed.
239
+ let passphrase;
240
+ const passphraseFile = args["passphrase-file"];
241
+ const envPassphrase = process.env.SEED_KEYCHAIN_PASSPHRASE;
242
+ delete process.env.SEED_KEYCHAIN_PASSPHRASE;
243
+ if (passphraseFile !== undefined && envPassphrase !== undefined) refuse("give the passphrase once: --passphrase-file or SEED_KEYCHAIN_PASSPHRASE, not both");
244
+ if (passphraseFile !== undefined) {
245
+ // stat first, so a FIFO, directory, socket or device is refused without opening it
246
+ // (opening a FIFO blocks until a writer appears); O_NONBLOCK covers a swap after the stat.
247
+ let first;
248
+ try { first = statSync(passphraseFile); } catch (e) { refuse(`cannot read --passphrase-file ${passphraseFile}: ${e.code ?? e.message}`); }
249
+ if (!first.isFile()) refuse(`--passphrase-file ${passphraseFile} is not a regular file`);
250
+ let fd;
251
+ try {
252
+ fd = openSync(passphraseFile, fsConstants.O_RDONLY | fsConstants.O_NONBLOCK);
253
+ const st = fstatSync(fd);
254
+ if (!st.isFile()) refuse(`--passphrase-file ${passphraseFile} is not a regular file`);
255
+ if (st.size > 4096) refuse(`--passphrase-file ${passphraseFile} is larger than 4096 bytes`);
256
+ if (st.mode & 0o077) console.error(`pillar-seed: warning: ${passphraseFile} can be read by other users (mode ${(st.mode & 0o777).toString(8)}); chmod 600 it`);
257
+ const buf = Buffer.alloc(st.size);
258
+ const n = st.size ? readSync(fd, buf, 0, st.size, 0) : 0;
259
+ passphrase = buf.subarray(0, n).toString("utf-8").replace(/\r?\n$/, "");
260
+ } catch (e) {
261
+ refuse(`cannot read --passphrase-file ${passphraseFile}: ${e.code ?? e.message}`);
262
+ } finally {
263
+ if (fd !== undefined) closeSync(fd);
264
+ }
265
+ if (passphrase === "") refuse(`--passphrase-file ${passphraseFile} is empty`);
266
+ } else if (envPassphrase !== undefined) {
267
+ passphrase = envPassphrase; // never "": an empty SEED_KEYCHAIN_PASSPHRASE was refused above
78
268
  }
79
269
 
80
270
  /**
81
271
  * The seed's identity. Distinct from any agent keychain on the box: it names
82
272
  * the SEED, is what /v1/seed-info is signed with, and is the subject of any
83
273
  * tier grant the seed earns.
274
+ *
275
+ * Its namespace is chosen once, when the key is minted: --namespace or
276
+ * SEED_NAMESPACE, else SERVICE_IDENTITY_NAMESPACE (foundation). A later start
277
+ * that names a different namespace refuses rather than minting a new key.
278
+ */
279
+ const requestedNamespace = args.namespace ?? process.env.SEED_NAMESPACE;
280
+ if (requestedNamespace !== undefined) {
281
+ try { mintNamespace(requestedNamespace); } catch (e) { refuse(e.message); }
282
+ }
283
+ const keyPath = join(home, "seed-keychain.json");
284
+ const keychain = new Keychain(keyPath);
285
+ /**
286
+ * The uuaid recorded in an existing key file's public part; a damaged file is
287
+ * refused, never replaced. The uuaid must be the one its public key derives:
288
+ * every seed key pillar-seed has minted is key-derived in a self-certifying
289
+ * namespace, so a mismatch is a file someone edited or swapped. Checked on
290
+ * every path (start, --status, --namespace), so a seed never starts or reports
291
+ * under a uuaid its key cannot prove.
84
292
  */
85
- mkdirSync(home, { recursive: true });
86
- const keychain = new Keychain(join(home, "seed-keychain.json"));
293
+ function savedUuaidOf() {
294
+ let pub;
295
+ try { pub = keychain.publicView(); } catch (e) {
296
+ refuse(`the seed key ${keyPath} is damaged or is not a key file (${String(e.code ?? e.message).replace(/\s+/g, " ").slice(0, 120)}). Nothing was replaced.`);
297
+ }
298
+ if (typeof pub?.uuaid !== "string" || pub.uuaid.split(":").length < 4) refuse(`the seed key ${keyPath} is damaged or is not a key file (no uuaid). Nothing was replaced.`);
299
+ if (typeof pub.publicKeyHex !== "string") refuse(`the seed key ${keyPath} is damaged or is not a key file (no public key). Nothing was replaced.`);
300
+ if (!keyDerivesUuaid(pub.publicKeyHex, pub.uuaid)) refuse(`the seed key ${keyPath} is damaged or is not a key file (its uuaid does not belong to its key). Nothing was replaced.`);
301
+ return pub.uuaid;
302
+ }
303
+ const savedUuaid = keychain.exists() ? savedUuaidOf() : undefined;
304
+ if (savedUuaid !== undefined && requestedNamespace !== undefined && savedUuaid.split(":")[1] !== requestedNamespace) {
305
+ refuse(`this seed's key is ${savedUuaid}; --namespace/SEED_NAMESPACE ${requestedNamespace} applies only when a new key is minted. Start without it, or use a new --home for a new key.`);
306
+ }
307
+ // --status is a query about an existing seed. It reads only the key's public part,
308
+ // so it needs no passphrase, never loads the private key and writes nothing.
309
+ if (args.status) {
310
+ if (!registryUrl) refuse("--status needs --announce <registry-url> to know which registry to ask");
311
+ if (savedUuaid === undefined) {
312
+ const homeGiven = args.home !== undefined || process.env.SEED_HOME !== undefined;
313
+ 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
+ }
315
+ console.log(`seed ${savedUuaid}`);
316
+ await printStanding(registryUrl, savedUuaid);
317
+ process.exit(0);
318
+ }
319
+ // Bind the host and port once, before the key or database exists, and keep the
320
+ // listener: the server takes it over below, so the port cannot be lost in between
321
+ // (2.5.3; up to 2.5.2 this listened, closed, and listened again after minting, and
322
+ // a port taken in that gap failed the start with the key already minted). A host
323
+ // that does not resolve, an address not on this machine, or a port in use is
324
+ // refused with nothing written. A connection that arrives before the seed serves
325
+ // is reset, as a closed port would refuse it.
326
+ const listener = await new Promise((done) => {
327
+ const probe = createServer((socket) => socket.destroy());
328
+ probe.once("error", (e) => {
329
+ const why = {
330
+ EADDRINUSE: `port ${port} is already in use on ${host}`,
331
+ EADDRNOTAVAIL: `${host} is not an address on this machine`,
332
+ ENOTFOUND: `${host} does not resolve`,
333
+ EAI_AGAIN: `${host} could not be resolved (EAI_AGAIN)`,
334
+ EACCES: `listening on port ${port} needs privileges`,
335
+ }[e.code] ?? `cannot listen on ${host}:${port} (${e.code ?? e.message})`;
336
+ refuse(`--host/--port: ${why}. Nothing was written.`);
337
+ });
338
+ probe.listen(port, host, () => done(probe));
339
+ });
340
+ const homeExisted = existsSync(home);
341
+ mkdirSync(home, { recursive: true, mode: 0o700 });
342
+ if (!homeExisted) chmodSync(home, 0o700); // whatever the umask; an existing home keeps its mode
87
343
  if (!keychain.exists()) {
88
- keychain.save(Keychain.generate({ uuaidNamespace: mintNamespace(SERVICE_IDENTITY_NAMESPACE) }));
89
- console.log(`minted seed identity -> ${join(home, "seed-keychain.json")}`);
344
+ const identity = requestedNamespace === undefined
345
+ ? Keychain.generate({ uuaidNamespace: mintNamespace(SERVICE_IDENTITY_NAMESPACE) })
346
+ : Keychain.generate({ uuaidNamespace: mintNamespace(requestedNamespace) });
347
+ keychain.save(identity, { passphrase });
348
+ console.log(`minted seed identity -> ${keyPath}${passphrase === undefined ? "" : " (passphrase-protected)"}`);
349
+ }
350
+ try {
351
+ keychain.load({ passphrase });
352
+ } catch (e) {
353
+ const hint = passphrase === undefined
354
+ ? "If it was saved with a passphrase, pass --passphrase-file or SEED_KEYCHAIN_PASSPHRASE."
355
+ : "A key saved by pillar-seed 2.4 or earlier has no passphrase: start without one. A passphrase cannot be added to an existing key.";
356
+ refuse(`cannot open the seed key ${keyPath}: wrong or missing passphrase, or a damaged file (${e.message}). Nothing was replaced. ${hint}`);
90
357
  }
91
- keychain.load();
92
358
 
93
359
  /** Ask a registry where we stand and print the ladder position. */
94
360
  async function printStanding(registry, uuaid) {
@@ -111,26 +377,27 @@ async function printStanding(registry, uuaid) {
111
377
  }
112
378
  }
113
379
 
114
- // --status is a query, not a server: report and exit.
115
- if (args.status) {
116
- if (!registryUrl) {
117
- console.error("--status needs --announce <registry-url> to know which registry to ask");
118
- process.exit(1);
380
+ // The database. An explicit --db or SEED_DB is used as given, as in 2.4. Without
381
+ // one, the default is <home>/seed.db; 2.4's default was ./pillar-seed.db in the
382
+ // working directory, so a seed upgraded in place keeps that file rather than
383
+ // starting empty beside it.
384
+ let dbPath = args.db ?? process.env.SEED_DB;
385
+ if (dbPath === undefined) {
386
+ const homeDb = join(home, "seed.db");
387
+ const legacyDb = resolve("pillar-seed.db");
388
+ if (!existsSync(homeDb) && existsSync(legacyDb)) {
389
+ dbPath = legacyDb;
390
+ console.log(`notice: using ${legacyDb}, the 2.4 default in the working directory.`);
391
+ console.log(` To move it: stop the seed, move pillar-seed.db and any pillar-seed.db-wal and`);
392
+ console.log(` pillar-seed.db-shm beside it to ${homeDb} (keeping the -wal/-shm suffixes), then start again.`);
393
+ } else {
394
+ dbPath = homeDb;
395
+ if (existsSync(legacyDb)) console.error(`pillar-seed: warning: ${legacyDb} exists but is not used; this seed's database is ${homeDb}.`);
119
396
  }
120
- console.log(`seed ${keychain._identity.uuaid}`);
121
- await printStanding(registryUrl, keychain._identity.uuaid);
122
- process.exit(0);
123
397
  }
124
398
 
125
- let communityInboxWaits;
126
- try {
127
- communityInboxWaits = parseCommunityWaits(args["community-waits"] ?? process.env.SEED_COMMUNITY_WAITS ?? process.env.CARRIER_COMMUNITY_WAITS);
128
- } catch (e) {
129
- console.error(`pillar-seed: ${e.message}`);
130
- process.exit(2);
131
- }
132
- const server = new CarrierServer({ dbPath, ttlDays, keychain, publicUrl, secureDelete, communityInboxWaits });
133
- const addr = await server.listen(port, host);
399
+ const server = new CarrierServer({ dbPath, ttlDays, keychain, publicUrl, secureDelete, communityInboxWaits, trustedProxies });
400
+ const addr = await server.listen(listener);
134
401
  console.log(`pillar-seed listening on http://${addr.address}:${addr.port}`);
135
402
  console.log(` uuaid: ${keychain._identity.uuaid}`);
136
403
  console.log(` db: ${dbPath}`);
@@ -168,19 +435,23 @@ if (registryUrl) {
168
435
  console.log(` enrollment refused: ${body.reason ?? res.status}`);
169
436
  if (String(body.reason ?? "").startsWith("seed-unreachable")) {
170
437
  console.log(` (the registry could not fetch ${publicUrl}/v1/seed-info — check DNS, TLS, and your proxy)`);
438
+ } else if (body.reason === undefined && (res.status === 404 || res.status === 405)) {
439
+ // A carrier with no registry mounted (pillar.uuaid.org today) answers 404 here (2.5.3).
440
+ console.log(` (no seed registry answers at ${registryUrl}: POST /v1/seeds is ${res.status}. This seed keeps`);
441
+ console.log(` running standalone, used by every client that lists ${publicUrl} as a carrier.)`);
171
442
  }
172
443
  }
173
444
  } catch (e) {
174
445
  console.log(` enrollment failed: ${e.message}`);
175
446
  }
176
447
  }
448
+ } else if (publicUrl) {
449
+ console.log(`\n serving ${publicUrl} through your proxy; not announced to any registry.`);
177
450
  } else if (host === "127.0.0.1") {
178
- console.log(`\n loopback seed — reachable only from this machine.`);
179
- console.log(` To join the mesh as a real seed: TLS-terminate a public URL, then`);
180
- console.log(` pillar-seed --host 0.0.0.0 --public-url https://<your-host> \\`);
181
- console.log(` --announce https://pillar.uuaid.org --operator <you> --region <region>`);
182
- console.log(` Enrollment is permissionless: the registry verifies the URL against your`);
183
- console.log(` seed key and lists you. Staying up is what earns the rest.`);
451
+ console.log(`\n loopback only: no public URL is set.`);
452
+ console.log(` To serve the public, put a TLS-terminating proxy (Caddy or nginx) on this`);
453
+ console.log(` machine in front of 127.0.0.1:${addr.port}, keep --host 127.0.0.1, and restart`);
454
+ console.log(` with --public-url https://<your-domain>.`);
184
455
  }
185
456
 
186
457
  // Vacuum expired envelopes hourly.
package/bin/pillar.mjs CHANGED
@@ -34,7 +34,8 @@ import { mkdirSync, existsSync, readFileSync, writeFileSync, renameSync } from "
34
34
  import { join, dirname } from "node:path";
35
35
  import { homedir } from "node:os";
36
36
  import { argv, exit } from "node:process";
37
- import { Keychain, mintNamespace, SELF_CERTIFYING_NAMESPACES } from "../src/identity/keychain.mjs";
37
+ import { Keychain, mintNamespace, SELF_CERTIFYING_NAMESPACES, localIdFromKey } from "../src/identity/keychain.mjs";
38
+ import { peerIdFromSeedHex } from "../src/net/transport.mjs";
38
39
  import { Pillar } from "../src/pillar.mjs";
39
40
  import { loadFleetAddressBook, inspectFleetFile, resolveRecipient, explainMissingKey } from "../src/address-book.mjs";
40
41
  import { loadTrustPolicy, POLICIES } from "../src/identity/trust.mjs";
@@ -211,7 +212,7 @@ function writeRuntimeFile(pillar, home) {
211
212
  pid: process.pid,
212
213
  startedAt: new Date().toISOString(),
213
214
  };
214
- writeFileSync(join(home, "runtime.json"), JSON.stringify(rt, null, 2));
215
+ writeFileSync(join(home, "runtime.json"), JSON.stringify(rt, null, 2), { mode: 0o600 });
215
216
  }
216
217
 
217
218
  // Carrier list + address book merge from a fetched directory — shared by
@@ -238,7 +239,7 @@ function mergeDirectoryAgents(home, d) {
238
239
  };
239
240
  if (!prev[key]) added++;
240
241
  }
241
- writeFileSync(fleetPath, JSON.stringify({ fleet }, null, 2));
242
+ writeFileSync(fleetPath, JSON.stringify({ fleet }, null, 2), { mode: 0o600 });
242
243
  return { count: Object.keys(fleet).length, added };
243
244
  }
244
245
 
@@ -277,7 +278,7 @@ async function cmdInit(args) {
277
278
  const cfgPath = join(home, "config.json");
278
279
  const cfg = existsSync(cfgPath) ? JSON.parse(readFileSync(cfgPath, "utf-8")) : {};
279
280
  cfg.carriers = list;
280
- writeFileSync(cfgPath, JSON.stringify(cfg, null, 2));
281
+ writeFileSync(cfgPath, JSON.stringify(cfg, null, 2), { mode: 0o600 });
281
282
  console.log(`carriers refreshed from ${args.directory}: ${list.join(", ")}`);
282
283
  const ab = mergeDirectoryAgents(home, d);
283
284
  if (ab) console.log(`address book: ${ab.count} peers in ${join(home, "fleet.json")} (${ab.added} new from directory)`);
@@ -331,7 +332,7 @@ async function cmdInit(args) {
331
332
  } else if (args.carriers) {
332
333
  cfg.carriers = args.carriers.split(",").map(s => s.trim()).filter(Boolean);
333
334
  }
334
- writeFileSync(join(home, "config.json"), JSON.stringify(cfg, null, 2));
335
+ writeFileSync(join(home, "config.json"), JSON.stringify(cfg, null, 2), { mode: 0o600 });
335
336
  console.log(`initialized pillar at ${home}`);
336
337
  console.log(`uuaid: ${id.uuaid}`);
337
338
  console.log(`publicKey: ${id.publicKeyHex}`);
@@ -415,20 +416,59 @@ async function confirmAndArchiveIdentity(home, old, args) {
415
416
  return { uuaid: current, dir };
416
417
  }
417
418
 
419
+ /**
420
+ * pillar id — read-only (2.5.3). It reads only the key file's public part and
421
+ * config.json: no passphrase, no mailbox, no libp2p node. Up to 2.5.2 it ran
422
+ * loadPillar + start(), which opened (and migrated) the mailbox and started a
423
+ * node on this identity, beside any `pillar recv` already running on it.
424
+ * The peerId needs the key itself (createTransport reads the seed as a
425
+ * secp256k1 key), so it is printed when the key opens with PILLAR_PASSPHRASE
426
+ * (default empty); opening it only decrypts it in memory. Live addresses come
427
+ * from runtime.json, written by a running `pillar recv`.
428
+ */
418
429
  async function cmdId(args) {
419
- const p = loadPillar(args);
420
- await p.start();
421
- console.log(`uuaid: ${p.uuaid}`);
422
- console.log(`publicKey: ${p.publicKeyHex}`);
423
- if (p.node) {
424
- console.log(`peerId: ${p.node.peerId.toString()}`);
425
- console.log(`addrs:`);
426
- for (const a of p.node.getMultiaddrs()) console.log(` ${a.toString()}`);
427
- } else {
430
+ const home = homePath(args);
431
+ const kc = new Keychain(join(home, "keychain.json"));
432
+ if (!kc.exists()) {
433
+ console.error(`no pillar found at ${home}. run: pillar init`);
434
+ exit(2);
435
+ }
436
+ let pub;
437
+ try { pub = kc.publicView(); } catch (e) {
438
+ console.error(`${kc.path} is damaged or is not a key file (${String(e.message).replace(/\s+/g, " ").slice(0, 120)})`);
439
+ exit(2);
440
+ }
441
+ const parts = typeof pub?.uuaid === "string" ? pub.uuaid.split(":") : [];
442
+ if (parts.length < 4 || typeof pub.publicKeyHex !== "string" || !/^[0-9a-f]{64}$/i.test(pub.publicKeyHex)
443
+ || parts[3] !== localIdFromKey(Buffer.from(pub.publicKeyHex, "hex"))) {
444
+ // The same integrity rule as Keychain.load(): the uuaid's local id comes from the key.
445
+ console.error(`${kc.path} is damaged or is not a key file (its uuaid does not belong to its key)`);
446
+ exit(2);
447
+ }
448
+ const cfg = readConfig(home);
449
+ console.log(`uuaid: ${pub.uuaid}`);
450
+ console.log(`publicKey: ${pub.publicKeyHex}`);
451
+ if (args["carrier-only"] || cfg.carrierOnly === true) {
428
452
  console.log(`mode: carrier-only (no libp2p)`);
453
+ } else {
454
+ let peerId = null;
455
+ try {
456
+ const der = kc.load({ passphrase: process.env.PILLAR_PASSPHRASE ?? "" }).privateKey.export({ type: "pkcs8", format: "der" });
457
+ peerId = peerIdFromSeedHex(Buffer.from(der.slice(der.length - 32)).toString("hex")).toString();
458
+ } catch { /* wrong or missing passphrase: the public part above is still right */ }
459
+ console.log(`peerId: ${peerId ?? "unknown: the key did not open (set PILLAR_PASSPHRASE to show it)"}`);
460
+ let rt = null;
461
+ try { rt = JSON.parse(readFileSync(join(home, "runtime.json"), "utf-8")); } catch { /* none, or unreadable */ }
462
+ if (rt?.uuaid === pub.uuaid && Array.isArray(rt.addrs) && rt.addrs.length) {
463
+ console.log(`addrs: (from runtime.json, written by pillar recv pid ${rt.pid ?? "?"} at ${rt.startedAt ?? "?"})`);
464
+ for (const a of rt.addrs) console.log(` ${a}`);
465
+ } else {
466
+ console.log(`addrs: none published (pillar id starts nothing; a running pillar recv writes its addresses to runtime.json)`);
467
+ }
429
468
  }
430
- if (p.carriers?.length) console.log(`carriers: ${p.carriers.join(", ")}`);
431
- await p.stop();
469
+ const carriers = args.carrier ? [args.carrier]
470
+ : (process.env.PILLAR_CARRIERS ? process.env.PILLAR_CARRIERS.split(",") : (cfg.carriers ?? []));
471
+ if (carriers.length) console.log(`carriers: ${carriers.join(", ")}`);
432
472
  }
433
473
 
434
474
  async function cmdSend(args) {
@@ -458,15 +498,17 @@ async function cmdSend(args) {
458
498
  exit(1);
459
499
  }
460
500
  try {
461
- const { envelope, delivery } = await p.send({
501
+ const sent = await p.send({
462
502
  recipient, kind, payload,
463
503
  recipientPublicKey: toKey, // explicit key for peers outside fleet.json
464
504
  resolveTimeoutMs: 5000,
465
505
  });
506
+ const { envelope, delivery } = sent;
466
507
  console.log(`sent envelope ${envelope.id}`);
467
508
  console.log(` to: ${recipient}${recipient !== recipientArg ? ` (${recipientArg})` : ""}`);
468
509
  console.log(` kind: ${kind}`);
469
- if (delivery?.peerId) console.log(` via peerId: ${delivery.peerId}`);
510
+ if (sent.direct?.peerId) console.log(` via peerId: ${sent.direct.peerId}${sent.confirmed === false ? " (a direct stream only: nothing confirms it arrived)" : ""}`);
511
+ if (sent.confirmed === false) console.error(`warning: no carrier accepted ${envelope.id}${sent.carrierError ? ` (${sent.carrierError.message})` : ""}; it was written to a direct stream, which is not a receipt, so it stays pending until ${recipient} acks it.`);
470
512
  if (delivery?.carrier) console.log(` accepted by carrier ${delivery.carrier} (seq ${delivery.seq}) — that is the carrier's receipt, not the recipient's`);
471
513
  if (args["wait-ack"] !== undefined) {
472
514
  const secs = args["wait-ack"] === true ? 60 : Number(args["wait-ack"]);
@@ -1253,7 +1295,7 @@ async function cmdReceipts(args) {
1253
1295
  console.error("usage: pillar receipts [on|off] | [delivered on|off] | [read on|off]");
1254
1296
  exit(2);
1255
1297
  }
1256
- if (a !== undefined) { cfg.receipts = r; writeFileSync(cfgPath, JSON.stringify(cfg, null, 2)); }
1298
+ if (a !== undefined) { cfg.receipts = r; writeFileSync(cfgPath, JSON.stringify(cfg, null, 2), { mode: 0o600 }); }
1257
1299
  console.log(`delivery acks: ${r.delivered ? "on" : "off"} read receipts: ${r.read ? "on" : "off"} (${cfgPath})`);
1258
1300
  console.log(`sent only to contacts (fleet.json, trust allow, members of groups you accepted); read receipts go out on --mark-read.`);
1259
1301
  console.log(`read receipts are symmetric: with them off, incoming read receipts are ignored too. Delivery acks from others are always recorded.`);
@@ -1269,7 +1311,7 @@ async function cmdTrust(args) {
1269
1311
  const tPath = join(home, "trust.json");
1270
1312
  const t = loadTrustPolicy(home);
1271
1313
  const sub = args._[1];
1272
- const save = () => writeFileSync(tPath, JSON.stringify({ policy: t.policy, allow: t.allow, block: t.block }, null, 2));
1314
+ const save = () => writeFileSync(tPath, JSON.stringify({ policy: t.policy, allow: t.allow, block: t.block }, null, 2), { mode: 0o600 });
1273
1315
  if (!sub) {
1274
1316
  console.log(`policy: ${t.policy}${t.exists ? "" : " (no trust.json — default)"}`);
1275
1317
  console.log(`allow (${t.allow.length}):`); for (const u of t.allow) console.log(` ${u}`);
@@ -1374,7 +1416,7 @@ async function cmdTier(args) {
1374
1416
  maxBodyBytes: args["max-body"] ? Number(args["max-body"]) : undefined,
1375
1417
  });
1376
1418
  const out = typeof args.out === "string" ? args.out : `tier-grant-${grantFingerprint(grant)}.json`;
1377
- writeFileSync(out, JSON.stringify(grant, null, 2));
1419
+ writeFileSync(out, JSON.stringify(grant, null, 2), { mode: 0o600 });
1378
1420
  console.log(`issued ${tier} grant for ${uuaid}`);
1379
1421
  console.log(` rate ${grant.envelopesPerMin}/min, maxBody ${grant.maxBodyBytes}B, expires ${expires}`);
1380
1422
  console.log(` issuer ${grant.issuer}`);
@@ -1393,7 +1435,7 @@ async function cmdTier(args) {
1393
1435
  }
1394
1436
  const v = verifyTierGrant(g, [g.issuer]); // structural check (sig by named issuer, expiry, ceilings)
1395
1437
  if (!v.ok) { console.error(`grant invalid: ${v.reason}`); exit(1); }
1396
- writeFileSync(join(home, "tier-grant.json"), JSON.stringify(g, null, 2));
1438
+ writeFileSync(join(home, "tier-grant.json"), JSON.stringify(g, null, 2), { mode: 0o600 });
1397
1439
  console.log(`installed ${g.tier} grant (fingerprint ${grantFingerprint(g)}) — sent with every carrier deliver`);
1398
1440
  console.log(`note: budgets rise only at carriers that trust issuer ${g.issuer.slice(0, 16)}…`);
1399
1441
  return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uuaid/pillar",
3
- "version": "2.4.1",
3
+ "version": "2.5.3",
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",
package/src/blob/blob.mjs CHANGED
@@ -379,6 +379,9 @@ export async function prepareBlobSend(keychain, { data, envelopeId, recipient, t
379
379
  try {
380
380
  await store.put(ref.object, ct);
381
381
  } catch (e) {
382
+ // The reservation will never be finalized: give it back where the broker
383
+ // can take it (2.5.3; the hosted broker has no such call and lets it expire).
384
+ if (broker && challengeId && typeof broker.release === "function") await broker.release({ challengeId }).catch(() => {});
382
385
  if (e instanceof BlobError) throw e;
383
386
  throw new BlobUploadError(`blob upload failed for ${ref.object}: ${e.message}`, e);
384
387
  }