@uuaid/pillar 2.8.2 → 2.8.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.
package/README.md CHANGED
@@ -1645,3 +1645,135 @@ When it is set:
1645
1645
  retries a `sendGroupV2` member result with `confirmed: false`, and this method
1646
1646
  refuses it too: a plain `send()` would carry no group context to the permit.
1647
1647
  On `rerouted` or `expired` the app decides whether to send anew.
1648
+
1649
+ ## Seed routes (2.8.3, opt-in)
1650
+
1651
+ `seedRoutes` gives an app a second, bounded list of carriers: seeds from a
1652
+ directory, kept apart from the fleet. A send uses a seed only when the caller
1653
+ asks for it, and only for a recipient whose verified listing names that seed.
1654
+ Callers that pass neither option keep 2.8.2 behavior.
1655
+
1656
+ ```js
1657
+ import { Pillar } from "@uuaid/pillar";
1658
+
1659
+ const pillar = new Pillar({
1660
+ keychain, mailboxPath,
1661
+ carriers: ["https://pillar.uuaid.org"], // the fleet: trust, adverts, ordinary sends
1662
+ trustedCarriers: ["https://pillar.uuaid.org"],
1663
+ registryUrl: "https://registry.uuaid.org", // where listings are verified
1664
+ seedRoutes: {
1665
+ direct: ["https://seed.example.org"], // HTTPS origins, at most 8
1666
+ relayed: ["https://relay.example.org/e/02d449a3-1fbb-267c-8f35-2e9968a79e3e"], // exact <relay>/e/<id>, at most 4
1667
+ },
1668
+ });
1669
+
1670
+ const r = await pillar.send({ recipient, recipientPublicKey, payload: { text: "hi" }, route: "listed" });
1671
+ // r.route = { seeds: ["https://seed.example.org"], accepted: [...], reason: null }
1672
+ // r.confirmed is true only when the fleet accepted. A seed's 202 alone gives via "seed", confirmed false.
1673
+
1674
+ pillar.startSeedPolling(); // apart from startCarrierPolling; stop with stopSeedPolling()
1675
+ ```
1676
+
1677
+ What the options do:
1678
+
1679
+ | Option | Values | Effect |
1680
+ | --- | --- | --- |
1681
+ | `seedRoutes` | `null` (default) or `{ direct?, relayed?, timeoutMs?, pollIntervalMs? }` | Seeds for `route` and seed polling. Set at construction; replace it with `setSeedRoutes(value)`. |
1682
+ | `setSeedRoutes(value)` | the same shape, or `null` | Replaces the seed set while the process runs (see "Changing the routes"). |
1683
+ | `send({ route })` | `null`, `"fleet"` (default) | The fleet only, as in 2.8.2. No registry read, no seed traffic. |
1684
+ | | `"listed"` | The fleet, plus each configured seed that the recipient's verified listing names. |
1685
+ | | `{ seed: url }` | The fleet, plus that one seed, on the same condition. |
1686
+ | `sendGroup` / `sendGroupV2({ route })` | as above | Passed to every member's `send()`. |
1687
+
1688
+ The rules (RedTeam Mac B directory review, items 1-4):
1689
+
1690
+ - **Caps.** Each entry is validated and canonicalized first. A direct seed is
1691
+ an HTTPS origin. A relayed seed is an exact `<relay origin>/e/<id>` URL. User
1692
+ information, a query, a fragment, a private or loopback host, and a path on a
1693
+ direct seed are refused. Duplicates of the fleet or of another entry are
1694
+ removed before the caps: 8 direct and 4 relayed. The rest are listed in
1695
+ `pillar.seedRoutes.skipped` as `{ url, reason }` (`duplicate`, `cap`, or the
1696
+ validation reason).
1697
+ - **Public connections only.** Every seed request resolves the host, refuses
1698
+ the request when any address is not global (`seed-address-refused`), and
1699
+ connects only to the checked addresses. It follows no redirect, reads at most
1700
+ 8 MiB, and stops after `timeoutMs` (default 5000 ms, at most 30000). A send
1701
+ with `route` can wait up to `timeoutMs` for the listing and up to `timeoutMs`
1702
+ for its seeds, which run beside the fleet post; a send without `route` waits
1703
+ for neither.
1704
+ All seed requests in the process share 4 slots, with 1 per origin, across
1705
+ every Pillar (owner and agents).
1706
+ - **Verified listed seed only.** For `route`, the SDK resolves the final
1707
+ recipient (after continuity and W-4) through `registryUrl` with the
1708
+ signature-checking resolver. The listing must be for that recipient and its
1709
+ sealing key. A seed gets the envelope only when the listing names it and it
1710
+ is configured. Otherwise `route.seeds` is empty and `route.reason` says why
1711
+ (`no-seed-routes`, `no-registry`, `no-fleet`, `not-listed`, `seed-not-listed`,
1712
+ `listing-not-recipient`, `listing-key-mismatch`, `listing-dead`,
1713
+ `listing-unverified:<resolver reason>`); the send continues on the fleet.
1714
+ - **A seed's 202 is storage, not delivery.** Seeds are never trusted carriers
1715
+ and never join `carriers`. Only the fleet's acceptance marks the row
1716
+ `delivered` (with `trustedCarriers` set, a trusted fleet carrier's). When
1717
+ every fleet carrier refuses and a seed accepts, `send()` returns
1718
+ `via: "seed"`, `confirmed: false`, and `carrierError`; the row stays `pending`.
1719
+ When the seeds refuse too, the fleet's error is thrown, with `route` on it.
1720
+ - **Permits stay on.** The send permit sees each seed dispatch (`carrier` is
1721
+ the seed URL). A refusal denies the send as on any carrier; a fleet
1722
+ acceptance before it is still recorded.
1723
+ - **Trust and adverts stay on the build lists.** `carriers`, `trustedCarriers`,
1724
+ carrier polling, `drainCarrierInbox`, auto-acks, read receipts, retired-key
1725
+ imports, `syncGroupV2` and `resendOutbound` do not use seeds.
1726
+ - **Group copies.** With `route`, a member copy that only a seed took is
1727
+ `confirmed: false`, and `sendGroupV2` returns `unconfirmed` (the count).
1728
+ Nothing in the SDK sends it again. A verified ack or read receipt from that
1729
+ member advances its row (`recipient_ack_at`), as for any send.
1730
+ - **Seed polling.** `startSeedPolling({ intervalMs, onError })` runs apart from the
1731
+ fleet poller. Each round sleeps a jittered 0.5x to 1.5x `intervalMs` (default
1732
+ `seedRoutes.pollIntervalMs`, 120000 ms; at least 10000 ms), then takes one
1733
+ `wait=0` page (at most 200 envelopes) from each seed in turn, with inbox auth
1734
+ v2. Each seed keeps its own cursor. A slow or empty seed costs at most
1735
+ `timeoutMs` and never delays a send or the fleet poller. `stop()` stops it
1736
+ too. `onError(error, { seed })` is called for a failed poll; if it throws,
1737
+ the error is counted (`seed.poll.onerror-threw`) and polling goes on. If the
1738
+ loop ever ends without `stopSeedPolling()`, its handle is cleared, so the
1739
+ next `startSeedPolling()` starts a new one.
1740
+ - **`pollSeedsOnce()`** runs one round now. It returns how many **new inbox
1741
+ rows** the round stored, quarantined rows included. Duplicates, items for
1742
+ another recipient, and items that fail to open are not counted. It is not a
1743
+ count of new mail to show a user.
1744
+
1745
+ ### Changing the routes: `setSeedRoutes(value)`
1746
+
1747
+ An app's route cache expires and refreshes while the process runs. Call
1748
+ `pillar.setSeedRoutes(value)` with the new set, or `null` to turn seed routes
1749
+ off. Call it on every Pillar that uses seeds (owner and agents).
1750
+
1751
+ - `value` is checked like the constructor's `seedRoutes`, against the same
1752
+ fleet. A bad value throws a `TypeError` and changes nothing. It returns the
1753
+ new normalized routes (`null` when off).
1754
+ - The next send and the next poll round use the new set. A seed that is no
1755
+ longer in it gets no new request. That includes a request still waiting on
1756
+ a send permit: the seed fetch refuses it (`seed-route-removed`), and the
1757
+ send's result comes from the fleet as usual. One already queued may still go
1758
+ within timeoutMs: a request that passed that check and waits in the seed
1759
+ concurrency limits is not called back.
1760
+ - Seeds that stay keep their cursors. The cursors of removed seeds are
1761
+ dropped, and a page that was in flight when its seed was removed writes
1762
+ nothing back. Fleet cursors are never touched.
1763
+ - `null`, or a set with no seeds, stops seed traffic. A running seed poller
1764
+ keeps running and polls nothing until a later call adds seeds. Its interval
1765
+ is the one it started with.
1766
+ - The new value replaces everything, including `timeoutMs`,
1767
+ `pollIntervalMs` and the test hooks below. Pass the whole object each time.
1768
+
1769
+ **Build `seedRoutes` field by field.** `allowPrivateUrls`, `lookup` and
1770
+ `fetch` are test hooks. `allowPrivateUrls: true` turns off the https and
1771
+ private-address checks for every seed send and poll, and it can be written in
1772
+ plain JSON. Never pass an object parsed from directory data or any other JSON
1773
+ to `new Pillar({ seedRoutes })` or `setSeedRoutes()`, and never spread one into
1774
+ it. Build `{ direct: [...], relayed: [...] }` from the checked URL strings
1775
+ only.
1776
+
1777
+ `@uuaid/pillar/seed-routes` exports the caps, `normalizeSeedRoutes`,
1778
+ `canonicalSeed`, `makeSeedFetch` and `listedSeeds` for an app that checks a
1779
+ directory itself.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uuaid/pillar",
3
- "version": "2.8.2",
3
+ "version": "2.8.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",
@@ -29,6 +29,7 @@
29
29
  "./seed-tier": "./src/net/seed-tier.mjs",
30
30
  "./seed-registry": "./src/net/seed-registry.mjs",
31
31
  "./discovery": "./src/net/discovery.mjs",
32
+ "./seed-routes": "./src/net/seed-routes.mjs",
32
33
  "./blob": "./src/blob/blob.mjs",
33
34
  "./blob/http": "./src/blob/http.mjs",
34
35
  "./blob/store": "./src/blob/store.mjs",
@@ -385,6 +385,12 @@ export class Mailbox {
385
385
  ).run(carrier, seq);
386
386
  }
387
387
 
388
+ /** 2.8.3: forget one carrier's cursor (Pillar#setSeedRoutes drops a removed seed's). True when a row went. */
389
+ deleteCarrierCursor(carrier) {
390
+ if (this._jsonDir) return this._jsonDir.deleteCarrierCursor(carrier);
391
+ return this.db.prepare("delete from carrier_cursors where carrier = ?").run(carrier).changes > 0;
392
+ }
393
+
388
394
  _getHead(logName) {
389
395
  const row = this.db.prepare("select chain_head from chain_state where log_name = ?").get(logName);
390
396
  return row?.chain_head ?? null;
@@ -86,11 +86,16 @@ export class CarrierClient {
86
86
  * only these carriers get inbox auth v1, and only their
87
87
  * acceptance counts as delivered (countsAcceptance). Unset:
88
88
  * 2.8.1 (v1 to every direct carrier, any acceptance counts).
89
+ * fetch 2.8.3, optional: the fetch for every request this client
90
+ * makes (seed routes pass the checked, bounded seed fetch).
91
+ * Unset: the global fetch, read at call time.
89
92
  */
90
- constructor({ keychain, carriers, tierGrant = null, carrierTiers = {}, trustedCarriers = null }) {
93
+ constructor({ keychain, carriers, tierGrant = null, carrierTiers = {}, trustedCarriers = null, fetch: fetchImpl = null }) {
91
94
  if (!keychain?._identity) throw new Error("CarrierClient needs a loaded keychain");
92
95
  if (!carriers?.length) throw new Error("CarrierClient needs at least one carrier URL");
93
96
  this.keychain = keychain;
97
+ if (fetchImpl != null && typeof fetchImpl !== "function") throw new TypeError("CarrierClient fetch must be a function");
98
+ this._fetch = fetchImpl;
94
99
  this.trustedCarriers = normalizeTrustedCarriers(trustedCarriers);
95
100
  this._trusted = this.trustedCarriers ? new Set(this.trustedCarriers) : null;
96
101
  // Normalise tier keys the same way as carrier URLs so a trailing slash on
@@ -182,7 +187,7 @@ export class CarrierClient {
182
187
  try {
183
188
  if (guard) { await guard({ phase: "dispatch", route: "carrier", carrier: base }); assertSendNotAborted(signal); } // @spaces-check send-permit-each-carrier
184
189
  attempted = true;
185
- const res = await fetch(`${base}/v1/envelopes`, {
190
+ const res = await (this._fetch ?? fetch)(`${base}/v1/envelopes`, {
186
191
  method: "POST",
187
192
  // 2.8.1: never follow a redirect. A 307/308 would replay the body and
188
193
  // the x-pillar-* headers to whatever host the answer names.
@@ -253,7 +258,7 @@ export class CarrierClient {
253
258
  const headers = this.usesInboxAuthV2(base)
254
259
  ? signInboxAuthV2(this.keychain, { audience: base, uuaid: this.uuaid, since, wait: waitS })
255
260
  : signInboxAuthV1(this.keychain, { uuaid: this.uuaid, since });
256
- const res = await fetch(`${String(base).replace(/\/+$/, "")}/v1/inbox/${encodeURIComponent(this.uuaid)}?since=${since}&wait=${waitS}`, {
261
+ const res = await (this._fetch ?? fetch)(`${String(base).replace(/\/+$/, "")}/v1/inbox/${encodeURIComponent(this.uuaid)}?since=${since}&wait=${waitS}`, {
257
262
  headers,
258
263
  // `signal` lets a caller cancel a long-poll early (peekCarrierInbox stops
259
264
  // the other carriers once one has mail).
@@ -357,6 +357,7 @@ function raceSignal(promise, signal) {
357
357
 
358
358
  function defaultFetch(input, init = {}) {
359
359
  const u = new URL(String(input));
360
+ const maxBytes = Number.isInteger(init.maxBytes) && init.maxBytes > 0 ? init.maxBytes : MAX_RESPONSE_BYTES;
360
361
  const reqFn = u.protocol === "https:" ? httpsRequest : httpRequest;
361
362
  const headers = { ...(init.headers ?? {}) };
362
363
  const body = init.body !== undefined && init.body !== null ? Buffer.from(init.body) : null;
@@ -384,7 +385,7 @@ function defaultFetch(input, init = {}) {
384
385
  let bytes = 0;
385
386
  res.on("data", (c) => {
386
387
  bytes += c.length;
387
- if (bytes > MAX_RESPONSE_BYTES) {
388
+ if (bytes > maxBytes) {
388
389
  req.destroy(new Error("seed response too large"));
389
390
  return;
390
391
  }
@@ -415,6 +416,13 @@ function defaultFetch(input, init = {}) {
415
416
  });
416
417
  }
417
418
 
419
+ /**
420
+ * 2.8.3: the same bounded request for seed routes (src/net/seed-routes.mjs).
421
+ * Node's http follows no redirect; `lookup` pins the checked addresses;
422
+ * `maxBytes` (default 1 MiB) bounds the body read.
423
+ */
424
+ export { defaultFetch as boundedFetch };
425
+
418
426
  /** Verify a /v1/seed-info document: signature, key/uuaid binding, URL match. */
419
427
  export function verifySeedInfo(doc, expectedUrl) {
420
428
  if (doc?.v !== 1) return { ok: false, reason: "bad-version" };
@@ -0,0 +1,214 @@
1
+ /**
2
+ * 2.8.3 opt-in seed routes: per-send route choice and bounded seed polling
3
+ * (RedTeam Mac B directory review, items 1-4).
4
+ *
5
+ * The fleet (`carriers`) keeps trust, advertisement and ordinary sends. Seeds
6
+ * are a separate, bounded list that a send uses only for a recipient whose
7
+ * verified listing names that seed (Pillar#send `route`). A seed's 202 is
8
+ * storage at an outside carrier: it never marks a send delivered.
9
+ *
10
+ * - At most MAX_DIRECT_SEEDS direct seeds (HTTPS origins) and
11
+ * MAX_RELAYED_SEEDS relayed seeds (exact `<relay origin>/e/<id>`), counted
12
+ * after validation, canonicalization and dedupe against the fleet and
13
+ * each other. User information, queries and fragments are refused.
14
+ * - Every seed request resolves its host first and connects only to the
15
+ * checked global addresses (resolveSeedUrl pins the lookup), follows no
16
+ * redirect, reads at most SEED_MAX_RESPONSE_BYTES, and has a timeout.
17
+ * - Seed requests share one process-wide limit and one per-origin limit,
18
+ * across every Pillar in the process (owner and agents).
19
+ */
20
+ import { checkSeedUrl, resolveSeedUrl, boundedFetch } from "./seed-registry.mjs";
21
+ import { isRelayedSeedUrl } from "./tunnel.mjs";
22
+
23
+ export const MAX_DIRECT_SEEDS = 8;
24
+ export const MAX_RELAYED_SEEDS = 4;
25
+ /** Per seed request. Bounds what a slow seed adds to a send. */
26
+ export const SEED_TIMEOUT_MS = 5000;
27
+ /** Seed polls are sparse: one wait=0 page per seed per round, jittered. */
28
+ export const SEED_POLL_INTERVAL_MS = 120_000;
29
+ export const SEED_MIN_POLL_INTERVAL_MS = 10_000;
30
+ /** One inbox page of 200 envelopes, each under the 2 MiB direct cap, is far below this in practice. */
31
+ export const SEED_MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
32
+ export const SEED_PROCESS_LIMIT = 4;
33
+ export const SEED_PER_ORIGIN_LIMIT = 1;
34
+ const MAX_URL_LENGTH = 2048;
35
+
36
+ /** A fleet carrier URL in the same form as a canonical seed, for dedupe. */
37
+ export function routeKey(raw) {
38
+ try {
39
+ const u = new URL(String(raw));
40
+ return `${u.origin}${u.pathname}`.replace(/\/+$/, "");
41
+ } catch (_e) {
42
+ return String(raw).replace(/\/+$/, "");
43
+ }
44
+ }
45
+
46
+ /**
47
+ * Validate and canonicalize one seed URL.
48
+ * @returns {{ ok: true, url: string } | { ok: false, reason: string }}
49
+ */
50
+ export function canonicalSeed(raw, { relayed = false, allowPrivateUrls = false } = {}) {
51
+ if (typeof raw !== "string" || !raw.trim()) return { ok: false, reason: "bad-url" };
52
+ if (raw.length > MAX_URL_LENGTH) return { ok: false, reason: "url-too-long" };
53
+ if (raw.includes("?") || raw.includes("#")) return { ok: false, reason: "query-in-url" };
54
+ const checked = checkSeedUrl(raw.trim(), { allowPrivateUrls });
55
+ if (!checked.ok) return checked;
56
+ const u = new URL(checked.url);
57
+ if (relayed) {
58
+ if (!isRelayedSeedUrl(checked.url)) return { ok: false, reason: "not-relay-path" };
59
+ return { ok: true, url: `${u.origin}${u.pathname}`.replace(/\/+$/, "") };
60
+ }
61
+ if (isRelayedSeedUrl(checked.url)) return { ok: false, reason: "relayed-in-direct" };
62
+ if (u.pathname !== "/" && u.pathname !== "") return { ok: false, reason: "path-in-origin" };
63
+ return { ok: true, url: u.origin };
64
+ }
65
+
66
+ /**
67
+ * The `seedRoutes` constructor option. null or undefined = unset (2.8.2
68
+ * behavior). A plain object with optional `direct` and `relayed` arrays of
69
+ * URLs. Entries that fail validation, repeat the fleet or another entry, or
70
+ * pass a cap are skipped and listed in `skipped` ({ url, reason }), in input
71
+ * order. `fetch` replaces the checked seed connection and is for tests only.
72
+ */
73
+ export function normalizeSeedRoutes(value, { fleet = [] } = {}) {
74
+ if (value == null) return null;
75
+ if (typeof value !== "object" || Array.isArray(value)) throw new TypeError("seedRoutes must be an object { direct?, relayed? }, or null");
76
+ const { direct = [], relayed = [], allowPrivateUrls = false, timeoutMs = SEED_TIMEOUT_MS, pollIntervalMs = SEED_POLL_INTERVAL_MS, lookup = undefined, fetch = undefined } = value;
77
+ if (!Array.isArray(direct) || !Array.isArray(relayed)) throw new TypeError("seedRoutes.direct and seedRoutes.relayed must be arrays of URLs");
78
+ if (!(Number.isFinite(timeoutMs) && timeoutMs > 0 && timeoutMs <= 30_000)) throw new TypeError("seedRoutes.timeoutMs must be 1-30000 ms");
79
+ if (!(Number.isFinite(pollIntervalMs) && pollIntervalMs >= SEED_MIN_POLL_INTERVAL_MS)) throw new TypeError(`seedRoutes.pollIntervalMs must be at least ${SEED_MIN_POLL_INTERVAL_MS} ms`);
80
+ if (fetch !== undefined && typeof fetch !== "function") throw new TypeError("seedRoutes.fetch must be a function");
81
+ const seen = new Set(fleet.map(routeKey));
82
+ const skipped = [];
83
+ const take = (list, relayedKind, cap) => {
84
+ const out = [];
85
+ for (const raw of list) {
86
+ const c = canonicalSeed(raw, { relayed: relayedKind, allowPrivateUrls: allowPrivateUrls === true });
87
+ if (!c.ok) { skipped.push({ url: String(raw).slice(0, MAX_URL_LENGTH), reason: c.reason }); continue; }
88
+ if (seen.has(c.url)) { skipped.push({ url: c.url, reason: "duplicate" }); continue; } // @t283 seed-dedupe-before-cap
89
+ if (out.length >= cap) { skipped.push({ url: c.url, reason: "cap" }); continue; } // @t283 seed-cap
90
+ seen.add(c.url);
91
+ out.push(c.url);
92
+ }
93
+ return out;
94
+ };
95
+ const d = take(direct, false, MAX_DIRECT_SEEDS);
96
+ const r = take(relayed, true, MAX_RELAYED_SEEDS);
97
+ return Object.freeze({
98
+ direct: Object.freeze(d),
99
+ relayed: Object.freeze(r),
100
+ all: Object.freeze([...d, ...r]),
101
+ skipped: Object.freeze(skipped),
102
+ allowPrivateUrls: allowPrivateUrls === true,
103
+ timeoutMs,
104
+ pollIntervalMs,
105
+ lookup,
106
+ fetch,
107
+ });
108
+ }
109
+
110
+ /** A counting gate. acquire() waits for a slot; an aborted signal ends the wait. */
111
+ function makeGate(max) {
112
+ let active = 0;
113
+ const waiters = [];
114
+ return {
115
+ get active() { return active; },
116
+ get waiting() { return waiters.length; },
117
+ acquire(signal) {
118
+ if (signal?.aborted) return Promise.reject(signal.reason ?? new Error("seed request aborted"));
119
+ if (active < max) { active++; return Promise.resolve(); }
120
+ return new Promise((resolve, reject) => {
121
+ const onAbort = () => {
122
+ const i = waiters.indexOf(grant);
123
+ if (i >= 0) waiters.splice(i, 1);
124
+ reject(signal.reason ?? new Error("seed request aborted"));
125
+ };
126
+ const grant = () => { signal?.removeEventListener("abort", onAbort); resolve(); };
127
+ signal?.addEventListener("abort", onAbort, { once: true });
128
+ waiters.push(grant);
129
+ });
130
+ },
131
+ release() {
132
+ const next = waiters.shift();
133
+ if (next) next(); else active--;
134
+ },
135
+ };
136
+ }
137
+
138
+ // Module scope on purpose: one budget for every Pillar in this process.
139
+ const processGate = makeGate(SEED_PROCESS_LIMIT);
140
+ const originGates = new Map();
141
+
142
+ /** Current seed I/O use, for tests and metrics. */
143
+ export function seedIoStats() {
144
+ let perOrigin = 0;
145
+ for (const g of originGates.values()) perOrigin = Math.max(perOrigin, g.active);
146
+ return { active: processGate.active, waiting: processGate.waiting, maxPerOrigin: perOrigin };
147
+ }
148
+
149
+ /**
150
+ * A fetch for seed traffic, in the shape CarrierClient uses. Each request
151
+ * takes a process slot and an origin slot, resolves the seed host and refuses
152
+ * any non-global address (unless allowPrivateUrls, tests only), connects to
153
+ * the checked address only, follows no redirect, and reads a bounded body.
154
+ */
155
+ export function makeSeedFetch({ allowPrivateUrls = false, lookup = undefined, fetch = undefined, maxBytes = SEED_MAX_RESPONSE_BYTES } = {}) {
156
+ return async (input, init = {}) => {
157
+ const u = new URL(String(input));
158
+ const origin = u.origin;
159
+ const signal = init.signal ?? undefined;
160
+ // The origin slot first: a request queued behind its own origin holds no process slot,
161
+ // so one busy seed cannot starve the others.
162
+ let gate = originGates.get(origin);
163
+ if (!gate) { gate = makeGate(SEED_PER_ORIGIN_LIMIT); originGates.set(origin, gate); }
164
+ try {
165
+ await gate.acquire(signal);
166
+ } catch (e) {
167
+ if (gate.active === 0 && gate.waiting === 0) originGates.delete(origin);
168
+ throw e;
169
+ }
170
+ try {
171
+ await processGate.acquire(signal); // @t283 seed-origin-before-process
172
+ } catch (e) {
173
+ gate.release();
174
+ if (gate.active === 0 && gate.waiting === 0) originGates.delete(origin);
175
+ throw e;
176
+ }
177
+ try {
178
+ if (fetch) return await fetch(String(input), init);
179
+ // The host check and the pinned lookup use the origin; the request keeps its path and query.
180
+ const resolved = await resolveSeedUrl(`${u.protocol}//${u.host}`, { allowPrivateUrls, lookup, signal });
181
+ if (!resolved.ok) { // @t283 seed-public-connection
182
+ const e = new Error(`seed connection refused: ${resolved.reason}`);
183
+ e.code = "seed-address-refused";
184
+ throw e;
185
+ }
186
+ return await boundedFetch(String(input), {
187
+ method: init.method, headers: init.headers, body: init.body, signal,
188
+ maxBytes, ...(resolved.lookup ? { lookup: resolved.lookup } : {}),
189
+ });
190
+ } finally {
191
+ gate.release();
192
+ processGate.release();
193
+ if (gate.active === 0 && gate.waiting === 0) originGates.delete(origin);
194
+ }
195
+ };
196
+ }
197
+
198
+ /**
199
+ * Which configured seeds a verified listing names for `recipient`.
200
+ * `res` is a resolveListing() result (signature-checked by pillar-core).
201
+ * @returns {{ seeds: string[], reason: string | null }}
202
+ */
203
+ export function listedSeeds(res, { recipient, publicKey, seeds, only = null }) {
204
+ if (!res?.ok) return { seeds: [], reason: `listing-unverified:${res?.reason ?? "unknown"}` };
205
+ if (res.current !== recipient || res.card?.uuaid !== recipient) return { seeds: [], reason: "listing-not-recipient" }; // @t283 seed-listing-recipient
206
+ // Defense in depth, not in T5.3: a uuaid derives from its key and seal() refuses a mismatched key, so no test reaches it.
207
+ if (res.card?.publicKey !== publicKey) return { seeds: [], reason: "listing-key-mismatch" }; // @rule seed.listing-key
208
+ if (res.status === "dead") return { seeds: [], reason: "listing-dead" };
209
+ const listed = new Set((Array.isArray(res.card?.carriers) ? res.card.carriers : []).map(routeKey));
210
+ let picked = seeds.filter((s) => listed.has(s)); // @t283 seed-listed-only
211
+ if (only !== null) picked = picked.filter((s) => s === only);
212
+ if (!picked.length) return { seeds: [], reason: only !== null ? "seed-not-listed" : "not-listed" };
213
+ return { seeds: picked, reason: null };
214
+ }
@@ -83,6 +83,15 @@ const SAFE_HEADERS = Object.freeze({
83
83
  "cache-control": "no-store",
84
84
  });
85
85
 
86
+ // 2.8.3 (RedTeam 70ef63): the CORS policy the carriers' nginx sets on /e/ (snippets/pillar-cors.conf, 2.8.1 cors-281),
87
+ // so a browser or WebView client can use a stock relay. A preflight gets 204 and these; every /e/* answer echoes the
88
+ // request's Origin. No credentials.
89
+ const CORS_PREFLIGHT = Object.freeze({
90
+ "access-control-allow-methods": "GET, POST, DELETE, OPTIONS",
91
+ "access-control-allow-headers": "content-type, x-pillar-pubkey, x-pillar-ts, x-pillar-sig, authorization, x-pillar-ticket, x-pillar-auth, x-pillar-nonce, x-pillar-delegation",
92
+ "access-control-max-age": "86400",
93
+ });
94
+
86
95
  const UUAID_LINE = /^uuaid:[a-z0-9-]+:[a-z0-9-]+:[^\s:]+$/;
87
96
 
88
97
  /**
@@ -398,6 +407,9 @@ export class TunnelRelay {
398
407
 
399
408
  /** The CarrierServer hands every /e/* request here. */
400
409
  async handleRequest(req, res, url) {
410
+ // 2.8.3 (RedTeam 70ef63): CORS as the carriers' nginx. setHeader keeps the echo on every answer below.
411
+ if (req.headers.origin) res.setHeader("access-control-allow-origin", req.headers.origin); // @rule relay.cors-origin
412
+ if (req.method === "OPTIONS") { res.writeHead(204, CORS_PREFLIGHT); return res.end(); } // @rule relay.cors-preflight
401
413
  const now = this.mono();
402
414
  const p = parseRelayPath(url.pathname);
403
415
  if (!p) return this._send(res, 404, { error: "not-found" });
package/src/pillar.mjs CHANGED
@@ -25,6 +25,8 @@ import {
25
25
  import { seal, open, decrypt, envelopeSha, mkEnvelopeId, ENVELOPE_VERSION } from "./net/envelope.mjs";
26
26
  import { Mailbox, isErasedRow } from "./mailbox/mailbox.mjs";
27
27
  import { CarrierClient, normalizeTrustedCarriers, acceptedByTrusted } from "./net/carrier-client.mjs";
28
+ import { normalizeSeedRoutes, makeSeedFetch, listedSeeds, routeKey, SEED_MIN_POLL_INTERVAL_MS } from "./net/seed-routes.mjs";
29
+ import { setTimeout as sleepTimer } from "node:timers/promises";
28
30
  import { REFUSAL_FIXES } from "./net/refusals.mjs";
29
31
  import { Observability } from "./observability.mjs";
30
32
  import { evaluateTrust, allowSenderInTrust, DEFAULT_KNOCK_ACCEPT_SCOPE } from "./identity/trust.mjs";
@@ -90,6 +92,18 @@ function resendBlocked(row, recipient, nowMs = Date.now()) {
90
92
  if (attemptExpired(stored, nowMs)) return "expired"; // @t282 resend-expired
91
93
  return null;
92
94
  }
95
+ /**
96
+ * 2.8.3: send()'s `route`. null, undefined or "fleet": the fleet only (2.8.2). "listed": the fleet, plus each
97
+ * configured seed the recipient's verified listing names. { seed: url }: the fleet, plus that one seed, on the
98
+ * same condition. Anything else is a TypeError, thrown before anything is sealed or sent.
99
+ */
100
+ function parseRouteAsk(route) {
101
+ if (route == null || route === "fleet") return null;
102
+ if (route === "listed") return { only: null };
103
+ if (route && typeof route === "object" && !Array.isArray(route) && typeof route.seed === "string" && route.seed.trim()) return { only: routeKey(route.seed.trim()) };
104
+ throw new TypeError('send: route must be "fleet", "listed", { seed: url }, or null');
105
+ }
106
+
93
107
  /** Over RESEND_MAX_AGE_MS old (or no readable createdAt): a carrier would refuse the stored envelope. */
94
108
  function attemptExpired(stored, nowMs = Date.now()) {
95
109
  const created = Date.parse(stored.createdAt);
@@ -137,6 +151,7 @@ export class Pillar {
137
151
  knockConfig = null, // vNext §4 knock policy: { requiredBits?, maxBytes?, introductions?, stake?, trustedIssuers?, trustedContacts?, lineageResolver?, lineages?, selfLineage?, card?, cap?, rateWindowMs?, now? }
138
152
  registryUrl = null, // vNext §3 registry base URL; when set, sends follow W-4 sender redirect policy (B5, T2.7)
139
153
  continuity = null, // 2.8.0 continuity: { passphrase?, now?, fetch?, urlMap?, allowInsecureLoopback? } (DESIGN-continuity)
154
+ seedRoutes = null, // 2.8.3 opt-in: { direct?, relayed?, timeoutMs?, pollIntervalMs? } seeds for send({ route }) and startSeedPolling; null = 2.8.2
140
155
  }) {
141
156
  if (!keychain?._identity) throw new Error("Pillar: keychain must be loaded before construction");
142
157
  if (outboundPolicy != null && typeof outboundPolicy !== "function") throw sendPermitDenied();
@@ -159,6 +174,11 @@ export class Pillar {
159
174
  this.dhtPeerInfoMapper = dhtPeerInfoMapper;
160
175
  this.carriers = carriers;
161
176
  this.carrierClient = carriers.length ? new CarrierClient({ keychain, carriers, tierGrant, trustedCarriers: this.trustedCarriers }) : null;
177
+ // 2.8.3: seeds stay apart from the fleet. They never join `carriers` or `trustedCarriers`, so trust,
178
+ // advertisement and every send without `route` stay on the fleet (RedTeam Mac B item 3).
179
+ this.seedRoutes = normalizeSeedRoutes(seedRoutes, { fleet: carriers });
180
+ this._seedFetch = this.seedRoutes ? makeSeedFetch({ allowPrivateUrls: this.seedRoutes.allowPrivateUrls, lookup: this.seedRoutes.lookup, fetch: this.seedRoutes.fetch }) : null;
181
+ this._seedPoller = null;
162
182
  this._carrierPoller = null;
163
183
  this._carrierStopping = Promise.resolve();
164
184
  this.enableLibp2p = enableLibp2p;
@@ -267,6 +287,7 @@ export class Pillar {
267
287
  }
268
288
 
269
289
  async stop() {
290
+ await this.stopSeedPolling();
270
291
  await this.stopCarrierPolling();
271
292
  if (!this.node) { this.mailbox.close(); return; }
272
293
  for (const push of this._openStreams.values()) { try { push.end(); } catch (_e) {} }
@@ -962,7 +983,8 @@ export class Pillar {
962
983
  return { direct: true, publicKey: pubKey, carrier: res.card?.carriers?.[0] };
963
984
  }
964
985
 
965
- async send({ recipient, recipientPublicKey, subject = null, routeFp = null, kind = "message", payload = {}, envelopeId = null, resolveTimeoutMs = 5000, registryUrl = null, confirmRecovered = false, now = null, urlMap = undefined, allowInsecureLoopback = false, fetch: fetchOverride = undefined, permit = null, signal = null, [RESEND]: resendId = null }) {
986
+ async send({ recipient, recipientPublicKey, subject = null, routeFp = null, kind = "message", payload = {}, envelopeId = null, resolveTimeoutMs = 5000, registryUrl = null, confirmRecovered = false, now = null, urlMap = undefined, allowInsecureLoopback = false, fetch: fetchOverride = undefined, permit = null, signal = null, route = null, [RESEND]: resendId = null }) {
987
+ const routeAsk = parseRouteAsk(route); // 2.8.3: before any I/O, so a bad value sends nothing
966
988
  if (!this.node && !this.carrierClient) {
967
989
  this.metrics.inc("send.error.not-started");
968
990
  throw new Error("pillar not started");
@@ -1022,6 +1044,8 @@ export class Pillar {
1022
1044
  throw new Error(`send: no public key known for ${recipient} — encryption is mandatory; register the peer (address book / fleet.json) or pass recipientPublicKey`);
1023
1045
  }
1024
1046
 
1047
+ // 2.8.3: a seed only when the recipient's verified listing names it, for the final recipient and the sealing key.
1048
+ const seedRoute = routeAsk ? await this._selectSeedRoute(recipient, pubkey, routeAsk, { registryUrl, now, fetch: fetchOverride, urlMap, allowInsecureLoopback, signal }) : null;
1025
1049
  this._recheckRoute(subj, cr.fp, recipient, now); // nothing above awaited may change the route unseen
1026
1050
  // A resend (syncGroupV2) dispatches the stored bytes of a live pending row, only while the route still lands on
1027
1051
  // their recipient and a carrier would still take them. Otherwise it returns `{ [RESEND]: why }` (resendBlocked).
@@ -1063,13 +1087,22 @@ export class Pillar {
1063
1087
  // (what status 'delivered' has always meant, mailbox.mjs). The recipient's
1064
1088
  // mailbox keys on (sender, envelope id), so a copy that arrives both ways is
1065
1089
  // stored and handled once.
1090
+ // 2.8.3: the selected seeds take a copy beside the fleet, bounded by seedRoutes.timeoutMs. A seed's acceptance
1091
+ // is never a delivery, and a permit refusal on a seed denies the send as on any carrier (RedTeam Mac B item 2).
1092
+ const seedP = seedRoute?.seeds.length ? this._deliverSeeds(envelope, seedRoute.seeds, { permit: carrierPermit, signal, timeoutMs: seedRoute.timeoutMs }) : null; // @t283 seed-parallel-bounded
1093
+ const routeOf = (o) => (seedRoute ? { route: { seeds: [...seedRoute.seeds], accepted: o?.accepted ?? [], reason: seedRoute.reason, ...(o?.error ? { error: o.error.message } : {}) } } : {});
1094
+ const seedOnly = (seeds, carrierError, extra = {}) => { // every fleet carrier refused; a listed seed holds a copy
1095
+ this.metrics.inc("send.via.seed-unconfirmed");
1096
+ return { envelope, persisted, via: "seed", delivery: seeds.result, confirmed: false, carrierError, ...extra, ...routeOf(seeds), ...w4Fields }; // @t283 seed-accept-not-delivered
1097
+ };
1066
1098
  if (this.node && book?.peerId && book?.multiaddr) {
1067
1099
  const [direct, carrier] = await Promise.allSettled([
1068
1100
  this._deliverToPeer(envelope, book.peerId, book.multiaddr, { guard: dispatchGuard, signal }),
1069
1101
  this.carrierClient ? this.carrierClient.deliver(envelope, { permit: carrierPermit, signal }) : Promise.resolve(null),
1070
1102
  ]);
1103
+ const seeds = seedP ? await seedP : null;
1071
1104
  const sentDirect = direct.status === "fulfilled" ? direct.value : null;
1072
- const denial = [direct, carrier].find((r) => r.status === "rejected" && isSendPermitDenied(r.reason));
1105
+ const denial = [direct, carrier].find((r) => r.status === "rejected" && isSendPermitDenied(r.reason)) ?? (seeds?.denied ? { reason: seeds.denied } : null);
1073
1106
  if (denial || resendStop) {
1074
1107
  const accepted = carrier.status === "fulfilled" && carrier.value;
1075
1108
  let counted = Boolean(accepted);
@@ -1082,12 +1115,12 @@ export class Pillar {
1082
1115
  }
1083
1116
  if (carrier.status === "fulfilled" && carrier.value) {
1084
1117
  // 2.8.2 trustedCarriers: only untrusted carriers (a relayed seed) took it. That is not a delivery; the row stays pending.
1085
- if (this.trustedCarriers && !acceptedByTrusted(carrier.value, this.trustedCarriers)) return this._untrustedAcceptance({ envelope, persisted, via: sentDirect ? "direct+carrier" : "carrier", delivery: carrier.value, direct: sentDirect }, w4Fields); // @t282 mark-direct-carrier
1118
+ if (this.trustedCarriers && !acceptedByTrusted(carrier.value, this.trustedCarriers)) return this._untrustedAcceptance({ envelope, persisted, via: sentDirect ? "direct+carrier" : "carrier", delivery: carrier.value, direct: sentDirect, ...routeOf(seeds) }, w4Fields); // @t282 mark-direct-carrier
1086
1119
  this.mailbox.markOutboundDelivered(envelope.id, envelopeSha(envelope));
1087
1120
  const via = sentDirect ? "direct+carrier" : "carrier";
1088
1121
  this.metrics.inc(`send.via.${via}`);
1089
1122
  this.metrics.observe(`send.latencyMs.via.${via}`, Date.now() - t0);
1090
- return { envelope, persisted, via, delivery: carrier.value, direct: sentDirect, confirmed: true, ...w4Fields };
1123
+ return { envelope, persisted, via, delivery: carrier.value, direct: sentDirect, confirmed: true, ...routeOf(seeds), ...w4Fields };
1091
1124
  }
1092
1125
  if (sentDirect) {
1093
1126
  // Written to a stream, and no carrier holds a copy: nothing confirms it
@@ -1095,8 +1128,9 @@ export class Pillar {
1095
1128
  // sends one, is recorded when it comes).
1096
1129
  this.metrics.inc("send.via.direct-unconfirmed");
1097
1130
  return { envelope, persisted, via: "direct", delivery: sentDirect, direct: sentDirect, confirmed: false,
1098
- carrierError: carrier.status === "rejected" ? carrier.reason : null, ...w4Fields };
1131
+ carrierError: carrier.status === "rejected" ? carrier.reason : null, ...routeOf(seeds), ...w4Fields };
1099
1132
  }
1133
+ if (seeds?.accepted.length) return seedOnly(seeds, carrier.status === "rejected" ? carrier.reason : direct.reason, { direct: null });
1100
1134
  this.metrics.inc("send.error.direct-delivery-failed");
1101
1135
  throw carrier.status === "rejected" ? carrier.reason : direct.reason;
1102
1136
  }
@@ -1106,17 +1140,26 @@ export class Pillar {
1106
1140
  let receipt;
1107
1141
  try { receipt = await this.carrierClient.deliver(envelope, { permit: carrierPermit, signal }); }
1108
1142
  catch (e) {
1143
+ const seeds = seedP ? await seedP : null;
1109
1144
  // 2.8.2 r2 (RedTeam 822828 P2): a denial during the fanout can follow an acceptance. Record it, then return the denial.
1110
1145
  if (this._partialAccepted(e)) this.mailbox.markOutboundDelivered(envelope.id, envelopeSha(envelope)); // @t282 partial-carrier
1111
1146
  if (resendStop) return { [RESEND]: resendStop };
1147
+ if (!isSendPermitDenied(e) && seeds?.denied) throw seeds.denied;
1148
+ if (!isSendPermitDenied(e) && seeds?.accepted.length) return seedOnly(seeds, e);
1149
+ if (seedRoute && e && typeof e === "object" && Object.isExtensible(e)) e.route = routeOf(seeds).route;
1112
1150
  throw e;
1113
1151
  }
1152
+ const seeds = seedP ? await seedP : null;
1153
+ if (seeds?.denied) { // a permit refused a seed dispatch: the send is denied; the fleet acceptance before it is still recorded
1154
+ if (!this.trustedCarriers || acceptedByTrusted(receipt, this.trustedCarriers)) this.mailbox.markOutboundDelivered(envelope.id, envelopeSha(envelope));
1155
+ throw seeds.denied;
1156
+ }
1114
1157
  // 2.8.2 trustedCarriers: only untrusted carriers (a relayed seed) took it. That is not a delivery; the row stays pending.
1115
- if (this.trustedCarriers && !acceptedByTrusted(receipt, this.trustedCarriers)) return this._untrustedAcceptance({ envelope, persisted, via: "carrier", delivery: receipt }, w4Fields); // @t282 mark-carrier
1158
+ if (this.trustedCarriers && !acceptedByTrusted(receipt, this.trustedCarriers)) return this._untrustedAcceptance({ envelope, persisted, via: "carrier", delivery: receipt, ...routeOf(seeds) }, w4Fields); // @t282 mark-carrier
1116
1159
  this.mailbox.markOutboundDelivered(envelope.id, envelopeSha(envelope));
1117
1160
  this.metrics.inc("send.via.carrier");
1118
1161
  this.metrics.observe("send.latencyMs.via.carrier", Date.now() - t0);
1119
- return { envelope, persisted, via: "carrier", delivery: receipt, ...(this.trustedCarriers ? { confirmed: true } : {}), ...w4Fields };
1162
+ return { envelope, persisted, via: "carrier", delivery: receipt, ...(this.trustedCarriers || seedRoute ? { confirmed: true } : {}), ...routeOf(seeds), ...w4Fields };
1120
1163
  }
1121
1164
 
1122
1165
  // 3. DHT path.
@@ -1160,7 +1203,7 @@ export class Pillar {
1160
1203
  * Refused (code group-v2-use-v2-send) for a pillar-group/2 group.
1161
1204
  * Returns { group, groupId, msgId, results: [{ member, ok, via?, envelopeId?, error?, code?, fix? }] }.
1162
1205
  */
1163
- async sendGroup({ group, groupId = null, members, kind = "message", payload = {}, op = "message", resolveTimeoutMs = 5000 }) {
1206
+ async sendGroup({ group, groupId = null, members, kind = "message", payload = {}, op = "message", resolveTimeoutMs = 5000, route = null }) {
1164
1207
  let g = groupId ? this.mailbox.getGroup(groupId) : null;
1165
1208
  if (groupId && !g) throw new Error(`sendGroup: no group ${groupId} in this home`);
1166
1209
  if (!g) {
@@ -1190,9 +1233,9 @@ export class Pillar {
1190
1233
  try {
1191
1234
  const r = await this.send({
1192
1235
  recipient: member, recipientPublicKey: this.addressBook?.get(member)?.publicKey ?? g.keys?.[member],
1193
- kind, payload: wrapped, resolveTimeoutMs,
1236
+ kind, payload: wrapped, resolveTimeoutMs, ...(route != null ? { route } : {}),
1194
1237
  });
1195
- results.push({ member, ok: true, via: r.via, envelopeId: r.envelope.id });
1238
+ results.push({ member, ok: true, via: r.via, envelopeId: r.envelope.id, ...(route != null && r.confirmed === false ? { confirmed: false } : {}), ...(r.route ? { route: r.route } : {}) });
1196
1239
  } catch (e) {
1197
1240
  results.push({ member, ok: false, error: e.message, ...(typeof e.code === "string" ? { code: e.code } : {}), ...(typeof e.fix === "string" ? { fix: e.fix } : {}) });
1198
1241
  }
@@ -1213,7 +1256,7 @@ export class Pillar {
1213
1256
  * any op but accept.request from a member who is only invited.
1214
1257
  * Returns { group, groupId, msgId, results } like sendGroup.
1215
1258
  */
1216
- async sendGroupV2({ groupId, op = "message", payload = {}, kind = "message", resolveTimeoutMs = 5000, permit = null, signal = null }) {
1259
+ async sendGroupV2({ groupId, op = "message", payload = {}, kind = "message", resolveTimeoutMs = 5000, permit = null, signal = null, route = null }) {
1217
1260
  const guard = createSendGuard({ outboundPolicy: this.#outboundPolicy, permit, signal, context: { groupId, op } });
1218
1261
  if (guard) { await guard({ phase: "seal", route: "group" }); assertSendNotAborted(signal); }
1219
1262
  if (!["message", "leave.request", "accept.request", "rename.request"].includes(op)) throw new Error(`sendGroupV2: op ${op} is not sent from here`);
@@ -1232,9 +1275,12 @@ export class Pillar {
1232
1275
  const results = [];
1233
1276
  for (const member of to) {
1234
1277
  try {
1235
- const r = await this.send({ recipient: member, recipientPublicKey: this.addressBook?.get(member)?.publicKey ?? row.keys?.[member], kind, payload: wrapped, resolveTimeoutMs, permit, signal });
1278
+ const r = await this.send({ recipient: member, recipientPublicKey: this.addressBook?.get(member)?.publicKey ?? row.keys?.[member], kind, payload: wrapped, resolveTimeoutMs, permit, signal, ...(route != null ? { route } : {}) });
1236
1279
  const sent = { member, ok: true, via: r.via, envelopeId: r.envelope.id };
1237
1280
  if (this.trustedCarriers && r.confirmed === false) sent.confirmed = false; // @t282 group-unconfirmed
1281
+ // 2.8.3: a copy only a seed took is unconfirmed; nothing resends it, and a recipient-matched ack or read advances its row.
1282
+ if (route != null && r.confirmed === false) sent.confirmed = false; // @t283 seed-group-unconfirmed
1283
+ if (r.route) sent.route = r.route;
1238
1284
  results.push(sent);
1239
1285
  } catch (e) {
1240
1286
  const code = sendErrorCode(e);
@@ -1244,7 +1290,8 @@ export class Pillar {
1244
1290
  }
1245
1291
  this.metrics.inc("sendGroupV2");
1246
1292
  const stopped = results.some((r) => r.code === SEND_PERMIT_DENIED);
1247
- return { group: head.name, groupId, msgId: tag.msgId, results, ...(stopped ? { stopped: true } : {}) };
1293
+ const unconfirmed = route != null ? results.filter((r) => r.ok && r.confirmed === false).length : 0;
1294
+ return { group: head.name, groupId, msgId: tag.msgId, results, ...(stopped ? { stopped: true } : {}), ...(route != null ? { unconfirmed } : {}) };
1248
1295
  }
1249
1296
 
1250
1297
  /**
@@ -1448,6 +1495,170 @@ export class Pillar {
1448
1495
  return { ...result, confirmed: false, ...w4Fields };
1449
1496
  }
1450
1497
 
1498
+ /**
1499
+ * 2.8.3: the seeds one send may use. Resolves the final recipient's listing through the registry
1500
+ * (signature-checked, bounded by seedRoutes.timeoutMs) and keeps the configured seeds it names.
1501
+ * Never throws: an unknown route is { seeds: [], reason }, and the send stays on the fleet.
1502
+ */
1503
+ async _selectSeedRoute(recipient, publicKey, ask, { registryUrl = null, now = null, fetch: fetchOverride = undefined, urlMap = undefined, allowInsecureLoopback = false, signal = null } = {}) {
1504
+ const report = (seeds, reason) => ({ seeds, reason });
1505
+ if (!this.seedRoutes?.all.length) return report([], "no-seed-routes");
1506
+ if (!this.carrierClient) return report([], "no-fleet");
1507
+ const reg = registryUrl ?? this.registryUrl;
1508
+ if (!reg) return report([], "no-registry");
1509
+ const timeout = AbortSignal.timeout(this.seedRoutes.timeoutMs);
1510
+ let res;
1511
+ try {
1512
+ res = await resolveListing(recipient, { registryUrl: reg, now: now ?? nowIsoSeconds(), fetch: fetchOverride ?? globalThis.fetch, urlMap, allowInsecureLoopback, signal: signal ? AbortSignal.any([signal, timeout]) : timeout });
1513
+ } catch (_e) {
1514
+ res = { ok: false, reason: "resolve-failed" };
1515
+ }
1516
+ assertSendNotAborted(signal);
1517
+ // 2.8.3 setSeedRoutes: the routes may have changed while the listing was read. Use the set as it is now.
1518
+ const cfg = this.seedRoutes;
1519
+ if (!cfg?.all.length) return report([], "no-seed-routes"); // @t283 seed-select-reread
1520
+ const picked = listedSeeds(res, { recipient, publicKey, seeds: cfg.all, only: ask.only });
1521
+ return { ...report(picked.seeds, picked.reason), timeoutMs: cfg.timeoutMs };
1522
+ }
1523
+
1524
+ /** 2.8.3: post one envelope to the selected seeds only. Never rejects: { result, accepted, denied?, error? }. */
1525
+ async _deliverSeeds(envelope, seeds, { permit = null, signal = null, timeoutMs } = {}) {
1526
+ // trustedCarriers [] = no seed is trusted: reads use inbox auth v2, and no acceptance counts.
1527
+ const client = new CarrierClient({ keychain: this.keychain, carriers: [...seeds], trustedCarriers: [], fetch: this._liveSeedFetch() });
1528
+ try {
1529
+ const result = await client.deliver(envelope, { timeoutMs, permit, signal });
1530
+ return { result, accepted: result.all.filter((r) => r.ok).map((r) => r.carrier) };
1531
+ } catch (e) {
1532
+ if (isSendPermitDenied(e)) return { denied: e, result: e.partial ?? null, accepted: (e.partial?.accepted ?? []).map((a) => a.carrier) };
1533
+ return { error: e, result: { all: Array.isArray(e?.refusals) ? e.refusals : [] }, accepted: [] };
1534
+ }
1535
+ }
1536
+
1537
+ /**
1538
+ * 2.8.3: poll the configured seeds, apart from the fleet poller (startCarrierPolling). Sparse: each round
1539
+ * sleeps a jittered [0.5, 1.5) x intervalMs, then takes one wait=0 page from each seed in turn, under the
1540
+ * process-wide and per-origin seed limits. Each seed keeps its own cursor. A slow or empty seed costs at
1541
+ * most seedRoutes.timeoutMs and never touches the fleet poller or a send. Returns { stop, done }.
1542
+ */
1543
+ startSeedPolling({ intervalMs = null, random = Math.random, sleep = sleepTimer, onError = null } = {}) {
1544
+ if (!this.seedRoutes?.all.length) throw new Error("no seed routes configured");
1545
+ if (this._seedPoller) return this._seedPoller;
1546
+ const every = intervalMs ?? this.seedRoutes.pollIntervalMs;
1547
+ if (!(Number.isFinite(every) && every >= SEED_MIN_POLL_INTERVAL_MS)) throw new TypeError(`startSeedPolling: intervalMs must be at least ${SEED_MIN_POLL_INTERVAL_MS} ms`);
1548
+ const controller = new AbortController();
1549
+ const { signal } = controller;
1550
+ const done = (async () => {
1551
+ while (!signal.aborted) {
1552
+ try { await sleep(Math.floor(every * (0.5 + random())), undefined, { signal }); } // @t283 seed-poll-sparse
1553
+ catch (_e) { break; }
1554
+ // Each round reads the routes as they are now (setSeedRoutes); null or empty polls nothing.
1555
+ for (const base of [...(this.seedRoutes?.all ?? [])]) {
1556
+ if (signal.aborted) break;
1557
+ if (!this._seedLive(base)) continue; // removed earlier in this round
1558
+ await this._pollSeedOnce(this._seedPollClient(), base, { signal, onError });
1559
+ }
1560
+ }
1561
+ })().catch(() => {});
1562
+ const handle = { stop: () => { controller.abort(); return done; }, done };
1563
+ // A loop that ends without stop() must not leave a dead handle that startSeedPolling would return again.
1564
+ done.then(() => { if (this._seedPoller === handle) this._seedPoller = null; }); // @t283 seed-poller-clear
1565
+ this._seedPoller = handle;
1566
+ return handle;
1567
+ }
1568
+
1569
+ /**
1570
+ * 2.8.3: replace the seed routes while the process runs (an app's route cache expired or refreshed). `value` is
1571
+ * checked like the constructor's `seedRoutes` (fleet = this.carriers), and a bad value throws and changes nothing.
1572
+ * The next send and the next poll round use the new set; a seed that is no longer in it gets no new request, also
1573
+ * none waiting on a permit. One already queued may still go within timeoutMs (it passed the check and waits in the
1574
+ * seed concurrency limits). Seeds that stay keep their cursors; the cursors of removed seeds are
1575
+ * dropped. null (or a set with no seeds) stops seed traffic: polling keeps running and polls nothing. Returns the
1576
+ * new normalized routes (null when off).
1577
+ */
1578
+ setSeedRoutes(value) {
1579
+ const next = normalizeSeedRoutes(value, { fleet: this.carriers });
1580
+ const prev = this.seedRoutes?.all ?? [];
1581
+ this.seedRoutes = next;
1582
+ this._seedFetch = next ? makeSeedFetch({ allowPrivateUrls: next.allowPrivateUrls, lookup: next.lookup, fetch: next.fetch }) : null; // @t283 seed-fetch-rebuild
1583
+ const keep = new Set(next?.all ?? []);
1584
+ const fleet = new Set(this.carriers.map(routeKey));
1585
+ for (const old of prev) {
1586
+ if (keep.has(old) || fleet.has(old)) continue;
1587
+ try { this.mailbox.deleteCarrierCursor?.(old); } catch (_e) { this.metrics.inc("seed.cursor.drop-failed"); } // @t283 seed-cursor-drop
1588
+ }
1589
+ return next;
1590
+ }
1591
+
1592
+ /**
1593
+ * 2.8.3: true while `url` (a seed base, or a request URL `<base>/v1/...`) is in the current seed routes. Exact,
1594
+ * not a prefix: a direct seed https://r.example and a relayed seed https://r.example/e/<id> are different seeds.
1595
+ */
1596
+ _seedLive(url) {
1597
+ const u = String(url);
1598
+ return (this.seedRoutes?.all ?? []).some((s) => u === s || u.startsWith(`${s}/v1/`));
1599
+ }
1600
+
1601
+ /** 2.8.3: the seed fetch, refusing any request to a seed that is no longer configured (setSeedRoutes). */
1602
+ _liveSeedFetch() {
1603
+ return (input, init) => (this._seedLive(String(input)) ? this._seedFetch(input, init) : Promise.reject(Object.assign(new Error("seed route removed"), { code: "seed-route-removed" }))); // @t283 seed-live-only
1604
+ }
1605
+
1606
+ stopSeedPolling() {
1607
+ const poller = this._seedPoller;
1608
+ this._seedPoller = null;
1609
+ return poller ? poller.stop() : Promise.resolve();
1610
+ }
1611
+
1612
+ /**
1613
+ * 2.8.3: one seed round now (one wait=0 page per seed). Returns how many NEW inbox rows the round stored
1614
+ * (quarantined rows included; duplicates and refused items are not counted). It is not a count of new mail
1615
+ * a user should see. Never throws.
1616
+ */
1617
+ async pollSeedsOnce({ signal = null, onError = null } = {}) {
1618
+ let n = 0;
1619
+ for (const base of [...(this.seedRoutes?.all ?? [])]) {
1620
+ if (signal?.aborted) break;
1621
+ if (!this._seedLive(base)) continue;
1622
+ n += await this._pollSeedOnce(this._seedPollClient(), base, { signal, onError });
1623
+ }
1624
+ return n;
1625
+ }
1626
+
1627
+ _seedPollClient() {
1628
+ return new CarrierClient({ keychain: this.keychain, carriers: [...this.seedRoutes.all], trustedCarriers: [], fetch: this._liveSeedFetch() });
1629
+ }
1630
+
1631
+ async _pollSeedOnce(client, base, { signal = null, onError = null } = {}) {
1632
+ let cursor = this.mailbox.getCarrierCursors?.()?.[base] ?? 0;
1633
+ let stored = 0;
1634
+ // An app's onError that throws must not end the poller (RedTeam 77840f P3).
1635
+ const tell = (e) => { try { onError?.(e, { seed: base }); } catch (_x) { this.metrics.inc("seed.poll.onerror-threw"); } }; // @t283 seed-onerror-guard
1636
+ try {
1637
+ const timeoutMs = this.seedRoutes?.timeoutMs;
1638
+ if (!timeoutMs) return 0;
1639
+ const r = await client.fetchInbox(base, { since: cursor, waitS: 0, timeoutMs, signal }); // @t283 seed-poll-wait0
1640
+ const page = Array.isArray(r?.envelopes) ? r.envelopes.slice(0, CARRIER_INBOX_PAGE) : []; // @t283 seed-poll-page
1641
+ for (const item of page) {
1642
+ if (signal?.aborted) break;
1643
+ if (!this._seedLive(base)) break; // removed while its page was in flight: no cursor write, no more items // @t283 seed-cursor-stop
1644
+ if (!Number.isSafeInteger(item?.seq) || item.seq <= cursor || !item.envelope || typeof item.envelope !== "object") continue;
1645
+ const env = item.envelope;
1646
+ const held = () => typeof env.id === "string" && typeof env.sender === "string" && Boolean(this.mailbox.getInbound(env.id, env.sender));
1647
+ const before = held();
1648
+ try { await this._receive(JSON.stringify(env), null); if (!before && held()) stored++; } // @t283 seed-count-stored
1649
+ catch (e) { tell(e); }
1650
+ cursor = item.seq;
1651
+ this.mailbox.setCarrierCursor?.(base, cursor);
1652
+ this.metrics.inc(`seed.poll.${base}`);
1653
+ }
1654
+ } catch (e) {
1655
+ if (signal?.aborted) return stored;
1656
+ this.metrics.inc(`seed.poll.error.${base}`);
1657
+ tell(e);
1658
+ }
1659
+ return stored;
1660
+ }
1661
+
1451
1662
  async _deliverToPeer(envelope, peerIdStr, multiaddrStr, { guard = null, signal = null } = {}) {
1452
1663
  const bytes = envelopeBodyBytes(envelope);
1453
1664
  if (bytes > MAX_INLINE_BODY_BYTES) {
@@ -1706,9 +1917,13 @@ export class Pillar {
1706
1917
  if (owned.has(q.id)) continue; // @t282 claim-owner
1707
1918
  owned.add(q.id);
1708
1919
  try {
1920
+ // 2.8.3 (RedTeam 6079d0 P3): `q` is this pass's snapshot. Another pass may have sent, dropped or retried the item
1921
+ // while this one awaited an earlier item, so read the row again now that this pass owns it.
1922
+ const fresh = this.mailbox.queuedGroupV2Sends(q.group_id).find((x) => x.id === q.id);
1923
+ if (!fresh) continue; // no longer queued // @t282 fresh-row
1709
1924
  // 2.8.2 r2 (RedTeam 822828 P2): one recoverable attempt per queue item. Its envelope id is saved on the
1710
1925
  // item before the first send, and later passes dispatch that stored envelope again (send() RESEND).
1711
- let attemptId = q.envelope_id ?? null;
1926
+ let attemptId = fresh.envelope_id ?? null; // 2.8.3: the fresh row's attempt, not the snapshot's
1712
1927
  const attemptRow = () => (attemptId ? this.mailbox.getOutbound(attemptId) : null);
1713
1928
  const done = (state, extra = {}) => {
1714
1929
  // 2.8.2 r4 (RedTeam 87e556 P2): write only while the item is still queued under this pass's attempt. A stale
@@ -1794,7 +2009,10 @@ export class Pillar {
1794
2009
  // 2.8.2 trustedCarriers: no trusted carrier accepted it, so the queued send stays queued and is sent again. Read the
1795
2010
  // row first: the recipient's ack may have landed during the send.
1796
2011
  if (this.trustedCarriers && r.confirmed === false && attemptSettled(attemptRow())) { done("sent", { envelopeId: attemptId }); continue; } // @t282 untrusted-reconcile
1797
- if (this.trustedCarriers && r.confirmed === false) { const reason = "no trusted carrier accepted"; if (this.mailbox.markGroupV2Send(q.id, "queued", { reason, attempt: attemptId })) out.push({ id: q.id, groupId: q.group_id, to: q.recipient, op: q.op, state: "queued", reason }); continue; } // @t282 sync-untrusted
2012
+ // 2.8.3 (RedTeam 6079d0 P3): this queue write names its attempt too (the owner check), as done() does.
2013
+ const untrusted = { reason: "no trusted carrier accepted" };
2014
+ untrusted.attempt = attemptId; // @t282 owner-write
2015
+ if (this.trustedCarriers && r.confirmed === false) { if (this.mailbox.markGroupV2Send(q.id, "queued", untrusted)) out.push({ id: q.id, groupId: q.group_id, to: q.recipient, op: q.op, state: "queued", reason: untrusted.reason }); continue; } // @t282 sync-untrusted
1798
2016
  done("sent", { envelopeId: r.envelope.id }); // @rule Q-sync-marks-sent
1799
2017
  } catch (e) {
1800
2018
  // Only a real denial drops the queue; any other failure, whatever code it names, stays queued for retry.
@@ -52,7 +52,7 @@ export const TTFA_METHODS = Object.freeze(["ci-canary", "field-cohort"]);
52
52
  export const TTFA_MIN_N = 10;
53
53
 
54
54
  /** Tool stamped on B8 verdicts (same string the `pillar verify` CLI uses). */
55
- export const STATS_VERDICT_TOOL = "pillar/2.8.2";
55
+ export const STATS_VERDICT_TOOL = "pillar/2.8.3";
56
56
 
57
57
  /** Closed key set of `pillar-ttfa-report/1`. */
58
58
  export const TTFA_REPORT_KEYS = Object.freeze([
@@ -283,6 +283,7 @@ export class JsonDirMailboxReader {
283
283
 
284
284
  eraseRows() { return this._readOnly("eraseRows"); }
285
285
  setCarrierCursor() { return this._readOnly("setCarrierCursor"); }
286
+ deleteCarrierCursor() { return this._readOnly("deleteCarrierCursor"); }
286
287
  appendOutbound() { return this._readOnly("appendOutbound"); }
287
288
  appendInbound() { return this._readOnly("appendInbound"); }
288
289
  markOutboundDelivered() { return this._readOnly("markOutboundDelivered"); }
@@ -423,6 +423,15 @@ export class JsonlMailboxStore {
423
423
  this._writeJsonObj("cursors", this.cursorsPath, cursors);
424
424
  }
425
425
 
426
+ /** 2.8.3: forget one carrier's cursor (Pillar#setSeedRoutes drops a removed seed's). True when one went. */
427
+ deleteCarrierCursor(carrier) {
428
+ const cursors = this.getCarrierCursors();
429
+ if (!Object.hasOwn(cursors, carrier)) return false;
430
+ delete cursors[carrier];
431
+ this._writeJsonObj("cursors", this.cursorsPath, cursors);
432
+ return true;
433
+ }
434
+
426
435
  // ── Outbox & Inbox ─────────────────────────────────────────────────────────
427
436
 
428
437
  appendOutbound(envelope, { thread = null, groupId = null, groupMsgId = null } = {}) {
@@ -1271,6 +1280,7 @@ export class JsonlMailboxStore {
1271
1280
  */
1272
1281
  export const LOCKED_METHODS = Object.freeze([
1273
1282
  "setCarrierCursor",
1283
+ "deleteCarrierCursor",
1274
1284
  "appendOutbound",
1275
1285
  "appendInbound",
1276
1286
  "markOutboundDelivered",
@@ -31,7 +31,7 @@ import {
31
31
  verifyStatsArtifact,
32
32
  } from "../registry/stats.mjs";
33
33
 
34
- export const VERIFY_CLI_TOOL = "pillar/2.8.2";
34
+ export const VERIFY_CLI_TOOL = "pillar/2.8.3";
35
35
  const TYPE_SET = new Set([...VERIFY_TYPES, TTFA_VERDICT_TYPE, REGISTRY_STATS_VERDICT_TYPE]);
36
36
 
37
37
  const VALUE_FLAGS = new Set([