@uuaid/pillar 2.7.3 → 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.
- package/HOSTING-LIMITS.md +95 -0
- package/README.md +242 -1
- package/bin/carrier.mjs +97 -1
- package/bin/pillar-directory.mjs +32 -5
- package/bin/pillar-seed.mjs +127 -11
- package/bin/pillar.mjs +11 -4
- package/package.json +1 -1
- package/src/mailbox/mailbox.mjs +12 -0
- package/src/net/carrier-server.mjs +191 -17
- package/src/net/discovery.mjs +72 -0
- package/src/net/refusals.mjs +15 -0
- package/src/net/seed-registry.mjs +334 -35
- package/src/net/seed-tier.mjs +35 -1
- package/src/net/tunnel-client.mjs +456 -0
- package/src/net/tunnel-relay.mjs +776 -0
- package/src/net/tunnel.mjs +288 -0
- package/src/notify-store.mjs +4 -1
- package/src/pillar.mjs +541 -9
- package/src/registry/directory-flags.mjs +7 -0
- package/src/registry/stats.mjs +1 -1
- package/src/vnext/continuity-cli.mjs +399 -0
- package/src/vnext/continuity.mjs +1801 -0
- package/src/vnext/init-cli.mjs +23 -7
- package/src/vnext/json-dir-mailbox.mjs +6 -0
- package/src/vnext/jsonl-mailbox.mjs +177 -23
- package/src/vnext/knock-cli.mjs +18 -0
- package/src/vnext/retired-import.mjs +556 -0
- package/src/vnext/verify-cli.mjs +1 -1
package/bin/pillar-seed.mjs
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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 (
|
|
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
|
|
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.
|
|
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",
|
package/src/mailbox/mailbox.mjs
CHANGED
|
@@ -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}`;
|
|
@@ -64,7 +64,7 @@
|
|
|
64
64
|
*/
|
|
65
65
|
import { createServer } from "node:http";
|
|
66
66
|
import { clientIpOf, DEFAULT_TRUSTED_PROXIES } from "./client-ip.mjs";
|
|
67
|
-
import { createHash } from "node:crypto";
|
|
67
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
68
68
|
import { requireBetterSqlite3 } from "../sqlite-loader.mjs";
|
|
69
69
|
import { open as openEnvelope, envelopeSha as canonicalEnvelopeSha } from "./envelope.mjs";
|
|
70
70
|
import { Keychain, keyDerivesUuaid, isStrictEd25519PublicKey } from "../identity/keychain.mjs";
|
|
@@ -74,8 +74,71 @@ import { verifyDelegationDoc, delegationCoversKind } from "./delegation.mjs";
|
|
|
74
74
|
import { withCarrierFix } from "./refusals.mjs"; // additive `fix` on refusals; reason/error/status unchanged
|
|
75
75
|
import { carrierReceiptSigningString, carrierReceiptShapeOk, carrierUuaidFromKey } from "./carrier-receipt.mjs";
|
|
76
76
|
import { rekeyToSenderUnique } from "../sqlite-rekey.mjs";
|
|
77
|
+
import { CHALLENGE_RE, makeServedProof } from "./tunnel.mjs";
|
|
77
78
|
|
|
78
79
|
const MAX_WAIT_S = 30;
|
|
80
|
+
/** Most rows in one inbox page. */
|
|
81
|
+
export const INBOX_PAGE_ROWS = 200;
|
|
82
|
+
/**
|
|
83
|
+
* Most stored-body bytes in one inbox page (2.8.0, RedTeam 82902d): a page
|
|
84
|
+
* ends before the row that would pass this, always with whole envelopes. It
|
|
85
|
+
* is the largest envelope the carrier accepts, so a page always holds at
|
|
86
|
+
* least one; a row larger than this (stored by an older build) is served
|
|
87
|
+
* alone. `more: true` says rows remain after the cut.
|
|
88
|
+
*/
|
|
89
|
+
export const INBOX_PAGE_BYTES = 2 * 1024 * 1024 + 8192;
|
|
90
|
+
/** Bytes a page row costs beyond its body (seq, JSON framing), for reservations. */
|
|
91
|
+
const INBOX_ROW_OVERHEAD = 64;
|
|
92
|
+
/** A page's JSON is held about twice while it is serialized and sent; reserve for both. */
|
|
93
|
+
const INBOX_RESERVE_FACTOR = 2;
|
|
94
|
+
// Pages whose reservation is at most this are "small" (chat-sized mail);
|
|
95
|
+
// large pages leave 1/INBOX_SMALL_SLICE of the budget to them, so small
|
|
96
|
+
// mail is still served while large pages hold the rest.
|
|
97
|
+
const INBOX_SMALL_PAGE_COST = 256 * 1024;
|
|
98
|
+
const INBOX_SMALL_SLICE = 8;
|
|
99
|
+
// One client address holds at most 1/INBOX_ADDRESS_SHARE of the budget (C7-2):
|
|
100
|
+
// past that, its reads get 503 seed-busy at once, and other addresses still
|
|
101
|
+
// find room. An address that holds no page may always take one.
|
|
102
|
+
export const INBOX_ADDRESS_SHARE = 4;
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Bytes of inbox pages a seed holds for clients at once (2.8.0, RedTeam
|
|
106
|
+
* 82902d). A page is reserved before it is read or built. The reservation is
|
|
107
|
+
* returned when the page has left this process: when its HTTP answer
|
|
108
|
+
* finishes, or, for a request the seed's own tunnel client made with a
|
|
109
|
+
* ticket from ticket(), when the tunnel client calls end(ticket) after it has
|
|
110
|
+
* sent the page to the relay or dropped the stream. Until then the page sits
|
|
111
|
+
* in the loopback socket and the tunnel client's queue, inside this process
|
|
112
|
+
* and its kernel buffers, so finishing the local answer is not enough.
|
|
113
|
+
*/
|
|
114
|
+
export class ResponseBudget {
|
|
115
|
+
constructor(limitBytes) {
|
|
116
|
+
this.limit = limitBytes;
|
|
117
|
+
this.used = 0;
|
|
118
|
+
this._tickets = new Map();
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Tunnel client: a one-use ticket for one local request. */
|
|
122
|
+
ticket() {
|
|
123
|
+
const t = randomBytes(16).toString("hex");
|
|
124
|
+
this._tickets.set(t, null);
|
|
125
|
+
return t;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Carrier: run `release` when `ticket` ends. False when the ticket is not a live one. */
|
|
129
|
+
holdUntil(ticket, release) {
|
|
130
|
+
if (typeof ticket !== "string" || !this._tickets.has(ticket) || this._tickets.get(ticket) !== null) return false;
|
|
131
|
+
this._tickets.set(ticket, release);
|
|
132
|
+
return true;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Tunnel client: the stream is over (sent or dropped); return what it held. */
|
|
136
|
+
end(ticket) {
|
|
137
|
+
const release = this._tickets.get(ticket);
|
|
138
|
+
this._tickets.delete(ticket);
|
|
139
|
+
if (typeof release === "function") release();
|
|
140
|
+
}
|
|
141
|
+
}
|
|
79
142
|
const MAX_BODY = 512 * 1024; // 512 KiB per envelope (community tier)
|
|
80
143
|
const MAX_BODY_STREAM = 2 * 1024 * 1024 + 8192; // absolute read cap: max tier body + grant/header slack
|
|
81
144
|
const MAX_SKEW_MS = 5 * 60 * 1000;
|
|
@@ -162,7 +225,7 @@ const ENVELOPES_COLUMNS = `
|
|
|
162
225
|
const ENVELOPES_INDEX = "create index if not exists idx_envelopes_recipient on envelopes(recipient, seq);";
|
|
163
226
|
|
|
164
227
|
export class CarrierServer {
|
|
165
|
-
constructor({ dbPath = "carrier.db", ttlDays = 14, cryptoInventory, trustedTierIssuers = [], keychain = null, publicUrl = null, secureDelete = true, receiptKeychain = null, communityInboxWaits = COMMUNITY_CONCURRENT_WAITS, trustedProxies = DEFAULT_TRUSTED_PROXIES } = {}) {
|
|
228
|
+
constructor({ dbPath = "carrier.db", ttlDays = 14, cryptoInventory, trustedTierIssuers = [], keychain = null, publicUrl = null, secureDelete = true, receiptKeychain = null, communityInboxWaits = COMMUNITY_CONCURRENT_WAITS, trustedProxies = DEFAULT_TRUSTED_PROXIES, relayOrigin = null, tunnelRelay = null, responseBudget = null } = {}) {
|
|
166
229
|
// Every row's retain_until is created_at + ttlDays, so the TTL must be a
|
|
167
230
|
// real positive duration (a NaN here used to surface only as a vacuum crash).
|
|
168
231
|
if (typeof ttlDays !== "number" || !Number.isFinite(ttlDays) || ttlDays <= 0) {
|
|
@@ -259,6 +322,21 @@ export class CarrierServer {
|
|
|
259
322
|
// does not expose /v1/seed-info.
|
|
260
323
|
this.keychain = keychain;
|
|
261
324
|
this.publicUrl = publicUrl ? String(publicUrl).replace(/\/+$/, "") : null;
|
|
325
|
+
// 2.8.0 egress seed: the relay origin this seed is served through, declared
|
|
326
|
+
// inside its signed /v1/seed-info. Null for a seed with its own public URL.
|
|
327
|
+
this.relayOrigin = relayOrigin ? String(relayOrigin) : null;
|
|
328
|
+
// 2.8.0 relay side: a TunnelRelay (./tunnel-relay.mjs) that serves
|
|
329
|
+
// /v1/tunnel and /e/<localId>/... Null (the default): both stay 404.
|
|
330
|
+
this.tunnelRelay = tunnelRelay ?? null;
|
|
331
|
+
// 2.8.0 (RedTeam 82902d): an optional ResponseBudget (any { limit, used }
|
|
332
|
+
// works; tickets need the class) every inbox page is reserved against
|
|
333
|
+
// BEFORE it is read from the store and built; a seed served through a
|
|
334
|
+
// relay sets one, so the pages it holds while clients read them stay
|
|
335
|
+
// bounded. Null: unlimited, as before.
|
|
336
|
+
this.responseBudget = responseBudget ?? null;
|
|
337
|
+
// Response-budget bytes reserved per client address, for the addresses
|
|
338
|
+
// that hold some (C7-2, INBOX_ADDRESS_SHARE).
|
|
339
|
+
this.reservedByAddress = new Map();
|
|
262
340
|
// Receipt identity: the carrier uuaid is DERIVED from the receipt key
|
|
263
341
|
// (uuaid:foundation:agent:<localId>), never read from the keychain file,
|
|
264
342
|
// so it is always the uuaid a client's pin check derives.
|
|
@@ -358,11 +436,15 @@ export class CarrierServer {
|
|
|
358
436
|
* net/seed-tier.mjs). What the signature does prove is the thing enrollment
|
|
359
437
|
* actually needs — that whoever controls this URL also controls this key.
|
|
360
438
|
*/
|
|
361
|
-
seedInfo() {
|
|
439
|
+
seedInfo({ challenge } = {}) {
|
|
362
440
|
if (!this.keychain?._identity || !this.publicUrl) return null;
|
|
363
441
|
const doc = {
|
|
364
442
|
v: 1,
|
|
365
443
|
url: this.publicUrl,
|
|
444
|
+
// 2.8.0: a relayed seed declares its relay, and echoes a registry's
|
|
445
|
+
// one-use challenge, both under its signature (RedTeam c3ff4d).
|
|
446
|
+
...(this.relayOrigin ? { relay: this.relayOrigin } : {}),
|
|
447
|
+
...(challenge ? { challenge } : {}),
|
|
366
448
|
uuaid: this.keychain._identity.uuaid,
|
|
367
449
|
publicKey: this.keychain._identity.publicKeyHex,
|
|
368
450
|
startedAt: new Date(this.startedAt).toISOString(),
|
|
@@ -394,10 +476,20 @@ export class CarrierServer {
|
|
|
394
476
|
try { grant = JSON.parse(Buffer.from(String(hdr), "base64").toString("utf-8")); }
|
|
395
477
|
catch (_e) { return fallback; }
|
|
396
478
|
if (grant?.uuaid !== sender) return fallback; // grant must name the claimed sender
|
|
479
|
+
const now = Date.now();
|
|
397
480
|
const cached = this._grantCache.get(sender);
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
481
|
+
let warm = Boolean(cached && cached.sig === grant.sig && now - cached.at < 60_000);
|
|
482
|
+
// A cached decision never outlives the grant it came from: at the grant's
|
|
483
|
+
// expiry the sender is verified again and falls to community (2.8.0,
|
|
484
|
+
// RedTeam 22f6c3 Q1: relayed seeds' grants can last minutes, not days).
|
|
485
|
+
if (warm && !(now < cached.expiresAt)) warm = false; // @rule tier.grant-cache-until-expiry
|
|
486
|
+
if (warm) return cached.resolved;
|
|
487
|
+
const v = verifyTierGrant(grant, this.trustedTierIssuers, now);
|
|
488
|
+
// verifyTierGrant still accepts a grant at the very millisecond it
|
|
489
|
+
// expires; here the sender falls to community at now >= expiry.
|
|
490
|
+
let granted = v.ok;
|
|
491
|
+
if (granted && !(now < Date.parse(grant.expires))) granted = false; // @rule tier.grant-expiry-exclusive
|
|
492
|
+
const resolved = granted
|
|
401
493
|
? {
|
|
402
494
|
tier: grant.tier,
|
|
403
495
|
envelopesPerMin: grant.envelopesPerMin,
|
|
@@ -410,7 +502,9 @@ export class CarrierServer {
|
|
|
410
502
|
}
|
|
411
503
|
: fallback;
|
|
412
504
|
if (this._grantCache.size > 4096) this._grantCache.clear(); // bounded
|
|
413
|
-
|
|
505
|
+
// NaN (an unparseable expiry) is never `now <` it, so such an entry is never reused.
|
|
506
|
+
const expiresAt = granted ? Date.parse(grant.expires) : Infinity;
|
|
507
|
+
this._grantCache.set(sender, { sig: grant.sig, at: now, resolved, expiresAt });
|
|
414
508
|
return resolved;
|
|
415
509
|
}
|
|
416
510
|
|
|
@@ -685,6 +779,13 @@ export class CarrierServer {
|
|
|
685
779
|
return { ok: true };
|
|
686
780
|
}
|
|
687
781
|
|
|
782
|
+
/** Reserve (n > 0) or return (n < 0) response-budget bytes for client address `ip`. */
|
|
783
|
+
_reserve(ip, n) {
|
|
784
|
+
this.responseBudget.used += n;
|
|
785
|
+
const left = (this.reservedByAddress.get(ip) ?? 0) + n;
|
|
786
|
+
if (left > 0) this.reservedByAddress.set(ip, left); else this.reservedByAddress.delete(ip);
|
|
787
|
+
}
|
|
788
|
+
|
|
688
789
|
async _handleInbox(req, res, uuaid, url) {
|
|
689
790
|
const since = Number(url.searchParams.get("since") ?? 0);
|
|
690
791
|
const wait = Math.min(Number(url.searchParams.get("wait") ?? 0), MAX_WAIT_S);
|
|
@@ -704,27 +805,91 @@ export class CarrierServer {
|
|
|
704
805
|
}
|
|
705
806
|
if (wait > 0) this.activeWaits++;
|
|
706
807
|
|
|
707
|
-
|
|
808
|
+
// A page is sized from body lengths first (no body is read), cut at
|
|
809
|
+
// INBOX_PAGE_BYTES with whole envelopes, reserved against the response
|
|
810
|
+
// budget, and only then read and built (RedTeam 82902d).
|
|
811
|
+
const sizeRows = () => {
|
|
708
812
|
// closed → the DB is gone; a long-poll timer armed before close() can
|
|
709
813
|
// fire afterwards. Never touch a closed connection.
|
|
710
814
|
if (this._closed) return [];
|
|
711
815
|
return this.db.prepare(
|
|
712
|
-
|
|
816
|
+
// octet_length: UTF-8 bytes. length() would count characters and
|
|
817
|
+
// undercount a non-ASCII body (SQLite >= 3.43; better-sqlite3 ships 3.53).
|
|
818
|
+
`select seq, octet_length(body) as n from envelopes where recipient = ? and seq > ? order by seq asc limit ${INBOX_PAGE_ROWS + 1}`
|
|
713
819
|
).all(uuaid, since);
|
|
714
820
|
};
|
|
715
821
|
|
|
822
|
+
let reserved = 0;
|
|
823
|
+
const ip = this._clientIp(req);
|
|
716
824
|
try {
|
|
717
|
-
let
|
|
825
|
+
let sized = sizeRows();
|
|
718
826
|
const deadline = Date.now() + wait * 1000;
|
|
719
|
-
while (
|
|
827
|
+
while (sized.length === 0 && Date.now() < deadline && !this._closed) {
|
|
720
828
|
await this._sleepOrWake(uuaid, 400);
|
|
721
|
-
|
|
829
|
+
sized = sizeRows();
|
|
722
830
|
}
|
|
831
|
+
// Whole envelopes up to the byte limit and, with a response budget, up
|
|
832
|
+
// to what the free budget holds; the first row always, so a page is
|
|
833
|
+
// never empty while mail waits (a single row may pass either limit:
|
|
834
|
+
// one envelope, alone, when nothing else is reserved).
|
|
835
|
+
const budget = this.responseBudget;
|
|
836
|
+
const cost = (b, n) => (b + n * INBOX_ROW_OVERHEAD) * INBOX_RESERVE_FACTOR;
|
|
837
|
+
const free = budget ? budget.limit - budget.used : Infinity;
|
|
838
|
+
let smallSlice = 0;
|
|
839
|
+
if (budget) smallSlice = Math.floor(budget.limit / INBOX_SMALL_SLICE); // @rule inbox.small-slice
|
|
840
|
+
// What this client address may still reserve: its share, less what its
|
|
841
|
+
// other pages hold; no limit while it holds none (C7-2).
|
|
842
|
+
const mine = this.reservedByAddress.get(ip) ?? 0;
|
|
843
|
+
let addressRoom = Infinity;
|
|
844
|
+
if (mine > 0) addressRoom = Math.floor(budget.limit / INBOX_ADDRESS_SHARE) - mine; // @rule inbox.address-share
|
|
845
|
+
const roomFor = (c) => Math.min(c <= INBOX_SMALL_PAGE_COST ? free : free - smallSlice, addressRoom);
|
|
846
|
+
let take = 0;
|
|
847
|
+
let bytes = 0;
|
|
848
|
+
while (take < sized.length && take < INBOX_PAGE_ROWS) {
|
|
849
|
+
const next = bytes + sized[take].n;
|
|
850
|
+
if (take > 0 && next > INBOX_PAGE_BYTES) break; // @rule inbox.page-bytes
|
|
851
|
+
const c = cost(next, take + 1);
|
|
852
|
+
if (take > 0 && c > roomFor(c)) break; // @rule inbox.page-fits-budget
|
|
853
|
+
bytes = next;
|
|
854
|
+
take++;
|
|
855
|
+
}
|
|
856
|
+
const more = take < sized.length;
|
|
857
|
+
if (take > 0 && budget) {
|
|
858
|
+
// Nobody left to send to (the client went during a long-poll): build nothing.
|
|
859
|
+
if (res.destroyed) return;
|
|
860
|
+
const need = cost(bytes, take);
|
|
861
|
+
// Refused only while other pages hold the budget; an idle budget
|
|
862
|
+
// always serves one page, so no mail is unreadable for good.
|
|
863
|
+
if (budget.used > 0 && need > roomFor(need)) return this._json(res, 503, { error: "seed-busy" }); // @rule inbox.reserve-first
|
|
864
|
+
this._reserve(ip, need);
|
|
865
|
+
reserved = need;
|
|
866
|
+
const release = () => { if (reserved) { this._reserve(ip, -reserved); reserved = 0; } };
|
|
867
|
+
// The seed's own tunnel client returns it once the page has gone to
|
|
868
|
+
// the relay; any other client, when its answer finishes.
|
|
869
|
+
let held = false;
|
|
870
|
+
held = budget.holdUntil?.(req.headers["x-pillar-budget-ticket"], release) === true; // @rule inbox.hold-until-sent
|
|
871
|
+
// Node 22 emits finish also when the client goes mid-page; close is
|
|
872
|
+
// the fallback. A ticket's page is returned by the tunnel client,
|
|
873
|
+
// which ends the ticket when the stream ends, resets or the tunnel goes.
|
|
874
|
+
if (!held) { res.once("finish", release); res.once("close", release); }
|
|
875
|
+
}
|
|
876
|
+
const rows = take === 0 ? [] : this.db.prepare(
|
|
877
|
+
"select seq, body from envelopes where recipient = ? and seq >= ? and seq <= ? order by seq asc"
|
|
878
|
+
).all(uuaid, sized[0].seq, sized[take - 1].seq);
|
|
723
879
|
if (rows.length) this._bump("served", rows.length);
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
880
|
+
const envelopes = rows.map(r => ({ seq: r.seq, envelope: JSON.parse(r.body) }));
|
|
881
|
+
// 2.8.0 served proof (RedTeam 085b71 C4): a seed asked with a one-use
|
|
882
|
+
// challenge signs the digest of this exact page, on this authenticated
|
|
883
|
+
// read, so a relay cannot answer a registry's round trip by itself.
|
|
884
|
+
const challenge = url.searchParams.get("challenge");
|
|
885
|
+
const proof = this.keychain?._identity && challenge !== null && CHALLENGE_RE.test(challenge) && Number.isSafeInteger(since)
|
|
886
|
+
? makeServedProof(this.keychain, { inbox: uuaid, since, challenge, envelopes })
|
|
887
|
+
: undefined;
|
|
888
|
+
this._json(res, 200, { envelopes, now: Date.now(), ...(more ? { more: true } : {}), ...(proof ? { proof } : {}) });
|
|
889
|
+
} catch (e) {
|
|
890
|
+
// Nothing was sent: give the reservation back before the error answer.
|
|
891
|
+
if (reserved && this.responseBudget) { this._reserve(ip, -reserved); reserved = 0; }
|
|
892
|
+
throw e;
|
|
728
893
|
} finally {
|
|
729
894
|
if (wait > 0) this.activeWaits--;
|
|
730
895
|
}
|
|
@@ -741,6 +906,9 @@ export class CarrierServer {
|
|
|
741
906
|
this.server = createServer(async (req, res) => {
|
|
742
907
|
try {
|
|
743
908
|
const url = new URL(req.url, `http://${req.headers.host ?? "localhost"}`);
|
|
909
|
+
// 2.8.0 relay routes, only when this carrier accepts tunnels.
|
|
910
|
+
if (this.tunnelRelay && url.pathname.startsWith("/e/")) return await this.tunnelRelay.handleRequest(req, res, url);
|
|
911
|
+
if (this.tunnelRelay && url.pathname === "/v1/tunnel") return this._json(res, 426, { error: "upgrade-required" });
|
|
744
912
|
if (req.method === "POST" && url.pathname === "/v1/envelopes") {
|
|
745
913
|
const raw = await this._readBody(req);
|
|
746
914
|
let envelope;
|
|
@@ -756,7 +924,11 @@ export class CarrierServer {
|
|
|
756
924
|
return await this._handleInbox(req, res, uuaid, url);
|
|
757
925
|
}
|
|
758
926
|
if (req.method === "GET" && url.pathname === "/v1/seed-info") {
|
|
759
|
-
const
|
|
927
|
+
const challenge = url.searchParams.get("challenge");
|
|
928
|
+
if (challenge !== null && this.keychain?._identity && this.publicUrl && !CHALLENGE_RE.test(challenge)) {
|
|
929
|
+
return this._json(res, 400, { error: "bad-challenge" });
|
|
930
|
+
}
|
|
931
|
+
const info = this.seedInfo({ challenge: challenge ?? undefined });
|
|
760
932
|
// A relay with no seed identity is not a seed and must not look
|
|
761
933
|
// like one to the registry.
|
|
762
934
|
if (!info) return this._json(res, 404, { error: "not-a-seed" });
|
|
@@ -773,6 +945,7 @@ export class CarrierServer {
|
|
|
773
945
|
this._json(res, 500, { error: "internal-error" });
|
|
774
946
|
}
|
|
775
947
|
});
|
|
948
|
+
if (this.tunnelRelay) this.server.on("upgrade", (req, socket, head) => this.tunnelRelay.handleUpgrade(req, socket, head));
|
|
776
949
|
return new Promise((resolve) => {
|
|
777
950
|
if (port !== null && typeof port === "object") this.server.listen(port, () => resolve(this.server.address()));
|
|
778
951
|
else this.server.listen(port, host, () => resolve(this.server.address()));
|
|
@@ -781,6 +954,7 @@ export class CarrierServer {
|
|
|
781
954
|
|
|
782
955
|
async close() {
|
|
783
956
|
this._closed = true;
|
|
957
|
+
this.tunnelRelay?.close();
|
|
784
958
|
for (const set of this._inboxWakers.values()) for (const wake of [...set]) wake();
|
|
785
959
|
if (this.server) {
|
|
786
960
|
// close() must not wait for in-flight connections: a client long-polling
|