@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.
- package/README.md +258 -2
- package/package.json +3 -1
- package/src/groups-v2-admin.mjs +3 -0
- package/src/groups-v2.mjs +198 -5
- package/src/mailbox/mailbox.mjs +36 -5
- package/src/net/carrier-client.mjs +81 -9
- package/src/net/seed-registry.mjs +9 -1
- package/src/net/seed-routes.mjs +214 -0
- package/src/net/tunnel-relay.mjs +12 -0
- package/src/pillar.mjs +547 -65
- package/src/registry/stats.mjs +1 -1
- package/src/send-permit.mjs +66 -0
- package/src/vnext/json-dir-mailbox.mjs +3 -0
- package/src/vnext/jsonl-mailbox.mjs +38 -2
- package/src/vnext/retired-import.mjs +4 -1
- package/src/vnext/verify-cli.mjs +1 -1
package/src/pillar.mjs
CHANGED
|
@@ -24,7 +24,9 @@ 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
|
+
import { normalizeSeedRoutes, makeSeedFetch, listedSeeds, routeKey, SEED_MIN_POLL_INTERVAL_MS } from "./net/seed-routes.mjs";
|
|
29
|
+
import { setTimeout as sleepTimer } from "node:timers/promises";
|
|
28
30
|
import { REFUSAL_FIXES } from "./net/refusals.mjs";
|
|
29
31
|
import { Observability } from "./observability.mjs";
|
|
30
32
|
import { evaluateTrust, allowSenderInTrust, DEFAULT_KNOCK_ACCEPT_SCOPE } from "./identity/trust.mjs";
|
|
@@ -33,7 +35,8 @@ import {
|
|
|
33
35
|
extractGroupTag, buildGroupTag, absorbGroupTag, newGroupId, newGroupMsgId, normalizeMembers, isGroupId,
|
|
34
36
|
} from "./groups.mjs";
|
|
35
37
|
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";
|
|
38
|
+
import { GroupReceiver, RosterStore, isGroupIdV2, adminOf, buildGroupTag as buildGroupTagV2, manifestHash as manifestHashOf, loadGroupForCommand, boundedJsonRecord } from "./groups-v2.mjs";
|
|
39
|
+
import { createSendGuard, assertSendNotAborted, sendPermitDenied, isSendPermitDenied, sendErrorCode, SEND_PERMIT_DENIED } from "./send-permit.mjs";
|
|
37
40
|
import { randomBytes } from "node:crypto";
|
|
38
41
|
import { dirname } from "node:path";
|
|
39
42
|
|
|
@@ -65,8 +68,61 @@ export class W4RefusalError extends Error {
|
|
|
65
68
|
}
|
|
66
69
|
|
|
67
70
|
const VALUE_STORE_PREFIX = "/uuaid/1.0";
|
|
71
|
+
// 2.8.2 r2 (RedTeam 822828 P2): the send() option that re-dispatches a stored pending outbox row (syncGroupV2). Its
|
|
72
|
+
// value is only a row id: send() reads that row from its own mailbox, so a caller that sees the symbol can at most
|
|
73
|
+
// resend this agent's own pending envelope, through every gate.
|
|
74
|
+
const RESEND = Symbol("pillar.resend");
|
|
75
|
+
// 2.8.2 r3 (RedTeam bcdc6c P2): a carrier refuses an envelope whose createdAt is over 24 h old before it dedupes
|
|
76
|
+
// (carrier-server.mjs MAX_ENVELOPE_AGE_MS), so a stored attempt is renewed at 23 h.
|
|
77
|
+
const RESEND_MAX_AGE_MS = 23 * 3600_000;
|
|
78
|
+
/** An attempt is settled when a carrier that counts took it (status delivered) or the recipient acked it. An erased
|
|
79
|
+
* row keeps both fields, so its erasure does not reopen it. */
|
|
80
|
+
const attemptSettled = (row) => !!row && (row.status === "delivered" || !!row.recipient_ack_at);
|
|
81
|
+
/**
|
|
82
|
+
* 2.8.2 r3 (RedTeam bcdc6c P2): why a resend of `row` must not dispatch, or null. send() returns `{ [RESEND]: why }`
|
|
83
|
+
* instead of one null for every case, so syncGroupV2 never seals a replacement over a completed attempt.
|
|
84
|
+
*/
|
|
85
|
+
function resendBlocked(row, recipient, nowMs = Date.now()) {
|
|
86
|
+
if (!row) return "missing";
|
|
87
|
+
if (attemptSettled(row)) return "completed"; // @t282 resend-completed
|
|
88
|
+
if (isErasedRow(row)) return "erased";
|
|
89
|
+
if (row.status !== "pending") return "superseded";
|
|
90
|
+
const stored = JSON.parse(row.envelope_json);
|
|
91
|
+
if (stored.recipient !== recipient) return "rerouted";
|
|
92
|
+
if (attemptExpired(stored, nowMs)) return "expired"; // @t282 resend-expired
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* 2.8.3: send()'s `route`. null, undefined or "fleet": the fleet only (2.8.2). "listed": the fleet, plus each
|
|
97
|
+
* configured seed the recipient's verified listing names. { seed: url }: the fleet, plus that one seed, on the
|
|
98
|
+
* same condition. Anything else is a TypeError, thrown before anything is sealed or sent.
|
|
99
|
+
*/
|
|
100
|
+
function parseRouteAsk(route) {
|
|
101
|
+
if (route == null || route === "fleet") return null;
|
|
102
|
+
if (route === "listed") return { only: null };
|
|
103
|
+
if (route && typeof route === "object" && !Array.isArray(route) && typeof route.seed === "string" && route.seed.trim()) return { only: routeKey(route.seed.trim()) };
|
|
104
|
+
throw new TypeError('send: route must be "fleet", "listed", { seed: url }, or null');
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Over RESEND_MAX_AGE_MS old (or no readable createdAt): a carrier would refuse the stored envelope. */
|
|
108
|
+
function attemptExpired(stored, nowMs = Date.now()) {
|
|
109
|
+
const created = Date.parse(stored.createdAt);
|
|
110
|
+
return !Number.isFinite(created) || nowMs - created > RESEND_MAX_AGE_MS;
|
|
111
|
+
}
|
|
112
|
+
/** Error thrown from a dispatch gate when a resend's row stopped being live (send() returns `{ [RESEND]: why }`). */
|
|
113
|
+
const resendStopped = (why) => Object.assign(new Error(`resend stopped: ${why}`), { code: "resend-stopped" });
|
|
114
|
+
// 2.8.2 r4 (RedTeam 87e556 P2): the syncGroupV2 queue items a live pass in this process holds, per mailbox. A pass owns
|
|
115
|
+
// an item from its first read to its last write, across every await; another pass skips it. In memory only, so a crash
|
|
116
|
+
// holds nothing. Across processes the claim and the owner check on every queue write (markGroupV2Send attempt) hold.
|
|
117
|
+
const GROUP_V2_OWNED = new WeakMap();
|
|
118
|
+
const ownedGroupV2Items = (mailbox) => {
|
|
119
|
+
let s = GROUP_V2_OWNED.get(mailbox);
|
|
120
|
+
if (!s) GROUP_V2_OWNED.set(mailbox, (s = new Set()));
|
|
121
|
+
return s;
|
|
122
|
+
};
|
|
68
123
|
|
|
69
124
|
export class Pillar {
|
|
125
|
+
#outboundPolicy;
|
|
70
126
|
constructor({
|
|
71
127
|
keychain,
|
|
72
128
|
mailboxPath,
|
|
@@ -88,13 +144,19 @@ export class Pillar {
|
|
|
88
144
|
reader = null, // reader key recorded on every row this process stores (src/readers.mjs)
|
|
89
145
|
receipts = null, // { delivered, read }: send signed acks / read receipts (receipts.mjs); null = neither
|
|
90
146
|
notifySink = null, // NotifySink (src/notify-events.mjs): eligibility events after final admission; null = none
|
|
147
|
+
outboundPolicy = null, // optional instance policy for send transports; requires exact true
|
|
148
|
+
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
149
|
groupsV2Home = null, // where groups-v2/ lives (pillar-group/2 store); default: the mailbox's directory
|
|
92
150
|
home = null, // agent home directory (for trust.json persistence on knock accept)
|
|
93
151
|
knockConfig = null, // vNext §4 knock policy: { requiredBits?, maxBytes?, introductions?, stake?, trustedIssuers?, trustedContacts?, lineageResolver?, lineages?, selfLineage?, card?, cap?, rateWindowMs?, now? }
|
|
94
152
|
registryUrl = null, // vNext §3 registry base URL; when set, sends follow W-4 sender redirect policy (B5, T2.7)
|
|
95
153
|
continuity = null, // 2.8.0 continuity: { passphrase?, now?, fetch?, urlMap?, allowInsecureLoopback? } (DESIGN-continuity)
|
|
154
|
+
seedRoutes = null, // 2.8.3 opt-in: { direct?, relayed?, timeoutMs?, pollIntervalMs? } seeds for send({ route }) and startSeedPolling; null = 2.8.2
|
|
96
155
|
}) {
|
|
97
156
|
if (!keychain?._identity) throw new Error("Pillar: keychain must be loaded before construction");
|
|
157
|
+
if (outboundPolicy != null && typeof outboundPolicy !== "function") throw sendPermitDenied();
|
|
158
|
+
this.#outboundPolicy = outboundPolicy;
|
|
159
|
+
this.trustedCarriers = normalizeTrustedCarriers(trustedCarriers);
|
|
98
160
|
this.keychain = keychain;
|
|
99
161
|
this.mailbox = new Mailbox(mailboxPath);
|
|
100
162
|
this.home = home ?? (typeof mailboxPath === "string" ? dirname(mailboxPath) : null);
|
|
@@ -111,7 +173,12 @@ export class Pillar {
|
|
|
111
173
|
this.dhtClientMode = dhtClientMode;
|
|
112
174
|
this.dhtPeerInfoMapper = dhtPeerInfoMapper;
|
|
113
175
|
this.carriers = carriers;
|
|
114
|
-
this.carrierClient = carriers.length ? new CarrierClient({ keychain, carriers, tierGrant }) : null;
|
|
176
|
+
this.carrierClient = carriers.length ? new CarrierClient({ keychain, carriers, tierGrant, trustedCarriers: this.trustedCarriers }) : null;
|
|
177
|
+
// 2.8.3: seeds stay apart from the fleet. They never join `carriers` or `trustedCarriers`, so trust,
|
|
178
|
+
// advertisement and every send without `route` stay on the fleet (RedTeam Mac B item 3).
|
|
179
|
+
this.seedRoutes = normalizeSeedRoutes(seedRoutes, { fleet: carriers });
|
|
180
|
+
this._seedFetch = this.seedRoutes ? makeSeedFetch({ allowPrivateUrls: this.seedRoutes.allowPrivateUrls, lookup: this.seedRoutes.lookup, fetch: this.seedRoutes.fetch }) : null;
|
|
181
|
+
this._seedPoller = null;
|
|
115
182
|
this._carrierPoller = null;
|
|
116
183
|
this._carrierStopping = Promise.resolve();
|
|
117
184
|
this.enableLibp2p = enableLibp2p;
|
|
@@ -220,6 +287,7 @@ export class Pillar {
|
|
|
220
287
|
}
|
|
221
288
|
|
|
222
289
|
async stop() {
|
|
290
|
+
await this.stopSeedPolling();
|
|
223
291
|
await this.stopCarrierPolling();
|
|
224
292
|
if (!this.node) { this.mailbox.close(); return; }
|
|
225
293
|
for (const push of this._openStreams.values()) { try { push.end(); } catch (_e) {} }
|
|
@@ -915,11 +983,15 @@ export class Pillar {
|
|
|
915
983
|
return { direct: true, publicKey: pubKey, carrier: res.card?.carriers?.[0] };
|
|
916
984
|
}
|
|
917
985
|
|
|
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 }) {
|
|
986
|
+
async send({ recipient, recipientPublicKey, subject = null, routeFp = null, kind = "message", payload = {}, envelopeId = null, resolveTimeoutMs = 5000, registryUrl = null, confirmRecovered = false, now = null, urlMap = undefined, allowInsecureLoopback = false, fetch: fetchOverride = undefined, permit = null, signal = null, route = null, [RESEND]: resendId = null }) {
|
|
987
|
+
const routeAsk = parseRouteAsk(route); // 2.8.3: before any I/O, so a bad value sends nothing
|
|
919
988
|
if (!this.node && !this.carrierClient) {
|
|
920
989
|
this.metrics.inc("send.error.not-started");
|
|
921
990
|
throw new Error("pillar not started");
|
|
922
991
|
}
|
|
992
|
+
const guard = createSendGuard({ outboundPolicy: this.#outboundPolicy, permit, signal, context: { recipient, groupId: payload?._group?.id ?? null, op: payload?._group?.op ?? null } });
|
|
993
|
+
if (guard) { await guard({ phase: "seal", route: "auto" }); assertSendNotAborted(signal); }
|
|
994
|
+
const transportPermit = guard ? (details) => guard({ ...details, recipient, groupId: payload?._group?.id ?? null, op: payload?._group?.op ?? null }) : null;
|
|
923
995
|
const t0 = Date.now();
|
|
924
996
|
let w4 = { direct: true }, w4Fields = {};
|
|
925
997
|
// `subject`: the identity a wrapper (sendKnock, sendBlob) was asked to reach before it chose `recipient`.
|
|
@@ -964,13 +1036,35 @@ export class Pillar {
|
|
|
964
1036
|
pubkey = dhtAdvert.publicKeyHex;
|
|
965
1037
|
} catch (_e) { /* fall through to the error below */ }
|
|
966
1038
|
}
|
|
1039
|
+
// 2.8.2 r2 (RedTeam 822828 P1): continuity or W-4 may have moved the recipient above. This gate and every
|
|
1040
|
+
// dispatch gate check the final recipient, the one the envelope is sealed to. The first gate saw the caller's.
|
|
1041
|
+
if (guard) { await guard({ phase: "seal", route: "auto", recipient }); assertSendNotAborted(signal); } // @t282 route-final
|
|
967
1042
|
if (!pubkey) {
|
|
968
1043
|
this.metrics.inc("send.error.no-public-key");
|
|
969
1044
|
throw new Error(`send: no public key known for ${recipient} — encryption is mandatory; register the peer (address book / fleet.json) or pass recipientPublicKey`);
|
|
970
1045
|
}
|
|
971
1046
|
|
|
1047
|
+
// 2.8.3: a seed only when the recipient's verified listing names it, for the final recipient and the sealing key.
|
|
1048
|
+
const seedRoute = routeAsk ? await this._selectSeedRoute(recipient, pubkey, routeAsk, { registryUrl, now, fetch: fetchOverride, urlMap, allowInsecureLoopback, signal }) : null;
|
|
972
1049
|
this._recheckRoute(subj, cr.fp, recipient, now); // nothing above awaited may change the route unseen
|
|
973
|
-
|
|
1050
|
+
// A resend (syncGroupV2) dispatches the stored bytes of a live pending row, only while the route still lands on
|
|
1051
|
+
// their recipient and a carrier would still take them. Otherwise it returns `{ [RESEND]: why }` (resendBlocked).
|
|
1052
|
+
const resend = resendId ? this.mailbox.getOutbound(resendId) : null;
|
|
1053
|
+
if (resendId) { const why = resendBlocked(resend, recipient); if (why) return { [RESEND]: why }; }
|
|
1054
|
+
const stored = resend ? JSON.parse(resend.envelope_json) : null;
|
|
1055
|
+
// seal() refuses a key that does not derive `recipient`, so the gated recipient binds the key too.
|
|
1056
|
+
const envelope = stored ?? seal(this.keychain, { recipient, recipientPublicKey: pubkey, kind, payload, id: envelopeId ?? undefined });
|
|
1057
|
+
let dispatchGuard = guard;
|
|
1058
|
+
if (guard) dispatchGuard = (details = {}) => guard({ ...details, recipient: envelope.recipient }); // @t282 route-final
|
|
1059
|
+
// 2.8.2 r4 (RedTeam 87e556 P2): a dispatch gate awaits (a permit can await a dialog), and the row can be erased,
|
|
1060
|
+
// completed or superseded meanwhile. A resend rereads its row after every dispatch gate, right before the bytes leave
|
|
1061
|
+
// on that route, also with no permit. A stop sends nothing more and returns `{ [RESEND]: why }`, the same reasons as
|
|
1062
|
+
// the check above; an acceptance that came before the stop is still recorded, as for a denial.
|
|
1063
|
+
let resendStop = null;
|
|
1064
|
+
const resendLive = () => { const why = resendBlocked(this.mailbox.getOutbound(resendId), recipient); if (why) { resendStop ??= why; throw resendStopped(why); } };
|
|
1065
|
+
let carrierPermit = transportPermit;
|
|
1066
|
+
if (resendId) { const gate = dispatchGuard; dispatchGuard = async (details = {}) => { if (gate) await gate(details); resendLive(); return true; }; } // @t282 resend-fence
|
|
1067
|
+
if (resendId) carrierPermit = async (details) => { if (transportPermit) await transportPermit(details); resendLive(); return true; }; // @t282 resend-fence
|
|
974
1068
|
const hardCap = preflightBodyBytes(envelopeBodyBytes(envelope), { maxBodyBytes: MAX_INLINE_BODY_BYTES });
|
|
975
1069
|
if (!hardCap.ok) {
|
|
976
1070
|
this.metrics.inc("send.error.direct-cap");
|
|
@@ -979,7 +1073,7 @@ export class Pillar {
|
|
|
979
1073
|
// Receipt matching needs the thread and group of this row, and the sealed
|
|
980
1074
|
// envelope cannot tell us later: we cannot decrypt our own outbox.
|
|
981
1075
|
const groupTag = extractGroupTag(payload);
|
|
982
|
-
const persisted = this.mailbox.appendOutbound(envelope, {
|
|
1076
|
+
const persisted = stored ? { envelopeId: stored.id, envelopeSha256: resend.envelope_sha256, chainHash: resend.chain_hash } : this.mailbox.appendOutbound(envelope, {
|
|
983
1077
|
thread: typeof payload?.thread === "string" && payload.thread ? payload.thread : null,
|
|
984
1078
|
groupId: groupTag && !groupTag.derivedId ? groupTag.id : null,
|
|
985
1079
|
groupMsgId: groupTag?.msgId ?? null,
|
|
@@ -993,18 +1087,40 @@ export class Pillar {
|
|
|
993
1087
|
// (what status 'delivered' has always meant, mailbox.mjs). The recipient's
|
|
994
1088
|
// mailbox keys on (sender, envelope id), so a copy that arrives both ways is
|
|
995
1089
|
// stored and handled once.
|
|
1090
|
+
// 2.8.3: the selected seeds take a copy beside the fleet, bounded by seedRoutes.timeoutMs. A seed's acceptance
|
|
1091
|
+
// is never a delivery, and a permit refusal on a seed denies the send as on any carrier (RedTeam Mac B item 2).
|
|
1092
|
+
const seedP = seedRoute?.seeds.length ? this._deliverSeeds(envelope, seedRoute.seeds, { permit: carrierPermit, signal, timeoutMs: seedRoute.timeoutMs }) : null; // @t283 seed-parallel-bounded
|
|
1093
|
+
const routeOf = (o) => (seedRoute ? { route: { seeds: [...seedRoute.seeds], accepted: o?.accepted ?? [], reason: seedRoute.reason, ...(o?.error ? { error: o.error.message } : {}) } } : {});
|
|
1094
|
+
const seedOnly = (seeds, carrierError, extra = {}) => { // every fleet carrier refused; a listed seed holds a copy
|
|
1095
|
+
this.metrics.inc("send.via.seed-unconfirmed");
|
|
1096
|
+
return { envelope, persisted, via: "seed", delivery: seeds.result, confirmed: false, carrierError, ...extra, ...routeOf(seeds), ...w4Fields }; // @t283 seed-accept-not-delivered
|
|
1097
|
+
};
|
|
996
1098
|
if (this.node && book?.peerId && book?.multiaddr) {
|
|
997
1099
|
const [direct, carrier] = await Promise.allSettled([
|
|
998
|
-
this._deliverToPeer(envelope, book.peerId, book.multiaddr),
|
|
999
|
-
this.carrierClient ? this.carrierClient.deliver(envelope) : Promise.resolve(null),
|
|
1100
|
+
this._deliverToPeer(envelope, book.peerId, book.multiaddr, { guard: dispatchGuard, signal }),
|
|
1101
|
+
this.carrierClient ? this.carrierClient.deliver(envelope, { permit: carrierPermit, signal }) : Promise.resolve(null),
|
|
1000
1102
|
]);
|
|
1103
|
+
const seeds = seedP ? await seedP : null;
|
|
1001
1104
|
const sentDirect = direct.status === "fulfilled" ? direct.value : null;
|
|
1105
|
+
const denial = [direct, carrier].find((r) => r.status === "rejected" && isSendPermitDenied(r.reason)) ?? (seeds?.denied ? { reason: seeds.denied } : null);
|
|
1106
|
+
if (denial || resendStop) {
|
|
1107
|
+
const accepted = carrier.status === "fulfilled" && carrier.value;
|
|
1108
|
+
let counted = Boolean(accepted);
|
|
1109
|
+
if (counted && this.trustedCarriers && !acceptedByTrusted(accepted, this.trustedCarriers)) counted = false; // @t282 mark-denial
|
|
1110
|
+
// 2.8.2 r2 (RedTeam 822828 P2): the carrier fanout itself was denied after another carrier accepted.
|
|
1111
|
+
if (!counted && carrier.status === "rejected") counted = this._partialAccepted(carrier.reason); // @t282 partial-direct
|
|
1112
|
+
if (counted) this.mailbox.markOutboundDelivered(envelope.id, envelopeSha(envelope));
|
|
1113
|
+
if (resendStop) return { [RESEND]: resendStop };
|
|
1114
|
+
throw sendPermitDenied({ envelopeId: envelope.id, direct: sentDirect ? { attempted: true, peerId: book.peerId } : (direct.reason?.partial?.direct ?? false), carrier: accepted || (carrier.reason?.partial ?? null) });
|
|
1115
|
+
}
|
|
1002
1116
|
if (carrier.status === "fulfilled" && carrier.value) {
|
|
1117
|
+
// 2.8.2 trustedCarriers: only untrusted carriers (a relayed seed) took it. That is not a delivery; the row stays pending.
|
|
1118
|
+
if (this.trustedCarriers && !acceptedByTrusted(carrier.value, this.trustedCarriers)) return this._untrustedAcceptance({ envelope, persisted, via: sentDirect ? "direct+carrier" : "carrier", delivery: carrier.value, direct: sentDirect, ...routeOf(seeds) }, w4Fields); // @t282 mark-direct-carrier
|
|
1003
1119
|
this.mailbox.markOutboundDelivered(envelope.id, envelopeSha(envelope));
|
|
1004
1120
|
const via = sentDirect ? "direct+carrier" : "carrier";
|
|
1005
1121
|
this.metrics.inc(`send.via.${via}`);
|
|
1006
1122
|
this.metrics.observe(`send.latencyMs.via.${via}`, Date.now() - t0);
|
|
1007
|
-
return { envelope, persisted, via, delivery: carrier.value, direct: sentDirect, confirmed: true, ...w4Fields };
|
|
1123
|
+
return { envelope, persisted, via, delivery: carrier.value, direct: sentDirect, confirmed: true, ...routeOf(seeds), ...w4Fields };
|
|
1008
1124
|
}
|
|
1009
1125
|
if (sentDirect) {
|
|
1010
1126
|
// Written to a stream, and no carrier holds a copy: nothing confirms it
|
|
@@ -1012,19 +1128,38 @@ export class Pillar {
|
|
|
1012
1128
|
// sends one, is recorded when it comes).
|
|
1013
1129
|
this.metrics.inc("send.via.direct-unconfirmed");
|
|
1014
1130
|
return { envelope, persisted, via: "direct", delivery: sentDirect, direct: sentDirect, confirmed: false,
|
|
1015
|
-
carrierError: carrier.status === "rejected" ? carrier.reason : null, ...w4Fields };
|
|
1131
|
+
carrierError: carrier.status === "rejected" ? carrier.reason : null, ...routeOf(seeds), ...w4Fields };
|
|
1016
1132
|
}
|
|
1133
|
+
if (seeds?.accepted.length) return seedOnly(seeds, carrier.status === "rejected" ? carrier.reason : direct.reason, { direct: null });
|
|
1017
1134
|
this.metrics.inc("send.error.direct-delivery-failed");
|
|
1018
1135
|
throw carrier.status === "rejected" ? carrier.reason : direct.reason;
|
|
1019
1136
|
}
|
|
1020
1137
|
|
|
1021
1138
|
// 2. Carrier path: universal store-and-forward.
|
|
1022
1139
|
if (this.carrierClient) {
|
|
1023
|
-
|
|
1140
|
+
let receipt;
|
|
1141
|
+
try { receipt = await this.carrierClient.deliver(envelope, { permit: carrierPermit, signal }); }
|
|
1142
|
+
catch (e) {
|
|
1143
|
+
const seeds = seedP ? await seedP : null;
|
|
1144
|
+
// 2.8.2 r2 (RedTeam 822828 P2): a denial during the fanout can follow an acceptance. Record it, then return the denial.
|
|
1145
|
+
if (this._partialAccepted(e)) this.mailbox.markOutboundDelivered(envelope.id, envelopeSha(envelope)); // @t282 partial-carrier
|
|
1146
|
+
if (resendStop) return { [RESEND]: resendStop };
|
|
1147
|
+
if (!isSendPermitDenied(e) && seeds?.denied) throw seeds.denied;
|
|
1148
|
+
if (!isSendPermitDenied(e) && seeds?.accepted.length) return seedOnly(seeds, e);
|
|
1149
|
+
if (seedRoute && e && typeof e === "object" && Object.isExtensible(e)) e.route = routeOf(seeds).route;
|
|
1150
|
+
throw e;
|
|
1151
|
+
}
|
|
1152
|
+
const seeds = seedP ? await seedP : null;
|
|
1153
|
+
if (seeds?.denied) { // a permit refused a seed dispatch: the send is denied; the fleet acceptance before it is still recorded
|
|
1154
|
+
if (!this.trustedCarriers || acceptedByTrusted(receipt, this.trustedCarriers)) this.mailbox.markOutboundDelivered(envelope.id, envelopeSha(envelope));
|
|
1155
|
+
throw seeds.denied;
|
|
1156
|
+
}
|
|
1157
|
+
// 2.8.2 trustedCarriers: only untrusted carriers (a relayed seed) took it. That is not a delivery; the row stays pending.
|
|
1158
|
+
if (this.trustedCarriers && !acceptedByTrusted(receipt, this.trustedCarriers)) return this._untrustedAcceptance({ envelope, persisted, via: "carrier", delivery: receipt, ...routeOf(seeds) }, w4Fields); // @t282 mark-carrier
|
|
1024
1159
|
this.mailbox.markOutboundDelivered(envelope.id, envelopeSha(envelope));
|
|
1025
1160
|
this.metrics.inc("send.via.carrier");
|
|
1026
1161
|
this.metrics.observe("send.latencyMs.via.carrier", Date.now() - t0);
|
|
1027
|
-
return { envelope, persisted, via: "carrier", delivery: receipt, ...w4Fields };
|
|
1162
|
+
return { envelope, persisted, via: "carrier", delivery: receipt, ...(this.trustedCarriers || seedRoute ? { confirmed: true } : {}), ...routeOf(seeds), ...w4Fields };
|
|
1028
1163
|
}
|
|
1029
1164
|
|
|
1030
1165
|
// 3. DHT path.
|
|
@@ -1035,11 +1170,14 @@ export class Pillar {
|
|
|
1035
1170
|
if (!dhtAdvert) {
|
|
1036
1171
|
try { dhtAdvert = await this.resolveUuaid(recipient, { timeoutMs: resolveTimeoutMs }); }
|
|
1037
1172
|
catch (e) {
|
|
1173
|
+
assertSendNotAborted(signal);
|
|
1038
1174
|
this.metrics.inc("send.error.resolve-failed");
|
|
1039
1175
|
throw new Error(`send: cannot resolve ${recipient}: ${e.message}`);
|
|
1040
1176
|
}
|
|
1041
1177
|
}
|
|
1042
|
-
|
|
1178
|
+
let delivery;
|
|
1179
|
+
try { delivery = await this._deliverToPeer(envelope, dhtAdvert.peerId, dhtAdvert.addrs?.[0], { guard: dispatchGuard, signal }); }
|
|
1180
|
+
catch (e) { if (resendStop) return { [RESEND]: resendStop }; throw e; }
|
|
1043
1181
|
this.metrics.inc("send.via.dht");
|
|
1044
1182
|
this.metrics.observe("send.latencyMs.via.dht", Date.now() - t0);
|
|
1045
1183
|
// No carrier: a closed stream confirms nothing, so the row stays pending.
|
|
@@ -1065,7 +1203,7 @@ export class Pillar {
|
|
|
1065
1203
|
* Refused (code group-v2-use-v2-send) for a pillar-group/2 group.
|
|
1066
1204
|
* Returns { group, groupId, msgId, results: [{ member, ok, via?, envelopeId?, error?, code?, fix? }] }.
|
|
1067
1205
|
*/
|
|
1068
|
-
async sendGroup({ group, groupId = null, members, kind = "message", payload = {}, op = "message", resolveTimeoutMs = 5000 }) {
|
|
1206
|
+
async sendGroup({ group, groupId = null, members, kind = "message", payload = {}, op = "message", resolveTimeoutMs = 5000, route = null }) {
|
|
1069
1207
|
let g = groupId ? this.mailbox.getGroup(groupId) : null;
|
|
1070
1208
|
if (groupId && !g) throw new Error(`sendGroup: no group ${groupId} in this home`);
|
|
1071
1209
|
if (!g) {
|
|
@@ -1095,9 +1233,9 @@ export class Pillar {
|
|
|
1095
1233
|
try {
|
|
1096
1234
|
const r = await this.send({
|
|
1097
1235
|
recipient: member, recipientPublicKey: this.addressBook?.get(member)?.publicKey ?? g.keys?.[member],
|
|
1098
|
-
kind, payload: wrapped, resolveTimeoutMs,
|
|
1236
|
+
kind, payload: wrapped, resolveTimeoutMs, ...(route != null ? { route } : {}),
|
|
1099
1237
|
});
|
|
1100
|
-
results.push({ member, ok: true, via: r.via, envelopeId: r.envelope.id });
|
|
1238
|
+
results.push({ member, ok: true, via: r.via, envelopeId: r.envelope.id, ...(route != null && r.confirmed === false ? { confirmed: false } : {}), ...(r.route ? { route: r.route } : {}) });
|
|
1101
1239
|
} catch (e) {
|
|
1102
1240
|
results.push({ member, ok: false, error: e.message, ...(typeof e.code === "string" ? { code: e.code } : {}), ...(typeof e.fix === "string" ? { fix: e.fix } : {}) });
|
|
1103
1241
|
}
|
|
@@ -1118,7 +1256,9 @@ export class Pillar {
|
|
|
1118
1256
|
* any op but accept.request from a member who is only invited.
|
|
1119
1257
|
* Returns { group, groupId, msgId, results } like sendGroup.
|
|
1120
1258
|
*/
|
|
1121
|
-
async sendGroupV2({ groupId, op = "message", payload = {}, kind = "message", resolveTimeoutMs = 5000 }) {
|
|
1259
|
+
async sendGroupV2({ groupId, op = "message", payload = {}, kind = "message", resolveTimeoutMs = 5000, permit = null, signal = null, route = null }) {
|
|
1260
|
+
const guard = createSendGuard({ outboundPolicy: this.#outboundPolicy, permit, signal, context: { groupId, op } });
|
|
1261
|
+
if (guard) { await guard({ phase: "seal", route: "group" }); assertSendNotAborted(signal); }
|
|
1122
1262
|
if (!["message", "leave.request", "accept.request", "rename.request"].includes(op)) throw new Error(`sendGroupV2: op ${op} is not sent from here`);
|
|
1123
1263
|
const rec = loadGroupForCommand(this.groupsV2.store, groupId); // throws for a group it does not hold, or one that no longer verifies
|
|
1124
1264
|
const row = this.mailbox.getGroup(groupId);
|
|
@@ -1135,14 +1275,23 @@ export class Pillar {
|
|
|
1135
1275
|
const results = [];
|
|
1136
1276
|
for (const member of to) {
|
|
1137
1277
|
try {
|
|
1138
|
-
const r = await this.send({ recipient: member, recipientPublicKey: this.addressBook?.get(member)?.publicKey ?? row.keys?.[member], kind, payload: wrapped, resolveTimeoutMs });
|
|
1139
|
-
|
|
1278
|
+
const r = await this.send({ recipient: member, recipientPublicKey: this.addressBook?.get(member)?.publicKey ?? row.keys?.[member], kind, payload: wrapped, resolveTimeoutMs, permit, signal, ...(route != null ? { route } : {}) });
|
|
1279
|
+
const sent = { member, ok: true, via: r.via, envelopeId: r.envelope.id };
|
|
1280
|
+
if (this.trustedCarriers && r.confirmed === false) sent.confirmed = false; // @t282 group-unconfirmed
|
|
1281
|
+
// 2.8.3: a copy only a seed took is unconfirmed; nothing resends it, and a recipient-matched ack or read advances its row.
|
|
1282
|
+
if (route != null && r.confirmed === false) sent.confirmed = false; // @t283 seed-group-unconfirmed
|
|
1283
|
+
if (r.route) sent.route = r.route;
|
|
1284
|
+
results.push(sent);
|
|
1140
1285
|
} catch (e) {
|
|
1141
|
-
|
|
1286
|
+
const code = sendErrorCode(e);
|
|
1287
|
+
results.push({ member, ok: false, error: e.message, ...(code ? { code } : {}), ...(typeof e.fix === "string" ? { fix: e.fix } : {}), ...(e.partial ? { partial: e.partial } : {}) });
|
|
1288
|
+
if (isSendPermitDenied(e)) break;
|
|
1142
1289
|
}
|
|
1143
1290
|
}
|
|
1144
1291
|
this.metrics.inc("sendGroupV2");
|
|
1145
|
-
|
|
1292
|
+
const stopped = results.some((r) => r.code === SEND_PERMIT_DENIED);
|
|
1293
|
+
const unconfirmed = route != null ? results.filter((r) => r.ok && r.confirmed === false).length : 0;
|
|
1294
|
+
return { group: head.name, groupId, msgId: tag.msgId, results, ...(stopped ? { stopped: true } : {}), ...(route != null ? { unconfirmed } : {}) };
|
|
1146
1295
|
}
|
|
1147
1296
|
|
|
1148
1297
|
/**
|
|
@@ -1330,20 +1479,218 @@ export class Pillar {
|
|
|
1330
1479
|
throw err;
|
|
1331
1480
|
}
|
|
1332
1481
|
|
|
1333
|
-
|
|
1482
|
+
/**
|
|
1483
|
+
* 2.8.2 r2 (RedTeam 822828 P2): true when a carrier fanout denial still holds a counted acceptance. Only a
|
|
1484
|
+
* denial this SDK raised counts (isSendPermitDenied: no carrier text can forge one); its `partial.all` is the
|
|
1485
|
+
* fanout result. Unset trustedCarriers: any acceptance, as the direct branch counts it. Set: a trusted one.
|
|
1486
|
+
*/
|
|
1487
|
+
_partialAccepted(e) {
|
|
1488
|
+
if (!isSendPermitDenied(e) || !Array.isArray(e.partial?.all)) return false;
|
|
1489
|
+
return this.trustedCarriers ? acceptedByTrusted(e.partial, this.trustedCarriers) : e.partial.all.some((r) => r?.ok === true);
|
|
1490
|
+
}
|
|
1491
|
+
|
|
1492
|
+
/** 2.8.2: the send() result when only carriers outside trustedCarriers accepted; the outbox row stays pending. */
|
|
1493
|
+
_untrustedAcceptance(result, w4Fields) {
|
|
1494
|
+
this.metrics.inc("send.via.carrier-untrusted");
|
|
1495
|
+
return { ...result, confirmed: false, ...w4Fields };
|
|
1496
|
+
}
|
|
1497
|
+
|
|
1498
|
+
/**
|
|
1499
|
+
* 2.8.3: the seeds one send may use. Resolves the final recipient's listing through the registry
|
|
1500
|
+
* (signature-checked, bounded by seedRoutes.timeoutMs) and keeps the configured seeds it names.
|
|
1501
|
+
* Never throws: an unknown route is { seeds: [], reason }, and the send stays on the fleet.
|
|
1502
|
+
*/
|
|
1503
|
+
async _selectSeedRoute(recipient, publicKey, ask, { registryUrl = null, now = null, fetch: fetchOverride = undefined, urlMap = undefined, allowInsecureLoopback = false, signal = null } = {}) {
|
|
1504
|
+
const report = (seeds, reason) => ({ seeds, reason });
|
|
1505
|
+
if (!this.seedRoutes?.all.length) return report([], "no-seed-routes");
|
|
1506
|
+
if (!this.carrierClient) return report([], "no-fleet");
|
|
1507
|
+
const reg = registryUrl ?? this.registryUrl;
|
|
1508
|
+
if (!reg) return report([], "no-registry");
|
|
1509
|
+
const timeout = AbortSignal.timeout(this.seedRoutes.timeoutMs);
|
|
1510
|
+
let res;
|
|
1511
|
+
try {
|
|
1512
|
+
res = await resolveListing(recipient, { registryUrl: reg, now: now ?? nowIsoSeconds(), fetch: fetchOverride ?? globalThis.fetch, urlMap, allowInsecureLoopback, signal: signal ? AbortSignal.any([signal, timeout]) : timeout });
|
|
1513
|
+
} catch (_e) {
|
|
1514
|
+
res = { ok: false, reason: "resolve-failed" };
|
|
1515
|
+
}
|
|
1516
|
+
assertSendNotAborted(signal);
|
|
1517
|
+
// 2.8.3 setSeedRoutes: the routes may have changed while the listing was read. Use the set as it is now.
|
|
1518
|
+
const cfg = this.seedRoutes;
|
|
1519
|
+
if (!cfg?.all.length) return report([], "no-seed-routes"); // @t283 seed-select-reread
|
|
1520
|
+
const picked = listedSeeds(res, { recipient, publicKey, seeds: cfg.all, only: ask.only });
|
|
1521
|
+
return { ...report(picked.seeds, picked.reason), timeoutMs: cfg.timeoutMs };
|
|
1522
|
+
}
|
|
1523
|
+
|
|
1524
|
+
/** 2.8.3: post one envelope to the selected seeds only. Never rejects: { result, accepted, denied?, error? }. */
|
|
1525
|
+
async _deliverSeeds(envelope, seeds, { permit = null, signal = null, timeoutMs } = {}) {
|
|
1526
|
+
// trustedCarriers [] = no seed is trusted: reads use inbox auth v2, and no acceptance counts.
|
|
1527
|
+
const client = new CarrierClient({ keychain: this.keychain, carriers: [...seeds], trustedCarriers: [], fetch: this._liveSeedFetch() });
|
|
1528
|
+
try {
|
|
1529
|
+
const result = await client.deliver(envelope, { timeoutMs, permit, signal });
|
|
1530
|
+
return { result, accepted: result.all.filter((r) => r.ok).map((r) => r.carrier) };
|
|
1531
|
+
} catch (e) {
|
|
1532
|
+
if (isSendPermitDenied(e)) return { denied: e, result: e.partial ?? null, accepted: (e.partial?.accepted ?? []).map((a) => a.carrier) };
|
|
1533
|
+
return { error: e, result: { all: Array.isArray(e?.refusals) ? e.refusals : [] }, accepted: [] };
|
|
1534
|
+
}
|
|
1535
|
+
}
|
|
1536
|
+
|
|
1537
|
+
/**
|
|
1538
|
+
* 2.8.3: poll the configured seeds, apart from the fleet poller (startCarrierPolling). Sparse: each round
|
|
1539
|
+
* sleeps a jittered [0.5, 1.5) x intervalMs, then takes one wait=0 page from each seed in turn, under the
|
|
1540
|
+
* process-wide and per-origin seed limits. Each seed keeps its own cursor. A slow or empty seed costs at
|
|
1541
|
+
* most seedRoutes.timeoutMs and never touches the fleet poller or a send. Returns { stop, done }.
|
|
1542
|
+
*/
|
|
1543
|
+
startSeedPolling({ intervalMs = null, random = Math.random, sleep = sleepTimer, onError = null } = {}) {
|
|
1544
|
+
if (!this.seedRoutes?.all.length) throw new Error("no seed routes configured");
|
|
1545
|
+
if (this._seedPoller) return this._seedPoller;
|
|
1546
|
+
const every = intervalMs ?? this.seedRoutes.pollIntervalMs;
|
|
1547
|
+
if (!(Number.isFinite(every) && every >= SEED_MIN_POLL_INTERVAL_MS)) throw new TypeError(`startSeedPolling: intervalMs must be at least ${SEED_MIN_POLL_INTERVAL_MS} ms`);
|
|
1548
|
+
const controller = new AbortController();
|
|
1549
|
+
const { signal } = controller;
|
|
1550
|
+
const done = (async () => {
|
|
1551
|
+
while (!signal.aborted) {
|
|
1552
|
+
try { await sleep(Math.floor(every * (0.5 + random())), undefined, { signal }); } // @t283 seed-poll-sparse
|
|
1553
|
+
catch (_e) { break; }
|
|
1554
|
+
// Each round reads the routes as they are now (setSeedRoutes); null or empty polls nothing.
|
|
1555
|
+
for (const base of [...(this.seedRoutes?.all ?? [])]) {
|
|
1556
|
+
if (signal.aborted) break;
|
|
1557
|
+
if (!this._seedLive(base)) continue; // removed earlier in this round
|
|
1558
|
+
await this._pollSeedOnce(this._seedPollClient(), base, { signal, onError });
|
|
1559
|
+
}
|
|
1560
|
+
}
|
|
1561
|
+
})().catch(() => {});
|
|
1562
|
+
const handle = { stop: () => { controller.abort(); return done; }, done };
|
|
1563
|
+
// A loop that ends without stop() must not leave a dead handle that startSeedPolling would return again.
|
|
1564
|
+
done.then(() => { if (this._seedPoller === handle) this._seedPoller = null; }); // @t283 seed-poller-clear
|
|
1565
|
+
this._seedPoller = handle;
|
|
1566
|
+
return handle;
|
|
1567
|
+
}
|
|
1568
|
+
|
|
1569
|
+
/**
|
|
1570
|
+
* 2.8.3: replace the seed routes while the process runs (an app's route cache expired or refreshed). `value` is
|
|
1571
|
+
* checked like the constructor's `seedRoutes` (fleet = this.carriers), and a bad value throws and changes nothing.
|
|
1572
|
+
* The next send and the next poll round use the new set; a seed that is no longer in it gets no new request, also
|
|
1573
|
+
* none waiting on a permit. One already queued may still go within timeoutMs (it passed the check and waits in the
|
|
1574
|
+
* seed concurrency limits). Seeds that stay keep their cursors; the cursors of removed seeds are
|
|
1575
|
+
* dropped. null (or a set with no seeds) stops seed traffic: polling keeps running and polls nothing. Returns the
|
|
1576
|
+
* new normalized routes (null when off).
|
|
1577
|
+
*/
|
|
1578
|
+
setSeedRoutes(value) {
|
|
1579
|
+
const next = normalizeSeedRoutes(value, { fleet: this.carriers });
|
|
1580
|
+
const prev = this.seedRoutes?.all ?? [];
|
|
1581
|
+
this.seedRoutes = next;
|
|
1582
|
+
this._seedFetch = next ? makeSeedFetch({ allowPrivateUrls: next.allowPrivateUrls, lookup: next.lookup, fetch: next.fetch }) : null; // @t283 seed-fetch-rebuild
|
|
1583
|
+
const keep = new Set(next?.all ?? []);
|
|
1584
|
+
const fleet = new Set(this.carriers.map(routeKey));
|
|
1585
|
+
for (const old of prev) {
|
|
1586
|
+
if (keep.has(old) || fleet.has(old)) continue;
|
|
1587
|
+
try { this.mailbox.deleteCarrierCursor?.(old); } catch (_e) { this.metrics.inc("seed.cursor.drop-failed"); } // @t283 seed-cursor-drop
|
|
1588
|
+
}
|
|
1589
|
+
return next;
|
|
1590
|
+
}
|
|
1591
|
+
|
|
1592
|
+
/**
|
|
1593
|
+
* 2.8.3: true while `url` (a seed base, or a request URL `<base>/v1/...`) is in the current seed routes. Exact,
|
|
1594
|
+
* not a prefix: a direct seed https://r.example and a relayed seed https://r.example/e/<id> are different seeds.
|
|
1595
|
+
*/
|
|
1596
|
+
_seedLive(url) {
|
|
1597
|
+
const u = String(url);
|
|
1598
|
+
return (this.seedRoutes?.all ?? []).some((s) => u === s || u.startsWith(`${s}/v1/`));
|
|
1599
|
+
}
|
|
1600
|
+
|
|
1601
|
+
/** 2.8.3: the seed fetch, refusing any request to a seed that is no longer configured (setSeedRoutes). */
|
|
1602
|
+
_liveSeedFetch() {
|
|
1603
|
+
return (input, init) => (this._seedLive(String(input)) ? this._seedFetch(input, init) : Promise.reject(Object.assign(new Error("seed route removed"), { code: "seed-route-removed" }))); // @t283 seed-live-only
|
|
1604
|
+
}
|
|
1605
|
+
|
|
1606
|
+
stopSeedPolling() {
|
|
1607
|
+
const poller = this._seedPoller;
|
|
1608
|
+
this._seedPoller = null;
|
|
1609
|
+
return poller ? poller.stop() : Promise.resolve();
|
|
1610
|
+
}
|
|
1611
|
+
|
|
1612
|
+
/**
|
|
1613
|
+
* 2.8.3: one seed round now (one wait=0 page per seed). Returns how many NEW inbox rows the round stored
|
|
1614
|
+
* (quarantined rows included; duplicates and refused items are not counted). It is not a count of new mail
|
|
1615
|
+
* a user should see. Never throws.
|
|
1616
|
+
*/
|
|
1617
|
+
async pollSeedsOnce({ signal = null, onError = null } = {}) {
|
|
1618
|
+
let n = 0;
|
|
1619
|
+
for (const base of [...(this.seedRoutes?.all ?? [])]) {
|
|
1620
|
+
if (signal?.aborted) break;
|
|
1621
|
+
if (!this._seedLive(base)) continue;
|
|
1622
|
+
n += await this._pollSeedOnce(this._seedPollClient(), base, { signal, onError });
|
|
1623
|
+
}
|
|
1624
|
+
return n;
|
|
1625
|
+
}
|
|
1626
|
+
|
|
1627
|
+
_seedPollClient() {
|
|
1628
|
+
return new CarrierClient({ keychain: this.keychain, carriers: [...this.seedRoutes.all], trustedCarriers: [], fetch: this._liveSeedFetch() });
|
|
1629
|
+
}
|
|
1630
|
+
|
|
1631
|
+
async _pollSeedOnce(client, base, { signal = null, onError = null } = {}) {
|
|
1632
|
+
let cursor = this.mailbox.getCarrierCursors?.()?.[base] ?? 0;
|
|
1633
|
+
let stored = 0;
|
|
1634
|
+
// An app's onError that throws must not end the poller (RedTeam 77840f P3).
|
|
1635
|
+
const tell = (e) => { try { onError?.(e, { seed: base }); } catch (_x) { this.metrics.inc("seed.poll.onerror-threw"); } }; // @t283 seed-onerror-guard
|
|
1636
|
+
try {
|
|
1637
|
+
const timeoutMs = this.seedRoutes?.timeoutMs;
|
|
1638
|
+
if (!timeoutMs) return 0;
|
|
1639
|
+
const r = await client.fetchInbox(base, { since: cursor, waitS: 0, timeoutMs, signal }); // @t283 seed-poll-wait0
|
|
1640
|
+
const page = Array.isArray(r?.envelopes) ? r.envelopes.slice(0, CARRIER_INBOX_PAGE) : []; // @t283 seed-poll-page
|
|
1641
|
+
for (const item of page) {
|
|
1642
|
+
if (signal?.aborted) break;
|
|
1643
|
+
if (!this._seedLive(base)) break; // removed while its page was in flight: no cursor write, no more items // @t283 seed-cursor-stop
|
|
1644
|
+
if (!Number.isSafeInteger(item?.seq) || item.seq <= cursor || !item.envelope || typeof item.envelope !== "object") continue;
|
|
1645
|
+
const env = item.envelope;
|
|
1646
|
+
const held = () => typeof env.id === "string" && typeof env.sender === "string" && Boolean(this.mailbox.getInbound(env.id, env.sender));
|
|
1647
|
+
const before = held();
|
|
1648
|
+
try { await this._receive(JSON.stringify(env), null); if (!before && held()) stored++; } // @t283 seed-count-stored
|
|
1649
|
+
catch (e) { tell(e); }
|
|
1650
|
+
cursor = item.seq;
|
|
1651
|
+
this.mailbox.setCarrierCursor?.(base, cursor);
|
|
1652
|
+
this.metrics.inc(`seed.poll.${base}`);
|
|
1653
|
+
}
|
|
1654
|
+
} catch (e) {
|
|
1655
|
+
if (signal?.aborted) return stored;
|
|
1656
|
+
this.metrics.inc(`seed.poll.error.${base}`);
|
|
1657
|
+
tell(e);
|
|
1658
|
+
}
|
|
1659
|
+
return stored;
|
|
1660
|
+
}
|
|
1661
|
+
|
|
1662
|
+
async _deliverToPeer(envelope, peerIdStr, multiaddrStr, { guard = null, signal = null } = {}) {
|
|
1334
1663
|
const bytes = envelopeBodyBytes(envelope);
|
|
1335
1664
|
if (bytes > MAX_INLINE_BODY_BYTES) {
|
|
1336
1665
|
throw new BlobSizeError(`direct envelope ${bytes}B exceeds the ${MAX_INLINE_BODY_BYTES}B hard cap`, { size: bytes, max: MAX_INLINE_BODY_BYTES });
|
|
1337
1666
|
}
|
|
1338
1667
|
const { peerIdFromString, multiaddr } = await loadP2pRuntime();
|
|
1668
|
+
// Two checks keep the 2.7.0-spaces boundary count (peer-id import, multiaddr import); 2.8.1 loads both in one call.
|
|
1669
|
+
if (guard) { await guard({ phase: "dispatch", route: "direct" }); assertSendNotAborted(signal); }
|
|
1670
|
+
if (guard) { await guard({ phase: "dispatch", route: "direct" }); assertSendNotAborted(signal); }
|
|
1339
1671
|
const peerId = peerIdFromString(peerIdStr);
|
|
1340
1672
|
if (multiaddrStr) {
|
|
1341
1673
|
try { await this.node.peerStore.patch(peerId, { multiaddrs: [multiaddr(multiaddrStr)] }); } catch (_e) {}
|
|
1674
|
+
if (guard) { await guard({ phase: "dispatch", route: "direct" }); assertSendNotAborted(signal); }
|
|
1342
1675
|
}
|
|
1343
|
-
|
|
1676
|
+
let stream;
|
|
1677
|
+
try { stream = await this.node.dialProtocol(peerId, PILLAR_PROTOCOL); }
|
|
1678
|
+
catch (error) { assertSendNotAborted(signal); throw error; }
|
|
1344
1679
|
const line = JSON.stringify(envelope) + "\n";
|
|
1345
|
-
|
|
1346
|
-
|
|
1680
|
+
try {
|
|
1681
|
+
if (guard) { await guard({ phase: "dispatch", route: "direct" }); assertSendNotAborted(signal); } // @spaces-check send-permit-after-dial
|
|
1682
|
+
stream.send(new Uint8Array(Buffer.from(line, "utf8")));
|
|
1683
|
+
} catch (error) {
|
|
1684
|
+
try { stream.abort?.(error); } catch {}
|
|
1685
|
+
throw error;
|
|
1686
|
+
}
|
|
1687
|
+
try { await stream.close(); }
|
|
1688
|
+
catch (error) {
|
|
1689
|
+
if (signal?.aborted || error?.code === SEND_PERMIT_DENIED) {
|
|
1690
|
+
throw sendPermitDenied({ envelopeId: envelope.id, direct: { attempted: true, peerId: peerIdStr } });
|
|
1691
|
+
}
|
|
1692
|
+
throw error;
|
|
1693
|
+
}
|
|
1347
1694
|
// Not marked delivered here: a closed stream is not a receipt (2.5.3).
|
|
1348
1695
|
return { peerId: peerIdStr };
|
|
1349
1696
|
}
|
|
@@ -1373,9 +1720,12 @@ export class Pillar {
|
|
|
1373
1720
|
* we bypass DHT lookup. Also useful when a caller already has the peer's
|
|
1374
1721
|
* connection info out of band.
|
|
1375
1722
|
*/
|
|
1376
|
-
async sendDirect({ recipient, recipientPublicKey, recipientPeerIdStr, recipientMultiaddr, kind = "message", payload = {} }) {
|
|
1723
|
+
async sendDirect({ recipient, recipientPublicKey, recipientPeerIdStr, recipientMultiaddr, kind = "message", payload = {}, permit = null, signal = null }) {
|
|
1724
|
+
const guard = createSendGuard({ outboundPolicy: this.#outboundPolicy, permit, signal, context: { recipient, groupId: payload?._group?.id ?? null, op: payload?._group?.op ?? null } });
|
|
1377
1725
|
const subject = recipient;
|
|
1378
1726
|
await this._drainNoticeBacklog();
|
|
1727
|
+
// 2.8.2: the seal check follows the 2.8.1 notice drain (an await), so a revoke during the drain seals nothing.
|
|
1728
|
+
if (guard) { await guard({ phase: "seal", route: "direct" }); assertSendNotAborted(signal); } // @t282 seal-after-drain
|
|
1379
1729
|
const cr = this._applyRoute(subject, recipientPublicKey); // @rule C-route-direct
|
|
1380
1730
|
// The peer id and address name the subject's host. A rewritten destination has no coordinates this
|
|
1381
1731
|
// call can verify, so a redirect is refused before anything is sealed (RedTeam 1c5e7a P1).
|
|
@@ -1391,13 +1741,32 @@ export class Pillar {
|
|
|
1391
1741
|
}
|
|
1392
1742
|
this.mailbox.appendOutbound(envelope);
|
|
1393
1743
|
const { peerIdFromString, multiaddr } = await loadP2pRuntime();
|
|
1744
|
+
// Two checks keep the 2.7.0-spaces boundary count (peer-id import, multiaddr import); 2.8.1 loads both in one call.
|
|
1745
|
+
if (guard) { await guard({ phase: "dispatch", route: "direct" }); assertSendNotAborted(signal); }
|
|
1746
|
+
if (guard) { await guard({ phase: "dispatch", route: "direct" }); assertSendNotAborted(signal); }
|
|
1394
1747
|
const peerId = peerIdFromString(recipientPeerIdStr);
|
|
1395
1748
|
const ma = multiaddr(recipientMultiaddr);
|
|
1396
|
-
await this.node.peerStore.patch(peerId, { multiaddrs: [ma] });
|
|
1397
|
-
|
|
1749
|
+
try { await this.node.peerStore.patch(peerId, { multiaddrs: [ma] }); }
|
|
1750
|
+
catch (error) { assertSendNotAborted(signal); throw error; }
|
|
1751
|
+
if (guard) { await guard({ phase: "dispatch", route: "direct" }); assertSendNotAborted(signal); }
|
|
1752
|
+
let stream;
|
|
1753
|
+
try { stream = await this.node.dialProtocol(peerId, PILLAR_PROTOCOL); }
|
|
1754
|
+
catch (error) { assertSendNotAborted(signal); throw error; }
|
|
1398
1755
|
const line = JSON.stringify(envelope) + "\n";
|
|
1399
|
-
|
|
1400
|
-
|
|
1756
|
+
try {
|
|
1757
|
+
if (guard) { await guard({ phase: "dispatch", route: "direct" }); assertSendNotAborted(signal); } // @spaces-check send-permit-after-dial
|
|
1758
|
+
stream.send(new Uint8Array(Buffer.from(line, "utf8")));
|
|
1759
|
+
} catch (error) {
|
|
1760
|
+
try { stream.abort?.(error); } catch {}
|
|
1761
|
+
throw error;
|
|
1762
|
+
}
|
|
1763
|
+
try { await stream.close(); }
|
|
1764
|
+
catch (error) {
|
|
1765
|
+
if (signal?.aborted || error?.code === SEND_PERMIT_DENIED) {
|
|
1766
|
+
throw sendPermitDenied({ envelopeId: envelope.id, direct: { attempted: true, peerId: recipientPeerIdStr } });
|
|
1767
|
+
}
|
|
1768
|
+
throw error;
|
|
1769
|
+
}
|
|
1401
1770
|
// Not marked delivered: a closed stream is not a receipt (2.5.3).
|
|
1402
1771
|
return envelope;
|
|
1403
1772
|
}
|
|
@@ -1500,47 +1869,160 @@ export class Pillar {
|
|
|
1500
1869
|
* sealed to its recipient alone. Final states: `sent` (with the envelope
|
|
1501
1870
|
* id) or `dropped` (with a reason). A failed attempt stays `queued`.
|
|
1502
1871
|
* A frozen group sends only its equivocation proof.
|
|
1872
|
+
* 2.8.2: a queued row keeps one envelope. Its id is claimed on the row
|
|
1873
|
+
* before the first send; a retry dispatches the stored outbox row again.
|
|
1874
|
+
* A moved route, an erased row or an envelope over 23 h old seals a new
|
|
1875
|
+
* one, once per attempt, and the old outbox row becomes `superseded`, as
|
|
1876
|
+
* does the pending row of a dropped item.
|
|
1503
1877
|
* Returns [{ id, groupId, to, op, state, envelopeId?, reason? }].
|
|
1504
1878
|
*/
|
|
1505
|
-
|
|
1879
|
+
reloadGroupV2(groupId) {
|
|
1880
|
+
loadGroupForCommand(this.groupsV2.store, groupId);
|
|
1881
|
+
this.groupsV2.records.delete(groupId);
|
|
1882
|
+
return this.groupsV2.state(groupId);
|
|
1883
|
+
}
|
|
1884
|
+
|
|
1885
|
+
/**
|
|
1886
|
+
* 2.8.2 r3 (Lead d79649): send a stored pending direct envelope again, byte for byte, for an app that owns its
|
|
1887
|
+
* retries (send() has no resender for a `confirmed: false` result). Every send() gate and the continuity route run
|
|
1888
|
+
* again; a trusted acceptance marks the row delivered. Returns send()'s result, or `{ resent: false, reason }` and
|
|
1889
|
+
* dispatches nothing. reason: completed (delivered or acked), erased, superseded, rerouted (the route no longer
|
|
1890
|
+
* lands on the stored recipient), expired (over 23 h old: a carrier refuses it after 24 h), missing, or group (a
|
|
1891
|
+
* group row. syncGroupV2 retries only its own queued rows; nothing retries a sendGroupV2 member result with
|
|
1892
|
+
* confirmed:false, and a plain send() would carry no group context to the permit). On rerouted or expired the
|
|
1893
|
+
* caller decides whether to send anew.
|
|
1894
|
+
*/
|
|
1895
|
+
async resendOutbound(envelopeId, { recipientPublicKey = null, resolveTimeoutMs = 5000, permit = null, signal = null } = {}) {
|
|
1896
|
+
const row = this.mailbox.getOutbound(envelopeId);
|
|
1897
|
+
// Settled before any gate runs: missing, completed, erased or superseded (resendBlocked checks the route only for a
|
|
1898
|
+
// live pending row, and those are not answered here).
|
|
1899
|
+
if (!row || isErasedRow(row) || row.status !== "pending" || attemptSettled(row)) return { resent: false, reason: resendBlocked(row, null) };
|
|
1900
|
+
if (row.group_id || row.group_msg_id) return { resent: false, reason: "group" }; // @t282 resend-public
|
|
1901
|
+
const stored = JSON.parse(row.envelope_json);
|
|
1902
|
+
// 2.8.2 r4 (RedTeam 87e556 P3): local expiry needs no key and no route, so it is named before send() looks either up.
|
|
1903
|
+
if (attemptExpired(stored)) return { resent: false, reason: "expired" }; // @t282 resend-expiry-first
|
|
1904
|
+
const r = await this.send({ recipient: stored.recipient, recipientPublicKey, kind: stored.kind, resolveTimeoutMs, permit, signal, [RESEND]: envelopeId });
|
|
1905
|
+
return r?.[RESEND] ? { resent: false, reason: r[RESEND] } : r; // @t282 resend-public
|
|
1906
|
+
}
|
|
1907
|
+
|
|
1908
|
+
async syncGroupV2({ groupId = null, resolveTimeoutMs = 5000, manifestPayload = null, permit = null, signal = null } = {}) {
|
|
1909
|
+
if (manifestPayload != null && typeof manifestPayload !== "function") throw new TypeError("manifestPayload must be a function");
|
|
1910
|
+
let stopped = false;
|
|
1506
1911
|
const ZERO = "0".repeat(64);
|
|
1507
1912
|
const out = [];
|
|
1913
|
+
const owned = ownedGroupV2Items(this.mailbox);
|
|
1508
1914
|
for (const q of this.mailbox.queuedGroupV2Sends(groupId)) {
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
if (
|
|
1512
|
-
|
|
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; }
|
|
1915
|
+
// 2.8.2 r4 (RedTeam 87e556 P2): another live pass owns this item (it may have claimed an id and not yet stored the
|
|
1916
|
+
// row). This pass reads, writes and sends nothing for it.
|
|
1917
|
+
if (owned.has(q.id)) continue; // @t282 claim-owner
|
|
1918
|
+
owned.add(q.id);
|
|
1537
1919
|
try {
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1920
|
+
// 2.8.3 (RedTeam 6079d0 P3): `q` is this pass's snapshot. Another pass may have sent, dropped or retried the item
|
|
1921
|
+
// while this one awaited an earlier item, so read the row again now that this pass owns it.
|
|
1922
|
+
const fresh = this.mailbox.queuedGroupV2Sends(q.group_id).find((x) => x.id === q.id);
|
|
1923
|
+
if (!fresh) continue; // no longer queued // @t282 fresh-row
|
|
1924
|
+
// 2.8.2 r2 (RedTeam 822828 P2): one recoverable attempt per queue item. Its envelope id is saved on the
|
|
1925
|
+
// item before the first send, and later passes dispatch that stored envelope again (send() RESEND).
|
|
1926
|
+
let attemptId = fresh.envelope_id ?? null; // 2.8.3: the fresh row's attempt, not the snapshot's
|
|
1927
|
+
const attemptRow = () => (attemptId ? this.mailbox.getOutbound(attemptId) : null);
|
|
1928
|
+
const done = (state, extra = {}) => {
|
|
1929
|
+
// 2.8.2 r4 (RedTeam 87e556 P2): write only while the item is still queued under this pass's attempt. A stale
|
|
1930
|
+
// pass (another process, or a snapshot read before another pass finished) writes and reports nothing.
|
|
1931
|
+
const write = { ...extra };
|
|
1932
|
+
write.attempt = attemptId; // @t282 owner-write
|
|
1933
|
+
if (!this.mailbox.markGroupV2Send(q.id, state, write)) return;
|
|
1934
|
+
// A dropped item leaves no live pending row: nothing would ever send or settle it.
|
|
1935
|
+
if (state === "dropped" && attemptId) this.mailbox.markOutboundSuperseded(attemptId); // @t282 retry-supersede
|
|
1936
|
+
out.push({ id: q.id, groupId: q.group_id, to: q.recipient, op: q.op, state, ...extra });
|
|
1937
|
+
};
|
|
1938
|
+
// Receipts first: the attempt already completed (a trusted acceptance, a denial's partial result, a pass cut short,
|
|
1939
|
+
// or the recipient's ack). An erased row keeps its status and ack.
|
|
1940
|
+
if (attemptSettled(attemptRow())) { done("sent", { envelopeId: attemptId }); continue; } // @t282 retry-reconcile
|
|
1941
|
+
if (stopped) { done("dropped", { reason: SEND_PERMIT_DENIED }); continue; }
|
|
1942
|
+
let rec = null;
|
|
1943
|
+
if (this.groupsV2.store.has(q.group_id)) {
|
|
1944
|
+
try { rec = this.groupsV2.store.load(q.group_id); } catch (e) { done("dropped", { reason: `store: ${e.message}` }); continue; }
|
|
1945
|
+
}
|
|
1946
|
+
if (rec?.frozen && q.op !== "equivocation") { done("dropped", { reason: "frozen" }); continue; } // @rule Q-sync-frozen-only-proof
|
|
1947
|
+
const msgId = `gm-${randomBytes(16).toString("hex")}`;
|
|
1948
|
+
const tag = rec
|
|
1949
|
+
? buildGroupTagV2(rec, { op: q.op, msgId })
|
|
1950
|
+
: { v: 2, id: q.group_id, name: "", members: [], msgId, op: q.op, mv: { version: 0, hash: ZERO } };
|
|
1951
|
+
let text;
|
|
1952
|
+
if (q.op === "manifest.request") {
|
|
1953
|
+
tag.want = { from: q.want_from, to: q.want_to };
|
|
1954
|
+
text = `asks for group manifests ${q.want_from}..${q.want_to ?? "newest"}`;
|
|
1955
|
+
} else if (q.op === "manifest") {
|
|
1956
|
+
const m = rec?.chain.find((x) => manifestHashOf(x) === q.manifest_hash);
|
|
1957
|
+
if (!m) { done("dropped", { reason: "manifest-not-held" }); continue; }
|
|
1958
|
+
tag.manifest = m;
|
|
1959
|
+
text = `group manifest v${m.version} (${m.transition.action})`;
|
|
1960
|
+
} else if (q.op === "equivocation") {
|
|
1961
|
+
const m = rec?.frozen?.manifests.find((x) => manifestHashOf(x) === q.manifest_hash);
|
|
1962
|
+
if (!m) { done("dropped", { reason: "proof-not-held" }); continue; }
|
|
1963
|
+
tag.manifest = m;
|
|
1964
|
+
tag.conflictsWith = q.conflicts_with;
|
|
1965
|
+
text = `the group admin signed two versions ${m.version}: this group is frozen`;
|
|
1966
|
+
} else { done("dropped", { reason: `op ${q.op} is not queued` }); continue; }
|
|
1967
|
+
const key = q.recipient_key ?? this.addressBook?.get(q.recipient)?.publicKey;
|
|
1968
|
+
if (!key) { done("dropped", { reason: "no key for the recipient" }); continue; }
|
|
1969
|
+
try {
|
|
1970
|
+
const guard = createSendGuard({ outboundPolicy: this.#outboundPolicy, permit, signal, context: { recipient: q.recipient, groupId: q.group_id, op: q.op } });
|
|
1971
|
+
if (guard) { await guard({ phase: "seal", route: "group" }); assertSendNotAborted(signal); }
|
|
1972
|
+
let extras = {};
|
|
1973
|
+
if (q.op === "manifest" && manifestPayload) {
|
|
1974
|
+
const freeze = (v) => { if (v && typeof v === "object") { for (const x of Object.values(v)) freeze(x); Object.freeze(v); } return v; };
|
|
1975
|
+
const context = freeze({ groupId: q.group_id, recipient: q.recipient, op: q.op, manifest: tag.manifest, chain: rec.chain, head: rec.head });
|
|
1976
|
+
try {
|
|
1977
|
+
const value = await manifestPayload(context);
|
|
1978
|
+
assertSendNotAborted(signal);
|
|
1979
|
+
extras = boundedJsonRecord(value, 32768);
|
|
1980
|
+
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
|
|
1981
|
+
} catch {
|
|
1982
|
+
assertSendNotAborted(signal);
|
|
1983
|
+
throw Object.assign(new Error("manifest payload unavailable or invalid"), { code: "manifest-payload-unavailable" });
|
|
1984
|
+
}
|
|
1985
|
+
}
|
|
1986
|
+
let r = null;
|
|
1987
|
+
const row = attemptRow();
|
|
1988
|
+
// The checks above ran again: store, frozen, manifest or proof held, key, the gate, and manifestPayload (a throw sends
|
|
1989
|
+
// nothing). send() runs all its gates and the continuity route again, then dispatches the stored bytes (their extras
|
|
1990
|
+
// are the first attempt's), or returns `{ [RESEND]: why }` (resendBlocked) and dispatches nothing.
|
|
1991
|
+
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
|
|
1992
|
+
if (r?.[RESEND]) r = null; // completed, erased, superseded, moved route, expired (23 h) or missing
|
|
1993
|
+
if (!r) {
|
|
1994
|
+
const old = attemptId ? this.mailbox.getOutbound(attemptId) : null;
|
|
1995
|
+
// 2.8.2 r3 (RedTeam bcdc6c P2): a completion that landed during the awaited gates or resend is this item's
|
|
1996
|
+
// result. Reconcile before any replacement; there is no await between this read and the claim.
|
|
1997
|
+
if (attemptSettled(old)) { done("sent", { envelopeId: attemptId }); continue; } // @t282 resend-completed
|
|
1998
|
+
// Claim before mint (RedTeam bcdc6c): a value swap on the queue item, so two passes never both seal an attempt for
|
|
1999
|
+
// it; the pass that loses writes nothing for the item. An id with no stored row (send() threw before its append)
|
|
2000
|
+
// was never sealed, so it is kept. Otherwise one new attempt replaces the stored one.
|
|
2001
|
+
if (!attemptId || old) {
|
|
2002
|
+
const next = mkEnvelopeId();
|
|
2003
|
+
if (!this.mailbox.claimGroupV2Attempt(q.id, attemptId, next)) continue; // @t282 claim-before-mint
|
|
2004
|
+
if (old) this.mailbox.markOutboundSuperseded(attemptId); // a new attempt replaces the stored one // @t282 retry-supersede
|
|
2005
|
+
attemptId = next; // an id that has a stored row is never sealed again // @t282 retry-save-id
|
|
2006
|
+
}
|
|
2007
|
+
r = await this.send({ recipient: q.recipient, recipientPublicKey: key, kind: "message", payload: { text, ...extras, _group: tag }, resolveTimeoutMs, permit, signal, envelopeId: attemptId });
|
|
2008
|
+
}
|
|
2009
|
+
// 2.8.2 trustedCarriers: no trusted carrier accepted it, so the queued send stays queued and is sent again. Read the
|
|
2010
|
+
// row first: the recipient's ack may have landed during the send.
|
|
2011
|
+
if (this.trustedCarriers && r.confirmed === false && attemptSettled(attemptRow())) { done("sent", { envelopeId: attemptId }); continue; } // @t282 untrusted-reconcile
|
|
2012
|
+
// 2.8.3 (RedTeam 6079d0 P3): this queue write names its attempt too (the owner check), as done() does.
|
|
2013
|
+
const untrusted = { reason: "no trusted carrier accepted" };
|
|
2014
|
+
untrusted.attempt = attemptId; // @t282 owner-write
|
|
2015
|
+
if (this.trustedCarriers && r.confirmed === false) { if (this.mailbox.markGroupV2Send(q.id, "queued", untrusted)) out.push({ id: q.id, groupId: q.group_id, to: q.recipient, op: q.op, state: "queued", reason: untrusted.reason }); continue; } // @t282 sync-untrusted
|
|
2016
|
+
done("sent", { envelopeId: r.envelope.id }); // @rule Q-sync-marks-sent
|
|
2017
|
+
} catch (e) {
|
|
2018
|
+
// Only a real denial drops the queue; any other failure, whatever code it names, stays queued for retry.
|
|
2019
|
+
const denied = isSendPermitDenied(e), state = denied ? "dropped" : "queued";
|
|
2020
|
+
stopped = denied;
|
|
2021
|
+
// A denial drops the item (the documented contract). When send() counted an acceptance from the denial's partial
|
|
2022
|
+
// result, the outbox row stays delivered: done() supersedes only a pending row.
|
|
2023
|
+
done(state, { reason: denied ? SEND_PERMIT_DENIED : e.message, ...(e.partial ? { partial: e.partial } : {}) });
|
|
2024
|
+
}
|
|
2025
|
+
} finally { owned.delete(q.id); }
|
|
1544
2026
|
}
|
|
1545
2027
|
this.metrics.inc("group-v2.sync", out.length);
|
|
1546
2028
|
return out;
|