@uuaid/pillar 2.8.1 → 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.
@@ -20,6 +20,7 @@ function isRedirect(res) {
20
20
  return res.type === "opaqueredirect" || (res.status >= 300 && res.status < 400);
21
21
  }
22
22
  import { setTimeout as sleepTimer } from "node:timers/promises";
23
+ import { createSendGuard, assertSendNotAborted, sendPermitDenied, isSendPermitDenied, SEND_PERMIT_DENIED } from "../send-permit.mjs";
23
24
 
24
25
  /**
25
26
  * Rank carriers by how proven they are, best first. Unknown carriers rank as
@@ -47,6 +48,30 @@ function keptReceipt(body) {
47
48
  return { receipt: r, receiptSig: body.receiptSig, receivedAt: new Date().toISOString() }; // @rule client.keeps-receipt
48
49
  }
49
50
 
51
+ /**
52
+ * 2.8.2 opt-in trusted carriers: exact base URLs, trailing slashes ignored.
53
+ * null or undefined = unset, the 2.8.1 behavior. [] = set, with no carrier trusted.
54
+ * Any other value but an array of non-empty strings is a TypeError.
55
+ */
56
+ export function normalizeTrustedCarriers(value) {
57
+ if (value == null) return null;
58
+ if (!Array.isArray(value) || !value.every((u) => typeof u === "string" && u.trim())) {
59
+ throw new TypeError("trustedCarriers must be an array of carrier URLs, or null");
60
+ }
61
+ return Object.freeze([...new Set(value.map((u) => u.trim().replace(/\/+$/, "")))]);
62
+ }
63
+
64
+ /**
65
+ * 2.8.2: true when a deliver() result holds an acceptance by a carrier in
66
+ * `trusted` (a normalizeTrustedCarriers list). Pure, so a caller can apply it
67
+ * to any client's result, including a replaced client.
68
+ */
69
+ export function acceptedByTrusted(result, trusted) {
70
+ const set = new Set(trusted ?? []);
71
+ const all = Array.isArray(result?.all) ? result.all : [];
72
+ return all.some((r) => r?.ok === true && typeof r.carrier === "string" && set.has(r.carrier.replace(/\/+$/, "")));
73
+ }
74
+
50
75
  export class CarrierClient {
51
76
  /**
52
77
  * @param {{keychain: import('../identity/keychain.mjs').Keychain, carriers: string[]}} opts
@@ -57,11 +82,22 @@ export class CarrierClient {
57
82
  * carrierTiers optional { "<url>": "<seed tier>" } from a directory's
58
83
  * seeds[]. Drives which carrier's receipt is authoritative
59
84
  * and which one is polled first — see `deliver`.
85
+ * trustedCarriers 2.8.2, optional (normalizeTrustedCarriers). When set,
86
+ * only these carriers get inbox auth v1, and only their
87
+ * acceptance counts as delivered (countsAcceptance). Unset:
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.
60
92
  */
61
- constructor({ keychain, carriers, tierGrant = null, carrierTiers = {} }) {
93
+ constructor({ keychain, carriers, tierGrant = null, carrierTiers = {}, trustedCarriers = null, fetch: fetchImpl = null }) {
62
94
  if (!keychain?._identity) throw new Error("CarrierClient needs a loaded keychain");
63
95
  if (!carriers?.length) throw new Error("CarrierClient needs at least one carrier URL");
64
96
  this.keychain = keychain;
97
+ if (fetchImpl != null && typeof fetchImpl !== "function") throw new TypeError("CarrierClient fetch must be a function");
98
+ this._fetch = fetchImpl;
99
+ this.trustedCarriers = normalizeTrustedCarriers(trustedCarriers);
100
+ this._trusted = this.trustedCarriers ? new Set(this.trustedCarriers) : null;
65
101
  // Normalise tier keys the same way as carrier URLs so a trailing slash on
66
102
  // one side does not silently drop a seed to `probation`.
67
103
  this.carrierTiers = Object.fromEntries(
@@ -81,6 +117,29 @@ export class CarrierClient {
81
117
  }
82
118
 
83
119
  get uuaid() { return this.keychain._identity.uuaid; }
120
+
121
+ /**
122
+ * 2.8.2: true when a read from `base` uses inbox auth v2. A relayed seed URL
123
+ * always does (2.8.1). With trustedCarriers set, so does every carrier not in
124
+ * that set: v1 names no carrier and stays valid for 5 minutes, so any carrier
125
+ * that receives it can replay it. A carrier that refuses v2 is not read; v1
126
+ * is never sent to it instead.
127
+ */
128
+ usesInboxAuthV2(base) {
129
+ const b = String(base).replace(/\/+$/, "");
130
+ if (isRelayedSeedUrl(b)) return true;
131
+ if (this._trusted && !this._trusted.has(b)) return true; // @t282 v1-only-trusted
132
+ return false;
133
+ }
134
+
135
+ /**
136
+ * 2.8.2: does a deliver() result count as delivered? Unset trustedCarriers:
137
+ * any acceptance (2.8.1). Set: only an acceptance by a trusted carrier.
138
+ */
139
+ countsAcceptance(result) {
140
+ if (!result) return false;
141
+ return this.trustedCarriers ? acceptedByTrusted(result, this.trustedCarriers) : true;
142
+ }
84
143
  get publicKeyHex() { return this.keychain._identity.publicKeyHex; }
85
144
 
86
145
  /**
@@ -110,7 +169,8 @@ export class CarrierClient {
110
169
  * still be there. With no tier information every carrier ranks equally and
111
170
  * the first-in-list receipt wins, exactly as before.
112
171
  */
113
- async deliver(envelope, { timeoutMs = 10000 } = {}) {
172
+ async deliver(envelope, { timeoutMs = 10000, permit = null, signal = null } = {}) {
173
+ const guard = createSendGuard({ permit, signal, context: { recipient: envelope.recipient, phase: "dispatch", route: "carrier" } });
114
174
  // Preflight against the carrier limits BEFORE any network call: the
115
175
  // tier inline limit first, then the 2 MiB direct hard cap — no tier
116
176
  // grant can raise the hard cap. Typed failure, not a carrier 413.
@@ -123,8 +183,11 @@ export class CarrierClient {
123
183
  throw e;
124
184
  }
125
185
  const attempt = async (base) => {
186
+ let attempted = false;
126
187
  try {
127
- const res = await fetch(`${base}/v1/envelopes`, {
188
+ if (guard) { await guard({ phase: "dispatch", route: "carrier", carrier: base }); assertSendNotAborted(signal); } // @spaces-check send-permit-each-carrier
189
+ attempted = true;
190
+ const res = await (this._fetch ?? fetch)(`${base}/v1/envelopes`, {
128
191
  method: "POST",
129
192
  // 2.8.1: never follow a redirect. A 307/308 would replay the body and
130
193
  // the x-pillar-* headers to whatever host the answer names.
@@ -134,7 +197,7 @@ export class CarrierClient {
134
197
  ...(this.tierGrantB64 ? { "x-pillar-tier-grant": this.tierGrantB64 } : {}),
135
198
  },
136
199
  body: JSON.stringify(envelope),
137
- signal: AbortSignal.timeout(timeoutMs),
200
+ signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs),
138
201
  });
139
202
  if (isRedirect(res)) {
140
203
  await res.body?.cancel().catch(() => {});
@@ -146,20 +209,28 @@ export class CarrierClient {
146
209
  if (res.status === 202 && body.accepted) {
147
210
  return { carrier: base, ok: true, seq: body.seq, sha: body.sha, duplicate: !!body.duplicate, ...keptReceipt(body) };
148
211
  }
149
- const reason = typeof body.reason === "string" && body.reason ? body.reason
212
+ let reason = typeof body.reason === "string" && body.reason ? body.reason
150
213
  : typeof body.error === "string" && body.error ? body.error : null;
214
+ // The local denial code is not a carrier's to give: it would stop a group fanout and drop queued sends.
215
+ // Such a refusal stays a failed carrier attempt (carrier-bad-response), with its text kept in `error`.
216
+ if (reason === SEND_PERMIT_DENIED) reason = null; // @spaces-check carrier-reason-not-denial
151
217
  return {
152
218
  carrier: base, ok: false, status: res.status,
153
219
  error: `${res.status} ${body.reason ?? body.error ?? (raw ? "non-json-response" : "empty-response")}`,
154
220
  ...(reason ? { reason, fix: (typeof body.fix === "string" && body.fix) || carrierFix(reason) } : {}),
155
221
  };
156
222
  } catch (e) {
157
- return { carrier: base, ok: false, error: e.message };
223
+ const denied = isSendPermitDenied(e) || signal?.aborted;
224
+ return { carrier: base, ok: false, error: denied ? "outbound send permission denied" : e.message,
225
+ ...(denied ? { code: SEND_PERMIT_DENIED, attempted } : {}) };
158
226
  }
159
227
  };
160
228
  const all = await Promise.allSettled(this.carriers.map(attempt)).then(rs =>
161
229
  rs.map(r => r.status === "fulfilled" ? r.value : { carrier: "?", ok: false, error: String(r.reason) }));
162
230
  const accepted = all.filter(r => r.ok);
231
+ if (all.some((r) => r.code === SEND_PERMIT_DENIED)) {
232
+ throw sendPermitDenied({ accepted: accepted.map(({ carrier, seq, sha }) => ({ carrier, seq, sha })), all });
233
+ }
163
234
  if (!accepted.length) {
164
235
  const e = new Error(`carrier deliver failed on all carriers: ${all.map(r => `${r.carrier}: ${r.error}`).join("; ")}`);
165
236
  // `all` is in rank order, so this is the most proven carrier's answer.
@@ -182,11 +253,12 @@ export class CarrierClient {
182
253
  async fetchInbox(base, { since = 0, waitS = 0, timeoutMs = 40000, signal = null } = {}) {
183
254
  // 2.8.1 (Lead 5e8cf6): a relayed seed URL gets inbox auth v2, bound to
184
255
  // that URL and single-use, so neither the seed nor its relay can replay it
185
- // to another carrier. A direct carrier gets v1, as in 2.8.0.
186
- const headers = isRelayedSeedUrl(base)
256
+ // to another carrier. A direct carrier gets v1, as in 2.8.0, unless the
257
+ // 2.8.2 trustedCarriers option is set and leaves it out (usesInboxAuthV2).
258
+ const headers = this.usesInboxAuthV2(base)
187
259
  ? signInboxAuthV2(this.keychain, { audience: base, uuaid: this.uuaid, since, wait: waitS })
188
260
  : signInboxAuthV1(this.keychain, { uuaid: this.uuaid, since });
189
- 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}`, {
190
262
  headers,
191
263
  // `signal` lets a caller cancel a long-poll early (peekCarrierInbox stops
192
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" });