@uuaid/pillar 2.8.0 → 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.
package/src/groups-v2.mjs CHANGED
@@ -50,6 +50,18 @@ export const BUFFER_LIMITS = Object.freeze({ invites: 64, invitesPerSender: 4, b
50
50
  export const ACTIONS = Object.freeze(["create", "invite", "accept", "leave", "remove", "rename", "ext_update", "admin_transfer"]);
51
51
  export const V2_OPS = Object.freeze([
52
52
  "message", "manifest", "accept.request", "leave.request", "rename.request", "manifest.request", "equivocation",
53
+ // Family A (co-admins in groups the owner's Mac creates; WIRE-family-A-v1 §3): a co-admin asks the
54
+ // creator to invite; the creator refuses a request it will not sign. Only new apps send them.
55
+ "invite.request", "request.refused",
56
+ ]);
57
+ // Family A `ext.admins` (WIRE-family-A-v1 §2). The creator alone signs it; co-admins stay role "member".
58
+ export const ADMINS_V = "pillar-group-admins/1";
59
+ export const CO_ADMIN_POWERS = Object.freeze(["invite", "rename"]);
60
+ export const MAX_CO_ADMINS = 8;
61
+ /** `request.refused` reasons, a closed list (§3). */
62
+ export const REFUSE_REASONS = Object.freeze([
63
+ "not-co-admin", "no-power", "owner-declined", "reinvite-creator-only", "target-not-invitable",
64
+ "bad-request", "group-full", "limit", "expired", "superseded",
53
65
  ]);
54
66
 
55
67
  const ID_RE = /^grp-[0-9a-f]{32}$/;
@@ -108,6 +120,43 @@ export function signingPreimage(m) { return canonicalJson(without(m, "sig")); }
108
120
  /** Manifest hash: the full signed manifest. `prev` and `mv.hash` use it. */
109
121
  export function manifestHash(m) { return sha256Hex(canonicalJson(m)); }
110
122
 
123
+ /** A bounded plain JSON record, detached from caller mutation; internal consumer helper. */
124
+ export function boundedJsonRecord(value, maxBytes = 32768) {
125
+ let budget = maxBytes;
126
+ const seen = new Set();
127
+ const visit = (v, depth) => {
128
+ if (depth > 32 || --budget < 0) throw new Error("JSON record exceeds bounds");
129
+ if (v === null || typeof v === "boolean") return v;
130
+ if (typeof v === "string") {
131
+ budget -= Buffer.byteLength(v);
132
+ if (budget < 0) throw new Error("JSON record exceeds bounds");
133
+ return v;
134
+ }
135
+ if (typeof v === "number" && Number.isFinite(v)) return v;
136
+ if (typeof v !== "object" || (!Array.isArray(v) && (!plain(v) || ![Object.prototype, null].includes(Object.getPrototypeOf(v)))) || seen.has(v)) throw new Error("expected plain JSON record");
137
+ if (Array.isArray(v) && v.length > maxBytes) throw new Error("JSON record exceeds bounds");
138
+ if (Object.getOwnPropertySymbols(v).length) throw new Error("expected plain JSON record");
139
+ if (Array.isArray(v) && (Object.keys(v).length !== v.length || !Array.from({ length: v.length }, (_, i) => Object.hasOwn(v, i)).every(Boolean))) throw new Error("expected dense JSON array");
140
+ seen.add(v);
141
+ const out = Array.isArray(v) ? [] : {};
142
+ for (const key of Object.keys(v)) {
143
+ if (["__proto__", "prototype", "constructor"].includes(key)) throw new Error("reserved JSON key");
144
+ const d = Object.getOwnPropertyDescriptor(v, key);
145
+ if (!d || !Object.hasOwn(d, "value")) throw new Error("JSON accessors are not supported");
146
+ budget -= Buffer.byteLength(key);
147
+ if (budget < 0) throw new Error("JSON record exceeds bounds");
148
+ out[key] = visit(d.value, depth + 1);
149
+ }
150
+ if (Array.isArray(v) && (out.length !== v.length || Object.keys(v).length !== v.length)) throw new Error("expected dense JSON array");
151
+ seen.delete(v);
152
+ return out;
153
+ };
154
+ if (!plain(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) throw new Error("expected plain JSON record");
155
+ const out = visit(value, 0);
156
+ if (Buffer.byteLength(canonicalJson(out)) > maxBytes) throw new Error("JSON record exceeds bounds");
157
+ return out;
158
+ }
159
+
111
160
  // ───────────────────────────────────────────── strict Ed25519 (RFC 8032) ──
112
161
  const L = 2n ** 252n + 27742317777372353535851937790883648493n;
113
162
  const leInt = (buf) => { let n = 0n; for (let i = buf.length - 1; i >= 0; i--) n = (n << 8n) | BigInt(buf[i]); return n; };
@@ -279,8 +328,8 @@ export function verifyNext(prev, m) {
279
328
  const t = m.transition;
280
329
  const needsRequest = t.action === "accept" || t.action === "leave";
281
330
  if (!row.actions.includes(t.action)) return no("transition-mismatch"); // @rule M1-transition-label
282
- if (t.actor !== pAdmin.uuaid || t.target !== row.target) return no("transition-mismatch");
283
- if (needsRequest ? !(typeof t.request === "string" && t.request.length > 0) : t.request !== null) return no("transition-mismatch");
331
+ if (t.actor !== pAdmin.uuaid || t.target !== row.target) return no("transition-mismatch"); // @rule M1-actor-target
332
+ if (needsRequest ? !(typeof t.request === "string" && t.request.length > 0) : t.request !== null) return no("transition-mismatch"); // @rule M1-request-null
284
333
  return { ok: true, action: t.action };
285
334
  }
286
335
 
@@ -374,6 +423,114 @@ export function signManifest(m, signer) {
374
423
  return { ...body, sig: { alg: "ed25519", keyId: id.uuaid ?? uuaidForKey(id.publicKeyHex), publicKey: id.publicKeyHex, signature } };
375
424
  }
376
425
 
426
+ // ───────────────────────────────────────────── Family A: ext.admins (WIRE-family-A-v1 §2, §4) ──
427
+ // Co-admins live only in the profile key `ext.admins`; the chain never names them as admins and the
428
+ // verifier never reads the key (§1: a co-admin's change is a creator-signed manifest, request null).
429
+ // Receivers read a malformed list as empty. The creator's builder refuses to sign one (§4).
430
+
431
+ const ADMINS_KEYS = ["v", "coAdmins"];
432
+ const CO_ADMIN_KEYS = ["uuaid", "powers"];
433
+ const strictlySorted = (xs) => xs.every((x, i) => i === 0 || xs[i - 1] < x);
434
+
435
+ /**
436
+ * The first §2 fault of `m.ext.admins`, or null. A manifest without the key has none (an empty list).
437
+ * Checked on every manifest: shape, then that each entry names a row of `m` that is not its admin.
438
+ * An entry whose row is not `active` is NOT a fault here: it is inert (coAdminsOf skips it), so a
439
+ * co-admin can still leave or be removed, one change per version (§2).
440
+ */
441
+ export function adminsFault(m) {
442
+ if (!plain(m?.ext) || !Object.hasOwn(m.ext, "admins")) return null;
443
+ const a = m.ext.admins;
444
+ if (!closed(a, ADMINS_KEYS, ADMINS_KEYS)) return "admins-keys"; // @rule FA-closed-top
445
+ if (a.v !== ADMINS_V) return "admins-version"; // @rule FA-version
446
+ if (!Array.isArray(a.coAdmins)) return "admins-list"; // @rule FA-list
447
+ if (a.coAdmins.length > MAX_CO_ADMINS) return "admins-too-many"; // @rule FA-max-entries
448
+ for (const e of a.coAdmins) {
449
+ if (!closed(e, CO_ADMIN_KEYS, CO_ADMIN_KEYS)) return "admins-entry-keys"; // @rule FA-closed-entry
450
+ if (typeof e.uuaid !== "string" || !UUAID_RE.test(e.uuaid)) return "admins-uuaid"; // @rule FA-entry-uuaid
451
+ if (!Array.isArray(e.powers) || e.powers.length === 0) return "admins-no-powers"; // @rule FA-powers-non-empty
452
+ if (!e.powers.every((p) => CO_ADMIN_POWERS.includes(p))) return "admins-power"; // @rule FA-powers-closed
453
+ if (!strictlySorted(e.powers)) return "admins-powers-order"; // @rule FA-powers-sorted
454
+ }
455
+ if (!strictlySorted(a.coAdmins.map((e) => e.uuaid))) return "admins-order"; // @rule FA-entries-sorted
456
+ const admin = adminOf(m)?.uuaid;
457
+ for (const e of a.coAdmins) {
458
+ if (!m.members.some((r) => r.uuaid === e.uuaid)) return "admins-non-member"; // @rule FA-entry-is-member
459
+ if (e.uuaid === admin) return "admins-admin-listed"; // @rule FA-entry-not-admin
460
+ }
461
+ return null;
462
+ }
463
+
464
+ /** uuaid -> its powers, for each co-admin of `m` whose row is `active`. Empty for a malformed list (§2). */
465
+ export function coAdminsOf(m) {
466
+ const out = new Map();
467
+ if (adminsFault(m)) return out; // @rule FA-malformed-is-empty
468
+ for (const e of m.ext.admins?.coAdmins ?? []) {
469
+ if (m.members.find((r) => r.uuaid === e.uuaid)?.status !== "active") continue; // @rule FA-inert-entry
470
+ out.set(e.uuaid, [...e.powers]);
471
+ }
472
+ return out;
473
+ }
474
+
475
+ /** Actions the builder still signs over an inherited malformed list it leaves byte-identical (§4, Lead ruling OPEN-3). */
476
+ const SIGN_OVER_INHERITED_DAMAGE = Object.freeze(["remove", "leave"]);
477
+
478
+ /**
479
+ * §4 builder refusal: the fault that forbids signing `next` (version 1 when `prev` is null), or null.
480
+ * - Inherited damage (Lead ruling OPEN-3): when `prev` already carries a malformed list and `next` keeps
481
+ * `ext.admins` byte-identical, only `remove` and the fold of a `leave.request` are signed (the list
482
+ * already reads as empty everywhere; blocking `remove` would stop the owner removing a member). Every
483
+ * other action waits for the repairing `ext_update`, which changes `ext.admins` and takes the path below.
484
+ * - Every other build needs a well-formed list (adminsFault).
485
+ * - No power revival (Lead ruling OPEN-1): an `invite` or `accept` whose target is listed in the head's
486
+ * `ext.admins` is refused; the owner unmakes the entry first.
487
+ * - A build that changes `ext.admins` (the owner's make- or unmake-admin click) also needs every listed
488
+ * member `active` and every other `ext` key unchanged.
489
+ */
490
+ export function adminsSigningFault(prev, next) {
491
+ const before = plain(prev?.ext) ? prev.ext.admins : undefined;
492
+ const after = next.ext.admins;
493
+ let unchanged = canonicalJson(before ?? null) === canonicalJson(after ?? null);
494
+ // 2.8.2 r2 (RedTeam 822828 P3): a present `admins: null` and a missing key differ; removing the field repairs it.
495
+ const listed = (ext) => plain(ext) && Object.hasOwn(ext, "admins");
496
+ if (listed(prev?.ext) !== listed(next.ext)) unchanged = false; // @t282 m1-presence
497
+ const inherited = prev ? adminsFault(prev) : null;
498
+ if (inherited && unchanged) {
499
+ return SIGN_OVER_INHERITED_DAMAGE.includes(next.transition?.action) ? null : "admins-repair-first"; // @rule FA-inherited-damage
500
+ }
501
+ const fault = adminsFault(next);
502
+ if (fault) return fault;
503
+ const action = next.transition?.action;
504
+ if ((action === "invite" || action === "accept") && (before?.coAdmins ?? []).some((e) => e?.uuaid === next.transition.target)) {
505
+ return "admins-target-listed"; // @rule FA-no-power-revival
506
+ }
507
+ if (unchanged) return null;
508
+ for (const e of after?.coAdmins ?? []) {
509
+ if (next.members.find((r) => r.uuaid === e.uuaid)?.status !== "active") return "admins-not-active"; // @rule FA-set-active-only
510
+ }
511
+ const rest = (x) => canonicalJson(without(plain(x) ? x : {}, "admins"));
512
+ if (prev && rest(prev.ext) !== rest(next.ext)) return "admins-other-ext-changed"; // @rule FA-other-ext-kept
513
+ return null;
514
+ }
515
+
516
+ /** Throws, before any signature, when adminsSigningFault forbids signing `next` (§4: nothing is sent). */
517
+ function assertAdminsSignable(prev, next) {
518
+ const fault = adminsSigningFault(prev, next);
519
+ if (fault) throw Object.assign(new Error(`refusing to sign version ${next.version}: ext.admins ${fault}`), { code: "group-v2-admins-refused", fault });
520
+ }
521
+
522
+ /**
523
+ * The optional binding body of a `rename.request` (§3): `{ name, purpose }` (purpose a string or null),
524
+ * or null when absent or malformed. Null leaves the request a suggestion, as before Family A.
525
+ */
526
+ export function parseRenameField(payload) {
527
+ const r = plain(payload) ? payload.rename : undefined;
528
+ if (!closed(r, ["name", "purpose"], ["name", "purpose"])) return null;
529
+ if (typeof r.name !== "string" || r.name.trim() === "" || codePoints(r.name) > MAX_NAME) return null; // @rule FA-rename-name
530
+ if (!(r.purpose === null || (typeof r.purpose === "string" && codePoints(r.purpose) <= MAX_PURPOSE))) return null;
531
+ return { name: r.name, purpose: r.purpose };
532
+ }
533
+
377
534
  // ───────────────────────────────────────────── store (pillar-group-store/2) ──
378
535
 
379
536
  /** A store record is fine only if its chain verifies and its head matches. */
@@ -520,9 +677,12 @@ export function reconcileMailboxRosters(store, mailbox, selfUuaid) {
520
677
  * Create a group: sign version 1 with `keychain`, verify it, store it, then
521
678
  * write the mailbox row. `members`: [{ uuaid, key }], each invited.
522
679
  */
523
- export function adminCreate({ store, mailbox, keychain, name, purpose, members = [] }) {
680
+ export function adminCreate({ store, mailbox, keychain, name, purpose, members = [], ext = {} }) {
681
+ ext = boundedJsonRecord(ext, MAX_MANIFEST_BYTES);
524
682
  const me = keychain._identity;
525
- const g = signManifest(buildGenesis({ name, purpose, creator: { uuaid: me.uuaid, publicKeyHex: me.publicKeyHex }, members }), keychain);
683
+ const built = buildGenesis({ name, purpose, creator: { uuaid: me.uuaid, publicKeyHex: me.publicKeyHex }, members, ext });
684
+ assertAdminsSignable(null, built); // @rule FA-builder-refuses-genesis
685
+ const g = signManifest(built, keychain);
526
686
  const v = verifyGenesis(g);
527
687
  if (!v.ok) throw new Error(`refusing to store a genesis that does not verify: ${v.reason}`);
528
688
  const rec = newRecord([g]);
@@ -540,7 +700,9 @@ export function adminChange({ store, mailbox, keychain, groupId, action, opts =
540
700
  const rec = loadGroupForCommand(store, groupId);
541
701
  if (rec.frozen) throw new Error(`${groupId} is frozen (equivocation); a frozen group can only be replaced by a new group`);
542
702
  const head = rec.chain[rec.chain.length - 1];
543
- const next = signManifest(buildNext(head, action, opts), keychain);
703
+ const built = buildNext(head, action, opts);
704
+ assertAdminsSignable(head, built); // @rule FA-builder-refuses
705
+ const next = signManifest(built, keychain);
544
706
  const v = verifyNext(head, next);
545
707
  if (!v.ok) throw new Error(`refusing to store version ${next.version}: ${v.reason}`);
546
708
  rec.chain.push(next);
@@ -696,6 +858,23 @@ function badTag(g) {
696
858
  return null;
697
859
  }
698
860
 
861
+ /**
862
+ * Family A bodies (§3), beside `text` and `_group` in the payload: the first malformed one, or null.
863
+ * Reported as `detail` with bad-group-message. `rename` on rename.request is optional and never
864
+ * drops a message: parseRenameField reads it, and a malformed one leaves a suggestion.
865
+ */
866
+ function badBody(p, op) {
867
+ if (op === "invite.request") {
868
+ const i = p.invite;
869
+ if (!closed(i, ["uuaid", "key"], ["uuaid", "key"]) || typeof i.uuaid !== "string" || !UUAID_RE.test(i.uuaid) || typeof i.key !== "string" || !HEX64.test(i.key)) return "invite";
870
+ }
871
+ if (op === "request.refused") {
872
+ const r = p.refused;
873
+ if (!closed(r, ["msgId", "reason"], ["msgId", "reason"]) || typeof r.msgId !== "string" || !MSGID_RE.test(r.msgId) || !REFUSE_REASONS.includes(r.reason)) return "refused";
874
+ }
875
+ return null;
876
+ }
877
+
699
878
  const res = (verdict, reason = null, extra = {}) => ({ verdict, reason, ...extra });
700
879
  const drop = (reason, extra) => res("dropped", reason, extra);
701
880
 
@@ -804,6 +983,8 @@ export class GroupReceiver {
804
983
  }
805
984
  const bad = badTag(g);
806
985
  if (bad) return drop("bad-group-message", { detail: bad }); // @rule R4-tag-shape
986
+ const badB = badBody(p, g.op);
987
+ if (badB) return drop("bad-group-message", { detail: badB }); // @rule FA-body-shape
807
988
  const rec = this._rec(g.id);
808
989
  if (!rec) return this._unknown(env, g, now, out);
809
990
  return this._judgeKnown(env, g, now, out);
@@ -871,6 +1052,10 @@ export class GroupReceiver {
871
1052
  // 7. Rule 3 under the receiver's own manifest: mv never widens authority.
872
1053
  const r3 = this._rule3(env, g, rec);
873
1054
  if (r3) return drop(r3);
1055
+ // Family A (§3): an invite.request goes to the creator only; a requester takes a refusal only from
1056
+ // the admin of its own current head. Whether the sender may ask is the creator app's call (§4).
1057
+ const fa = this._familyA(env, g, rec);
1058
+ if (fa) return drop(fa);
874
1059
  const k = this._seenKey(env.from, g.msgId);
875
1060
  if (rec.seen.has(k)) return drop("duplicate-msgid"); // @rule R3-msgid-dedupe
876
1061
  this._markSeen(rec, k);
@@ -881,6 +1066,14 @@ export class GroupReceiver {
881
1066
  return res("accepted");
882
1067
  }
883
1068
 
1069
+ /** Family A routing (§3). Null when the message may be accepted. */
1070
+ _familyA(env, g, rec) {
1071
+ const admin = adminOf(this._head(rec)).uuaid;
1072
+ if (g.op === "invite.request" && admin !== this.self.uuaid) return "request-not-for-admin"; // @rule FA-request-to-admin
1073
+ if (g.op === "request.refused" && env.from !== admin) return "refused-not-from-admin"; // @rule FA-refused-from-admin
1074
+ return null;
1075
+ }
1076
+
884
1077
  _effects(env, g, rec, out) {
885
1078
  const head = this._head(rec);
886
1079
  if (g.op === "leave.request" && !rec.leaving.includes(env.from)) {
@@ -494,6 +494,15 @@ export class Mailbox {
494
494
  .run(new Date().toISOString(), ackSha256 ?? null, envelopeId);
495
495
  }
496
496
 
497
+ /**
498
+ * 2.8.2 r2: status 'superseded' for a live pending row that no SDK path will send again (a group v2 queue
499
+ * item moved to a new envelope, or ended). A carrier that holds a copy may still deliver it. Other rows: no-op.
500
+ */
501
+ markOutboundSuperseded(envelopeId) {
502
+ if (this._jsonDir) return this._jsonDir.markOutboundSuperseded(envelopeId);
503
+ this.db.prepare(`update outbox set status = 'superseded' where envelope_id = ? and status = 'pending' and ${LIVE_ENVELOPE_SQL}`).run(envelopeId);
504
+ }
505
+
497
506
  outboxTip() { return this._jsonDir ? this._jsonDir.outboxTip() : (this._getHead("outbox") ?? "0".repeat(64)); }
498
507
  inboxTip() { return this._jsonDir ? this._jsonDir.inboxTip() : (this._getHead("inbox") ?? "0".repeat(64)); }
499
508
 
@@ -733,11 +742,27 @@ export class Mailbox {
733
742
  : this.db.prepare("select * from group_v2_sendq where state = 'queued' order by queued_at, rowid").all();
734
743
  }
735
744
 
736
- /** state: sent | dropped (final), or queued with a reason (a failed attempt). */
737
- markGroupV2Send(id, state, { envelopeId = null, reason = null } = {}) {
738
- if (this._jsonDir) return this._jsonDir.markGroupV2Send(id, state, { envelopeId, reason });
739
- this.db.prepare("update group_v2_sendq set state = ?, state_at = ?, envelope_id = coalesce(?, envelope_id), reason = ? where id = ?")
740
- .run(state, new Date().toISOString(), envelopeId, reason ? String(reason).slice(0, 200) : null, id);
745
+ /**
746
+ * state: sent | dropped (final), or queued with a reason (a failed attempt). True when the row changed.
747
+ * 2.8.2 r4 (RedTeam 87e556): with `attempt` (an envelope id, or null before a first attempt), it writes only while
748
+ * the item is queued and still names that attempt: the owner check before syncGroupV2 records a result.
749
+ */
750
+ markGroupV2Send(id, state, { envelopeId = null, reason = null, attempt } = {}) {
751
+ if (this._jsonDir) return this._jsonDir.markGroupV2Send(id, state, { envelopeId, reason, attempt });
752
+ const owner = attempt === undefined ? "" : " and state = 'queued' and envelope_id is ?";
753
+ return this.db.prepare(`update group_v2_sendq set state = ?, state_at = ?, envelope_id = coalesce(?, envelope_id), reason = ? where id = ?${owner}`)
754
+ .run(state, new Date().toISOString(), envelopeId, reason ? String(reason).slice(0, 200) : null, id, ...(owner ? [attempt] : [])).changes === 1;
755
+ }
756
+
757
+ /**
758
+ * 2.8.2 r3 (RedTeam bcdc6c): claim a queued item's next attempt. It sets envelope_id to `next` only while the item
759
+ * is queued and still names `expected` (null before a first attempt). True when this caller won. A value swap, not
760
+ * a lock, so a crash leaves nothing held.
761
+ */
762
+ claimGroupV2Attempt(id, expected, next) {
763
+ if (this._jsonDir) return this._jsonDir.claimGroupV2Attempt(id, expected, next);
764
+ return this.db.prepare("update group_v2_sendq set envelope_id = ?, state_at = ? where id = ? and state = 'queued' and envelope_id is ?")
765
+ .run(next, new Date().toISOString(), id, expected ?? null).changes === 1;
741
766
  }
742
767
 
743
768
  /**
@@ -8,7 +8,19 @@
8
8
  import { envelopeBodyBytes, preflightBodyBytes } from "../blob/blob.mjs";
9
9
  import { seedTier } from "./seed-tier.mjs";
10
10
  import { carrierFix, REFUSAL_FIXES } from "./refusals.mjs";
11
+ import { isRelayedSeedUrl } from "./tunnel.mjs";
12
+ import { signInboxAuthV1, signInboxAuthV2 } from "./inbox-auth.mjs";
13
+
14
+ /**
15
+ * A 3xx answer under `redirect: "manual"` (2.8.1). Node's fetch hands back the
16
+ * 3xx itself; a browser-style runtime hands back an opaque redirect (status 0).
17
+ * Either way the client stops here and sends nothing to the target.
18
+ */
19
+ function isRedirect(res) {
20
+ return res.type === "opaqueredirect" || (res.status >= 300 && res.status < 400);
21
+ }
11
22
  import { setTimeout as sleepTimer } from "node:timers/promises";
23
+ import { createSendGuard, assertSendNotAborted, sendPermitDenied, isSendPermitDenied, SEND_PERMIT_DENIED } from "../send-permit.mjs";
12
24
 
13
25
  /**
14
26
  * Rank carriers by how proven they are, best first. Unknown carriers rank as
@@ -36,6 +48,30 @@ function keptReceipt(body) {
36
48
  return { receipt: r, receiptSig: body.receiptSig, receivedAt: new Date().toISOString() }; // @rule client.keeps-receipt
37
49
  }
38
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
+
39
75
  export class CarrierClient {
40
76
  /**
41
77
  * @param {{keychain: import('../identity/keychain.mjs').Keychain, carriers: string[]}} opts
@@ -46,11 +82,17 @@ export class CarrierClient {
46
82
  * carrierTiers optional { "<url>": "<seed tier>" } from a directory's
47
83
  * seeds[]. Drives which carrier's receipt is authoritative
48
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).
49
89
  */
50
- constructor({ keychain, carriers, tierGrant = null, carrierTiers = {} }) {
90
+ constructor({ keychain, carriers, tierGrant = null, carrierTiers = {}, trustedCarriers = null }) {
51
91
  if (!keychain?._identity) throw new Error("CarrierClient needs a loaded keychain");
52
92
  if (!carriers?.length) throw new Error("CarrierClient needs at least one carrier URL");
53
93
  this.keychain = keychain;
94
+ this.trustedCarriers = normalizeTrustedCarriers(trustedCarriers);
95
+ this._trusted = this.trustedCarriers ? new Set(this.trustedCarriers) : null;
54
96
  // Normalise tier keys the same way as carrier URLs so a trailing slash on
55
97
  // one side does not silently drop a seed to `probation`.
56
98
  this.carrierTiers = Object.fromEntries(
@@ -70,6 +112,29 @@ export class CarrierClient {
70
112
  }
71
113
 
72
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
+ }
73
138
  get publicKeyHex() { return this.keychain._identity.publicKeyHex; }
74
139
 
75
140
  /**
@@ -99,7 +164,8 @@ export class CarrierClient {
99
164
  * still be there. With no tier information every carrier ranks equally and
100
165
  * the first-in-list receipt wins, exactly as before.
101
166
  */
102
- 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" } });
103
169
  // Preflight against the carrier limits BEFORE any network call: the
104
170
  // tier inline limit first, then the 2 MiB direct hard cap — no tier
105
171
  // grant can raise the hard cap. Typed failure, not a carrier 413.
@@ -112,36 +178,54 @@ export class CarrierClient {
112
178
  throw e;
113
179
  }
114
180
  const attempt = async (base) => {
181
+ let attempted = false;
115
182
  try {
183
+ if (guard) { await guard({ phase: "dispatch", route: "carrier", carrier: base }); assertSendNotAborted(signal); } // @spaces-check send-permit-each-carrier
184
+ attempted = true;
116
185
  const res = await fetch(`${base}/v1/envelopes`, {
117
186
  method: "POST",
187
+ // 2.8.1: never follow a redirect. A 307/308 would replay the body and
188
+ // the x-pillar-* headers to whatever host the answer names.
189
+ redirect: "manual",
118
190
  headers: {
119
191
  "content-type": "application/json",
120
192
  ...(this.tierGrantB64 ? { "x-pillar-tier-grant": this.tierGrantB64 } : {}),
121
193
  },
122
194
  body: JSON.stringify(envelope),
123
- signal: AbortSignal.timeout(timeoutMs),
195
+ signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs),
124
196
  });
197
+ if (isRedirect(res)) {
198
+ await res.body?.cancel().catch(() => {});
199
+ return { carrier: base, ok: false, status: res.status, error: `${res.status} carrier-redirect-refused`, reason: "carrier-redirect-refused", fix: carrierFix("carrier-redirect-refused") };
200
+ }
125
201
  const raw = await res.text();
126
202
  let body = {};
127
203
  try { body = raw ? JSON.parse(raw) : {}; } catch (_error) {}
128
204
  if (res.status === 202 && body.accepted) {
129
205
  return { carrier: base, ok: true, seq: body.seq, sha: body.sha, duplicate: !!body.duplicate, ...keptReceipt(body) };
130
206
  }
131
- const reason = typeof body.reason === "string" && body.reason ? body.reason
207
+ let reason = typeof body.reason === "string" && body.reason ? body.reason
132
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
133
212
  return {
134
213
  carrier: base, ok: false, status: res.status,
135
214
  error: `${res.status} ${body.reason ?? body.error ?? (raw ? "non-json-response" : "empty-response")}`,
136
215
  ...(reason ? { reason, fix: (typeof body.fix === "string" && body.fix) || carrierFix(reason) } : {}),
137
216
  };
138
217
  } catch (e) {
139
- 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 } : {}) };
140
221
  }
141
222
  };
142
223
  const all = await Promise.allSettled(this.carriers.map(attempt)).then(rs =>
143
224
  rs.map(r => r.status === "fulfilled" ? r.value : { carrier: "?", ok: false, error: String(r.reason) }));
144
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
+ }
145
229
  if (!accepted.length) {
146
230
  const e = new Error(`carrier deliver failed on all carriers: ${all.map(r => `${r.carrier}: ${r.error}`).join("; ")}`);
147
231
  // `all` is in rank order, so this is the most proven carrier's answer.
@@ -162,19 +246,30 @@ export class CarrierClient {
162
246
  * Signed request; carrier verifies our key before serving.
163
247
  */
164
248
  async fetchInbox(base, { since = 0, waitS = 0, timeoutMs = 40000, signal = null } = {}) {
165
- const path = `GET /v1/inbox/${this.uuaid}?since=${since}`;
166
- const ts = String(Date.now());
167
- const sig = this.keychain.sign(Buffer.from(`${path}\n${ts}`, "utf-8")).toString("hex");
168
- const res = await fetch(`${base}/v1/inbox/${encodeURIComponent(this.uuaid)}?since=${since}&wait=${waitS}`, {
169
- headers: {
170
- "x-pillar-pubkey": this.publicKeyHex,
171
- "x-pillar-ts": ts,
172
- "x-pillar-sig": sig,
173
- },
249
+ // 2.8.1 (Lead 5e8cf6): a relayed seed URL gets inbox auth v2, bound to
250
+ // that URL and single-use, so neither the seed nor its relay can replay it
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)
254
+ ? signInboxAuthV2(this.keychain, { audience: base, uuaid: this.uuaid, since, wait: waitS })
255
+ : signInboxAuthV1(this.keychain, { uuaid: this.uuaid, since });
256
+ const res = await fetch(`${String(base).replace(/\/+$/, "")}/v1/inbox/${encodeURIComponent(this.uuaid)}?since=${since}&wait=${waitS}`, {
257
+ headers,
174
258
  // `signal` lets a caller cancel a long-poll early (peekCarrierInbox stops
175
259
  // the other carriers once one has mail).
176
260
  signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs),
261
+ // 2.8.1: never follow a redirect; the signed inbox headers would go to
262
+ // the host the answer names, and stay replayable there for 5 minutes.
263
+ redirect: "manual",
177
264
  });
265
+ if (isRedirect(res)) {
266
+ await res.body?.cancel().catch(() => {});
267
+ const e = new Error(`inbox fetch ${base}: ${res.status} carrier-redirect-refused`);
268
+ e.code = "carrier-redirect-refused";
269
+ e.fix = carrierFix(e.code);
270
+ e.status = res.status; e.carrier = base;
271
+ throw e;
272
+ }
178
273
  if (res.status !== 200) {
179
274
  const body = await res.json().catch(() => ({}));
180
275
  const e = new Error(`inbox fetch ${base}: ${res.status} ${body.error ?? ""}`);