@uuaid/pillar 2.4.1 → 2.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/HOSTING-LIMITS.md CHANGED
@@ -5,7 +5,9 @@ clients do about each one, and how push/wake works. Read it before you write
5
5
  a poll loop or host a carrier, seed, or push relay.
6
6
 
7
7
  **Sources.** Each number is cited once, as `path:line`. Paths under `src/` and
8
- `bin/` are in this package (`@uuaid/pillar` 2.0.1). Paths under
8
+ `bin/` are in this package. `bin/` lines are as of 2.5.2. `src/` lines were
9
+ first cited at 2.0.1; `src/` is unchanged from 2.4.1 to 2.5.2, and the ones
10
+ spot-checked against it still match. Paths under
9
11
  `apps/`, `packages/` and `infra/` are in the UUAID monorepo at commit
10
12
  `7e51fa2`, which is not public. `infra/pillar-blob/server.mjs` is cited at
11
13
  monorepo commit `229c217`, the agent-first broker with RedTeam's conditions
@@ -80,10 +82,15 @@ start. Without the option nothing changes.
80
82
  **Windows, memory, retention.** Every rate window is a sliding 60 s (:84),
81
83
  held in process memory (:230), so a restart resets every budget; past 10,000
82
84
  keys the oldest is dropped (:90). Envelopes are kept 14 days by default (:156;
83
- `--ttl`, bin/carrier.mjs:32, bin/pillar-seed.mjs:66) and expired rows are
84
- deleted hourly (bin/carrier.mjs:46-49, bin/pillar-seed.mjs:171-174). Each row
85
+ `--ttl`, bin/carrier.mjs:46, bin/pillar-seed.mjs:204) and expired rows are
86
+ deleted hourly (bin/carrier.mjs:106-111, bin/pillar-seed.mjs:442-447). Each row
85
87
  keeps the deadline set when it was stored (`retain_until` = acceptance time +
86
88
  TTL), so lowering `--ttl` later never deletes a row before that deadline.
89
+ From 2.5.2 a seed's `--ttl` is at most 36500 days (bin/pillar-seed.mjs:207):
90
+ the deadline is stored as an ISO-8601 string, and past year 9999 it reads
91
+ `+010000-…`, which the hourly expiry compares as already past, so from about
92
+ 2,912,144 days mail was deleted on the next pass. `pillar-carrier --ttl` has
93
+ no ceiling yet; every shipped carrier unit passes `--ttl 14`.
87
94
 
88
95
  **Tier grants** (src/identity/tier.mjs:52-56). A signed grant in
89
96
  `x-pillar-tier-grant` raises its holder's send budgets:
@@ -98,8 +105,8 @@ TTL), so lowering `--ttl` later never deletes a row before that deadline.
98
105
 
99
106
  No grant can go above 6,000 sends per window or 2 MiB
100
107
  (src/identity/tier.mjs:67-68). Only `pillar-carrier --tier-issuers <hex>`
101
- honors grants (bin/carrier.mjs:35-38). `pillar-seed` passes no issuers
102
- (bin/pillar-seed.mjs:117), so on a seed every sender gets community budgets
108
+ honors grants (bin/carrier.mjs:57-58). `pillar-seed` passes no issuers
109
+ (bin/pillar-seed.mjs:387), so on a seed every sender gets community budgets
103
110
  and the priority reserves are never used. `@uuaid/pillar-client` never sends a
104
111
  grant.
105
112
 
@@ -296,11 +303,13 @@ registrations and 4 poll tokens.
296
303
  ## 5. Hosting a carrier, seed or relay
297
304
 
298
305
  `pillar-carrier` and `pillar-seed` listen on 127.0.0.1:8799 by default
299
- (bin/carrier.mjs:29-30, bin/pillar-seed.mjs:63-64). The relay listens on
306
+ (bin/carrier.mjs:43-44, bin/pillar-seed.mjs:195, :201). The relay listens on
300
307
  127.0.0.1:8801 (apps/pillar-push/src/config.ts:38-39). Put a TLS proxy in
301
- front of each one.
308
+ front of each one. The templates in the third column are in the monorepo
309
+ (see the top of this file), not in this package; the examples after the
310
+ table are complete on their own.
302
311
 
303
- | Proxy rule | Why | pillar-sfo (live) and repo template |
312
+ | Proxy rule | Why | pillar-sfo (live) and monorepo template |
304
313
  |---|---|---|
305
314
  | Carrier read timeout > 30 s + margin | The carrier can hold a request for 30 s plus one 400 ms tick | `/v1/` → 127.0.0.1:8799, 40 s; template: infra/pillar-carrier-fleet/provision-carrier.sh:102 |
306
315
  | Replace `X-Forwarded-For` with the peer's address | The carrier takes the first XFF entry as the client IP (:395-399). If the proxy appends to XFF, a client can pick its own rate bucket. If the proxy sends no XFF, all clients share the proxy's one bucket | template: `$remote_addr` (infra/pillar-carrier-fleet/provision-carrier.sh:107) |
@@ -308,6 +317,83 @@ front of each one.
308
317
  | CORS: allow `x-pillar-pubkey`, `x-pillar-ts`, `x-pillar-sig` | Browser clients send them. Also allow `x-pillar-delegation` and `x-pillar-tier-grant` if browsers poll by delegation or send grants | the template allows neither of those two (infra/pillar-carrier-nyc/nginx-setup.sh:25) |
309
318
  | Relay: a short timeout is fine | No relay route long-polls | `/push/` → 127.0.0.1:8801/, 30 s |
310
319
  | Blob objects: at least 50 MiB + headers | The largest blob object is 50 MiB | `/blob/objects/` 52m and 300 s; `/blob/` 1m and 40 s (infra/pillar-carrier-nyc/install-blob.sh:59-62, infra/pillar-carrier-nyc/install-blob.sh:71-74) |
320
+ | Answer the CORS preflight | The carrier sets no `Access-Control-*` header and has no `OPTIONS` route: it answers 404 (src/net/carrier-server.mjs). A browser sends `OPTIONS` before every `POST` with JSON and before every request carrying an `x-pillar-*` header | template: `OPTIONS` → 204 with the headers, and `Access-Control-Allow-Origin` on every response (infra/pillar-carrier-nyc/nginx-setup.sh:22-30). Both examples below do the same |
321
+
322
+ **Listen address.** Keep `--host 127.0.0.1` (the default) when the proxy runs
323
+ on the same machine. `--host 0.0.0.0` publishes the seed's plain-HTTP port
324
+ beside the proxy on every interface the firewall lets through. Use another
325
+ address only for a proxy on another machine, and allow the port from that
326
+ machine alone. Pass an absolute `--home`. From 2.5.1 `--db` defaults to
327
+ `<home>/seed.db`; up to 2.4.1 it defaulted to `pillar-seed.db` in the working
328
+ directory, and a seed upgraded in place keeps using that file until it is moved
329
+ (the start prints how). The seed key can be saved under a long random
330
+ passphrase from a file or `SEED_KEYCHAIN_PASSPHRASE` (README, "Running a
331
+ seed"). A `SEED_*` variable set to an empty string is refused (from 2.5.1): in
332
+ 2.4 an empty `SEED_HOST` listened on every interface, beside the proxy.
333
+
334
+ **A seed behind Caddy** (Caddy obtains the TLS certificate itself; its
335
+ `reverse_proxy` has no response timeout by default, so a 30 s long-poll passes):
336
+
337
+ ```caddyfile
338
+ seed.example.org {
339
+ header {
340
+ Access-Control-Allow-Origin "*"
341
+ Access-Control-Allow-Methods "GET, POST, OPTIONS"
342
+ Access-Control-Allow-Headers "content-type, x-pillar-pubkey, x-pillar-ts, x-pillar-sig, x-pillar-delegation, x-pillar-tier-grant"
343
+ Access-Control-Max-Age "600"
344
+ }
345
+
346
+ @preflight method OPTIONS
347
+ respond @preflight 204
348
+
349
+ request_body {
350
+ max_size 520KiB
351
+ }
352
+
353
+ reverse_proxy 127.0.0.1:8799 {
354
+ header_up X-Forwarded-For {remote_host}
355
+ }
356
+ }
357
+ ```
358
+
359
+ **The same with nginx** (certificates from your CA or certbot; certbot's HTTP-01
360
+ check needs port 80, so keep a `:80` server block, use `certbot --nginx`, or run
361
+ certbot standalone before nginx starts):
362
+
363
+ ```nginx
364
+ server {
365
+ listen 443 ssl;
366
+ listen [::]:443 ssl;
367
+ server_name seed.example.org;
368
+ ssl_certificate /etc/letsencrypt/live/seed.example.org/fullchain.pem;
369
+ ssl_certificate_key /etc/letsencrypt/live/seed.example.org/privkey.pem;
370
+
371
+ location /v1/ {
372
+ if ($request_method = OPTIONS) {
373
+ add_header Access-Control-Allow-Origin "*" always;
374
+ add_header Access-Control-Allow-Methods "GET, POST, OPTIONS" always;
375
+ add_header Access-Control-Allow-Headers "content-type, x-pillar-pubkey, x-pillar-ts, x-pillar-sig, x-pillar-delegation, x-pillar-tier-grant" always;
376
+ add_header Access-Control-Max-Age 600 always;
377
+ return 204;
378
+ }
379
+ add_header Access-Control-Allow-Origin "*" always;
380
+ client_max_body_size 520k;
381
+ proxy_pass http://127.0.0.1:8799;
382
+ proxy_http_version 1.1;
383
+ proxy_read_timeout 40s;
384
+ proxy_set_header Host $host;
385
+ proxy_set_header X-Forwarded-For $remote_addr;
386
+ }
387
+ }
388
+ ```
389
+
390
+ **Firewalls.** Open 80 and 443 in the **host** firewall as well as the cloud
391
+ provider's, and leave 8799 closed. Some cloud images ship host rules that
392
+ reject everything but SSH: Oracle's Ubuntu 24.04 image does.
393
+
394
+ **Use a real domain.** Free no-DNS hostnames (`*.sslip.io` and the like) are
395
+ blocked by some home and corporate network filters, so clients behind them
396
+ cannot reach a seed on one.
311
397
 
312
398
  **Under load:**
313
399
  - **`carrier-full` does not clear by itself.** `vacuum()` deletes expired rows
@@ -319,7 +405,7 @@ front of each one.
319
405
  carrier, run `sqlite3 <db> 'VACUUM;'`, and restart it. On a `pillar-seed`
320
406
  every sender is community, so that means everyone. Watch the file size.
321
407
  - **From 2.4.0 a start may run `VACUUM`.** Re-keying the envelopes table (see
322
- RELEASE-NOTES-2.4.0.md) copies it and frees the old copy, which would double
408
+ RELEASE-NOTES-2.4.0.md in the pillar source repository) copies it and frees the old copy, which would double
323
409
  the counted size. The carrier reclaims those pages right after the re-key,
324
410
  then truncates the WAL (:212-224). It also vacuums on any later start that
325
411
  finds more than a quarter of the file's pages free. That retries a first
package/README.md CHANGED
@@ -180,20 +180,96 @@ mail there. To re-sync carriers and contacts without a new identity, use
180
180
  | Bin | What it runs | Ongoing requirements |
181
181
  |---|---|---|
182
182
  | `pillar-responder` | Always-on auto-attendant: acks requests instantly, replies from fixed text or a command hook. Run it as a service; agents anywhere get ack+reply without you being live. | one process, outbound HTTPS |
183
- | `pillar-seed` | A carrier seed — makes you part of the p2p mesh. Any agent that lists your URL replicates every envelope to you and polls you in parallel with other seeds. `--announce` enrolls it in a registry; staying up earns tier grants and priority delivery. | one process, one SQLite file, TLS-terminating proxy in front |
183
+ | `pillar-seed` | A carrier seed — makes you part of the p2p mesh. Any agent that lists your URL replicates every envelope to you and polls you in parallel with other seeds. `--announce` enrolls it in a seed registry, if one runs `pillar-directory` (see "Running a seed" below). | one process, one SQLite file, TLS-terminating proxy in front |
184
184
  | `pillar-directory` | The seed registry: serves `directory.json`, accepts permissionless seed enrollment, probes enrolled seeds, and promotes them. Run one if you publish a directory. | one process, one SQLite file |
185
185
  | `pillar` | The full CLI (`init`, `id`, `send`, `group`, `groups`, `send-group`, `recv`, `inbox`, `wait`, `readers`, `status`, `receipts`, `trust`, `tier`, `peers`, `delegate`) — optional libp2p DHT, or carrier-only. | only when used interactively |
186
186
 
187
187
  ```sh
188
188
  pillar-responder --home ~/.pillar-responder --reply-text "ack" &
189
- pillar-seed --port 8799 --db /var/lib/pillar/seed.db & # loopback by default
189
+ pillar-seed --home /var/lib/pillar/seed --db /var/lib/pillar/seed.db & # 127.0.0.1:8799 by default
190
190
 
191
- # join the mesh for real (one command, behind your TLS proxy):
192
- pillar-seed --host 0.0.0.0 --public-url https://seed.example.org \
193
- --announce https://pillar.uuaid.org --operator you --region eu
194
- pillar-seed --status --announce https://pillar.uuaid.org # your rung + what's left
191
+ # serve it to the world: a TLS proxy on this machine in front of 127.0.0.1:8799, then
192
+ pillar-seed --home /var/lib/pillar/seed --db /var/lib/pillar/seed.db \
193
+ --public-url https://seed.example.org
194
+ pillar-seed --help # every flag, and its environment variable
195
195
  ```
196
196
 
197
+ ### Running a seed
198
+
199
+ What an outside operator needs to know before the first start:
200
+
201
+ - **Pass an absolute `--home`.** It holds the seed key and defaults to
202
+ `~/.pillar-seed`. From 2.5.1 the database defaults to `<home>/seed.db`. Up to
203
+ 2.4.1 it defaulted to `pillar-seed.db` **in the working directory**; a seed
204
+ upgraded in place keeps using that file and prints a notice saying how to move
205
+ it. An explicit `--db` (or `SEED_DB`) is used as given.
206
+ - **Keep `--host 127.0.0.1`** (the default) when the TLS proxy runs on the same
207
+ machine, which is the normal case. `--host 0.0.0.0` also publishes the seed's
208
+ plain-HTTP port next to the proxy wherever the firewall lets it through. Use
209
+ another address only for a proxy on another host, and firewall the port to it.
210
+ From 2.5.1 a `SEED_*` variable set to an empty string is refused rather than
211
+ read as a value: in 2.4 an empty `SEED_HOST` listened on every interface.
212
+ Before it creates the key or the database, the start listens once on the
213
+ host and port and closes again, so a host that does not resolve, an address
214
+ not on this machine, or a port in use stops it with nothing written.
215
+ - **The seed's identity is `uuaid:foundation:agent:…` by default.** Every
216
+ service identity this package mints (seed, directory, escrow) uses the
217
+ `foundation` namespace unless told otherwise. The namespace names neither the
218
+ operator nor the kind of key: agents minted before 2.4.0, and any
219
+ `pillar init --namespace foundation`, show `foundation` too, and so does an
220
+ outside operator's seed. `--operator` is the field that names you. From 2.5.1,
221
+ `--namespace pillar` or `--namespace agentnet` (or `SEED_NAMESPACE`) picks
222
+ another namespace **for a new key only**. An existing key keeps its uuaid, and
223
+ naming a different namespace for it refuses to start rather than minting a new one.
224
+ From 2.5.2 the key file's uuaid must be the one its public key derives: a
225
+ file whose uuaid or public key was edited or swapped is refused as damaged,
226
+ on every start and on `--status`, and is left as it is.
227
+ - **Protect the seed key.** Without a passphrase, `seed-keychain.json` (mode
228
+ 0600) is protected by its file mode alone: anyone who can read it can sign as
229
+ your seed. From 2.5.1 a new key can be saved under a passphrase, read from a
230
+ file with `--passphrase-file <path>` or from `SEED_KEYCHAIN_PASSPHRASE`. One
231
+ trailing newline in the file is ignored. **Use a long random passphrase, not
232
+ a memorable one:** the key file's passphrase goes through a single HKDF-SHA256
233
+ with no work factor (`src/identity/keychain.mjs:172`, `:203`), so a short or
234
+ human-chosen one can be guessed offline from a copied key file. Prefer the
235
+ file to the variable: an environment variable can be read back from the
236
+ process by root and by the seed's own user. Under systemd, a credential keeps
237
+ it out of the unit file:
238
+
239
+ ```sh
240
+ openssl rand -base64 32 > /etc/pillar/seed-pass && chmod 600 /etc/pillar/seed-pass
241
+ ```
242
+
243
+ ```ini
244
+ [Service]
245
+ User=pillar
246
+ # systemd creates /var/lib/pillar for User=, mode 0700; pillar-seed creates
247
+ # the home below it, also 0700.
248
+ StateDirectory=pillar
249
+ StateDirectoryMode=0700
250
+ LoadCredential=seed-pass:/etc/pillar/seed-pass
251
+ ExecStart=/usr/bin/pillar-seed --home /var/lib/pillar/seed --passphrase-file ${CREDENTIALS_DIRECTORY}/seed-pass
252
+ ```
253
+
254
+ A wrong or missing passphrase refuses to start, and the key is never replaced.
255
+ A key saved without a passphrase (every key from 2.4 or earlier) keeps
256
+ opening without one; a passphrase cannot be added to an existing key. Run the
257
+ seed as its own user, keep `--home` private, and encrypt the disk either way.
258
+ - **Keep `--ttl` at the default 14 days unless you need longer.** From 2.5.2 it
259
+ is at most 36500 days (100 years). Larger values used to be accepted, and from
260
+ about 2,912,144 days the seed deleted mail on the next hourly pass.
261
+ - **There is no public seed registry yet** (as of 2.5.2, October 2026).
262
+ `https://pillar.uuaid.org` does not answer `/v1/seeds`, so
263
+ `--announce https://pillar.uuaid.org` cannot enroll.
264
+ A seed runs standalone: it carries mail for every client configured with its
265
+ URL (`pillar init --carriers https://seed.example.org`). `--announce` works
266
+ against a registry that runs `pillar-directory`.
267
+ - **Use a real domain.** Free no-DNS names (such as `*.sslip.io`) are blocked
268
+ by some home and corporate network filters, so some clients cannot reach a
269
+ seed on one.
270
+ - The proxy, the firewall and CORS: HOSTING-LIMITS.md §5 has a Caddy and an
271
+ nginx example.
272
+
197
273
  ## Abuse resistance — consent at the edge, budgets at the carrier
198
274
 
199
275
  Identity is unforgeable (the sender derives from the signing key), the
@@ -264,11 +340,14 @@ survivors.
264
340
 
265
341
  ### Joining is permissionless
266
342
 
267
- TLS-terminate a public URL and announce it:
343
+ When a registry runs `pillar-directory`, TLS-terminate a public URL and announce
344
+ it there (there is no public registry yet; see "Running a seed" above):
268
345
 
269
346
  ```sh
270
- pillar-seed --host 0.0.0.0 --public-url https://seed.example.org \
271
- --announce https://pillar.uuaid.org --operator you --region eu
347
+ pillar-seed --home /var/lib/pillar/seed --db /var/lib/pillar/seed.db \
348
+ --public-url https://seed.example.org \
349
+ --announce https://<registry> --operator you --region eu
350
+ pillar-seed --status --home /var/lib/pillar/seed --announce https://<registry> # your rung + what's left
272
351
  ```
273
352
 
274
353
  The registry fetches `https://seed.example.org/v1/seed-info` and checks the
@@ -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,170 @@
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";
47
+ import { join, resolve } from "node:path";
46
48
  import { CarrierServer, parseSecureDelete, parseCommunityWaits } from "../src/net/carrier-server.mjs";
47
- import { Keychain, mintNamespace, SERVICE_IDENTITY_NAMESPACE } from "../src/identity/keychain.mjs";
49
+ import { Keychain, keyDerivesUuaid, mintNamespace, SERVICE_IDENTITY_NAMESPACE } from "../src/identity/keychain.mjs";
50
+
51
+ const USAGE = `usage: pillar-seed [flags]
52
+
53
+ Runs a pillar seed: a carrier server that stores and forwards sealed envelopes.
54
+ It listens on 127.0.0.1 by default; put a TLS-terminating proxy in front of it
55
+ and pass the proxy's address as --public-url.
56
+
57
+ --home <dir> seed key directory (SEED_HOME, default ~/.pillar-seed)
58
+ --db <file> SQLite database (SEED_DB, default <home>/seed.db; a
59
+ ./pillar-seed.db left by 2.4 or earlier is still used)
60
+ --namespace <ns> foundation, pillar or agentnet, for a NEW key only
61
+ (SEED_NAMESPACE, default foundation)
62
+ --passphrase-file <f> file holding the seed key's passphrase; or set
63
+ SEED_KEYCHAIN_PASSPHRASE. Default: no passphrase
64
+ --host <addr> listen address (SEED_HOST, default 127.0.0.1)
65
+ --port <n> listen port (SEED_PORT, default 8799)
66
+ --ttl <days> envelope lifetime (SEED_TTL_DAYS, default 14, at most 36500)
67
+ --public-url <https://> the URL your proxy serves (SEED_PUBLIC_URL)
68
+ --secure-delete <on|off> zero expired envelopes (SEED_SECURE_DELETE, default on)
69
+ --community-waits <n> long-poll slots (SEED_COMMUNITY_WAITS, default 48)
70
+ --announce <registry> enroll --public-url in a seed registry
71
+ --operator <name> operator label sent with --announce (SEED_OPERATOR)
72
+ --region <name> region label sent with --announce (SEED_REGION)
73
+ --status with --announce: print this seed's standing, then exit
74
+ -h, --help print this help and exit
75
+
76
+ Write a value as --flag value or --flag=value. A value that starts with "-"
77
+ must be written --flag=<value>: a separate token starting with "-" is never
78
+ taken as a value. The first start creates the seed key in --home (mode 0700 if
79
+ pillar-seed creates it), with --namespace and the passphrase given then; an
80
+ existing key keeps its namespace and passphrase. --status reads only the key's
81
+ public part, so it needs no passphrase.
82
+
83
+ Refused before anything is written: an unknown flag; a bare word (such as
84
+ "help"); a value flag with no value; a value given to --help or --status; a
85
+ SEED_* variable set to an empty string; an invalid --port, --ttl (digits with
86
+ an optional decimal part, above 0, at most 36500) or --community-waits; a
87
+ --host with spaces; a host and port that cannot be listened on (unresolvable,
88
+ not on this machine, or in use); a --passphrase-file that is not a regular
89
+ file; and a damaged key file, including one whose uuaid does not belong to its
90
+ key. Every refusal is one line on stderr, with exit code 2.`;
91
+
92
+ // Every flag this command reads. Every other token is refused before the seed
93
+ // key or the database is touched, so a typo, a bare word or `--help` never
94
+ // starts a seed.
95
+ const FLAGS = new Set(["announce", "community-waits", "db", "help", "home", "host", "namespace", "operator", "passphrase-file", "port", "public-url", "region", "secure-delete", "status", "ttl"]);
96
+ // Flags that only mean something with a value. Given bare, 2.4 fell through to a
97
+ // later crash (--home, --db) or a wrong value (--port meant port 1).
98
+ const VALUE_FLAGS = ["announce", "community-waits", "db", "home", "host", "namespace", "operator", "passphrase-file", "port", "public-url", "region", "ttl"];
99
+ // Flags that take no value in either form. `--help=` would otherwise set help to
100
+ // "" (falsy) and start a seed; `--status help` would swallow the word.
101
+ const BOOL_FLAGS = new Set(["help", "status"]);
102
+ // Every environment variable this command reads as a setting. One set to "" is
103
+ // refused like a bare flag: in 2.4 an empty SEED_HOST listened on every
104
+ // interface, an empty SEED_PORT took a random port, and an empty SEED_DB kept
105
+ // mail only in memory.
106
+ 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_TTL_DAYS"];
107
+
108
+ const VALUE_SET = new Set(VALUE_FLAGS);
109
+ // The longest envelope lifetime accepted. Every stored row's retain_until is
110
+ // created_at + ttl as an ISO string, and vacuum() compares those strings. Past
111
+ // year 9999 toISOString() writes "+010000-…", which sorts BELOW "2026-…", so
112
+ // from about 2,912,144 days the hourly vacuum deleted mail the moment it was
113
+ // accepted (and above about 99,979,245 days every POST failed). 100 years.
114
+ const MAX_TTL_DAYS = 36500;
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
+ function oneLine(text) {
162
+ return String(text).replace(/[\u0000-\u001f\u007f-\u009f]/g, (c) => ESCAPES[c] ?? `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
163
+ }
164
+ /** An operator's token as a message shows it: as typed when it is plain, else JSON-quoted. */
165
+ const shown = (token) => (/^[\x21-\x7e]+$/.test(token) ? token : JSON.stringify(token));
166
+
167
+ const { args, unknown, dashed } = parseArgs(process.argv.slice(2));
168
+ // Checked before --help: in `--home -h` the "-h" may have been meant as the value.
169
+ // The names come from `dashed` as well as from `args`: a repeated flag
170
+ // (`--port -1 --port 0`) has a value in `args` by now, and is still refused.
171
+ if (dashed.length) {
172
+ const missing = VALUE_FLAGS.filter((k) => dashed.includes(k) || args[k] === true || args[k] === "").map((k) => `--${k}`);
173
+ refuse(`${missing.join(", ")} need${missing.length > 1 ? "" : "s"} a value; a value that starts with "-" is written --${dashed[0]}=<value>. See pillar-seed --help.`);
174
+ }
175
+ if (args.help) {
176
+ console.log(USAGE);
177
+ process.exit(0);
178
+ }
179
+ if (unknown.length) {
180
+ const flags = unknown.filter((t) => /^-./.test(t) && t !== "--");
181
+ const words = unknown.filter((t) => !flags.includes(t));
182
+ const parts = [];
183
+ const valued = flags.filter((t) => t.endsWith("="));
184
+ const unknownFlags = flags.filter((t) => !t.endsWith("="));
185
+ if (unknownFlags.length) parts.push(`unknown flag${unknownFlags.length > 1 ? "s" : ""} ${unknownFlags.map(shown).join(", ")}`);
186
+ if (valued.length) parts.push(`${valued.map((t) => t.slice(0, -1)).join(", ")} take${valued.length > 1 ? "" : "s"} no value`);
187
+ if (words.length) parts.push(`unexpected argument${words.length > 1 ? "s" : ""} ${words.map((w) => JSON.stringify(w)).join(", ")} (pillar-seed takes only flags)`);
188
+ refuse(`${parts.join("; ")}. See pillar-seed --help.`);
189
+ }
190
+ const bare = VALUE_FLAGS.filter((k) => args[k] === true || args[k] === "").map((k) => `--${k}`);
191
+ if (bare.length) refuse(`${bare.join(", ")} need${bare.length > 1 ? "" : "s"} a value. See pillar-seed --help.`);
192
+ const emptyEnv = SEED_ENV.filter((n) => process.env[n] === "");
193
+ 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
194
  const home = args.home ?? process.env.SEED_HOME ?? join(homedir(), ".pillar-seed");
63
- const port = Number(args.port ?? process.env.SEED_PORT ?? 8799);
195
+ const portText = String(args.port ?? process.env.SEED_PORT ?? 8799);
196
+ const port = Number(portText);
197
+ // The rule Node's listen() applies anyway, checked here so a bad value is refused
198
+ // before the key is minted rather than after. Digits only, so " " or "0x10" is not
199
+ // read as a port (Number(" ") is 0, a random port).
200
+ if (!/^[0-9]+$/.test(portText) || port > 65535) refuse(`--port must be a whole number from 0 to 65535, not ${JSON.stringify(portText)}`);
64
201
  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);
202
+ if (/\s/.test(host)) refuse(`--host must not contain spaces, not ${JSON.stringify(host)}`);
203
+ const ttlText = String(args.ttl ?? process.env.SEED_TTL_DAYS ?? 14);
204
+ const ttlDays = Number(ttlText);
205
+ // Digits with an optional decimal part: Number() alone also took "0x10", "1e3", "+14" and " 14".
206
+ 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)}`);
207
+ if (ttlDays > MAX_TTL_DAYS) refuse(`--ttl must be at most ${MAX_TTL_DAYS} days (100 years), not ${JSON.stringify(ttlText)}`);
67
208
  const publicUrl = args["public-url"] ?? process.env.SEED_PUBLIC_URL ?? null;
68
209
  const registryUrl = typeof args.announce === "string" ? args.announce.replace(/\/+$/, "") : null;
69
210
  const operator = args.operator ?? process.env.SEED_OPERATOR ?? null;
@@ -73,22 +214,135 @@ let secureDelete;
73
214
  try {
74
215
  secureDelete = parseSecureDelete(args["secure-delete"] ?? process.env.SEED_SECURE_DELETE);
75
216
  } catch (e) {
76
- console.error(`pillar-seed: ${e.message}`);
77
- process.exit(2);
217
+ refuse(e.message);
218
+ }
219
+ let communityInboxWaits;
220
+ try {
221
+ communityInboxWaits = parseCommunityWaits(args["community-waits"] ?? process.env.SEED_COMMUNITY_WAITS ?? process.env.CARRIER_COMMUNITY_WAITS);
222
+ } catch (e) {
223
+ refuse(e.message);
224
+ }
225
+
226
+ // The seed key's passphrase: a file (preferred: a systemd credential) or an
227
+ // environment variable, never a flag value, so it is never in argv or ps. It is
228
+ // used to save a new key and to open an existing one. Without either, the key
229
+ // is saved and opened with no passphrase, as in 2.4. It is never printed.
230
+ let passphrase;
231
+ const passphraseFile = args["passphrase-file"];
232
+ const envPassphrase = process.env.SEED_KEYCHAIN_PASSPHRASE;
233
+ delete process.env.SEED_KEYCHAIN_PASSPHRASE;
234
+ if (passphraseFile !== undefined && envPassphrase !== undefined) refuse("give the passphrase once: --passphrase-file or SEED_KEYCHAIN_PASSPHRASE, not both");
235
+ if (passphraseFile !== undefined) {
236
+ // stat first, so a FIFO, directory, socket or device is refused without opening it
237
+ // (opening a FIFO blocks until a writer appears); O_NONBLOCK covers a swap after the stat.
238
+ let first;
239
+ try { first = statSync(passphraseFile); } catch (e) { refuse(`cannot read --passphrase-file ${passphraseFile}: ${e.code ?? e.message}`); }
240
+ if (!first.isFile()) refuse(`--passphrase-file ${passphraseFile} is not a regular file`);
241
+ let fd;
242
+ try {
243
+ fd = openSync(passphraseFile, fsConstants.O_RDONLY | fsConstants.O_NONBLOCK);
244
+ const st = fstatSync(fd);
245
+ if (!st.isFile()) refuse(`--passphrase-file ${passphraseFile} is not a regular file`);
246
+ if (st.size > 4096) refuse(`--passphrase-file ${passphraseFile} is larger than 4096 bytes`);
247
+ 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`);
248
+ const buf = Buffer.alloc(st.size);
249
+ const n = st.size ? readSync(fd, buf, 0, st.size, 0) : 0;
250
+ passphrase = buf.subarray(0, n).toString("utf-8").replace(/\r?\n$/, "");
251
+ } catch (e) {
252
+ refuse(`cannot read --passphrase-file ${passphraseFile}: ${e.code ?? e.message}`);
253
+ } finally {
254
+ if (fd !== undefined) closeSync(fd);
255
+ }
256
+ if (passphrase === "") refuse(`--passphrase-file ${passphraseFile} is empty`);
257
+ } else if (envPassphrase !== undefined) {
258
+ passphrase = envPassphrase; // never "": an empty SEED_KEYCHAIN_PASSPHRASE was refused above
78
259
  }
79
260
 
80
261
  /**
81
262
  * The seed's identity. Distinct from any agent keychain on the box: it names
82
263
  * the SEED, is what /v1/seed-info is signed with, and is the subject of any
83
264
  * tier grant the seed earns.
265
+ *
266
+ * Its namespace is chosen once, when the key is minted: --namespace or
267
+ * SEED_NAMESPACE, else SERVICE_IDENTITY_NAMESPACE (foundation). A later start
268
+ * that names a different namespace refuses rather than minting a new key.
269
+ */
270
+ const requestedNamespace = args.namespace ?? process.env.SEED_NAMESPACE;
271
+ if (requestedNamespace !== undefined) {
272
+ try { mintNamespace(requestedNamespace); } catch (e) { refuse(e.message); }
273
+ }
274
+ const keyPath = join(home, "seed-keychain.json");
275
+ const keychain = new Keychain(keyPath);
276
+ /**
277
+ * The uuaid recorded in an existing key file's public part; a damaged file is
278
+ * refused, never replaced. The uuaid must be the one its public key derives:
279
+ * every seed key pillar-seed has minted is key-derived in a self-certifying
280
+ * namespace, so a mismatch is a file someone edited or swapped. Checked on
281
+ * every path (start, --status, --namespace), so a seed never starts or reports
282
+ * under a uuaid its key cannot prove.
84
283
  */
85
- mkdirSync(home, { recursive: true });
86
- const keychain = new Keychain(join(home, "seed-keychain.json"));
284
+ function savedUuaidOf() {
285
+ let pub;
286
+ try { pub = keychain.publicView(); } catch (e) {
287
+ 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.`);
288
+ }
289
+ 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.`);
290
+ if (typeof pub.publicKeyHex !== "string") refuse(`the seed key ${keyPath} is damaged or is not a key file (no public key). Nothing was replaced.`);
291
+ 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.`);
292
+ return pub.uuaid;
293
+ }
294
+ const savedUuaid = keychain.exists() ? savedUuaidOf() : undefined;
295
+ if (savedUuaid !== undefined && requestedNamespace !== undefined && savedUuaid.split(":")[1] !== requestedNamespace) {
296
+ 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.`);
297
+ }
298
+ // --status is a query about an existing seed. It reads only the key's public part,
299
+ // so it needs no passphrase, never loads the private key and writes nothing.
300
+ if (args.status) {
301
+ if (!registryUrl) refuse("--status needs --announce <registry-url> to know which registry to ask");
302
+ if (savedUuaid === undefined) {
303
+ const homeGiven = args.home !== undefined || process.env.SEED_HOME !== undefined;
304
+ 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."}`);
305
+ }
306
+ console.log(`seed ${savedUuaid}`);
307
+ await printStanding(registryUrl, savedUuaid);
308
+ process.exit(0);
309
+ }
310
+ // Listen once on the same host and port and close again, so a host that does not
311
+ // resolve, an address not on this machine, or a port in use is refused before the
312
+ // key or database exists. (A port taken between this check and the start still
313
+ // fails at the start, after the key exists.)
314
+ await new Promise((done) => {
315
+ const probe = createServer();
316
+ probe.once("error", (e) => {
317
+ const why = {
318
+ EADDRINUSE: `port ${port} is already in use on ${host}`,
319
+ EADDRNOTAVAIL: `${host} is not an address on this machine`,
320
+ ENOTFOUND: `${host} does not resolve`,
321
+ EAI_AGAIN: `${host} could not be resolved (EAI_AGAIN)`,
322
+ EACCES: `listening on port ${port} needs privileges`,
323
+ }[e.code] ?? `cannot listen on ${host}:${port} (${e.code ?? e.message})`;
324
+ refuse(`--host/--port: ${why}. Nothing was written.`);
325
+ });
326
+ probe.listen(port, host, () => probe.close(done));
327
+ });
328
+ const homeExisted = existsSync(home);
329
+ mkdirSync(home, { recursive: true, mode: 0o700 });
330
+ if (!homeExisted) chmodSync(home, 0o700); // whatever the umask; an existing home keeps its mode
87
331
  if (!keychain.exists()) {
88
- keychain.save(Keychain.generate({ uuaidNamespace: mintNamespace(SERVICE_IDENTITY_NAMESPACE) }));
89
- console.log(`minted seed identity -> ${join(home, "seed-keychain.json")}`);
332
+ const identity = requestedNamespace === undefined
333
+ ? Keychain.generate({ uuaidNamespace: mintNamespace(SERVICE_IDENTITY_NAMESPACE) })
334
+ : Keychain.generate({ uuaidNamespace: mintNamespace(requestedNamespace) });
335
+ keychain.save(identity, { passphrase });
336
+ console.log(`minted seed identity -> ${keyPath}${passphrase === undefined ? "" : " (passphrase-protected)"}`);
337
+ }
338
+ try {
339
+ keychain.load({ passphrase });
340
+ } catch (e) {
341
+ const hint = passphrase === undefined
342
+ ? "If it was saved with a passphrase, pass --passphrase-file or SEED_KEYCHAIN_PASSPHRASE."
343
+ : "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.";
344
+ refuse(`cannot open the seed key ${keyPath}: wrong or missing passphrase, or a damaged file (${e.message}). Nothing was replaced. ${hint}`);
90
345
  }
91
- keychain.load();
92
346
 
93
347
  /** Ask a registry where we stand and print the ladder position. */
94
348
  async function printStanding(registry, uuaid) {
@@ -111,24 +365,25 @@ async function printStanding(registry, uuaid) {
111
365
  }
112
366
  }
113
367
 
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);
368
+ // The database. An explicit --db or SEED_DB is used as given, as in 2.4. Without
369
+ // one, the default is <home>/seed.db; 2.4's default was ./pillar-seed.db in the
370
+ // working directory, so a seed upgraded in place keeps that file rather than
371
+ // starting empty beside it.
372
+ let dbPath = args.db ?? process.env.SEED_DB;
373
+ if (dbPath === undefined) {
374
+ const homeDb = join(home, "seed.db");
375
+ const legacyDb = resolve("pillar-seed.db");
376
+ if (!existsSync(homeDb) && existsSync(legacyDb)) {
377
+ dbPath = legacyDb;
378
+ console.log(`notice: using ${legacyDb}, the 2.4 default in the working directory.`);
379
+ console.log(` To move it: stop the seed, move pillar-seed.db and any pillar-seed.db-wal and`);
380
+ console.log(` pillar-seed.db-shm beside it to ${homeDb} (keeping the -wal/-shm suffixes), then start again.`);
381
+ } else {
382
+ dbPath = homeDb;
383
+ if (existsSync(legacyDb)) console.error(`pillar-seed: warning: ${legacyDb} exists but is not used; this seed's database is ${homeDb}.`);
119
384
  }
120
- console.log(`seed ${keychain._identity.uuaid}`);
121
- await printStanding(registryUrl, keychain._identity.uuaid);
122
- process.exit(0);
123
385
  }
124
386
 
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
387
  const server = new CarrierServer({ dbPath, ttlDays, keychain, publicUrl, secureDelete, communityInboxWaits });
133
388
  const addr = await server.listen(port, host);
134
389
  console.log(`pillar-seed listening on http://${addr.address}:${addr.port}`);
@@ -174,13 +429,13 @@ if (registryUrl) {
174
429
  console.log(` enrollment failed: ${e.message}`);
175
430
  }
176
431
  }
432
+ } else if (publicUrl) {
433
+ console.log(`\n serving ${publicUrl} through your proxy; not announced to any registry.`);
177
434
  } 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.`);
435
+ console.log(`\n loopback only: no public URL is set.`);
436
+ console.log(` To serve the public, put a TLS-terminating proxy (Caddy or nginx) on this`);
437
+ console.log(` machine in front of 127.0.0.1:${addr.port}, keep --host 127.0.0.1, and restart`);
438
+ console.log(` with --public-url https://<your-domain>.`);
184
439
  }
185
440
 
186
441
  // Vacuum expired envelopes hourly.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uuaid/pillar",
3
- "version": "2.4.1",
3
+ "version": "2.5.2",
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",