@uuaid/pillar 2.8.1 → 2.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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,17 @@ 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).
60
89
  */
61
- constructor({ keychain, carriers, tierGrant = null, carrierTiers = {} }) {
90
+ constructor({ keychain, carriers, tierGrant = null, carrierTiers = {}, trustedCarriers = null }) {
62
91
  if (!keychain?._identity) throw new Error("CarrierClient needs a loaded keychain");
63
92
  if (!carriers?.length) throw new Error("CarrierClient needs at least one carrier URL");
64
93
  this.keychain = keychain;
94
+ this.trustedCarriers = normalizeTrustedCarriers(trustedCarriers);
95
+ this._trusted = this.trustedCarriers ? new Set(this.trustedCarriers) : null;
65
96
  // Normalise tier keys the same way as carrier URLs so a trailing slash on
66
97
  // one side does not silently drop a seed to `probation`.
67
98
  this.carrierTiers = Object.fromEntries(
@@ -81,6 +112,29 @@ export class CarrierClient {
81
112
  }
82
113
 
83
114
  get uuaid() { return this.keychain._identity.uuaid; }
115
+
116
+ /**
117
+ * 2.8.2: true when a read from `base` uses inbox auth v2. A relayed seed URL
118
+ * always does (2.8.1). With trustedCarriers set, so does every carrier not in
119
+ * that set: v1 names no carrier and stays valid for 5 minutes, so any carrier
120
+ * that receives it can replay it. A carrier that refuses v2 is not read; v1
121
+ * is never sent to it instead.
122
+ */
123
+ usesInboxAuthV2(base) {
124
+ const b = String(base).replace(/\/+$/, "");
125
+ if (isRelayedSeedUrl(b)) return true;
126
+ if (this._trusted && !this._trusted.has(b)) return true; // @t282 v1-only-trusted
127
+ return false;
128
+ }
129
+
130
+ /**
131
+ * 2.8.2: does a deliver() result count as delivered? Unset trustedCarriers:
132
+ * any acceptance (2.8.1). Set: only an acceptance by a trusted carrier.
133
+ */
134
+ countsAcceptance(result) {
135
+ if (!result) return false;
136
+ return this.trustedCarriers ? acceptedByTrusted(result, this.trustedCarriers) : true;
137
+ }
84
138
  get publicKeyHex() { return this.keychain._identity.publicKeyHex; }
85
139
 
86
140
  /**
@@ -110,7 +164,8 @@ export class CarrierClient {
110
164
  * still be there. With no tier information every carrier ranks equally and
111
165
  * the first-in-list receipt wins, exactly as before.
112
166
  */
113
- async deliver(envelope, { timeoutMs = 10000 } = {}) {
167
+ async deliver(envelope, { timeoutMs = 10000, permit = null, signal = null } = {}) {
168
+ const guard = createSendGuard({ permit, signal, context: { recipient: envelope.recipient, phase: "dispatch", route: "carrier" } });
114
169
  // Preflight against the carrier limits BEFORE any network call: the
115
170
  // tier inline limit first, then the 2 MiB direct hard cap — no tier
116
171
  // grant can raise the hard cap. Typed failure, not a carrier 413.
@@ -123,7 +178,10 @@ export class CarrierClient {
123
178
  throw e;
124
179
  }
125
180
  const attempt = async (base) => {
181
+ let attempted = false;
126
182
  try {
183
+ if (guard) { await guard({ phase: "dispatch", route: "carrier", carrier: base }); assertSendNotAborted(signal); } // @spaces-check send-permit-each-carrier
184
+ attempted = true;
127
185
  const res = await fetch(`${base}/v1/envelopes`, {
128
186
  method: "POST",
129
187
  // 2.8.1: never follow a redirect. A 307/308 would replay the body and
@@ -134,7 +192,7 @@ export class CarrierClient {
134
192
  ...(this.tierGrantB64 ? { "x-pillar-tier-grant": this.tierGrantB64 } : {}),
135
193
  },
136
194
  body: JSON.stringify(envelope),
137
- signal: AbortSignal.timeout(timeoutMs),
195
+ signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs),
138
196
  });
139
197
  if (isRedirect(res)) {
140
198
  await res.body?.cancel().catch(() => {});
@@ -146,20 +204,28 @@ export class CarrierClient {
146
204
  if (res.status === 202 && body.accepted) {
147
205
  return { carrier: base, ok: true, seq: body.seq, sha: body.sha, duplicate: !!body.duplicate, ...keptReceipt(body) };
148
206
  }
149
- const reason = typeof body.reason === "string" && body.reason ? body.reason
207
+ let reason = typeof body.reason === "string" && body.reason ? body.reason
150
208
  : typeof body.error === "string" && body.error ? body.error : null;
209
+ // The local denial code is not a carrier's to give: it would stop a group fanout and drop queued sends.
210
+ // Such a refusal stays a failed carrier attempt (carrier-bad-response), with its text kept in `error`.
211
+ if (reason === SEND_PERMIT_DENIED) reason = null; // @spaces-check carrier-reason-not-denial
151
212
  return {
152
213
  carrier: base, ok: false, status: res.status,
153
214
  error: `${res.status} ${body.reason ?? body.error ?? (raw ? "non-json-response" : "empty-response")}`,
154
215
  ...(reason ? { reason, fix: (typeof body.fix === "string" && body.fix) || carrierFix(reason) } : {}),
155
216
  };
156
217
  } catch (e) {
157
- return { carrier: base, ok: false, error: e.message };
218
+ const denied = isSendPermitDenied(e) || signal?.aborted;
219
+ return { carrier: base, ok: false, error: denied ? "outbound send permission denied" : e.message,
220
+ ...(denied ? { code: SEND_PERMIT_DENIED, attempted } : {}) };
158
221
  }
159
222
  };
160
223
  const all = await Promise.allSettled(this.carriers.map(attempt)).then(rs =>
161
224
  rs.map(r => r.status === "fulfilled" ? r.value : { carrier: "?", ok: false, error: String(r.reason) }));
162
225
  const accepted = all.filter(r => r.ok);
226
+ if (all.some((r) => r.code === SEND_PERMIT_DENIED)) {
227
+ throw sendPermitDenied({ accepted: accepted.map(({ carrier, seq, sha }) => ({ carrier, seq, sha })), all });
228
+ }
163
229
  if (!accepted.length) {
164
230
  const e = new Error(`carrier deliver failed on all carriers: ${all.map(r => `${r.carrier}: ${r.error}`).join("; ")}`);
165
231
  // `all` is in rank order, so this is the most proven carrier's answer.
@@ -182,8 +248,9 @@ export class CarrierClient {
182
248
  async fetchInbox(base, { since = 0, waitS = 0, timeoutMs = 40000, signal = null } = {}) {
183
249
  // 2.8.1 (Lead 5e8cf6): a relayed seed URL gets inbox auth v2, bound to
184
250
  // 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)
251
+ // to another carrier. A direct carrier gets v1, as in 2.8.0, unless the
252
+ // 2.8.2 trustedCarriers option is set and leaves it out (usesInboxAuthV2).
253
+ const headers = this.usesInboxAuthV2(base)
187
254
  ? signInboxAuthV2(this.keychain, { audience: base, uuaid: this.uuaid, since, wait: waitS })
188
255
  : signInboxAuthV1(this.keychain, { uuaid: this.uuaid, since });
189
256
  const res = await fetch(`${String(base).replace(/\/+$/, "")}/v1/inbox/${encodeURIComponent(this.uuaid)}?since=${since}&wait=${waitS}`, {