@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/pillar.mjs CHANGED
@@ -24,7 +24,7 @@ import {
24
24
  } from "./net/transport.mjs";
25
25
  import { seal, open, decrypt, envelopeSha, mkEnvelopeId, ENVELOPE_VERSION } from "./net/envelope.mjs";
26
26
  import { Mailbox, isErasedRow } from "./mailbox/mailbox.mjs";
27
- import { CarrierClient } from "./net/carrier-client.mjs";
27
+ import { CarrierClient, normalizeTrustedCarriers, acceptedByTrusted } from "./net/carrier-client.mjs";
28
28
  import { REFUSAL_FIXES } from "./net/refusals.mjs";
29
29
  import { Observability } from "./observability.mjs";
30
30
  import { evaluateTrust, allowSenderInTrust, DEFAULT_KNOCK_ACCEPT_SCOPE } from "./identity/trust.mjs";
@@ -33,7 +33,8 @@ import {
33
33
  extractGroupTag, buildGroupTag, absorbGroupTag, newGroupId, newGroupMsgId, normalizeMembers, isGroupId,
34
34
  } from "./groups.mjs";
35
35
  import { applyReceipt, answersOurSend, deliveryAck, isReadReceipt, planReadReceipts, readReceipt } from "./receipts.mjs";
36
- import { GroupReceiver, RosterStore, isGroupIdV2, adminOf, buildGroupTag as buildGroupTagV2, manifestHash as manifestHashOf, loadGroupForCommand } from "./groups-v2.mjs";
36
+ import { GroupReceiver, RosterStore, isGroupIdV2, adminOf, buildGroupTag as buildGroupTagV2, manifestHash as manifestHashOf, loadGroupForCommand, boundedJsonRecord } from "./groups-v2.mjs";
37
+ import { createSendGuard, assertSendNotAborted, sendPermitDenied, isSendPermitDenied, sendErrorCode, SEND_PERMIT_DENIED } from "./send-permit.mjs";
37
38
  import { randomBytes } from "node:crypto";
38
39
  import { dirname } from "node:path";
39
40
 
@@ -65,8 +66,49 @@ export class W4RefusalError extends Error {
65
66
  }
66
67
 
67
68
  const VALUE_STORE_PREFIX = "/uuaid/1.0";
69
+ // 2.8.2 r2 (RedTeam 822828 P2): the send() option that re-dispatches a stored pending outbox row (syncGroupV2). Its
70
+ // value is only a row id: send() reads that row from its own mailbox, so a caller that sees the symbol can at most
71
+ // resend this agent's own pending envelope, through every gate.
72
+ const RESEND = Symbol("pillar.resend");
73
+ // 2.8.2 r3 (RedTeam bcdc6c P2): a carrier refuses an envelope whose createdAt is over 24 h old before it dedupes
74
+ // (carrier-server.mjs MAX_ENVELOPE_AGE_MS), so a stored attempt is renewed at 23 h.
75
+ const RESEND_MAX_AGE_MS = 23 * 3600_000;
76
+ /** An attempt is settled when a carrier that counts took it (status delivered) or the recipient acked it. An erased
77
+ * row keeps both fields, so its erasure does not reopen it. */
78
+ const attemptSettled = (row) => !!row && (row.status === "delivered" || !!row.recipient_ack_at);
79
+ /**
80
+ * 2.8.2 r3 (RedTeam bcdc6c P2): why a resend of `row` must not dispatch, or null. send() returns `{ [RESEND]: why }`
81
+ * instead of one null for every case, so syncGroupV2 never seals a replacement over a completed attempt.
82
+ */
83
+ function resendBlocked(row, recipient, nowMs = Date.now()) {
84
+ if (!row) return "missing";
85
+ if (attemptSettled(row)) return "completed"; // @t282 resend-completed
86
+ if (isErasedRow(row)) return "erased";
87
+ if (row.status !== "pending") return "superseded";
88
+ const stored = JSON.parse(row.envelope_json);
89
+ if (stored.recipient !== recipient) return "rerouted";
90
+ if (attemptExpired(stored, nowMs)) return "expired"; // @t282 resend-expired
91
+ return null;
92
+ }
93
+ /** Over RESEND_MAX_AGE_MS old (or no readable createdAt): a carrier would refuse the stored envelope. */
94
+ function attemptExpired(stored, nowMs = Date.now()) {
95
+ const created = Date.parse(stored.createdAt);
96
+ return !Number.isFinite(created) || nowMs - created > RESEND_MAX_AGE_MS;
97
+ }
98
+ /** Error thrown from a dispatch gate when a resend's row stopped being live (send() returns `{ [RESEND]: why }`). */
99
+ const resendStopped = (why) => Object.assign(new Error(`resend stopped: ${why}`), { code: "resend-stopped" });
100
+ // 2.8.2 r4 (RedTeam 87e556 P2): the syncGroupV2 queue items a live pass in this process holds, per mailbox. A pass owns
101
+ // an item from its first read to its last write, across every await; another pass skips it. In memory only, so a crash
102
+ // holds nothing. Across processes the claim and the owner check on every queue write (markGroupV2Send attempt) hold.
103
+ const GROUP_V2_OWNED = new WeakMap();
104
+ const ownedGroupV2Items = (mailbox) => {
105
+ let s = GROUP_V2_OWNED.get(mailbox);
106
+ if (!s) GROUP_V2_OWNED.set(mailbox, (s = new Set()));
107
+ return s;
108
+ };
68
109
 
69
110
  export class Pillar {
111
+ #outboundPolicy;
70
112
  constructor({
71
113
  keychain,
72
114
  mailboxPath,
@@ -88,6 +130,8 @@ export class Pillar {
88
130
  reader = null, // reader key recorded on every row this process stores (src/readers.mjs)
89
131
  receipts = null, // { delivered, read }: send signed acks / read receipts (receipts.mjs); null = neither
90
132
  notifySink = null, // NotifySink (src/notify-events.mjs): eligibility events after final admission; null = none
133
+ outboundPolicy = null, // optional instance policy for send transports; requires exact true
134
+ trustedCarriers = null, // 2.8.2 opt-in: carrier URLs that alone get inbox auth v1 and count as delivered; null = 2.8.1 trust (the queue changes apply either way)
91
135
  groupsV2Home = null, // where groups-v2/ lives (pillar-group/2 store); default: the mailbox's directory
92
136
  home = null, // agent home directory (for trust.json persistence on knock accept)
93
137
  knockConfig = null, // vNext §4 knock policy: { requiredBits?, maxBytes?, introductions?, stake?, trustedIssuers?, trustedContacts?, lineageResolver?, lineages?, selfLineage?, card?, cap?, rateWindowMs?, now? }
@@ -95,6 +139,9 @@ export class Pillar {
95
139
  continuity = null, // 2.8.0 continuity: { passphrase?, now?, fetch?, urlMap?, allowInsecureLoopback? } (DESIGN-continuity)
96
140
  }) {
97
141
  if (!keychain?._identity) throw new Error("Pillar: keychain must be loaded before construction");
142
+ if (outboundPolicy != null && typeof outboundPolicy !== "function") throw sendPermitDenied();
143
+ this.#outboundPolicy = outboundPolicy;
144
+ this.trustedCarriers = normalizeTrustedCarriers(trustedCarriers);
98
145
  this.keychain = keychain;
99
146
  this.mailbox = new Mailbox(mailboxPath);
100
147
  this.home = home ?? (typeof mailboxPath === "string" ? dirname(mailboxPath) : null);
@@ -111,7 +158,7 @@ export class Pillar {
111
158
  this.dhtClientMode = dhtClientMode;
112
159
  this.dhtPeerInfoMapper = dhtPeerInfoMapper;
113
160
  this.carriers = carriers;
114
- this.carrierClient = carriers.length ? new CarrierClient({ keychain, carriers, tierGrant }) : null;
161
+ this.carrierClient = carriers.length ? new CarrierClient({ keychain, carriers, tierGrant, trustedCarriers: this.trustedCarriers }) : null;
115
162
  this._carrierPoller = null;
116
163
  this._carrierStopping = Promise.resolve();
117
164
  this.enableLibp2p = enableLibp2p;
@@ -915,11 +962,14 @@ export class Pillar {
915
962
  return { direct: true, publicKey: pubKey, carrier: res.card?.carriers?.[0] };
916
963
  }
917
964
 
918
- 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 }) {
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 }) {
919
966
  if (!this.node && !this.carrierClient) {
920
967
  this.metrics.inc("send.error.not-started");
921
968
  throw new Error("pillar not started");
922
969
  }
970
+ const guard = createSendGuard({ outboundPolicy: this.#outboundPolicy, permit, signal, context: { recipient, groupId: payload?._group?.id ?? null, op: payload?._group?.op ?? null } });
971
+ if (guard) { await guard({ phase: "seal", route: "auto" }); assertSendNotAborted(signal); }
972
+ const transportPermit = guard ? (details) => guard({ ...details, recipient, groupId: payload?._group?.id ?? null, op: payload?._group?.op ?? null }) : null;
923
973
  const t0 = Date.now();
924
974
  let w4 = { direct: true }, w4Fields = {};
925
975
  // `subject`: the identity a wrapper (sendKnock, sendBlob) was asked to reach before it chose `recipient`.
@@ -964,13 +1014,33 @@ export class Pillar {
964
1014
  pubkey = dhtAdvert.publicKeyHex;
965
1015
  } catch (_e) { /* fall through to the error below */ }
966
1016
  }
1017
+ // 2.8.2 r2 (RedTeam 822828 P1): continuity or W-4 may have moved the recipient above. This gate and every
1018
+ // dispatch gate check the final recipient, the one the envelope is sealed to. The first gate saw the caller's.
1019
+ if (guard) { await guard({ phase: "seal", route: "auto", recipient }); assertSendNotAborted(signal); } // @t282 route-final
967
1020
  if (!pubkey) {
968
1021
  this.metrics.inc("send.error.no-public-key");
969
1022
  throw new Error(`send: no public key known for ${recipient} — encryption is mandatory; register the peer (address book / fleet.json) or pass recipientPublicKey`);
970
1023
  }
971
1024
 
972
1025
  this._recheckRoute(subj, cr.fp, recipient, now); // nothing above awaited may change the route unseen
973
- const envelope = seal(this.keychain, { recipient, recipientPublicKey: pubkey, kind, payload, id: envelopeId ?? undefined });
1026
+ // A resend (syncGroupV2) dispatches the stored bytes of a live pending row, only while the route still lands on
1027
+ // their recipient and a carrier would still take them. Otherwise it returns `{ [RESEND]: why }` (resendBlocked).
1028
+ const resend = resendId ? this.mailbox.getOutbound(resendId) : null;
1029
+ if (resendId) { const why = resendBlocked(resend, recipient); if (why) return { [RESEND]: why }; }
1030
+ const stored = resend ? JSON.parse(resend.envelope_json) : null;
1031
+ // seal() refuses a key that does not derive `recipient`, so the gated recipient binds the key too.
1032
+ const envelope = stored ?? seal(this.keychain, { recipient, recipientPublicKey: pubkey, kind, payload, id: envelopeId ?? undefined });
1033
+ let dispatchGuard = guard;
1034
+ if (guard) dispatchGuard = (details = {}) => guard({ ...details, recipient: envelope.recipient }); // @t282 route-final
1035
+ // 2.8.2 r4 (RedTeam 87e556 P2): a dispatch gate awaits (a permit can await a dialog), and the row can be erased,
1036
+ // completed or superseded meanwhile. A resend rereads its row after every dispatch gate, right before the bytes leave
1037
+ // on that route, also with no permit. A stop sends nothing more and returns `{ [RESEND]: why }`, the same reasons as
1038
+ // the check above; an acceptance that came before the stop is still recorded, as for a denial.
1039
+ let resendStop = null;
1040
+ const resendLive = () => { const why = resendBlocked(this.mailbox.getOutbound(resendId), recipient); if (why) { resendStop ??= why; throw resendStopped(why); } };
1041
+ let carrierPermit = transportPermit;
1042
+ if (resendId) { const gate = dispatchGuard; dispatchGuard = async (details = {}) => { if (gate) await gate(details); resendLive(); return true; }; } // @t282 resend-fence
1043
+ if (resendId) carrierPermit = async (details) => { if (transportPermit) await transportPermit(details); resendLive(); return true; }; // @t282 resend-fence
974
1044
  const hardCap = preflightBodyBytes(envelopeBodyBytes(envelope), { maxBodyBytes: MAX_INLINE_BODY_BYTES });
975
1045
  if (!hardCap.ok) {
976
1046
  this.metrics.inc("send.error.direct-cap");
@@ -979,7 +1049,7 @@ export class Pillar {
979
1049
  // Receipt matching needs the thread and group of this row, and the sealed
980
1050
  // envelope cannot tell us later: we cannot decrypt our own outbox.
981
1051
  const groupTag = extractGroupTag(payload);
982
- const persisted = this.mailbox.appendOutbound(envelope, {
1052
+ const persisted = stored ? { envelopeId: stored.id, envelopeSha256: resend.envelope_sha256, chainHash: resend.chain_hash } : this.mailbox.appendOutbound(envelope, {
983
1053
  thread: typeof payload?.thread === "string" && payload.thread ? payload.thread : null,
984
1054
  groupId: groupTag && !groupTag.derivedId ? groupTag.id : null,
985
1055
  groupMsgId: groupTag?.msgId ?? null,
@@ -995,11 +1065,24 @@ export class Pillar {
995
1065
  // stored and handled once.
996
1066
  if (this.node && book?.peerId && book?.multiaddr) {
997
1067
  const [direct, carrier] = await Promise.allSettled([
998
- this._deliverToPeer(envelope, book.peerId, book.multiaddr),
999
- this.carrierClient ? this.carrierClient.deliver(envelope) : Promise.resolve(null),
1068
+ this._deliverToPeer(envelope, book.peerId, book.multiaddr, { guard: dispatchGuard, signal }),
1069
+ this.carrierClient ? this.carrierClient.deliver(envelope, { permit: carrierPermit, signal }) : Promise.resolve(null),
1000
1070
  ]);
1001
1071
  const sentDirect = direct.status === "fulfilled" ? direct.value : null;
1072
+ const denial = [direct, carrier].find((r) => r.status === "rejected" && isSendPermitDenied(r.reason));
1073
+ if (denial || resendStop) {
1074
+ const accepted = carrier.status === "fulfilled" && carrier.value;
1075
+ let counted = Boolean(accepted);
1076
+ if (counted && this.trustedCarriers && !acceptedByTrusted(accepted, this.trustedCarriers)) counted = false; // @t282 mark-denial
1077
+ // 2.8.2 r2 (RedTeam 822828 P2): the carrier fanout itself was denied after another carrier accepted.
1078
+ if (!counted && carrier.status === "rejected") counted = this._partialAccepted(carrier.reason); // @t282 partial-direct
1079
+ if (counted) this.mailbox.markOutboundDelivered(envelope.id, envelopeSha(envelope));
1080
+ if (resendStop) return { [RESEND]: resendStop };
1081
+ throw sendPermitDenied({ envelopeId: envelope.id, direct: sentDirect ? { attempted: true, peerId: book.peerId } : (direct.reason?.partial?.direct ?? false), carrier: accepted || (carrier.reason?.partial ?? null) });
1082
+ }
1002
1083
  if (carrier.status === "fulfilled" && carrier.value) {
1084
+ // 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
1003
1086
  this.mailbox.markOutboundDelivered(envelope.id, envelopeSha(envelope));
1004
1087
  const via = sentDirect ? "direct+carrier" : "carrier";
1005
1088
  this.metrics.inc(`send.via.${via}`);
@@ -1020,11 +1103,20 @@ export class Pillar {
1020
1103
 
1021
1104
  // 2. Carrier path: universal store-and-forward.
1022
1105
  if (this.carrierClient) {
1023
- const receipt = await this.carrierClient.deliver(envelope);
1106
+ let receipt;
1107
+ try { receipt = await this.carrierClient.deliver(envelope, { permit: carrierPermit, signal }); }
1108
+ catch (e) {
1109
+ // 2.8.2 r2 (RedTeam 822828 P2): a denial during the fanout can follow an acceptance. Record it, then return the denial.
1110
+ if (this._partialAccepted(e)) this.mailbox.markOutboundDelivered(envelope.id, envelopeSha(envelope)); // @t282 partial-carrier
1111
+ if (resendStop) return { [RESEND]: resendStop };
1112
+ throw e;
1113
+ }
1114
+ // 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
1024
1116
  this.mailbox.markOutboundDelivered(envelope.id, envelopeSha(envelope));
1025
1117
  this.metrics.inc("send.via.carrier");
1026
1118
  this.metrics.observe("send.latencyMs.via.carrier", Date.now() - t0);
1027
- return { envelope, persisted, via: "carrier", delivery: receipt, ...w4Fields };
1119
+ return { envelope, persisted, via: "carrier", delivery: receipt, ...(this.trustedCarriers ? { confirmed: true } : {}), ...w4Fields };
1028
1120
  }
1029
1121
 
1030
1122
  // 3. DHT path.
@@ -1035,11 +1127,14 @@ export class Pillar {
1035
1127
  if (!dhtAdvert) {
1036
1128
  try { dhtAdvert = await this.resolveUuaid(recipient, { timeoutMs: resolveTimeoutMs }); }
1037
1129
  catch (e) {
1130
+ assertSendNotAborted(signal);
1038
1131
  this.metrics.inc("send.error.resolve-failed");
1039
1132
  throw new Error(`send: cannot resolve ${recipient}: ${e.message}`);
1040
1133
  }
1041
1134
  }
1042
- const delivery = await this._deliverToPeer(envelope, dhtAdvert.peerId, dhtAdvert.addrs?.[0]);
1135
+ let delivery;
1136
+ try { delivery = await this._deliverToPeer(envelope, dhtAdvert.peerId, dhtAdvert.addrs?.[0], { guard: dispatchGuard, signal }); }
1137
+ catch (e) { if (resendStop) return { [RESEND]: resendStop }; throw e; }
1043
1138
  this.metrics.inc("send.via.dht");
1044
1139
  this.metrics.observe("send.latencyMs.via.dht", Date.now() - t0);
1045
1140
  // No carrier: a closed stream confirms nothing, so the row stays pending.
@@ -1118,7 +1213,9 @@ export class Pillar {
1118
1213
  * any op but accept.request from a member who is only invited.
1119
1214
  * Returns { group, groupId, msgId, results } like sendGroup.
1120
1215
  */
1121
- async sendGroupV2({ groupId, op = "message", payload = {}, kind = "message", resolveTimeoutMs = 5000 }) {
1216
+ async sendGroupV2({ groupId, op = "message", payload = {}, kind = "message", resolveTimeoutMs = 5000, permit = null, signal = null }) {
1217
+ const guard = createSendGuard({ outboundPolicy: this.#outboundPolicy, permit, signal, context: { groupId, op } });
1218
+ if (guard) { await guard({ phase: "seal", route: "group" }); assertSendNotAborted(signal); }
1122
1219
  if (!["message", "leave.request", "accept.request", "rename.request"].includes(op)) throw new Error(`sendGroupV2: op ${op} is not sent from here`);
1123
1220
  const rec = loadGroupForCommand(this.groupsV2.store, groupId); // throws for a group it does not hold, or one that no longer verifies
1124
1221
  const row = this.mailbox.getGroup(groupId);
@@ -1135,14 +1232,19 @@ export class Pillar {
1135
1232
  const results = [];
1136
1233
  for (const member of to) {
1137
1234
  try {
1138
- const r = await this.send({ recipient: member, recipientPublicKey: this.addressBook?.get(member)?.publicKey ?? row.keys?.[member], kind, payload: wrapped, resolveTimeoutMs });
1139
- results.push({ member, ok: true, via: r.via, envelopeId: r.envelope.id });
1235
+ const r = await this.send({ recipient: member, recipientPublicKey: this.addressBook?.get(member)?.publicKey ?? row.keys?.[member], kind, payload: wrapped, resolveTimeoutMs, permit, signal });
1236
+ const sent = { member, ok: true, via: r.via, envelopeId: r.envelope.id };
1237
+ if (this.trustedCarriers && r.confirmed === false) sent.confirmed = false; // @t282 group-unconfirmed
1238
+ results.push(sent);
1140
1239
  } catch (e) {
1141
- results.push({ member, ok: false, error: e.message, ...(typeof e.code === "string" ? { code: e.code } : {}), ...(typeof e.fix === "string" ? { fix: e.fix } : {}) });
1240
+ const code = sendErrorCode(e);
1241
+ results.push({ member, ok: false, error: e.message, ...(code ? { code } : {}), ...(typeof e.fix === "string" ? { fix: e.fix } : {}), ...(e.partial ? { partial: e.partial } : {}) });
1242
+ if (isSendPermitDenied(e)) break;
1142
1243
  }
1143
1244
  }
1144
1245
  this.metrics.inc("sendGroupV2");
1145
- return { group: head.name, groupId, msgId: tag.msgId, results };
1246
+ const stopped = results.some((r) => r.code === SEND_PERMIT_DENIED);
1247
+ return { group: head.name, groupId, msgId: tag.msgId, results, ...(stopped ? { stopped: true } : {}) };
1146
1248
  }
1147
1249
 
1148
1250
  /**
@@ -1330,20 +1432,54 @@ export class Pillar {
1330
1432
  throw err;
1331
1433
  }
1332
1434
 
1333
- async _deliverToPeer(envelope, peerIdStr, multiaddrStr) {
1435
+ /**
1436
+ * 2.8.2 r2 (RedTeam 822828 P2): true when a carrier fanout denial still holds a counted acceptance. Only a
1437
+ * denial this SDK raised counts (isSendPermitDenied: no carrier text can forge one); its `partial.all` is the
1438
+ * fanout result. Unset trustedCarriers: any acceptance, as the direct branch counts it. Set: a trusted one.
1439
+ */
1440
+ _partialAccepted(e) {
1441
+ if (!isSendPermitDenied(e) || !Array.isArray(e.partial?.all)) return false;
1442
+ return this.trustedCarriers ? acceptedByTrusted(e.partial, this.trustedCarriers) : e.partial.all.some((r) => r?.ok === true);
1443
+ }
1444
+
1445
+ /** 2.8.2: the send() result when only carriers outside trustedCarriers accepted; the outbox row stays pending. */
1446
+ _untrustedAcceptance(result, w4Fields) {
1447
+ this.metrics.inc("send.via.carrier-untrusted");
1448
+ return { ...result, confirmed: false, ...w4Fields };
1449
+ }
1450
+
1451
+ async _deliverToPeer(envelope, peerIdStr, multiaddrStr, { guard = null, signal = null } = {}) {
1334
1452
  const bytes = envelopeBodyBytes(envelope);
1335
1453
  if (bytes > MAX_INLINE_BODY_BYTES) {
1336
1454
  throw new BlobSizeError(`direct envelope ${bytes}B exceeds the ${MAX_INLINE_BODY_BYTES}B hard cap`, { size: bytes, max: MAX_INLINE_BODY_BYTES });
1337
1455
  }
1338
1456
  const { peerIdFromString, multiaddr } = await loadP2pRuntime();
1457
+ // Two checks keep the 2.7.0-spaces boundary count (peer-id import, multiaddr import); 2.8.1 loads both in one call.
1458
+ if (guard) { await guard({ phase: "dispatch", route: "direct" }); assertSendNotAborted(signal); }
1459
+ if (guard) { await guard({ phase: "dispatch", route: "direct" }); assertSendNotAborted(signal); }
1339
1460
  const peerId = peerIdFromString(peerIdStr);
1340
1461
  if (multiaddrStr) {
1341
1462
  try { await this.node.peerStore.patch(peerId, { multiaddrs: [multiaddr(multiaddrStr)] }); } catch (_e) {}
1463
+ if (guard) { await guard({ phase: "dispatch", route: "direct" }); assertSendNotAborted(signal); }
1342
1464
  }
1343
- const stream = await this.node.dialProtocol(peerId, PILLAR_PROTOCOL);
1465
+ let stream;
1466
+ try { stream = await this.node.dialProtocol(peerId, PILLAR_PROTOCOL); }
1467
+ catch (error) { assertSendNotAborted(signal); throw error; }
1344
1468
  const line = JSON.stringify(envelope) + "\n";
1345
- stream.send(new Uint8Array(Buffer.from(line, "utf8")));
1346
- await stream.close();
1469
+ try {
1470
+ if (guard) { await guard({ phase: "dispatch", route: "direct" }); assertSendNotAborted(signal); } // @spaces-check send-permit-after-dial
1471
+ stream.send(new Uint8Array(Buffer.from(line, "utf8")));
1472
+ } catch (error) {
1473
+ try { stream.abort?.(error); } catch {}
1474
+ throw error;
1475
+ }
1476
+ try { await stream.close(); }
1477
+ catch (error) {
1478
+ if (signal?.aborted || error?.code === SEND_PERMIT_DENIED) {
1479
+ throw sendPermitDenied({ envelopeId: envelope.id, direct: { attempted: true, peerId: peerIdStr } });
1480
+ }
1481
+ throw error;
1482
+ }
1347
1483
  // Not marked delivered here: a closed stream is not a receipt (2.5.3).
1348
1484
  return { peerId: peerIdStr };
1349
1485
  }
@@ -1373,9 +1509,12 @@ export class Pillar {
1373
1509
  * we bypass DHT lookup. Also useful when a caller already has the peer's
1374
1510
  * connection info out of band.
1375
1511
  */
1376
- async sendDirect({ recipient, recipientPublicKey, recipientPeerIdStr, recipientMultiaddr, kind = "message", payload = {} }) {
1512
+ async sendDirect({ recipient, recipientPublicKey, recipientPeerIdStr, recipientMultiaddr, kind = "message", payload = {}, permit = null, signal = null }) {
1513
+ const guard = createSendGuard({ outboundPolicy: this.#outboundPolicy, permit, signal, context: { recipient, groupId: payload?._group?.id ?? null, op: payload?._group?.op ?? null } });
1377
1514
  const subject = recipient;
1378
1515
  await this._drainNoticeBacklog();
1516
+ // 2.8.2: the seal check follows the 2.8.1 notice drain (an await), so a revoke during the drain seals nothing.
1517
+ if (guard) { await guard({ phase: "seal", route: "direct" }); assertSendNotAborted(signal); } // @t282 seal-after-drain
1379
1518
  const cr = this._applyRoute(subject, recipientPublicKey); // @rule C-route-direct
1380
1519
  // The peer id and address name the subject's host. A rewritten destination has no coordinates this
1381
1520
  // call can verify, so a redirect is refused before anything is sealed (RedTeam 1c5e7a P1).
@@ -1391,13 +1530,32 @@ export class Pillar {
1391
1530
  }
1392
1531
  this.mailbox.appendOutbound(envelope);
1393
1532
  const { peerIdFromString, multiaddr } = await loadP2pRuntime();
1533
+ // Two checks keep the 2.7.0-spaces boundary count (peer-id import, multiaddr import); 2.8.1 loads both in one call.
1534
+ if (guard) { await guard({ phase: "dispatch", route: "direct" }); assertSendNotAborted(signal); }
1535
+ if (guard) { await guard({ phase: "dispatch", route: "direct" }); assertSendNotAborted(signal); }
1394
1536
  const peerId = peerIdFromString(recipientPeerIdStr);
1395
1537
  const ma = multiaddr(recipientMultiaddr);
1396
- await this.node.peerStore.patch(peerId, { multiaddrs: [ma] });
1397
- const stream = await this.node.dialProtocol(peerId, PILLAR_PROTOCOL);
1538
+ try { await this.node.peerStore.patch(peerId, { multiaddrs: [ma] }); }
1539
+ catch (error) { assertSendNotAborted(signal); throw error; }
1540
+ if (guard) { await guard({ phase: "dispatch", route: "direct" }); assertSendNotAborted(signal); }
1541
+ let stream;
1542
+ try { stream = await this.node.dialProtocol(peerId, PILLAR_PROTOCOL); }
1543
+ catch (error) { assertSendNotAborted(signal); throw error; }
1398
1544
  const line = JSON.stringify(envelope) + "\n";
1399
- stream.send(new Uint8Array(Buffer.from(line, "utf8")));
1400
- await stream.close();
1545
+ try {
1546
+ if (guard) { await guard({ phase: "dispatch", route: "direct" }); assertSendNotAborted(signal); } // @spaces-check send-permit-after-dial
1547
+ stream.send(new Uint8Array(Buffer.from(line, "utf8")));
1548
+ } catch (error) {
1549
+ try { stream.abort?.(error); } catch {}
1550
+ throw error;
1551
+ }
1552
+ try { await stream.close(); }
1553
+ catch (error) {
1554
+ if (signal?.aborted || error?.code === SEND_PERMIT_DENIED) {
1555
+ throw sendPermitDenied({ envelopeId: envelope.id, direct: { attempted: true, peerId: recipientPeerIdStr } });
1556
+ }
1557
+ throw error;
1558
+ }
1401
1559
  // Not marked delivered: a closed stream is not a receipt (2.5.3).
1402
1560
  return envelope;
1403
1561
  }
@@ -1500,47 +1658,153 @@ export class Pillar {
1500
1658
  * sealed to its recipient alone. Final states: `sent` (with the envelope
1501
1659
  * id) or `dropped` (with a reason). A failed attempt stays `queued`.
1502
1660
  * A frozen group sends only its equivocation proof.
1661
+ * 2.8.2: a queued row keeps one envelope. Its id is claimed on the row
1662
+ * before the first send; a retry dispatches the stored outbox row again.
1663
+ * A moved route, an erased row or an envelope over 23 h old seals a new
1664
+ * one, once per attempt, and the old outbox row becomes `superseded`, as
1665
+ * does the pending row of a dropped item.
1503
1666
  * Returns [{ id, groupId, to, op, state, envelopeId?, reason? }].
1504
1667
  */
1505
- async syncGroupV2({ groupId = null, resolveTimeoutMs = 5000 } = {}) {
1668
+ reloadGroupV2(groupId) {
1669
+ loadGroupForCommand(this.groupsV2.store, groupId);
1670
+ this.groupsV2.records.delete(groupId);
1671
+ return this.groupsV2.state(groupId);
1672
+ }
1673
+
1674
+ /**
1675
+ * 2.8.2 r3 (Lead d79649): send a stored pending direct envelope again, byte for byte, for an app that owns its
1676
+ * retries (send() has no resender for a `confirmed: false` result). Every send() gate and the continuity route run
1677
+ * again; a trusted acceptance marks the row delivered. Returns send()'s result, or `{ resent: false, reason }` and
1678
+ * dispatches nothing. reason: completed (delivered or acked), erased, superseded, rerouted (the route no longer
1679
+ * lands on the stored recipient), expired (over 23 h old: a carrier refuses it after 24 h), missing, or group (a
1680
+ * group row. syncGroupV2 retries only its own queued rows; nothing retries a sendGroupV2 member result with
1681
+ * confirmed:false, and a plain send() would carry no group context to the permit). On rerouted or expired the
1682
+ * caller decides whether to send anew.
1683
+ */
1684
+ async resendOutbound(envelopeId, { recipientPublicKey = null, resolveTimeoutMs = 5000, permit = null, signal = null } = {}) {
1685
+ const row = this.mailbox.getOutbound(envelopeId);
1686
+ // Settled before any gate runs: missing, completed, erased or superseded (resendBlocked checks the route only for a
1687
+ // live pending row, and those are not answered here).
1688
+ if (!row || isErasedRow(row) || row.status !== "pending" || attemptSettled(row)) return { resent: false, reason: resendBlocked(row, null) };
1689
+ if (row.group_id || row.group_msg_id) return { resent: false, reason: "group" }; // @t282 resend-public
1690
+ const stored = JSON.parse(row.envelope_json);
1691
+ // 2.8.2 r4 (RedTeam 87e556 P3): local expiry needs no key and no route, so it is named before send() looks either up.
1692
+ if (attemptExpired(stored)) return { resent: false, reason: "expired" }; // @t282 resend-expiry-first
1693
+ const r = await this.send({ recipient: stored.recipient, recipientPublicKey, kind: stored.kind, resolveTimeoutMs, permit, signal, [RESEND]: envelopeId });
1694
+ return r?.[RESEND] ? { resent: false, reason: r[RESEND] } : r; // @t282 resend-public
1695
+ }
1696
+
1697
+ async syncGroupV2({ groupId = null, resolveTimeoutMs = 5000, manifestPayload = null, permit = null, signal = null } = {}) {
1698
+ if (manifestPayload != null && typeof manifestPayload !== "function") throw new TypeError("manifestPayload must be a function");
1699
+ let stopped = false;
1506
1700
  const ZERO = "0".repeat(64);
1507
1701
  const out = [];
1702
+ const owned = ownedGroupV2Items(this.mailbox);
1508
1703
  for (const q of this.mailbox.queuedGroupV2Sends(groupId)) {
1509
- const done = (state, extra = {}) => { this.mailbox.markGroupV2Send(q.id, state, extra); out.push({ id: q.id, groupId: q.group_id, to: q.recipient, op: q.op, state, ...extra }); };
1510
- let rec = null;
1511
- if (this.groupsV2.store.has(q.group_id)) {
1512
- try { rec = this.groupsV2.store.load(q.group_id); } catch (e) { done("dropped", { reason: `store: ${e.message}` }); continue; }
1513
- }
1514
- if (rec?.frozen && q.op !== "equivocation") { done("dropped", { reason: "frozen" }); continue; } // @rule Q-sync-frozen-only-proof
1515
- const msgId = `gm-${randomBytes(16).toString("hex")}`;
1516
- const tag = rec
1517
- ? buildGroupTagV2(rec, { op: q.op, msgId })
1518
- : { v: 2, id: q.group_id, name: "", members: [], msgId, op: q.op, mv: { version: 0, hash: ZERO } };
1519
- let text;
1520
- if (q.op === "manifest.request") {
1521
- tag.want = { from: q.want_from, to: q.want_to };
1522
- text = `asks for group manifests ${q.want_from}..${q.want_to ?? "newest"}`;
1523
- } else if (q.op === "manifest") {
1524
- const m = rec?.chain.find((x) => manifestHashOf(x) === q.manifest_hash);
1525
- if (!m) { done("dropped", { reason: "manifest-not-held" }); continue; }
1526
- tag.manifest = m;
1527
- text = `group manifest v${m.version} (${m.transition.action})`;
1528
- } else if (q.op === "equivocation") {
1529
- const m = rec?.frozen?.manifests.find((x) => manifestHashOf(x) === q.manifest_hash);
1530
- if (!m) { done("dropped", { reason: "proof-not-held" }); continue; }
1531
- tag.manifest = m;
1532
- tag.conflictsWith = q.conflicts_with;
1533
- text = `the group admin signed two versions ${m.version}: this group is frozen`;
1534
- } else { done("dropped", { reason: `op ${q.op} is not queued` }); continue; }
1535
- const key = q.recipient_key ?? this.addressBook?.get(q.recipient)?.publicKey;
1536
- if (!key) { done("dropped", { reason: "no key for the recipient" }); continue; }
1704
+ // 2.8.2 r4 (RedTeam 87e556 P2): another live pass owns this item (it may have claimed an id and not yet stored the
1705
+ // row). This pass reads, writes and sends nothing for it.
1706
+ if (owned.has(q.id)) continue; // @t282 claim-owner
1707
+ owned.add(q.id);
1537
1708
  try {
1538
- const r = await this.send({ recipient: q.recipient, recipientPublicKey: key, kind: "message", payload: { text, _group: tag }, resolveTimeoutMs });
1539
- done("sent", { envelopeId: r.envelope.id }); // @rule Q-sync-marks-sent
1540
- } catch (e) {
1541
- this.mailbox.markGroupV2Send(q.id, "queued", { reason: e.message });
1542
- out.push({ id: q.id, groupId: q.group_id, to: q.recipient, op: q.op, state: "queued", reason: e.message });
1543
- }
1709
+ // 2.8.2 r2 (RedTeam 822828 P2): one recoverable attempt per queue item. Its envelope id is saved on the
1710
+ // item before the first send, and later passes dispatch that stored envelope again (send() RESEND).
1711
+ let attemptId = q.envelope_id ?? null;
1712
+ const attemptRow = () => (attemptId ? this.mailbox.getOutbound(attemptId) : null);
1713
+ const done = (state, extra = {}) => {
1714
+ // 2.8.2 r4 (RedTeam 87e556 P2): write only while the item is still queued under this pass's attempt. A stale
1715
+ // pass (another process, or a snapshot read before another pass finished) writes and reports nothing.
1716
+ const write = { ...extra };
1717
+ write.attempt = attemptId; // @t282 owner-write
1718
+ if (!this.mailbox.markGroupV2Send(q.id, state, write)) return;
1719
+ // A dropped item leaves no live pending row: nothing would ever send or settle it.
1720
+ if (state === "dropped" && attemptId) this.mailbox.markOutboundSuperseded(attemptId); // @t282 retry-supersede
1721
+ out.push({ id: q.id, groupId: q.group_id, to: q.recipient, op: q.op, state, ...extra });
1722
+ };
1723
+ // Receipts first: the attempt already completed (a trusted acceptance, a denial's partial result, a pass cut short,
1724
+ // or the recipient's ack). An erased row keeps its status and ack.
1725
+ if (attemptSettled(attemptRow())) { done("sent", { envelopeId: attemptId }); continue; } // @t282 retry-reconcile
1726
+ if (stopped) { done("dropped", { reason: SEND_PERMIT_DENIED }); continue; }
1727
+ let rec = null;
1728
+ if (this.groupsV2.store.has(q.group_id)) {
1729
+ try { rec = this.groupsV2.store.load(q.group_id); } catch (e) { done("dropped", { reason: `store: ${e.message}` }); continue; }
1730
+ }
1731
+ if (rec?.frozen && q.op !== "equivocation") { done("dropped", { reason: "frozen" }); continue; } // @rule Q-sync-frozen-only-proof
1732
+ const msgId = `gm-${randomBytes(16).toString("hex")}`;
1733
+ const tag = rec
1734
+ ? buildGroupTagV2(rec, { op: q.op, msgId })
1735
+ : { v: 2, id: q.group_id, name: "", members: [], msgId, op: q.op, mv: { version: 0, hash: ZERO } };
1736
+ let text;
1737
+ if (q.op === "manifest.request") {
1738
+ tag.want = { from: q.want_from, to: q.want_to };
1739
+ text = `asks for group manifests ${q.want_from}..${q.want_to ?? "newest"}`;
1740
+ } else if (q.op === "manifest") {
1741
+ const m = rec?.chain.find((x) => manifestHashOf(x) === q.manifest_hash);
1742
+ if (!m) { done("dropped", { reason: "manifest-not-held" }); continue; }
1743
+ tag.manifest = m;
1744
+ text = `group manifest v${m.version} (${m.transition.action})`;
1745
+ } else if (q.op === "equivocation") {
1746
+ const m = rec?.frozen?.manifests.find((x) => manifestHashOf(x) === q.manifest_hash);
1747
+ if (!m) { done("dropped", { reason: "proof-not-held" }); continue; }
1748
+ tag.manifest = m;
1749
+ tag.conflictsWith = q.conflicts_with;
1750
+ text = `the group admin signed two versions ${m.version}: this group is frozen`;
1751
+ } else { done("dropped", { reason: `op ${q.op} is not queued` }); continue; }
1752
+ const key = q.recipient_key ?? this.addressBook?.get(q.recipient)?.publicKey;
1753
+ if (!key) { done("dropped", { reason: "no key for the recipient" }); continue; }
1754
+ try {
1755
+ const guard = createSendGuard({ outboundPolicy: this.#outboundPolicy, permit, signal, context: { recipient: q.recipient, groupId: q.group_id, op: q.op } });
1756
+ if (guard) { await guard({ phase: "seal", route: "group" }); assertSendNotAborted(signal); }
1757
+ let extras = {};
1758
+ if (q.op === "manifest" && manifestPayload) {
1759
+ const freeze = (v) => { if (v && typeof v === "object") { for (const x of Object.values(v)) freeze(x); Object.freeze(v); } return v; };
1760
+ const context = freeze({ groupId: q.group_id, recipient: q.recipient, op: q.op, manifest: tag.manifest, chain: rec.chain, head: rec.head });
1761
+ try {
1762
+ const value = await manifestPayload(context);
1763
+ assertSendNotAborted(signal);
1764
+ extras = boundedJsonRecord(value, 32768);
1765
+ for (const key of ["_group", "text", "thread", "quote", "blobRef", "inReplyTo", "type", "upTo"]) if (Object.hasOwn(extras, key)) throw new Error("reserved payload key"); // @spaces-check manifest-payload-protected
1766
+ } catch {
1767
+ assertSendNotAborted(signal);
1768
+ throw Object.assign(new Error("manifest payload unavailable or invalid"), { code: "manifest-payload-unavailable" });
1769
+ }
1770
+ }
1771
+ let r = null;
1772
+ const row = attemptRow();
1773
+ // The checks above ran again: store, frozen, manifest or proof held, key, the gate, and manifestPayload (a throw sends
1774
+ // nothing). send() runs all its gates and the continuity route again, then dispatches the stored bytes (their extras
1775
+ // are the first attempt's), or returns `{ [RESEND]: why }` (resendBlocked) and dispatches nothing.
1776
+ if (row?.status === "pending" && !isErasedRow(row)) r = await this.send({ recipient: q.recipient, recipientPublicKey: key, kind: "message", payload: { text, _group: tag }, resolveTimeoutMs, permit, signal, [RESEND]: attemptId }); // @t282 retry-same-envelope
1777
+ if (r?.[RESEND]) r = null; // completed, erased, superseded, moved route, expired (23 h) or missing
1778
+ if (!r) {
1779
+ const old = attemptId ? this.mailbox.getOutbound(attemptId) : null;
1780
+ // 2.8.2 r3 (RedTeam bcdc6c P2): a completion that landed during the awaited gates or resend is this item's
1781
+ // result. Reconcile before any replacement; there is no await between this read and the claim.
1782
+ if (attemptSettled(old)) { done("sent", { envelopeId: attemptId }); continue; } // @t282 resend-completed
1783
+ // Claim before mint (RedTeam bcdc6c): a value swap on the queue item, so two passes never both seal an attempt for
1784
+ // it; the pass that loses writes nothing for the item. An id with no stored row (send() threw before its append)
1785
+ // was never sealed, so it is kept. Otherwise one new attempt replaces the stored one.
1786
+ if (!attemptId || old) {
1787
+ const next = mkEnvelopeId();
1788
+ if (!this.mailbox.claimGroupV2Attempt(q.id, attemptId, next)) continue; // @t282 claim-before-mint
1789
+ if (old) this.mailbox.markOutboundSuperseded(attemptId); // a new attempt replaces the stored one // @t282 retry-supersede
1790
+ attemptId = next; // an id that has a stored row is never sealed again // @t282 retry-save-id
1791
+ }
1792
+ r = await this.send({ recipient: q.recipient, recipientPublicKey: key, kind: "message", payload: { text, ...extras, _group: tag }, resolveTimeoutMs, permit, signal, envelopeId: attemptId });
1793
+ }
1794
+ // 2.8.2 trustedCarriers: no trusted carrier accepted it, so the queued send stays queued and is sent again. Read the
1795
+ // row first: the recipient's ack may have landed during the send.
1796
+ 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
1798
+ done("sent", { envelopeId: r.envelope.id }); // @rule Q-sync-marks-sent
1799
+ } catch (e) {
1800
+ // Only a real denial drops the queue; any other failure, whatever code it names, stays queued for retry.
1801
+ const denied = isSendPermitDenied(e), state = denied ? "dropped" : "queued";
1802
+ stopped = denied;
1803
+ // A denial drops the item (the documented contract). When send() counted an acceptance from the denial's partial
1804
+ // result, the outbox row stays delivered: done() supersedes only a pending row.
1805
+ done(state, { reason: denied ? SEND_PERMIT_DENIED : e.message, ...(e.partial ? { partial: e.partial } : {}) });
1806
+ }
1807
+ } finally { owned.delete(q.id); }
1544
1808
  }
1545
1809
  this.metrics.inc("group-v2.sync", out.length);
1546
1810
  return out;
@@ -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.0";
55
+ export const STATS_VERDICT_TOOL = "pillar/2.8.2";
56
56
 
57
57
  /** Closed key set of `pillar-ttfa-report/1`. */
58
58
  export const TTFA_REPORT_KEYS = Object.freeze([
@@ -0,0 +1,66 @@
1
+ /** Optional, instance-bound outbound policy. No payload, keys or exception text crosses this boundary. */
2
+ export const SEND_PERMIT_DENIED = "send-permit-denied";
3
+ // Denials this SDK raised. The code string alone proves nothing: a carrier's refusal reason, a
4
+ // transport error or a caller's own error can carry the same text.
5
+ const DENIALS = new WeakSet();
6
+
7
+ export function sendPermitDenied(partial = null) {
8
+ const error = new Error("outbound send permission denied");
9
+ error.code = SEND_PERMIT_DENIED;
10
+ if (partial) error.partial = partial;
11
+ DENIALS.add(error);
12
+ return error;
13
+ }
14
+
15
+ /** A denial raised here (permit, outbound policy or abort), never one that only names the code. */
16
+ export function isSendPermitDenied(error) {
17
+ if (!DENIALS.has(error)) return false; // @spaces-check denial-by-identity
18
+ return error?.code === SEND_PERMIT_DENIED;
19
+ }
20
+
21
+ /** The code a caller may match on. The reserved denial code survives only on a real denial. */
22
+ export function sendErrorCode(error) {
23
+ const code = typeof error?.code === "string" ? error.code : null;
24
+ return code === SEND_PERMIT_DENIED && !isSendPermitDenied(error) ? null : code;
25
+ }
26
+
27
+ export function assertSendNotAborted(signal) {
28
+ if (signal?.aborted) throw sendPermitDenied();
29
+ }
30
+
31
+ /** Null preserves the omitted-option path (including its scheduling/parallelism). */
32
+ export function createSendGuard({ outboundPolicy = null, permit = null, signal = null, context = {} } = {}) {
33
+ if (outboundPolicy == null && permit == null && signal == null) return null;
34
+ for (const policy of [outboundPolicy, permit]) {
35
+ if (policy != null && typeof policy !== "function") throw sendPermitDenied();
36
+ }
37
+ if (signal != null && !(signal instanceof AbortSignal)) throw sendPermitDenied();
38
+ return async (details = {}) => {
39
+ assertSendNotAborted(signal);
40
+ const fields = { phase: "seal", route: "auto", recipient: null, groupId: null, op: null, ...context, ...details };
41
+ // Only scalar routing metadata reaches policy callbacks, never caller objects.
42
+ const dto = Object.freeze({ phase: fields.phase, route: fields.route,
43
+ recipient: typeof fields.recipient === "string" ? fields.recipient : null,
44
+ groupId: typeof fields.groupId === "string" ? fields.groupId : null,
45
+ op: typeof fields.op === "string" ? fields.op : null,
46
+ ...(typeof fields.carrier === "string" ? { carrier: fields.carrier } : {}) });
47
+ for (const policy of [outboundPolicy, permit]) {
48
+ if (!policy) continue;
49
+ let allowed;
50
+ try { allowed = await policy(dto); } catch { throw sendPermitDenied(); }
51
+ assertSendNotAborted(signal);
52
+ if (allowed !== true) throw sendPermitDenied(); // @spaces-check send-permit-exact-true
53
+ }
54
+ // A consent callback may await a dialog or itself retire the host. Re-read
55
+ // the instance baseline after it, before giving the caller its final gate.
56
+ if (outboundPolicy && permit) {
57
+ let allowed;
58
+ try { allowed = outboundPolicy(dto); if (allowed && typeof allowed.then === "function") allowed = await allowed; }
59
+ catch { throw sendPermitDenied(); }
60
+ assertSendNotAborted(signal);
61
+ if (allowed !== true) throw sendPermitDenied();
62
+ }
63
+ assertSendNotAborted(signal);
64
+ return true;
65
+ };
66
+ }