@aglyn/shared-util-email 1.0.0-beta.200 → 1.0.0-beta.202
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/package.json +3 -3
- package/src/index.d.ts +6 -0
- package/src/index.js +16 -0
- package/src/index.js.map +1 -1
- package/src/lib/email-deliverability.d.ts +200 -0
- package/src/lib/email-deliverability.js +461 -0
- package/src/lib/email-deliverability.js.map +1 -0
- package/src/lib/email-delivery-events.d.ts +16 -39
- package/src/lib/email-delivery-events.js +28 -12
- package/src/lib/email-delivery-events.js.map +1 -1
- package/src/lib/email-linkify.d.ts +24 -0
- package/src/lib/email-linkify.js +73 -0
- package/src/lib/email-linkify.js.map +1 -0
- package/src/lib/email-render.js +6 -1
- package/src/lib/email-render.js.map +1 -1
- package/src/lib/hosted-page-screen.d.ts +60 -0
- package/src/lib/hosted-page-screen.js +314 -0
- package/src/lib/hosted-page-screen.js.map +1 -0
- package/src/lib/mail-bounce.d.ts +42 -0
- package/src/lib/mail-bounce.js +108 -0
- package/src/lib/mail-bounce.js.map +1 -0
- package/src/lib/mail-gateway.d.ts +161 -0
- package/src/lib/mail-gateway.js +330 -0
- package/src/lib/mail-gateway.js.map +1 -0
- package/src/lib/outbound-phishing-screen.d.ts +248 -0
- package/src/lib/outbound-phishing-screen.js +769 -0
- package/src/lib/outbound-phishing-screen.js.map +1 -0
- package/src/lib/outbound-screen-gate.d.ts +95 -0
- package/src/lib/outbound-screen-gate.js +109 -0
- package/src/lib/outbound-screen-gate.js.map +1 -0
- package/src/lib/send-email.d.ts +79 -1
- package/src/lib/send-email.js +153 -10
- package/src/lib/send-email.js.map +1 -1
- package/src/lib/sending-domain.d.ts +22 -1
- package/src/lib/sending-domain.js +0 -95
- package/src/lib/sending-domain.js.map +1 -1
- package/src/lib/system-email-catalog.js +400 -0
- package/src/lib/system-email-catalog.js.map +1 -1
- package/src/lib/text-email-html.d.ts +38 -0
- package/src/lib/text-email-html.js +3 -44
- package/src/lib/text-email-html.js.map +1 -1
package/src/lib/send-email.js
CHANGED
|
@@ -24,6 +24,9 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
24
24
|
import { renderTextEmailHtml } from "./text-email-html.js";
|
|
25
25
|
import { sendingIdentityRefusal, pooledMarketingRefusal } from "./sending-domain.js";
|
|
26
26
|
import { appendUnsubscribeHtml, appendUnsubscribeText, getMarketingSendGate, isMarketingMessage, unsubscribeHeaders } from "./marketing-send.js";
|
|
27
|
+
import { EMAIL_DELIVERABILITY_PREFLIGHT_TIMEOUT_MS, getEmailDeliverabilityPreflight } from "./email-deliverability.js";
|
|
28
|
+
import { bareSenderAddress } from "./email-delivery-events.js";
|
|
29
|
+
import { screenTenantMessage } from "./outbound-screen-gate.js";
|
|
27
30
|
export const RESEND_SEND_ENDPOINT = 'https://api.resend.com/emails';
|
|
28
31
|
/**
|
|
29
32
|
* The `context` tag, attached to every send (AGL-2407).
|
|
@@ -146,6 +149,83 @@ export const RESEND_SEND_ENDPOINT = 'https://api.resend.com/emails';
|
|
|
146
149
|
const reason = sendFailureReason(result);
|
|
147
150
|
return reason === 'rate-limited' || reason === 'frequency-capped';
|
|
148
151
|
}
|
|
152
|
+
/**
|
|
153
|
+
* Who a message is for, as the deliverability preflight reads it
|
|
154
|
+
* (AGL-3328): `bulk` for anything a control may already refuse — marketing
|
|
155
|
+
* by either of its two marks, a campaign, a resumable sweep — and
|
|
156
|
+
* `transactional` for the rest, which a gateway hold never touches.
|
|
157
|
+
*
|
|
158
|
+
* Derived from what a sender already declares, for the reason
|
|
159
|
+
* `isMarketingMessage` is: a label callers had to remember would be
|
|
160
|
+
* forgotten by the one that matters, and the permissive answer is the one a
|
|
161
|
+
* forgotten caller gets.
|
|
162
|
+
*/ export function emailSendPurpose(options) {
|
|
163
|
+
var _options_headers;
|
|
164
|
+
if (isMarketingMessage(options)) return 'bulk';
|
|
165
|
+
if ((_options_headers = options.headers) == null ? void 0 : _options_headers['List-Unsubscribe']) return 'bulk';
|
|
166
|
+
return isRefusablePriority(resolveSendPriority(options.context, options.priority)) ? 'bulk' : 'transactional';
|
|
167
|
+
}
|
|
168
|
+
/** The preflight's answer, or `null` when none is installed, it failed or it ran out of time. */ async function askDeliverabilityPreflight(request, label) {
|
|
169
|
+
const preflight = getEmailDeliverabilityPreflight();
|
|
170
|
+
if (!preflight) return null;
|
|
171
|
+
let timer;
|
|
172
|
+
try {
|
|
173
|
+
return await Promise.race([
|
|
174
|
+
preflight(request),
|
|
175
|
+
new Promise((resolve)=>{
|
|
176
|
+
var _timer_unref;
|
|
177
|
+
timer = setTimeout(()=>{
|
|
178
|
+
console.warn(`${label} deliverability preflight timed out — allowing`);
|
|
179
|
+
resolve(null);
|
|
180
|
+
}, EMAIL_DELIVERABILITY_PREFLIGHT_TIMEOUT_MS);
|
|
181
|
+
timer == null ? void 0 : (_timer_unref = timer.unref) == null ? void 0 : _timer_unref.call(timer);
|
|
182
|
+
})
|
|
183
|
+
]);
|
|
184
|
+
} catch (error) {
|
|
185
|
+
// Fails OPEN, the governor's posture: an outage on the control must not
|
|
186
|
+
// become an outage on the mail.
|
|
187
|
+
console.error(`${label} deliverability preflight failed — allowing`, error);
|
|
188
|
+
return null;
|
|
189
|
+
} finally{
|
|
190
|
+
if (timer) clearTimeout(timer);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* The send seam's half of the outbound phishing screen (AGL-3356): every
|
|
195
|
+
* message a SITE sends whose identity carries the workspace
|
|
196
|
+
* `hostSendingIdentity` stamped, through {@link screenTenantMessage} — the
|
|
197
|
+
* pure screen, its tiers, and the installed review store. `null` when the
|
|
198
|
+
* message may go; fails open, as that function documents.
|
|
199
|
+
*/ export async function askOutboundScreen(options, label = 'email') {
|
|
200
|
+
var _options_fromName, _ref, _options_replyTo, _options_context, _options_releasedReviewId;
|
|
201
|
+
var _options_sendingIdentity, _options_sendingIdentity1;
|
|
202
|
+
const workspace = (_options_sendingIdentity = options.sendingIdentity) == null ? void 0 : _options_sendingIdentity.workspace;
|
|
203
|
+
if (options.audience !== 'tenant' || !(workspace == null ? void 0 : workspace.hostId)) return null;
|
|
204
|
+
const refusal = await screenTenantMessage({
|
|
205
|
+
workspace,
|
|
206
|
+
subject: options.subject,
|
|
207
|
+
fromName: (_options_fromName = options.fromName) != null ? _options_fromName : null,
|
|
208
|
+
// The resolved address, never anything the caller passed: the only
|
|
209
|
+
// `From:` this message can leave on (AGL-3362).
|
|
210
|
+
fromAddress: (_ref = (_options_sendingIdentity1 = options.sendingIdentity) == null ? void 0 : _options_sendingIdentity1.from) != null ? _ref : null,
|
|
211
|
+
replyTo: (_options_replyTo = options.replyTo) != null ? _options_replyTo : null,
|
|
212
|
+
bodies: [
|
|
213
|
+
options.text,
|
|
214
|
+
options.html
|
|
215
|
+
],
|
|
216
|
+
// A marketing message is never owed, whatever it declares.
|
|
217
|
+
owed: Boolean(options.owedFor) && !isMarketingMessage(options),
|
|
218
|
+
context: (_options_context = options.context) != null ? _options_context : null,
|
|
219
|
+
releasedReviewId: (_options_releasedReviewId = options.releasedReviewId) != null ? _options_releasedReviewId : null
|
|
220
|
+
}, label);
|
|
221
|
+
if (!refusal) return null;
|
|
222
|
+
console.warn(`${label} not sent — ${refusal.detail}`);
|
|
223
|
+
return {
|
|
224
|
+
sent: false,
|
|
225
|
+
reason: 'held-for-review',
|
|
226
|
+
detail: refusal.detail
|
|
227
|
+
};
|
|
228
|
+
}
|
|
149
229
|
/**
|
|
150
230
|
* Reads the email environment.
|
|
151
231
|
*
|
|
@@ -238,8 +318,8 @@ function normalizeRecipients(to) {
|
|
|
238
318
|
* `{ sent: false, reason: 'unconfigured' }` rather than failing, so local and
|
|
239
319
|
* preview environments keep working without a Resend account.
|
|
240
320
|
*/ export async function sendEmail(options) {
|
|
241
|
-
var _ref, _ref1, _ref2, _options_text;
|
|
242
|
-
var _options_sendingIdentity, _options_marketing, _options_marketing1, _options_headers;
|
|
321
|
+
var _ref, _ref1, _ref2, _ref3, _ref4, _options_text;
|
|
322
|
+
var _options_sendingIdentity, _options_sendingIdentity1, _options_marketing, _preflight_refused, _preflight_held, _options_marketing1, _options_marketing2, _options_headers;
|
|
243
323
|
const { apiKey, from: configuredFrom } = getEmailConfig();
|
|
244
324
|
const label = options.context ? `${options.context} email` : 'email';
|
|
245
325
|
/*
|
|
@@ -258,7 +338,9 @@ function normalizeRecipients(to) {
|
|
|
258
338
|
console.warn(`${label} refused — ${identityRefusal.message}`);
|
|
259
339
|
return {
|
|
260
340
|
sent: false,
|
|
261
|
-
|
|
341
|
+
// A suspension is not a DNS state, and the merchant reading the
|
|
342
|
+
// failure has nothing to finish — so it is named for what it is.
|
|
343
|
+
reason: identityRefusal.code === 'workspace-suspended' ? 'suspended' : 'unverified-domain',
|
|
262
344
|
detail: identityRefusal.message
|
|
263
345
|
};
|
|
264
346
|
}
|
|
@@ -300,7 +382,7 @@ function normalizeRecipients(to) {
|
|
|
300
382
|
reason: 'unconfigured'
|
|
301
383
|
};
|
|
302
384
|
}
|
|
303
|
-
|
|
385
|
+
let to = normalizeRecipients(options.to);
|
|
304
386
|
if (!to.length) {
|
|
305
387
|
console.warn(`${label} skipped — no valid recipient address`);
|
|
306
388
|
return {
|
|
@@ -309,6 +391,67 @@ function normalizeRecipients(to) {
|
|
|
309
391
|
};
|
|
310
392
|
}
|
|
311
393
|
/*
|
|
394
|
+
* THE OUTBOUND PHISHING SCREEN (AGL-3356).
|
|
395
|
+
*
|
|
396
|
+
* Asked for every message a SITE sends whose identity came through
|
|
397
|
+
* `hostSendingIdentity` — which stamps the workspace on it — so one check
|
|
398
|
+
* covers every tenant sender, first-party or marketplace, without any of
|
|
399
|
+
* them calling it. See `outbound-screen-gate.ts`.
|
|
400
|
+
*
|
|
401
|
+
* Ahead of the preflight and every other gate: a message that must not
|
|
402
|
+
* leave is decided before anything is spent on who receives it.
|
|
403
|
+
*/ const screenRefusal = await askOutboundScreen(options, label);
|
|
404
|
+
if (screenRefusal) return screenRefusal;
|
|
405
|
+
/*
|
|
406
|
+
* THE DELIVERABILITY PREFLIGHT (AGL-3328).
|
|
407
|
+
*
|
|
408
|
+
* Asked before every other gate, because its refusal is the most final: a
|
|
409
|
+
* recipient whose domain takes no mail is not a recipient this message or
|
|
410
|
+
* any other can reach, and spending the marketing gate's reads or the
|
|
411
|
+
* governor's hourly budget deciding more about them would be spending it
|
|
412
|
+
* on a bounce. A recipient behind a gateway that refused this sending
|
|
413
|
+
* domain twice is held — for bulk mail only; the purpose decides that,
|
|
414
|
+
* and the preflight is told it.
|
|
415
|
+
*
|
|
416
|
+
* A multi-recipient message drops the refused and held recipients and goes
|
|
417
|
+
* to the rest: one colleague's dead address must not stop the others'
|
|
418
|
+
* notification.
|
|
419
|
+
*/ const sendingAddress = bareSenderAddress(from);
|
|
420
|
+
const preflight = await askDeliverabilityPreflight({
|
|
421
|
+
recipients: to.map((address)=>address.toLowerCase()),
|
|
422
|
+
purpose: emailSendPurpose(options),
|
|
423
|
+
sendingDomain: sendingAddress ? sendingAddress.slice(sendingAddress.lastIndexOf('@') + 1) : null,
|
|
424
|
+
sendingSource: (_ref1 = (_options_sendingIdentity1 = options.sendingIdentity) == null ? void 0 : _options_sendingIdentity1.source) != null ? _ref1 : 'platform',
|
|
425
|
+
context: options.context,
|
|
426
|
+
hostId: (_ref2 = (_options_marketing = options.marketing) == null ? void 0 : _options_marketing.hostId) != null ? _ref2 : null
|
|
427
|
+
}, label);
|
|
428
|
+
if (preflight && (((_preflight_refused = preflight.refused) == null ? void 0 : _preflight_refused.length) || ((_preflight_held = preflight.held) == null ? void 0 : _preflight_held.length))) {
|
|
429
|
+
var _preflight_refused1, _preflight_held1;
|
|
430
|
+
const stopped = new Set([
|
|
431
|
+
...(_preflight_refused1 = preflight.refused) != null ? _preflight_refused1 : [],
|
|
432
|
+
...(_preflight_held1 = preflight.held) != null ? _preflight_held1 : []
|
|
433
|
+
].map((entry)=>{
|
|
434
|
+
var _ref;
|
|
435
|
+
return String((_ref = entry == null ? void 0 : entry.email) != null ? _ref : '').toLowerCase();
|
|
436
|
+
}));
|
|
437
|
+
const remaining = to.filter((address)=>!stopped.has(address.toLowerCase()));
|
|
438
|
+
if (!remaining.length) {
|
|
439
|
+
var _ref5, _ref6;
|
|
440
|
+
var _preflight_refused2, _preflight_held2;
|
|
441
|
+
const refused = (_preflight_refused2 = preflight.refused) == null ? void 0 : _preflight_refused2[0];
|
|
442
|
+
const held = (_preflight_held2 = preflight.held) == null ? void 0 : _preflight_held2[0];
|
|
443
|
+
const detail = (_ref5 = (_ref6 = refused == null ? void 0 : refused.reason) != null ? _ref6 : held == null ? void 0 : held.reason) != null ? _ref5 : 'The recipient cannot receive this message.';
|
|
444
|
+
console.warn(`${label} not sent — ${detail}`);
|
|
445
|
+
return {
|
|
446
|
+
sent: false,
|
|
447
|
+
reason: refused ? 'undeliverable' : 'gateway-held',
|
|
448
|
+
detail
|
|
449
|
+
};
|
|
450
|
+
}
|
|
451
|
+
console.warn(`${label} — ${to.length - remaining.length} of ${to.length} recipients ` + 'dropped by the deliverability preflight');
|
|
452
|
+
to = remaining;
|
|
453
|
+
}
|
|
454
|
+
/*
|
|
312
455
|
* THE MARKETING GATE.
|
|
313
456
|
*
|
|
314
457
|
* Everything a marketing message owes, asked once, here — because the four
|
|
@@ -337,8 +480,8 @@ function normalizeRecipients(to) {
|
|
|
337
480
|
* It falls back to `unsubscribeUrl` for a caller that minted one link and
|
|
338
481
|
* named no page, which is the only shape that was ever possible before the
|
|
339
482
|
* gate minted the pair.
|
|
340
|
-
*/ let unsubscribeUrl = (
|
|
341
|
-
let oneClickUrl = (
|
|
483
|
+
*/ let unsubscribeUrl = (_ref3 = (_options_marketing1 = options.marketing) == null ? void 0 : _options_marketing1.unsubscribeUrl) != null ? _ref3 : '';
|
|
484
|
+
let oneClickUrl = (_ref4 = (_options_marketing2 = options.marketing) == null ? void 0 : _options_marketing2.oneClickUrl) != null ? _ref4 : '';
|
|
342
485
|
if (options.marketing) {
|
|
343
486
|
if (to.length !== 1) {
|
|
344
487
|
// Not a delivery outcome — a caller error, and one that would put the
|
|
@@ -505,7 +648,7 @@ function normalizeRecipients(to) {
|
|
|
505
648
|
*/ const text = unsubscribeUrl ? appendUnsubscribeText((_options_text = options.text) != null ? _options_text : '', unsubscribeUrl) : options.text;
|
|
506
649
|
const html = unsubscribeUrl ? options.html ? appendUnsubscribeHtml(options.html, unsubscribeUrl) : renderTextEmailHtml(text != null ? text : '', options.subject) : options.html;
|
|
507
650
|
try {
|
|
508
|
-
var
|
|
651
|
+
var _ref7;
|
|
509
652
|
const response = await postResendEmail(apiKey, _extends({
|
|
510
653
|
from,
|
|
511
654
|
to,
|
|
@@ -572,15 +715,15 @@ function normalizeRecipients(to) {
|
|
|
572
715
|
const body = await response.json().catch(()=>null);
|
|
573
716
|
return {
|
|
574
717
|
sent: true,
|
|
575
|
-
id: (
|
|
718
|
+
id: (_ref7 = body == null ? void 0 : body.id) != null ? _ref7 : null
|
|
576
719
|
};
|
|
577
720
|
} catch (error) {
|
|
578
|
-
var
|
|
721
|
+
var _ref8;
|
|
579
722
|
console.error(`${label} failed`, error);
|
|
580
723
|
return {
|
|
581
724
|
sent: false,
|
|
582
725
|
reason: 'network',
|
|
583
|
-
detail: String((
|
|
726
|
+
detail: String((_ref8 = error == null ? void 0 : error.message) != null ? _ref8 : error).slice(0, 500)
|
|
584
727
|
};
|
|
585
728
|
}
|
|
586
729
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/shared/util/email/src/lib/send-email.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The Resend send endpoint. Every outbound application email in Aglyn goes\n * through here — invites, receipts, usage summaries, campaigns, staff alerts.\n *\n * Auth email (verification, password reset) is Firebase's job and does NOT\n * come through this module.\n */\nimport {\n type EmailSendPriority,\n emailSendRateWindowStartMs,\n getEmailSendGovernor,\n isRefusablePriority,\n resolveSendPriority,\n} from './send-rate'\nimport { renderTextEmailHtml } from './text-email-html'\nimport {\n sendingIdentityRefusal,\n pooledMarketingRefusal,\n type SendingIdentityAudience,\n type SendingIdentityVerdict,\n} from './sending-domain'\nimport {\n appendUnsubscribeHtml,\n appendUnsubscribeText,\n getMarketingSendGate,\n isMarketingMessage,\n unsubscribeHeaders,\n type MarketingSendContext,\n} from './marketing-send'\n\nexport const RESEND_SEND_ENDPOINT = 'https://api.resend.com/emails'\n\n/** A Resend delivery tag, used for webhook attribution (AGL-268). */\nexport interface EmailTag {\n name: string\n value: string\n}\n\nexport interface SendEmailOptions {\n /** One or more recipient addresses. */\n to: string | string[]\n subject: string\n /** Plain-text body. Supply at least one of `text` or `html`. */\n text?: string\n /**\n * HTML body. Supply at least one of `text` or `html`.\n *\n * Omitted, one is synthesized from `text` so the message always carries an\n * HTML part — a text-only message has no anchors, so its links are inert in\n * the inbox and Resend's click tracking has nothing to rewrite. See\n * `text-email-html.ts`.\n */\n html?: string\n /** Extra MIME headers, e.g. `List-Unsubscribe`. */\n headers?: Record<string, string>\n /** Delivery tags for the opens/clicks webhook. */\n tags?: EmailTag[]\n replyTo?: string | string[]\n /*\n * THERE IS NO `from`.\n *\n * There was: a raw override of the configured sender, subordinate to a\n * resolved identity but winning over everything else, verified against\n * nothing. Every address this function can send from now comes from one of\n * exactly two places — the deployment's own `USAGE_EMAIL_FROM`, or a\n * {@link SendingIdentityVerdict} the server resolved from a document — and\n * neither is reachable from a request body.\n *\n * Deleting it rather than guarding it is what makes that a property instead\n * of a habit. A guard would have to be written correctly at each of the\n * ninety-odd call sites, or once here and then trusted; an option that does\n * not exist cannot be passed by the next sender, and `resolveSendingIdentity`\n * becomes the whole of the answer to \"as whom does this leave\".\n *\n * The resolution below reads no `from` from `options` either, so this is not\n * only a compile-time close. Marketplace plugin bundles reach `sendEmail` as\n * JavaScript and are typechecked against nothing.\n */\n /**\n * White-label display name for the sender (White-Label Phase 1). Replaces\n * only the display name in front of the verified address — the address\n * itself is never taken from the caller, so this cannot forge a different\n * sender. Callers pass `resolveBrandingProfile(org).fromName` here so an\n * agency's mail reads as their brand instead of \"Aglyn\".\n */\n fromName?: string\n /**\n * The server-resolved sending identity for this message, from\n * `resolveSendingIdentity`.\n *\n * Supplied, it decides the address and it may refuse the send outright —\n * `fromName` is subordinate to it, because a verdict is the answer to \"may\n * this leave, and as whom\" and a display name is not. Omitted, every\n * existing caller keeps the behavior it had: the configured platform\n * identity with an optional display name.\n *\n * Callers resolve it from the ORG DOCUMENT, never from request input. An\n * address assembled from a request body is a `From:` override wearing a new\n * name, and the invariant `applyFromName` exists to hold is that the\n * address cannot move off a verified identity.\n */\n sendingIdentity?: SendingIdentityVerdict | null\n /**\n * Whose mail this is — see {@link SendingIdentityAudience}.\n *\n * `tenant` says the message belongs to a SITE, and it makes the platform\n * sender unreachable: a tenant message with no resolved identity is refused\n * rather than sent from `aglyn.com`. Pair it with `sendingIdentity` from\n * `hostSendingIdentity(hostId)` and the ordinary path is unchanged; the flag\n * is what decides the behavior when that resolution is missing or refuses.\n *\n * Omitted, a send is platform mail and keeps the configured sender, because\n * that is what the console's own senders are. `email-audience-coverage.spec`\n * sweeps the tenant-owned trees so the omission cannot be an accident there.\n */\n audience?: SendingIdentityAudience\n /**\n * Short label for logs, e.g. `'invite'` or `'usage-summary'`. Makes a\n * failure in the runtime logs traceable to the feature that caused it.\n *\n * Since AGL-2407 it is also stamped as a Resend `context` TAG on every\n * send — see `contextTag` below.\n */\n context?: string\n /**\n * What the platform send-rate governor is allowed to do to this message\n * (AGL-2409). Omitted, it is derived from `context`: `'campaign'` is a\n * campaign and everything else is transactional, so no existing caller\n * changes and the default is the one that can never be refused.\n *\n * Set it to `'bulk'` ONLY from a resumable sweep — a cron that leaves its\n * subject unstamped and picks it up on the next run. A refusal for a bulk\n * send means \"not this hour\", and a caller that cannot come back would turn\n * that into a message nobody ever gets.\n */\n priority?: EmailSendPriority\n /**\n * Declares this message as MARKETING mail for one site's audience — see\n * `marketing-send.ts` for what that means and why it is one seam.\n *\n * Set it and the message gains, in one place, the three things marketing\n * mail owes: the RFC 8058 unsubscribe header pair plus a visible opt-out\n * link, a check against both suppression lists, and a ceiling on how much\n * one person receives from one site.\n *\n * ONE RECIPIENT. An unsubscribe link is an HMAC over the address it belongs\n * to, and a suppression verdict is about one person — so a marketing send\n * addressed to a list would carry the wrong link for everybody after the\n * first, and would ask the gate about one of them. Callers fan out.\n */\n marketing?: MarketingSendContext\n}\n\n/**\n * The `context` tag, attached to every send (AGL-2407).\n *\n * ## Why this is here and not at 37 call sites\n *\n * Until now `tags` were set by exactly one sender, `campaign-send.ts`, which\n * stamps `hostId` and `campaignId` for the opens/clicks webhook. Everything\n * else went out with NO tags at all, so a bounce on an invite, a password\n * reset, a receipt or a usage summary reached the webhook carrying nothing to\n * identify it, and was dropped.\n *\n * The obvious fix — thread an identifier through every call site — asks 37\n * places to remember, which is the shape that produces the 38th that does\n * not. But `context` is ALREADY threaded through 35 of the 37 for logging,\n * and it is exactly the right value: it names the sender. So the tag is\n * derived here, once, and no caller changes.\n *\n * Resend tag values are restricted to ASCII letters, digits, `_` and `-`;\n * anything else is rejected and would fail the whole send. Every `context` in\n * the tree is already a plain slug, but this is mail delivery — a value that\n * makes the send fail is far worse than a value that is sanitised — so the\n * label is normalised rather than trusted, and a context that sanitises to\n * nothing yields no tag rather than an invalid one.\n */\nexport function contextTag(context: string | undefined): EmailTag[] {\n const value = String(context ?? '')\n .trim()\n .replace(/[^A-Za-z0-9_-]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 64)\n return value ? [{ name: 'context', value }] : []\n}\n\n/**\n * Why a send did not happen. `unconfigured` and `no-recipient` mean nothing\n * was attempted; `rejected` and `network` mean Resend was called and failed;\n * `rate-limited` is either, and says so in `status`.\n *\n * `rate-limited` (AGL-2409) and `frequency-capped` are the two a caller may\n * reasonably retry unchanged — see {@link isDeferrableSendResult}, which is\n * where that distinction is made once rather than at each sweep.\n */\nexport type SendEmailFailureReason =\n | 'unconfigured'\n | 'no-recipient'\n /**\n * Resend answered and would not take this message.\n *\n * Per-message and terminal: a malformed payload, an address the provider\n * will not accept, a tag it rejected. A caller that retries it unchanged\n * gets the same answer, so a batch settles the recipient rather than\n * holding a slot open for them.\n *\n * A 429 is deliberately NOT this. See `rate-limited`.\n */\n | 'rejected'\n | 'network'\n /**\n * A refusal that is about the RATE, not about this message — so the message\n * is intact and a later attempt sends it.\n *\n * Two sources, which is why it is one value. The platform hourly governor\n * refuses before the network and nothing is attempted (AGL-2409). Resend\n * answers `429` on the wire when requests arrive faster than it accepts\n * them, and `status` is 429 in that case.\n *\n * The provider arm reports here rather than as `rejected` because of what\n * the two mean to a batch. A `rejected` recipient is settled and never\n * addressed again, which is right for an address the provider will not take\n * and wrong for every recipient a 429 touches: nothing about them was\n * refused, the request was simply too soon. Classified as `rejected` a\n * single rate-limited burst silently deletes the rest of a campaign's\n * audience while the campaign reports itself complete — and the `sent`\n * figure stays honest throughout, so no rate on the report can show it.\n *\n * The provider's quota errors — `daily_quota_exceeded`,\n * `monthly_quota_exceeded` — are also 429 and also land here. That is the\n * right answer for the same reason: none of them is a statement about the\n * recipient, and all of them clear with time.\n */\n | 'rate-limited'\n /**\n * The org selected a custom sending domain and that domain is not verified.\n *\n * Distinct from `unconfigured` because the two need opposite responses: an\n * unconfigured deployment is the operator's to fix, while this is a\n * customer's DNS that is not finished, and the customer is the only person\n * who can finish it. `detail` carries the sentence naming the domain.\n *\n * This is the LAST line of defence, not the visible one. A caller that\n * reaches it has already skipped the check its route should have made, and\n * a refusal seen only here is a log line — which is the shape of the\n * `USAGE_EMAIL_FROM` outage. `performCampaignSend` refuses first, with a\n * `409`, so a person finds out.\n */\n | 'unverified-domain'\n /**\n * A MARKETING send whose recipient is on a suppression list — they\n * unsubscribed from this site, hard-bounced, or pressed \"report spam\".\n *\n * Terminal, and the only outcome here a caller must not retry: retrying is\n * the behavior the suppression exists to stop. Distinct from `rejected`\n * because nothing was attempted and nothing failed — this is the control\n * working.\n */\n | 'suppressed'\n /**\n * A MARKETING send refused because this person has already received their\n * ceiling from this site inside the window.\n *\n * Retryable, unlike `suppressed`: the window rolls. A resumable sweep does\n * not need to do anything about it — its next run asks again.\n */\n | 'frequency-capped'\n /**\n * A MARKETING send refused because this site has been mailing this person\n * for longer than the sunset window with nothing to show for it.\n *\n * TERMINAL for a sweep, and it sits with `suppressed` rather than with\n * `frequency-capped` for a reason worth stating: the frequency window\n * clears by the passage of time, so waiting works. A sunset clears when the\n * PERSON engages, which more mail from us cannot cause — so a sweep that\n * treated it as deferrable would re-read the same doomed row on every beat\n * forever. Nothing about the recipient has been reduced; the next message\n * after they open anything goes.\n */\n | 'unengaged'\n\nexport type SendEmailResult =\n | { sent: true; id: string | null }\n | {\n sent: false\n reason: SendEmailFailureReason\n /** HTTP status, when Resend answered. */\n status?: number\n /** Resend's error body or the thrown message, trimmed for logs. */\n detail?: string\n /**\n * `rate-limited` only: the earliest instant a caller may try again —\n * when the platform hourly window rolls, or what the provider's own\n * `retry-after` asked for. A resumable sweep does not need to wait on\n * it; its next scheduled run is the retry.\n */\n retryAtMs?: number\n }\n\n/**\n * The retry instant when the platform send-rate governor deferred this\n * message, or `null` for every other outcome (AGL-2409).\n *\n * A FUNCTION rather than `result.reason === 'rate-limited'` at each call site,\n * because `strictNullChecks` is OFF repo-wide and TypeScript will not narrow a\n * boolean-literal discriminant without it: `if (result.sent) … else\n * result.reason` does not compile, in every consumer, for a reason that has\n * nothing to do with this union. One helper is also one place to change if the\n * shape of a deferral ever moves.\n */\nexport function rateLimitedRetryAtMs(\n result: SendEmailResult | null | undefined,\n): number | null {\n const failure = result as { reason?: string; retryAtMs?: number } | null\n if (!failure || failure.reason !== 'rate-limited') return null\n const retryAtMs = Number(failure.retryAtMs)\n return Number.isFinite(retryAtMs) ? retryAtMs : 0\n}\n\n/**\n * How long to wait when the provider names no interval of its own.\n *\n * One second, because Resend's rate limit is counted per second — so a wait\n * of a whole window is the shortest one that is certain to have cleared it.\n */\nconst PROVIDER_RETRY_FALLBACK_MS = 1_000\n\n/**\n * The longest wait a provider header may ask for.\n *\n * A `retry-after` is read off the network and reaches a scheduler, so it is\n * clamped rather than trusted: a header of `86400` would park a campaign for\n * a day on one response nobody saw. An hour is past every documented window\n * and short enough that a wrong one costs a run rather than a day.\n */\nconst PROVIDER_RETRY_MAX_MS = 3_600_000\n\n/** One header as whole seconds, or null when it is absent or unreadable. */\nfunction headerSeconds(\n headers: { get?: (name: string) => string | null } | null | undefined,\n name: string,\n): number | null {\n const raw = headers?.get?.(name)\n // `Number(null)` and `Number('')` are both 0, which would read as \"retry\n // immediately\" for a header that is not there at all.\n if (raw === null || raw === undefined || String(raw).trim() === '') return null\n const seconds = Number(raw)\n return Number.isFinite(seconds) && seconds >= 0 ? seconds : null\n}\n\n/**\n * When the provider says a refused request may be repeated.\n *\n * Read from the two headers Resend documents beside a 429, both in whole\n * seconds: `retry-after` first because it is the direct answer to this\n * question, then `ratelimit-reset`, which names when the window rolls. A\n * response carrying neither falls back to one window.\n */\nexport function providerRetryAtMs(\n headers: { get?: (name: string) => string | null } | null | undefined,\n nowMs: number = Date.now(),\n): number {\n const seconds =\n headerSeconds(headers, 'retry-after') ??\n headerSeconds(headers, 'ratelimit-reset')\n const waitMs =\n seconds === null\n ? PROVIDER_RETRY_FALLBACK_MS\n : Math.min(seconds * 1_000, PROVIDER_RETRY_MAX_MS)\n return nowMs + waitMs\n}\n\n/**\n * Why a send did not happen, or `null` when it did.\n *\n * The same accessor `rateLimitedRetryAtMs` is, generalized: `strictNullChecks`\n * is OFF repo-wide, so TypeScript will not narrow the union on `result.sent`\n * and reading `result.reason` at a call site does not compile.\n */\nexport function sendFailureReason(\n result: SendEmailResult | null | undefined,\n): SendEmailFailureReason | null {\n const failure = result as {\n sent?: boolean\n reason?: SendEmailFailureReason\n } | null\n if (!failure || failure.sent) return null\n return failure.reason ?? null\n}\n\n/**\n * Whether this outcome is worth coming back for.\n *\n * TRUE only for the two refusals a later attempt can pass: the platform hour\n * rolls, and so does the marketing frequency window. Everything else is\n * either a delivery that happened or a failure a retry repeats — a\n * suppression most of all, since retrying is the exact behavior a suppression\n * exists to stop, and a sunset for the same reason at one remove: it clears\n * when the recipient engages, which no amount of further mail from us brings\n * about.\n *\n * A resumable sweep uses this to decide whether to leave its subject\n * unstamped. Stamping on a deferrable refusal discards a message; NOT\n * stamping on a terminal one re-reads the same doomed row on every beat until\n * it crowds out the work that could succeed. Both are silent, so the\n * distinction lives here instead of at each sweep.\n *\n * A FUNCTION rather than `result.reason === …` at each call site, because\n * `strictNullChecks` is OFF repo-wide and TypeScript will not narrow a\n * boolean-literal discriminant without it — the same reason\n * {@link rateLimitedRetryAtMs} beside it is one.\n */\nexport function isDeferrableSendResult(\n result: SendEmailResult | null | undefined,\n): boolean {\n const reason = sendFailureReason(result)\n return reason === 'rate-limited' || reason === 'frequency-capped'\n}\n\nexport interface EmailConfig {\n apiKey: string | undefined\n from: string | undefined\n}\n\n/**\n * Reads the email environment.\n *\n * Deliberately read per call rather than captured at module load: these run\n * in serverless handlers where the module may be evaluated during a build,\n * long before the runtime env exists.\n */\nexport function getEmailConfig(): EmailConfig {\n return {\n apiKey: process.env.RESEND_API_KEY || undefined,\n from: process.env.USAGE_EMAIL_FROM || undefined,\n }\n}\n\n/**\n * True when both `RESEND_API_KEY` and `USAGE_EMAIL_FROM` are present.\n *\n * Callers that answer an HTTP request (rather than firing best-effort mail)\n * use this to return a 501 with an actionable message instead of pretending\n * to have sent something.\n */\nexport function isEmailConfigured(): boolean {\n const { apiKey, from } = getEmailConfig()\n return Boolean(apiKey && from)\n}\n\n/**\n * Applies a white-label display name to a configured sender while keeping\n * its verified address (White-Label Phase 1). Accepts either a bare address\n * (`noreply@aglyn.com`) or an RFC-5322 `Name <addr>` header and returns\n * `\"<fromName>\" <addr>`. A blank name, or a value with no extractable\n * address, yields the original `from` untouched — the sender identity is\n * never dropped on the floor.\n */\nexport function applyFromName(\n from: string | undefined,\n fromName: string | undefined,\n): string | undefined {\n const name = (fromName ?? '').trim()\n if (!from || !name) return from\n const angle = from.match(/<([^>]+)>/)\n const address = (angle ? angle[1] : from).trim()\n if (!address.includes('@')) return from\n // Quote the display name so commas/specials stay inside one mailbox.\n return `\"${name.replace(/\"/g, '')}\" <${address}>`\n}\n\nfunction normalizeRecipients(to: string | string[]): string[] {\n const list = Array.isArray(to) ? to : [to]\n return list\n .map((address) => String(address ?? '').trim())\n .filter((address) => address.includes('@'))\n}\n\n/** A Resend send payload in the provider's own wire shape. */\nexport interface ResendSendPayload {\n to?: unknown\n from?: unknown\n subject?: unknown\n [field: string]: unknown\n}\n\n/**\n * The one place that POSTs to Resend's send endpoint, and the last thing\n * standing between a payload and the network.\n *\n * A payload carrying no recipient cannot become a message. Resend answers it\n * `422 missing_required_field`, which costs an API call and then shows up in\n * the vendor dashboard as a red line indistinguishable from mail that\n * genuinely failed to deliver — carrying no subject, no recipient and nothing\n * naming the code that produced it. Diagnosing that means reading a log\n * outside the deployment and guessing. So the refusal happens here, before\n * the fetch, and names the caller's `context`.\n *\n * It throws rather than returning a `SendEmailResult`: this is a programming\n * error, not a delivery outcome. `sendEmail` filters recipients well before\n * it reaches this call, so nothing on the ordinary path can trip it. The\n * guard exists because `RESEND_SEND_ENDPOINT` is exported and any module can\n * therefore reach the send endpoint on its own, bypassing every check\n * `sendEmail` owns.\n */\nexport async function postResendEmail(\n apiKey: string,\n payload: ResendSendPayload,\n context?: string,\n): Promise<Response> {\n const raw = payload?.to\n const recipients = (Array.isArray(raw) ? raw : raw == null ? [] : [raw])\n .map((address) => String(address ?? '').trim())\n .filter(Boolean)\n if (!recipients.length) {\n throw new Error(\n `${context ? `${context} ` : ''}send refused before the network — a ` +\n 'Resend payload with no `to` field cannot become a message, and the ' +\n 'attempt would surface only as a 422 in the Resend dashboard',\n )\n }\n\n return fetch(RESEND_SEND_ENDPOINT, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${apiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(payload),\n })\n}\n\n/**\n * Sends one email through Resend.\n *\n * **Never throws and never rejects.** Outbound mail is best-effort across\n * every caller in this codebase — a checkout must not fail because a receipt\n * bounced — so every outcome comes back as a `SendEmailResult` instead. The\n * one thing callers must not do is ignore the result: `sent` is what tells\n * the user whether a message actually went out (AGL-708).\n *\n * When the env vars are missing this warns once per call and returns\n * `{ sent: false, reason: 'unconfigured' }` rather than failing, so local and\n * preview environments keep working without a Resend account.\n */\nexport async function sendEmail(\n options: SendEmailOptions,\n): Promise<SendEmailResult> {\n const { apiKey, from: configuredFrom } = getEmailConfig()\n const label = options.context ? `${options.context} email` : 'email'\n\n /*\n * THE SENDING-IDENTITY REFUSAL.\n *\n * Enforced here AND at the campaign route, independently, for the reason\n * the send-rate governor is enforced twice: the route's check is the one a\n * person sees, and this one is what holds when a caller does not make it.\n * A governor is injectable and a route is skippable, so neither may be the\n * only thing standing between an unverified domain and a send.\n *\n * Placed above the `apiKey`/`from` gate so a refusal cannot be reported as\n * `unconfigured` — the two have different owners and different fixes.\n */\n const identityRefusal = sendingIdentityRefusal(options.sendingIdentity)\n if (identityRefusal) {\n console.warn(`${label} refused — ${identityRefusal.message}`)\n return {\n sent: false,\n reason: 'unverified-domain',\n detail: identityRefusal.message,\n }\n }\n\n // A resolved identity outranks the configured sender: it is the server's\n // answer to which verified address this message leaves on. Without one, the\n // white-label display name is applied to the configured verified sender\n // (White-Label Phase 1).\n //\n // Two sources, and `options` is neither of them. Nothing the caller passes\n // reaches the address — only the display name in front of it.\n const resolvedFrom = options.sendingIdentity?.from ?? null\n\n /*\n * THE PLATFORM DOMAIN IS NOT A FALLBACK FOR TENANT MAIL.\n *\n * `configuredFrom` is `USAGE_EMAIL_FROM` — an address on `aglyn.com`, where\n * Aglyn's own billing, account and console mail leaves from. A site's mail\n * reaching it means that site's list quality is charged against the domain\n * every other customer's password reset depends on.\n *\n * `resolveHostSendingIdentity` already refuses above, so a tenant caller\n * that resolved an identity never arrives here with `resolvedFrom` null.\n * This is the arm for a tenant caller that resolved NOTHING — the shape a\n * new send site takes when its author does not know an identity is owed —\n * and it is checked here rather than left to the call sites because ninety\n * of them cannot each be relied on to remember.\n */\n if (options.audience === 'tenant' && !resolvedFrom) {\n console.warn(\n `${label} refused — a site's mail cannot leave on the shared platform ` +\n 'domain, and no sending identity was resolved for it',\n )\n return {\n sent: false,\n reason: 'unverified-domain',\n detail:\n 'This message belongs to a site and no sending identity was ' +\n 'resolved for it, so it was refused rather than sent from the ' +\n 'shared Aglyn address.',\n }\n }\n\n const from = applyFromName(\n resolvedFrom ?? configuredFrom,\n options.fromName,\n )\n\n if (!apiKey || !from) {\n console.warn(\n `${label} skipped — set RESEND_API_KEY and USAGE_EMAIL_FROM to ` +\n 'deliver mail',\n )\n return { sent: false, reason: 'unconfigured' }\n }\n\n const to = normalizeRecipients(options.to)\n if (!to.length) {\n console.warn(`${label} skipped — no valid recipient address`)\n return { sent: false, reason: 'no-recipient' }\n }\n\n /*\n * THE MARKETING GATE.\n *\n * Everything a marketing message owes, asked once, here — because the four\n * merchant-triggered bulk paths that owed it discharged none of it, and\n * asking four call sites to remember is the shape that produces the fifth\n * that does not.\n *\n * Ahead of the send-rate governor deliberately. A refusal here is a message\n * that must never leave, so spending platform hourly budget deciding that\n * would be budget the rest of the hour's mail no longer has.\n *\n * Nothing installed is UNGATED. Same posture as the governor: the durable\n * half lives in another library, and a deployment that never installs it\n * must still send.\n */\n /*\n * TWO URLS, and which one goes where is the whole RFC 8058 story.\n *\n * `unsubscribeUrl` is what a PERSON clicks in the footer below, and the\n * gate points it at the preference page so the stream this message belongs\n * to is one of the things they can stop instead of all of it.\n * `oneClickUrl` is what `List-Unsubscribe` names, and it must stay on the\n * route whose POST writes immediately — a mailbox provider POSTs it with\n * nobody present and reads the 200 as \"done\", which a page of checkboxes\n * cannot honor.\n *\n * It falls back to `unsubscribeUrl` for a caller that minted one link and\n * named no page, which is the only shape that was ever possible before the\n * gate minted the pair.\n */\n let unsubscribeUrl = options.marketing?.unsubscribeUrl ?? ''\n let oneClickUrl = options.marketing?.oneClickUrl ?? ''\n if (options.marketing) {\n if (to.length !== 1) {\n // Not a delivery outcome — a caller error, and one that would put the\n // first recipient's signed unsubscribe link in everybody else's copy.\n console.error(\n `${label} refused — a marketing send addresses exactly one ` +\n `recipient, and this one names ${to.length}`,\n )\n return {\n sent: false,\n reason: 'no-recipient',\n detail: 'A marketing send addresses exactly one recipient.',\n }\n }\n const gate = getMarketingSendGate()\n if (gate) {\n let verdict: Awaited<ReturnType<typeof gate>> | null\n try {\n verdict = await gate({\n hostId: options.marketing.hostId,\n siteBase: options.marketing.siteBase,\n email: to[0],\n context: options.context,\n capped: options.marketing.capped !== false,\n // Passed through verbatim, INCLUDING absent. A default topic\n // applied here would invent a stream for every caller that named\n // none and let a topic opt-out refuse messages that belong to no\n // stream — see `MarketingSendContext.topicId`.\n ...(options.marketing.topicId\n ? { topicId: options.marketing.topicId }\n : {}),\n consentHostIds: options.marketing.consentHostIds,\n consentAwaitsConfirmation: options.marketing.consentAwaitsConfirmation,\n })\n } catch (error) {\n /*\n * FAILS OPEN, and the asymmetry with `filterSendableForHost` is\n * deliberate rather than an oversight. That helper fails CLOSED\n * because a suppression list it could not read is not a list that\n * said an address is safe to mail — and it keeps doing so, inside\n * the gate. What is being caught here is the gate itself being\n * unreachable or throwing, which is an outage on the control; an\n * outage on a control that becomes an outage on the product is the\n * worse of the two bugs, and it is the posture `sendEmail` takes\n * everywhere else.\n */\n console.error(`${label} marketing gate failed — allowing`, error)\n verdict = null\n }\n if (verdict && !verdict.allowed) {\n /*\n * A cadence refusal reports as `frequency-capped` rather than earning\n * a value of its own in {@link SendEmailFailureReason}.\n *\n * That union is what {@link isDeferrableSendResult} switches on, and\n * the two are deferrable for exactly the same reason: a later attempt\n * passes because time went by. A third value would have to be added\n * to that predicate as well, and a sweep built against the older\n * vocabulary would silently treat the recipient's own request as\n * terminal and stamp the subject — discarding a message the recipient\n * asked to receive later rather than never. Which of the two it was\n * is in `detail`, where a person reading a log needs it.\n */\n const reason: SendEmailFailureReason =\n verdict.refusal === 'frequency-capped' ||\n verdict.refusal === 'cadence-limited'\n ? 'frequency-capped'\n : verdict.refusal === 'unengaged'\n ? 'unengaged'\n : 'suppressed'\n console.warn(`${label} not sent — ${verdict.detail ?? reason}`)\n return { sent: false, reason, detail: verdict.detail }\n }\n unsubscribeUrl = unsubscribeUrl || verdict?.unsubscribeUrl || ''\n oneClickUrl = oneClickUrl || verdict?.oneClickUrl || ''\n }\n if (!unsubscribeUrl) {\n // A marketing message with no way out is the defect this gate exists to\n // close, so it is said out loud rather than shipped quietly. Not a\n // refusal: the cause is a missing `EMAIL_UNSUBSCRIBE_SECRET` or a host\n // with no public origin — an operator's configuration, not the\n // recipient's problem — and refusing here would turn it into silence.\n console.warn(\n `${label} carries no unsubscribe link — set ` +\n 'EMAIL_UNSUBSCRIBE_SECRET and publish the site on a domain',\n )\n }\n }\n\n /*\n * BULK MAIL WITH NO WAY OUT DOES NOT LEAVE ON THE POOLED IDENTITY.\n *\n * The pool carries marketing for every site that has no domain of its own,\n * and what keeps that survivable is that a recipient can always stop it: the\n * complaint that would otherwise be charged to every other site on the member\n * has a cheaper alternative one click away. A message that lost its\n * unsubscribe link removes that alternative, so it is refused here rather\n * than sent at other people's expense.\n *\n * Asked AFTER the gate, because only here is the answer known. The URL may\n * arrive from the caller, from the gate that mints one per recipient, or —\n * for a campaign, which composes its own one-click pair upstream — as a\n * `List-Unsubscribe` header and no marketing context at all. Reading only one\n * of the three would refuse the senders that are behaving.\n *\n * The classification is DERIVED, never declared. See `isMarketingMessage`.\n */\n const pooledRefusal = isMarketingMessage(options)\n ? pooledMarketingRefusal(\n options.sendingIdentity,\n Boolean(unsubscribeUrl) ||\n Boolean(options.headers?.['List-Unsubscribe']),\n )\n : null\n if (pooledRefusal) {\n console.warn(`${label} refused — ${pooledRefusal.message}`)\n return {\n sent: false,\n reason: 'unverified-domain',\n detail: pooledRefusal.message,\n }\n }\n\n /*\n * THE PLATFORM SEND-RATE GOVERNOR (AGL-2409).\n *\n * Asked on EVERY send, including transactional ones, because the ceiling is\n * about total volume on one sending domain — a governor that only saw\n * campaigns would report a quiet hour while ten thousand receipts went out.\n * The governor counts what it grants.\n *\n * Two properties this block must have, in order:\n *\n * 1. **A refusal is honoured only for a refusable priority.** This is the\n * second of the two enforcement points described in `send-rate.ts`.\n * `emailSendRateVerdict` already cannot refuse a transactional send;\n * the governor is INJECTABLE, so a wrong one is reachable, and the send\n * path must still be unable to drop a password reset. Anything that is\n * not explicitly a campaign or a bulk sweep sends regardless of the\n * answer.\n * 2. **It fails open.** A governor that throws — Firestore unreachable, no\n * Admin app, a bug — must not stop mail. The counter being unavailable\n * is an outage on the control, and an outage on a control that turns\n * into an outage on the product is a worse bug than the burst it was\n * guarding. The same posture `sendEmail` takes everywhere else: it\n * never throws, and neither does this.\n */\n const priority = resolveSendPriority(options.context, options.priority)\n const governor = getEmailSendGovernor()\n if (governor) {\n let verdict: Awaited<ReturnType<typeof governor>> | null\n try {\n verdict = await governor({\n priority,\n count: to.length,\n context: options.context,\n })\n } catch (error) {\n console.error(`${label} send-rate governor failed — allowing`, error)\n verdict = null\n }\n if (verdict && !verdict.allowed && isRefusablePriority(priority)) {\n const retryAtMs =\n verdict.retryAtMs ?? emailSendRateWindowStartMs(Date.now())\n console.warn(\n `${label} deferred — platform send rate reached ` +\n `(${verdict.used ?? '?'}/${verdict.ceiling ?? '?'} this hour)`,\n )\n return {\n sent: false,\n reason: 'rate-limited',\n retryAtMs,\n detail:\n `Platform hourly send rate reached (${verdict.ceiling ?? '?'}/hour). ` +\n 'Transactional mail is unaffected.',\n }\n }\n }\n\n /*\n * THE VISIBLE OPT-OUT, on both parts.\n *\n * The header pair below is for the mailbox provider; this is for the person\n * — CAN-SPAM asks for a mechanism the recipient can see and use, and most\n * clients render no control for the header at all. Both helpers are\n * idempotent by URL, so a sender that placed its own link (a designed\n * template rendering `{{unsubscribeUrl}}`, the campaign body's footer)\n * keeps its own placement and does not get a second one.\n *\n * `text` first and `html` from the result, so the synthesized HTML part\n * that stands in for a text-only message carries the link as an anchor\n * rather than as characters.\n */\n const text = unsubscribeUrl\n ? appendUnsubscribeText(options.text ?? '', unsubscribeUrl)\n : options.text\n const html = unsubscribeUrl\n ? options.html\n ? appendUnsubscribeHtml(options.html, unsubscribeUrl)\n : renderTextEmailHtml(text ?? '', options.subject)\n : options.html\n\n try {\n const response = await postResendEmail(\n apiKey,\n {\n from,\n to,\n subject: options.subject,\n ...(text ? { text } : {}),\n // The HTML part, from the caller when it has one and otherwise\n // synthesized from `text`. A message with no HTML part carries no\n // anchors, so its links are not links in the inbox AND Resend has\n // nothing to rewrite for click tracking — see `text-email-html.ts`.\n // The caller always wins: this can only fill a gap, never override a\n // designed template.\n ...(() => {\n const body = html || renderTextEmailHtml(text ?? '', options.subject)\n return body ? { html: body } : {}\n })(),\n // The caller's headers plus the RFC 8058 pair for a marketing send.\n // Caller-first, so the campaign sender's own pair is the one that\n // ships and a merchant-authored header is never silently replaced.\n ...(() => {\n const headers = {\n ...unsubscribeHeaders(oneClickUrl || unsubscribeUrl),\n ...(options.headers ?? {}),\n }\n return Object.keys(headers).length ? { headers } : {}\n })(),\n // The caller's tags plus the `context` tag (AGL-2407). Caller-first\n // so a sender that stamps its own `context` keeps it: a tag list with\n // two entries of one name is not a shape worth discovering in\n // production, and the explicit one is the more specific.\n ...(() => {\n const caller = options.tags ?? []\n const derived = caller.some((tag) => tag?.name === 'context')\n ? []\n : contextTag(options.context)\n const tags = [...caller, ...derived]\n return tags.length ? { tags } : {}\n })(),\n ...(options.replyTo ? { reply_to: options.replyTo } : {}),\n },\n options.context,\n )\n\n if (!response.ok) {\n const detail = await response.text().catch(() => '')\n /*\n * A 429 IS NOT A STATEMENT ABOUT THIS RECIPIENT, so it does not report\n * as one. See the `rate-limited` member of\n * {@link SendEmailFailureReason} for why the distinction is load-bearing\n * rather than cosmetic — every caller in the tree already has a branch\n * for a deferral, and none of them has one for \"rejected, but try this\n * exact address again later\".\n *\n * A warning rather than an error: the provider asking for a slower pace\n * is a normal thing to be told, and logging it at the level a failed\n * delivery uses is what teaches an operator to skim past both.\n */\n if (response.status === 429) {\n const retryAtMs = providerRetryAtMs(response.headers)\n console.warn(\n `${label} deferred — the provider is rate limiting; retry in ` +\n `${Math.max(0, Math.round((retryAtMs - Date.now()) / 1000))}s`,\n )\n return {\n sent: false,\n reason: 'rate-limited',\n status: response.status,\n retryAtMs,\n detail: detail.slice(0, 500),\n }\n }\n console.error(`${label} failed`, response.status, detail)\n return {\n sent: false,\n reason: 'rejected',\n status: response.status,\n detail: detail.slice(0, 500),\n }\n }\n\n const body = (await response.json().catch(() => null)) as {\n id?: string\n } | null\n return { sent: true, id: body?.id ?? null }\n } catch (error) {\n console.error(`${label} failed`, error)\n return {\n sent: false,\n reason: 'network',\n detail: String((error as Error)?.message ?? error).slice(0, 500),\n }\n }\n}\n\nexport default sendEmail\n"],"names":["emailSendRateWindowStartMs","getEmailSendGovernor","isRefusablePriority","resolveSendPriority","renderTextEmailHtml","sendingIdentityRefusal","pooledMarketingRefusal","appendUnsubscribeHtml","appendUnsubscribeText","getMarketingSendGate","isMarketingMessage","unsubscribeHeaders","RESEND_SEND_ENDPOINT","contextTag","context","value","String","trim","replace","slice","name","rateLimitedRetryAtMs","result","failure","reason","retryAtMs","Number","isFinite","PROVIDER_RETRY_FALLBACK_MS","PROVIDER_RETRY_MAX_MS","headerSeconds","headers","raw","get","undefined","seconds","providerRetryAtMs","nowMs","Date","now","waitMs","Math","min","sendFailureReason","sent","isDeferrableSendResult","getEmailConfig","apiKey","process","env","RESEND_API_KEY","from","USAGE_EMAIL_FROM","isEmailConfigured","Boolean","applyFromName","fromName","angle","match","address","includes","normalizeRecipients","to","list","Array","isArray","map","filter","postResendEmail","payload","recipients","length","Error","fetch","method","Authorization","body","JSON","stringify","sendEmail","options","configuredFrom","label","identityRefusal","sendingIdentity","console","warn","message","detail","resolvedFrom","audience","unsubscribeUrl","marketing","oneClickUrl","error","gate","verdict","hostId","siteBase","email","capped","topicId","consentHostIds","consentAwaitsConfirmation","allowed","refusal","pooledRefusal","priority","governor","count","used","ceiling","text","html","subject","response","Object","keys","caller","tags","derived","some","tag","replyTo","reply_to","ok","catch","status","max","round","json","id"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;CAMC,GACD,SAEEA,0BAA0B,EAC1BC,oBAAoB,EACpBC,mBAAmB,EACnBC,mBAAmB,QACd,iBAAa;AACpB,SAASC,mBAAmB,QAAQ,uBAAmB;AACvD,SACEC,sBAAsB,EACtBC,sBAAsB,QAGjB,sBAAkB;AACzB,SACEC,qBAAqB,EACrBC,qBAAqB,EACrBC,oBAAoB,EACpBC,kBAAkB,EAClBC,kBAAkB,QAEb,sBAAkB;AAEzB,OAAO,MAAMC,uBAAuB,gCAA+B;AA2HnE;;;;;;;;;;;;;;;;;;;;;;;CAuBC,GACD,OAAO,SAASC,WAAWC,OAA2B;IACpD,MAAMC,QAAQC,OAAOF,kBAAAA,UAAW,IAC7BG,IAAI,GACJC,OAAO,CAAC,oBAAoB,KAC5BA,OAAO,CAAC,YAAY,IACpBC,KAAK,CAAC,GAAG;IACZ,OAAOJ,QAAQ;QAAC;YAAEK,MAAM;YAAWL;QAAM;KAAE,GAAG,EAAE;AAClD;AAmHA;;;;;;;;;;CAUC,GACD,OAAO,SAASM,qBACdC,MAA0C;IAE1C,MAAMC,UAAUD;IAChB,IAAI,CAACC,WAAWA,QAAQC,MAAM,KAAK,gBAAgB,OAAO;IAC1D,MAAMC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AAO;gBACpDsD,QAAQC,IAAI,CACV,GAAGJ,MAAM,oDAAoD,CAAC,GAC5D,GAAGzC,KAAKuF,GAAG,CAAC,GAAGvF,KAAKwF,KAAK,CAAC,AAACxG,CAAAA,YAAYa,KAAKC,GAAG,EAAC,IAAK,OAAO,CAAC,CAAC;gBAElE,OAAO;oBACLK,MAAM;oBACNpB,QAAQ;oBACRuG,QAAQZ,SAASY,MAAM;oBACvBtG;oBACA+D,QAAQA,OAAOrE,KAAK,CAAC,GAAG;gBAC1B;YACF;YACAkE,QAAQS,KAAK,CAAC,GAAGZ,MAAM,OAAO,CAAC,EAAEiC,SAASY,MAAM,EAAEvC;YAClD,OAAO;gBACL5C,MAAM;gBACNpB,QAAQ;gBACRuG,QAAQZ,SAASY,MAAM;gBACvBvC,QAAQA,OAAOrE,KAAK,CAAC,GAAG;YAC1B;QACF;QAEA,MAAMyD,OAAQ,MAAMuC,SAASe,IAAI,GAAGJ,KAAK,CAAC,IAAM;QAGhD,OAAO;YAAElF,MAAM;YAAMuF,EAAE,WAAEvD,wBAAAA,KAAMuD,EAAE,oBAAI;QAAK;IAC5C,EAAE,OAAOrC,OAAO;;QACdT,QAAQS,KAAK,CAAC,GAAGZ,MAAM,OAAO,CAAC,EAAEY;QACjC,OAAO;YACLlD,MAAM;YACNpB,QAAQ;YACRgE,QAAQxE,gBAAQ8E,yBAAD,AAACA,MAAiBP,OAAO,oBAAIO,OAAO3E,KAAK,CAAC,GAAG;QAC9D;IACF;AACF;AAEA,eAAe4D,UAAS"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/shared/util/email/src/lib/send-email.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The Resend send endpoint. Every outbound application email in Aglyn goes\n * through here — invites, receipts, usage summaries, campaigns, staff alerts.\n *\n * Auth email (verification, password reset) is Firebase's job and does NOT\n * come through this module.\n */\nimport {\n type EmailSendPriority,\n emailSendRateWindowStartMs,\n getEmailSendGovernor,\n isRefusablePriority,\n resolveSendPriority,\n} from './send-rate'\nimport { renderTextEmailHtml } from './text-email-html'\nimport {\n sendingIdentityRefusal,\n pooledMarketingRefusal,\n type SendingIdentityAudience,\n type SendingIdentityVerdict,\n} from './sending-domain'\nimport {\n appendUnsubscribeHtml,\n appendUnsubscribeText,\n getMarketingSendGate,\n isMarketingMessage,\n unsubscribeHeaders,\n type MarketingSendContext,\n} from './marketing-send'\nimport {\n EMAIL_DELIVERABILITY_PREFLIGHT_TIMEOUT_MS,\n getEmailDeliverabilityPreflight,\n type EmailDeliverabilityPreflightVerdict,\n type EmailSendPurpose,\n} from './email-deliverability'\nimport { bareSenderAddress } from './email-delivery-events'\nimport { screenTenantMessage } from './outbound-screen-gate'\n\nexport const RESEND_SEND_ENDPOINT = 'https://api.resend.com/emails'\n\n/** A Resend delivery tag, used for webhook attribution (AGL-268). */\nexport interface EmailTag {\n name: string\n value: string\n}\n\nexport interface SendEmailOptions {\n /** One or more recipient addresses. */\n to: string | string[]\n subject: string\n /** Plain-text body. Supply at least one of `text` or `html`. */\n text?: string\n /**\n * HTML body. Supply at least one of `text` or `html`.\n *\n * Omitted, one is synthesized from `text` so the message always carries an\n * HTML part — a text-only message has no anchors, so its links are inert in\n * the inbox and Resend's click tracking has nothing to rewrite. See\n * `text-email-html.ts`.\n */\n html?: string\n /** Extra MIME headers, e.g. `List-Unsubscribe`. */\n headers?: Record<string, string>\n /** Delivery tags for the opens/clicks webhook. */\n tags?: EmailTag[]\n replyTo?: string | string[]\n /*\n * THERE IS NO `from`.\n *\n * There was: a raw override of the configured sender, subordinate to a\n * resolved identity but winning over everything else, verified against\n * nothing. Every address this function can send from now comes from one of\n * exactly two places — the deployment's own `USAGE_EMAIL_FROM`, or a\n * {@link SendingIdentityVerdict} the server resolved from a document — and\n * neither is reachable from a request body.\n *\n * Deleting it rather than guarding it is what makes that a property instead\n * of a habit. A guard would have to be written correctly at each of the\n * ninety-odd call sites, or once here and then trusted; an option that does\n * not exist cannot be passed by the next sender, and `resolveSendingIdentity`\n * becomes the whole of the answer to \"as whom does this leave\".\n *\n * The resolution below reads no `from` from `options` either, so this is not\n * only a compile-time close. Marketplace plugin bundles reach `sendEmail` as\n * JavaScript and are typechecked against nothing.\n */\n /**\n * White-label display name for the sender (White-Label Phase 1). Replaces\n * only the display name in front of the verified address — the address\n * itself is never taken from the caller, so this cannot forge a different\n * sender. Callers pass `resolveBrandingProfile(org).fromName` here so an\n * agency's mail reads as their brand instead of \"Aglyn\".\n */\n fromName?: string\n /**\n * The server-resolved sending identity for this message, from\n * `resolveSendingIdentity`.\n *\n * Supplied, it decides the address and it may refuse the send outright —\n * `fromName` is subordinate to it, because a verdict is the answer to \"may\n * this leave, and as whom\" and a display name is not. Omitted, every\n * existing caller keeps the behavior it had: the configured platform\n * identity with an optional display name.\n *\n * Callers resolve it from the ORG DOCUMENT, never from request input. An\n * address assembled from a request body is a `From:` override wearing a new\n * name, and the invariant `applyFromName` exists to hold is that the\n * address cannot move off a verified identity.\n */\n sendingIdentity?: SendingIdentityVerdict | null\n /**\n * Whose mail this is — see {@link SendingIdentityAudience}.\n *\n * `tenant` says the message belongs to a SITE, and it makes the platform\n * sender unreachable: a tenant message with no resolved identity is refused\n * rather than sent from `aglyn.com`. Pair it with `sendingIdentity` from\n * `hostSendingIdentity(hostId)` and the ordinary path is unchanged; the flag\n * is what decides the behavior when that resolution is missing or refuses.\n *\n * Omitted, a send is platform mail and keeps the configured sender, because\n * that is what the console's own senders are. `email-audience-coverage.spec`\n * sweeps the tenant-owned trees so the omission cannot be an accident there.\n */\n audience?: SendingIdentityAudience\n /**\n * Short label for logs, e.g. `'invite'` or `'usage-summary'`. Makes a\n * failure in the runtime logs traceable to the feature that caused it.\n *\n * Since AGL-2407 it is also stamped as a Resend `context` TAG on every\n * send — see `contextTag` below.\n */\n context?: string\n /**\n * What the platform send-rate governor is allowed to do to this message\n * (AGL-2409). Omitted, it is derived from `context`: `'campaign'` is a\n * campaign and everything else is transactional, so no existing caller\n * changes and the default is the one that can never be refused.\n *\n * Set it to `'bulk'` ONLY from a resumable sweep — a cron that leaves its\n * subject unstamped and picks it up on the next run. A refusal for a bulk\n * send means \"not this hour\", and a caller that cannot come back would turn\n * that into a message nobody ever gets.\n */\n priority?: EmailSendPriority\n /**\n * Declares this message as MARKETING mail for one site's audience — see\n * `marketing-send.ts` for what that means and why it is one seam.\n *\n * Set it and the message gains, in one place, the three things marketing\n * mail owes: the RFC 8058 unsubscribe header pair plus a visible opt-out\n * link, a check against both suppression lists, and a ceiling on how much\n * one person receives from one site.\n *\n * ONE RECIPIENT. An unsubscribe link is an HMAC over the address it belongs\n * to, and a suppression verdict is about one person — so a marketing send\n * addressed to a list would carry the wrong link for everybody after the\n * first, and would ask the gate about one of them. Callers fan out.\n */\n marketing?: MarketingSendContext\n /**\n * What the RECIPIENT did that makes this message owed to them (AGL-3356):\n * `order` — a receipt, a gift card, a shipping notice for something they\n * bought; `booking` — a confirmation, reminder or change to something they\n * booked; `account` — a password reset or sign-in link they asked for.\n *\n * The outbound phishing screen's SOFT rules never hold an owed message; a\n * lookalike link still does, because a receipt that links to a brand's\n * disguise is the disguise. Omitted — the default, and the one a forgotten\n * caller gets — the message is treated as merchant-authored and every\n * tier applies. A MARKETING message is never owed, whatever it declares.\n */\n owedFor?: 'order' | 'booking' | 'account'\n /**\n * A review row that the caller's own screen held and staff RELEASED for\n * exactly this content — a campaign put back on the clock, an automation\n * step whose hold was dismissed. The send seam's screen honors it only\n * after confirming, through the installed gate, that it is a release for\n * this site; naming a row is not a way past the screen.\n */\n releasedReviewId?: string | null\n}\n\n/**\n * The `context` tag, attached to every send (AGL-2407).\n *\n * ## Why this is here and not at 37 call sites\n *\n * Until now `tags` were set by exactly one sender, `campaign-send.ts`, which\n * stamps `hostId` and `campaignId` for the opens/clicks webhook. Everything\n * else went out with NO tags at all, so a bounce on an invite, a password\n * reset, a receipt or a usage summary reached the webhook carrying nothing to\n * identify it, and was dropped.\n *\n * The obvious fix — thread an identifier through every call site — asks 37\n * places to remember, which is the shape that produces the 38th that does\n * not. But `context` is ALREADY threaded through 35 of the 37 for logging,\n * and it is exactly the right value: it names the sender. So the tag is\n * derived here, once, and no caller changes.\n *\n * Resend tag values are restricted to ASCII letters, digits, `_` and `-`;\n * anything else is rejected and would fail the whole send. Every `context` in\n * the tree is already a plain slug, but this is mail delivery — a value that\n * makes the send fail is far worse than a value that is sanitised — so the\n * label is normalised rather than trusted, and a context that sanitises to\n * nothing yields no tag rather than an invalid one.\n */\nexport function contextTag(context: string | undefined): EmailTag[] {\n const value = String(context ?? '')\n .trim()\n .replace(/[^A-Za-z0-9_-]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 64)\n return value ? [{ name: 'context', value }] : []\n}\n\n/**\n * Why a send did not happen. `unconfigured` and `no-recipient` mean nothing\n * was attempted; `rejected` and `network` mean Resend was called and failed;\n * `rate-limited` is either, and says so in `status`.\n *\n * `rate-limited` (AGL-2409) and `frequency-capped` are the two a caller may\n * reasonably retry unchanged — see {@link isDeferrableSendResult}, which is\n * where that distinction is made once rather than at each sweep.\n */\nexport type SendEmailFailureReason =\n | 'unconfigured'\n | 'no-recipient'\n /**\n * Resend answered and would not take this message.\n *\n * Per-message and terminal: a malformed payload, an address the provider\n * will not accept, a tag it rejected. A caller that retries it unchanged\n * gets the same answer, so a batch settles the recipient rather than\n * holding a slot open for them.\n *\n * A 429 is deliberately NOT this. See `rate-limited`.\n */\n | 'rejected'\n | 'network'\n /**\n * A refusal that is about the RATE, not about this message — so the message\n * is intact and a later attempt sends it.\n *\n * Two sources, which is why it is one value. The platform hourly governor\n * refuses before the network and nothing is attempted (AGL-2409). Resend\n * answers `429` on the wire when requests arrive faster than it accepts\n * them, and `status` is 429 in that case.\n *\n * The provider arm reports here rather than as `rejected` because of what\n * the two mean to a batch. A `rejected` recipient is settled and never\n * addressed again, which is right for an address the provider will not take\n * and wrong for every recipient a 429 touches: nothing about them was\n * refused, the request was simply too soon. Classified as `rejected` a\n * single rate-limited burst silently deletes the rest of a campaign's\n * audience while the campaign reports itself complete — and the `sent`\n * figure stays honest throughout, so no rate on the report can show it.\n *\n * The provider's quota errors — `daily_quota_exceeded`,\n * `monthly_quota_exceeded` — are also 429 and also land here. That is the\n * right answer for the same reason: none of them is a statement about the\n * recipient, and all of them clear with time.\n */\n | 'rate-limited'\n /**\n * The org selected a custom sending domain and that domain is not verified.\n *\n * Distinct from `unconfigured` because the two need opposite responses: an\n * unconfigured deployment is the operator's to fix, while this is a\n * customer's DNS that is not finished, and the customer is the only person\n * who can finish it. `detail` carries the sentence naming the domain.\n *\n * This is the LAST line of defence, not the visible one. A caller that\n * reaches it has already skipped the check its route should have made, and\n * a refusal seen only here is a log line — which is the shape of the\n * `USAGE_EMAIL_FROM` outage. `performCampaignSend` refuses first, with a\n * `409`, so a person finds out.\n */\n | 'unverified-domain'\n /**\n * A MARKETING send whose recipient is on a suppression list — they\n * unsubscribed from this site, hard-bounced, or pressed \"report spam\".\n *\n * Terminal, and the only outcome here a caller must not retry: retrying is\n * the behavior the suppression exists to stop. Distinct from `rejected`\n * because nothing was attempted and nothing failed — this is the control\n * working.\n */\n | 'suppressed'\n /**\n * A MARKETING send refused because this person has already received their\n * ceiling from this site inside the window.\n *\n * Retryable, unlike `suppressed`: the window rolls. A resumable sweep does\n * not need to do anything about it — its next run asks again.\n */\n | 'frequency-capped'\n /**\n * A MARKETING send refused because this site has been mailing this person\n * for longer than the sunset window with nothing to show for it.\n *\n * TERMINAL for a sweep, and it sits with `suppressed` rather than with\n * `frequency-capped` for a reason worth stating: the frequency window\n * clears by the passage of time, so waiting works. A sunset clears when the\n * PERSON engages, which more mail from us cannot cause — so a sweep that\n * treated it as deferrable would re-read the same doomed row on every beat\n * forever. Nothing about the recipient has been reduced; the next message\n * after they open anything goes.\n */\n | 'unengaged'\n /**\n * The recipient's domain takes no mail — no MX and no address record, or\n * an RFC 7505 null MX — so the message would only have bounced\n * (AGL-3328). Refused for every purpose, transactional included, before\n * the provider was called; the address is suppressed with a reason of its\n * own. Terminal: the preflight answers the same until the domain's DNS\n * changes, which it re-reads daily.\n */\n | 'undeliverable'\n /**\n * A BULK or cold message whose recipient sits behind a mail gateway that\n * refused this sending domain twice in thirty days and delivered nothing\n * (AGL-3328). Terminal for this message rather than deferrable: the hold\n * lifts when the gateway delivers again or the refusals age out, which is\n * not something a sweep's next beat can wait out. Mail the recipient asked\n * for is never held.\n */\n | 'gateway-held'\n /**\n * The site or workspace this message belongs to is under a full lockdown\n * (AGL-3356), carried in on its sending identity. Terminal for this\n * message: a sweep that holds work across a suspension skips the host\n * before it gets here, so a caller that reaches this refusal is one with\n * no way to come back, and retrying would only ask the same question.\n */\n | 'suspended'\n /**\n * The outbound phishing screen held this message for staff review, or\n * staff already rejected a message carrying the same signals from this\n * site (AGL-3356). Nothing was attempted. Terminal for this message:\n * `detail` names the `HS-…` reference, and once staff release the review\n * the site's next message carrying the same signals sends.\n */\n | 'held-for-review'\n\nexport type SendEmailResult =\n | { sent: true; id: string | null }\n | {\n sent: false\n reason: SendEmailFailureReason\n /** HTTP status, when Resend answered. */\n status?: number\n /** Resend's error body or the thrown message, trimmed for logs. */\n detail?: string\n /**\n * `rate-limited` only: the earliest instant a caller may try again —\n * when the platform hourly window rolls, or what the provider's own\n * `retry-after` asked for. A resumable sweep does not need to wait on\n * it; its next scheduled run is the retry.\n */\n retryAtMs?: number\n }\n\n/**\n * The retry instant when the platform send-rate governor deferred this\n * message, or `null` for every other outcome (AGL-2409).\n *\n * A FUNCTION rather than `result.reason === 'rate-limited'` at each call site,\n * because `strictNullChecks` is OFF repo-wide and TypeScript will not narrow a\n * boolean-literal discriminant without it: `if (result.sent) … else\n * result.reason` does not compile, in every consumer, for a reason that has\n * nothing to do with this union. One helper is also one place to change if the\n * shape of a deferral ever moves.\n */\nexport function rateLimitedRetryAtMs(\n result: SendEmailResult | null | undefined,\n): number | null {\n const failure = result as { reason?: string; retryAtMs?: number } | null\n if (!failure || failure.reason !== 'rate-limited') return null\n const retryAtMs = Number(failure.retryAtMs)\n return Number.isFinite(retryAtMs) ? retryAtMs : 0\n}\n\n/**\n * How long to wait when the provider names no interval of its own.\n *\n * One second, because Resend's rate limit is counted per second — so a wait\n * of a whole window is the shortest one that is certain to have cleared it.\n */\nconst PROVIDER_RETRY_FALLBACK_MS = 1_000\n\n/**\n * The longest wait a provider header may ask for.\n *\n * A `retry-after` is read off the network and reaches a scheduler, so it is\n * clamped rather than trusted: a header of `86400` would park a campaign for\n * a day on one response nobody saw. An hour is past every documented window\n * and short enough that a wrong one costs a run rather than a day.\n */\nconst PROVIDER_RETRY_MAX_MS = 3_600_000\n\n/** One header as whole seconds, or null when it is absent or unreadable. */\nfunction headerSeconds(\n headers: { get?: (name: string) => string | null } | null | undefined,\n name: string,\n): number | null {\n const raw = headers?.get?.(name)\n // `Number(null)` and `Number('')` are both 0, which would read as \"retry\n // immediately\" for a header that is not there at all.\n if (raw === null || raw === undefined || String(raw).trim() === '') return null\n const seconds = Number(raw)\n return Number.isFinite(seconds) && seconds >= 0 ? seconds : null\n}\n\n/**\n * When the provider says a refused request may be repeated.\n *\n * Read from the two headers Resend documents beside a 429, both in whole\n * seconds: `retry-after` first because it is the direct answer to this\n * question, then `ratelimit-reset`, which names when the window rolls. A\n * response carrying neither falls back to one window.\n */\nexport function providerRetryAtMs(\n headers: { get?: (name: string) => string | null } | null | undefined,\n nowMs: number = Date.now(),\n): number {\n const seconds =\n headerSeconds(headers, 'retry-after') ??\n headerSeconds(headers, 'ratelimit-reset')\n const waitMs =\n seconds === null\n ? PROVIDER_RETRY_FALLBACK_MS\n : Math.min(seconds * 1_000, PROVIDER_RETRY_MAX_MS)\n return nowMs + waitMs\n}\n\n/**\n * Why a send did not happen, or `null` when it did.\n *\n * The same accessor `rateLimitedRetryAtMs` is, generalized: `strictNullChecks`\n * is OFF repo-wide, so TypeScript will not narrow the union on `result.sent`\n * and reading `result.reason` at a call site does not compile.\n */\nexport function sendFailureReason(\n result: SendEmailResult | null | undefined,\n): SendEmailFailureReason | null {\n const failure = result as {\n sent?: boolean\n reason?: SendEmailFailureReason\n } | null\n if (!failure || failure.sent) return null\n return failure.reason ?? null\n}\n\n/**\n * Whether this outcome is worth coming back for.\n *\n * TRUE only for the two refusals a later attempt can pass: the platform hour\n * rolls, and so does the marketing frequency window. Everything else is\n * either a delivery that happened or a failure a retry repeats — a\n * suppression most of all, since retrying is the exact behavior a suppression\n * exists to stop, and a sunset for the same reason at one remove: it clears\n * when the recipient engages, which no amount of further mail from us brings\n * about.\n *\n * A resumable sweep uses this to decide whether to leave its subject\n * unstamped. Stamping on a deferrable refusal discards a message; NOT\n * stamping on a terminal one re-reads the same doomed row on every beat until\n * it crowds out the work that could succeed. Both are silent, so the\n * distinction lives here instead of at each sweep.\n *\n * A FUNCTION rather than `result.reason === …` at each call site, because\n * `strictNullChecks` is OFF repo-wide and TypeScript will not narrow a\n * boolean-literal discriminant without it — the same reason\n * {@link rateLimitedRetryAtMs} beside it is one.\n */\nexport function isDeferrableSendResult(\n result: SendEmailResult | null | undefined,\n): boolean {\n const reason = sendFailureReason(result)\n return reason === 'rate-limited' || reason === 'frequency-capped'\n}\n\n/**\n * Who a message is for, as the deliverability preflight reads it\n * (AGL-3328): `bulk` for anything a control may already refuse — marketing\n * by either of its two marks, a campaign, a resumable sweep — and\n * `transactional` for the rest, which a gateway hold never touches.\n *\n * Derived from what a sender already declares, for the reason\n * `isMarketingMessage` is: a label callers had to remember would be\n * forgotten by the one that matters, and the permissive answer is the one a\n * forgotten caller gets.\n */\nexport function emailSendPurpose(\n options: Pick<SendEmailOptions, 'priority' | 'context' | 'headers'> & { marketing?: unknown },\n): EmailSendPurpose {\n if (isMarketingMessage(options)) return 'bulk'\n if (options.headers?.['List-Unsubscribe']) return 'bulk'\n return isRefusablePriority(resolveSendPriority(options.context, options.priority))\n ? 'bulk'\n : 'transactional'\n}\n\n/** The preflight's answer, or `null` when none is installed, it failed or it ran out of time. */\nasync function askDeliverabilityPreflight(\n request: Parameters<NonNullable<ReturnType<typeof getEmailDeliverabilityPreflight>>>[0],\n label: string,\n): Promise<EmailDeliverabilityPreflightVerdict | null> {\n const preflight = getEmailDeliverabilityPreflight()\n if (!preflight) return null\n let timer: ReturnType<typeof setTimeout> | undefined\n try {\n return await Promise.race([\n preflight(request),\n new Promise<null>((resolve) => {\n timer = setTimeout(() => {\n console.warn(`${label} deliverability preflight timed out — allowing`)\n resolve(null)\n }, EMAIL_DELIVERABILITY_PREFLIGHT_TIMEOUT_MS)\n ;(timer as { unref?: () => void })?.unref?.()\n }),\n ])\n } catch (error) {\n // Fails OPEN, the governor's posture: an outage on the control must not\n // become an outage on the mail.\n console.error(`${label} deliverability preflight failed — allowing`, error)\n return null\n } finally {\n if (timer) clearTimeout(timer)\n }\n}\n\n/**\n * The send seam's half of the outbound phishing screen (AGL-3356): every\n * message a SITE sends whose identity carries the workspace\n * `hostSendingIdentity` stamped, through {@link screenTenantMessage} — the\n * pure screen, its tiers, and the installed review store. `null` when the\n * message may go; fails open, as that function documents.\n */\nexport async function askOutboundScreen(\n options: SendEmailOptions,\n label = 'email',\n): Promise<SendEmailResult | null> {\n const workspace = options.sendingIdentity?.workspace\n if (options.audience !== 'tenant' || !workspace?.hostId) return null\n const refusal = await screenTenantMessage(\n {\n workspace,\n subject: options.subject,\n fromName: options.fromName ?? null,\n // The resolved address, never anything the caller passed: the only\n // `From:` this message can leave on (AGL-3362).\n fromAddress: options.sendingIdentity?.from ?? null,\n replyTo: options.replyTo ?? null,\n bodies: [options.text, options.html],\n // A marketing message is never owed, whatever it declares.\n owed: Boolean(options.owedFor) && !isMarketingMessage(options),\n context: options.context ?? null,\n releasedReviewId: options.releasedReviewId ?? null,\n },\n label,\n )\n if (!refusal) return null\n console.warn(`${label} not sent — ${refusal.detail}`)\n return { sent: false, reason: 'held-for-review', detail: refusal.detail }\n}\n\nexport interface EmailConfig {\n apiKey: string | undefined\n from: string | undefined\n}\n\n/**\n * Reads the email environment.\n *\n * Deliberately read per call rather than captured at module load: these run\n * in serverless handlers where the module may be evaluated during a build,\n * long before the runtime env exists.\n */\nexport function getEmailConfig(): EmailConfig {\n return {\n apiKey: process.env.RESEND_API_KEY || undefined,\n from: process.env.USAGE_EMAIL_FROM || undefined,\n }\n}\n\n/**\n * True when both `RESEND_API_KEY` and `USAGE_EMAIL_FROM` are present.\n *\n * Callers that answer an HTTP request (rather than firing best-effort mail)\n * use this to return a 501 with an actionable message instead of pretending\n * to have sent something.\n */\nexport function isEmailConfigured(): boolean {\n const { apiKey, from } = getEmailConfig()\n return Boolean(apiKey && from)\n}\n\n/**\n * Applies a white-label display name to a configured sender while keeping\n * its verified address (White-Label Phase 1). Accepts either a bare address\n * (`noreply@aglyn.com`) or an RFC-5322 `Name <addr>` header and returns\n * `\"<fromName>\" <addr>`. A blank name, or a value with no extractable\n * address, yields the original `from` untouched — the sender identity is\n * never dropped on the floor.\n */\nexport function applyFromName(\n from: string | undefined,\n fromName: string | undefined,\n): string | undefined {\n const name = (fromName ?? '').trim()\n if (!from || !name) return from\n const angle = from.match(/<([^>]+)>/)\n const address = (angle ? angle[1] : from).trim()\n if (!address.includes('@')) return from\n // Quote the display name so commas/specials stay inside one mailbox.\n return `\"${name.replace(/\"/g, '')}\" <${address}>`\n}\n\nfunction normalizeRecipients(to: string | string[]): string[] {\n const list = Array.isArray(to) ? to : [to]\n return list\n .map((address) => String(address ?? '').trim())\n .filter((address) => address.includes('@'))\n}\n\n/** A Resend send payload in the provider's own wire shape. */\nexport interface ResendSendPayload {\n to?: unknown\n from?: unknown\n subject?: unknown\n [field: string]: unknown\n}\n\n/**\n * The one place that POSTs to Resend's send endpoint, and the last thing\n * standing between a payload and the network.\n *\n * A payload carrying no recipient cannot become a message. Resend answers it\n * `422 missing_required_field`, which costs an API call and then shows up in\n * the vendor dashboard as a red line indistinguishable from mail that\n * genuinely failed to deliver — carrying no subject, no recipient and nothing\n * naming the code that produced it. Diagnosing that means reading a log\n * outside the deployment and guessing. So the refusal happens here, before\n * the fetch, and names the caller's `context`.\n *\n * It throws rather than returning a `SendEmailResult`: this is a programming\n * error, not a delivery outcome. `sendEmail` filters recipients well before\n * it reaches this call, so nothing on the ordinary path can trip it. The\n * guard exists because `RESEND_SEND_ENDPOINT` is exported and any module can\n * therefore reach the send endpoint on its own, bypassing every check\n * `sendEmail` owns.\n */\nexport async function postResendEmail(\n apiKey: string,\n payload: ResendSendPayload,\n context?: string,\n): Promise<Response> {\n const raw = payload?.to\n const recipients = (Array.isArray(raw) ? raw : raw == null ? [] : [raw])\n .map((address) => String(address ?? '').trim())\n .filter(Boolean)\n if (!recipients.length) {\n throw new Error(\n `${context ? `${context} ` : ''}send refused before the network — a ` +\n 'Resend payload with no `to` field cannot become a message, and the ' +\n 'attempt would surface only as a 422 in the Resend dashboard',\n )\n }\n\n return fetch(RESEND_SEND_ENDPOINT, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${apiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(payload),\n })\n}\n\n/**\n * Sends one email through Resend.\n *\n * **Never throws and never rejects.** Outbound mail is best-effort across\n * every caller in this codebase — a checkout must not fail because a receipt\n * bounced — so every outcome comes back as a `SendEmailResult` instead. The\n * one thing callers must not do is ignore the result: `sent` is what tells\n * the user whether a message actually went out (AGL-708).\n *\n * When the env vars are missing this warns once per call and returns\n * `{ sent: false, reason: 'unconfigured' }` rather than failing, so local and\n * preview environments keep working without a Resend account.\n */\nexport async function sendEmail(\n options: SendEmailOptions,\n): Promise<SendEmailResult> {\n const { apiKey, from: configuredFrom } = getEmailConfig()\n const label = options.context ? `${options.context} email` : 'email'\n\n /*\n * THE SENDING-IDENTITY REFUSAL.\n *\n * Enforced here AND at the campaign route, independently, for the reason\n * the send-rate governor is enforced twice: the route's check is the one a\n * person sees, and this one is what holds when a caller does not make it.\n * A governor is injectable and a route is skippable, so neither may be the\n * only thing standing between an unverified domain and a send.\n *\n * Placed above the `apiKey`/`from` gate so a refusal cannot be reported as\n * `unconfigured` — the two have different owners and different fixes.\n */\n const identityRefusal = sendingIdentityRefusal(options.sendingIdentity)\n if (identityRefusal) {\n console.warn(`${label} refused — ${identityRefusal.message}`)\n return {\n sent: false,\n // A suspension is not a DNS state, and the merchant reading the\n // failure has nothing to finish — so it is named for what it is.\n reason:\n identityRefusal.code === 'workspace-suspended'\n ? 'suspended'\n : 'unverified-domain',\n detail: identityRefusal.message,\n }\n }\n\n // A resolved identity outranks the configured sender: it is the server's\n // answer to which verified address this message leaves on. Without one, the\n // white-label display name is applied to the configured verified sender\n // (White-Label Phase 1).\n //\n // Two sources, and `options` is neither of them. Nothing the caller passes\n // reaches the address — only the display name in front of it.\n const resolvedFrom = options.sendingIdentity?.from ?? null\n\n /*\n * THE PLATFORM DOMAIN IS NOT A FALLBACK FOR TENANT MAIL.\n *\n * `configuredFrom` is `USAGE_EMAIL_FROM` — an address on `aglyn.com`, where\n * Aglyn's own billing, account and console mail leaves from. A site's mail\n * reaching it means that site's list quality is charged against the domain\n * every other customer's password reset depends on.\n *\n * `resolveHostSendingIdentity` already refuses above, so a tenant caller\n * that resolved an identity never arrives here with `resolvedFrom` null.\n * This is the arm for a tenant caller that resolved NOTHING — the shape a\n * new send site takes when its author does not know an identity is owed —\n * and it is checked here rather than left to the call sites because ninety\n * of them cannot each be relied on to remember.\n */\n if (options.audience === 'tenant' && !resolvedFrom) {\n console.warn(\n `${label} refused — a site's mail cannot leave on the shared platform ` +\n 'domain, and no sending identity was resolved for it',\n )\n return {\n sent: false,\n reason: 'unverified-domain',\n detail:\n 'This message belongs to a site and no sending identity was ' +\n 'resolved for it, so it was refused rather than sent from the ' +\n 'shared Aglyn address.',\n }\n }\n\n const from = applyFromName(\n resolvedFrom ?? configuredFrom,\n options.fromName,\n )\n\n if (!apiKey || !from) {\n console.warn(\n `${label} skipped — set RESEND_API_KEY and USAGE_EMAIL_FROM to ` +\n 'deliver mail',\n )\n return { sent: false, reason: 'unconfigured' }\n }\n\n let to = normalizeRecipients(options.to)\n if (!to.length) {\n console.warn(`${label} skipped — no valid recipient address`)\n return { sent: false, reason: 'no-recipient' }\n }\n\n /*\n * THE OUTBOUND PHISHING SCREEN (AGL-3356).\n *\n * Asked for every message a SITE sends whose identity came through\n * `hostSendingIdentity` — which stamps the workspace on it — so one check\n * covers every tenant sender, first-party or marketplace, without any of\n * them calling it. See `outbound-screen-gate.ts`.\n *\n * Ahead of the preflight and every other gate: a message that must not\n * leave is decided before anything is spent on who receives it.\n */\n const screenRefusal = await askOutboundScreen(options, label)\n if (screenRefusal) return screenRefusal\n\n /*\n * THE DELIVERABILITY PREFLIGHT (AGL-3328).\n *\n * Asked before every other gate, because its refusal is the most final: a\n * recipient whose domain takes no mail is not a recipient this message or\n * any other can reach, and spending the marketing gate's reads or the\n * governor's hourly budget deciding more about them would be spending it\n * on a bounce. A recipient behind a gateway that refused this sending\n * domain twice is held — for bulk mail only; the purpose decides that,\n * and the preflight is told it.\n *\n * A multi-recipient message drops the refused and held recipients and goes\n * to the rest: one colleague's dead address must not stop the others'\n * notification.\n */\n const sendingAddress = bareSenderAddress(from)\n const preflight = await askDeliverabilityPreflight(\n {\n recipients: to.map((address) => address.toLowerCase()),\n purpose: emailSendPurpose(options),\n sendingDomain: sendingAddress ? sendingAddress.slice(sendingAddress.lastIndexOf('@') + 1) : null,\n sendingSource: options.sendingIdentity?.source ?? 'platform',\n context: options.context,\n hostId: options.marketing?.hostId ?? null,\n },\n label,\n )\n if (preflight && (preflight.refused?.length || preflight.held?.length)) {\n const stopped = new Set(\n [...(preflight.refused ?? []), ...(preflight.held ?? [])].map((entry) =>\n String(entry?.email ?? '').toLowerCase(),\n ),\n )\n const remaining = to.filter((address) => !stopped.has(address.toLowerCase()))\n if (!remaining.length) {\n const refused = preflight.refused?.[0]\n const held = preflight.held?.[0]\n const detail = refused?.reason ?? held?.reason ?? 'The recipient cannot receive this message.'\n console.warn(`${label} not sent — ${detail}`)\n return { sent: false, reason: refused ? 'undeliverable' : 'gateway-held', detail }\n }\n console.warn(\n `${label} — ${to.length - remaining.length} of ${to.length} recipients ` +\n 'dropped by the deliverability preflight',\n )\n to = remaining\n }\n\n /*\n * THE MARKETING GATE.\n *\n * Everything a marketing message owes, asked once, here — because the four\n * merchant-triggered bulk paths that owed it discharged none of it, and\n * asking four call sites to remember is the shape that produces the fifth\n * that does not.\n *\n * Ahead of the send-rate governor deliberately. A refusal here is a message\n * that must never leave, so spending platform hourly budget deciding that\n * would be budget the rest of the hour's mail no longer has.\n *\n * Nothing installed is UNGATED. Same posture as the governor: the durable\n * half lives in another library, and a deployment that never installs it\n * must still send.\n */\n /*\n * TWO URLS, and which one goes where is the whole RFC 8058 story.\n *\n * `unsubscribeUrl` is what a PERSON clicks in the footer below, and the\n * gate points it at the preference page so the stream this message belongs\n * to is one of the things they can stop instead of all of it.\n * `oneClickUrl` is what `List-Unsubscribe` names, and it must stay on the\n * route whose POST writes immediately — a mailbox provider POSTs it with\n * nobody present and reads the 200 as \"done\", which a page of checkboxes\n * cannot honor.\n *\n * It falls back to `unsubscribeUrl` for a caller that minted one link and\n * named no page, which is the only shape that was ever possible before the\n * gate minted the pair.\n */\n let unsubscribeUrl = options.marketing?.unsubscribeUrl ?? ''\n let oneClickUrl = options.marketing?.oneClickUrl ?? ''\n if (options.marketing) {\n if (to.length !== 1) {\n // Not a delivery outcome — a caller error, and one that would put the\n // first recipient's signed unsubscribe link in everybody else's copy.\n console.error(\n `${label} refused — a marketing send addresses exactly one ` +\n `recipient, and this one names ${to.length}`,\n )\n return {\n sent: false,\n reason: 'no-recipient',\n detail: 'A marketing send addresses exactly one recipient.',\n }\n }\n const gate = getMarketingSendGate()\n if (gate) {\n let verdict: Awaited<ReturnType<typeof gate>> | null\n try {\n verdict = await gate({\n hostId: options.marketing.hostId,\n siteBase: options.marketing.siteBase,\n email: to[0],\n context: options.context,\n capped: options.marketing.capped !== false,\n // Passed through verbatim, INCLUDING absent. A default topic\n // applied here would invent a stream for every caller that named\n // none and let a topic opt-out refuse messages that belong to no\n // stream — see `MarketingSendContext.topicId`.\n ...(options.marketing.topicId\n ? { topicId: options.marketing.topicId }\n : {}),\n consentHostIds: options.marketing.consentHostIds,\n consentAwaitsConfirmation: options.marketing.consentAwaitsConfirmation,\n })\n } catch (error) {\n /*\n * FAILS OPEN, and the asymmetry with `filterSendableForHost` is\n * deliberate rather than an oversight. That helper fails CLOSED\n * because a suppression list it could not read is not a list that\n * said an address is safe to mail — and it keeps doing so, inside\n * the gate. What is being caught here is the gate itself being\n * unreachable or throwing, which is an outage on the control; an\n * outage on a control that becomes an outage on the product is the\n * worse of the two bugs, and it is the posture `sendEmail` takes\n * everywhere else.\n */\n console.error(`${label} marketing gate failed — allowing`, error)\n verdict = null\n }\n if (verdict && !verdict.allowed) {\n /*\n * A cadence refusal reports as `frequency-capped` rather than earning\n * a value of its own in {@link SendEmailFailureReason}.\n *\n * That union is what {@link isDeferrableSendResult} switches on, and\n * the two are deferrable for exactly the same reason: a later attempt\n * passes because time went by. A third value would have to be added\n * to that predicate as well, and a sweep built against the older\n * vocabulary would silently treat the recipient's own request as\n * terminal and stamp the subject — discarding a message the recipient\n * asked to receive later rather than never. Which of the two it was\n * is in `detail`, where a person reading a log needs it.\n */\n const reason: SendEmailFailureReason =\n verdict.refusal === 'frequency-capped' ||\n verdict.refusal === 'cadence-limited'\n ? 'frequency-capped'\n : verdict.refusal === 'unengaged'\n ? 'unengaged'\n : 'suppressed'\n console.warn(`${label} not sent — ${verdict.detail ?? reason}`)\n return { sent: false, reason, detail: verdict.detail }\n }\n unsubscribeUrl = unsubscribeUrl || verdict?.unsubscribeUrl || ''\n oneClickUrl = oneClickUrl || verdict?.oneClickUrl || ''\n }\n if (!unsubscribeUrl) {\n // A marketing message with no way out is the defect this gate exists to\n // close, so it is said out loud rather than shipped quietly. Not a\n // refusal: the cause is a missing `EMAIL_UNSUBSCRIBE_SECRET` or a host\n // with no public origin — an operator's configuration, not the\n // recipient's problem — and refusing here would turn it into silence.\n console.warn(\n `${label} carries no unsubscribe link — set ` +\n 'EMAIL_UNSUBSCRIBE_SECRET and publish the site on a domain',\n )\n }\n }\n\n /*\n * BULK MAIL WITH NO WAY OUT DOES NOT LEAVE ON THE POOLED IDENTITY.\n *\n * The pool carries marketing for every site that has no domain of its own,\n * and what keeps that survivable is that a recipient can always stop it: the\n * complaint that would otherwise be charged to every other site on the member\n * has a cheaper alternative one click away. A message that lost its\n * unsubscribe link removes that alternative, so it is refused here rather\n * than sent at other people's expense.\n *\n * Asked AFTER the gate, because only here is the answer known. The URL may\n * arrive from the caller, from the gate that mints one per recipient, or —\n * for a campaign, which composes its own one-click pair upstream — as a\n * `List-Unsubscribe` header and no marketing context at all. Reading only one\n * of the three would refuse the senders that are behaving.\n *\n * The classification is DERIVED, never declared. See `isMarketingMessage`.\n */\n const pooledRefusal = isMarketingMessage(options)\n ? pooledMarketingRefusal(\n options.sendingIdentity,\n Boolean(unsubscribeUrl) ||\n Boolean(options.headers?.['List-Unsubscribe']),\n )\n : null\n if (pooledRefusal) {\n console.warn(`${label} refused — ${pooledRefusal.message}`)\n return {\n sent: false,\n reason: 'unverified-domain',\n detail: pooledRefusal.message,\n }\n }\n\n /*\n * THE PLATFORM SEND-RATE GOVERNOR (AGL-2409).\n *\n * Asked on EVERY send, including transactional ones, because the ceiling is\n * about total volume on one sending domain — a governor that only saw\n * campaigns would report a quiet hour while ten thousand receipts went out.\n * The governor counts what it grants.\n *\n * Two properties this block must have, in order:\n *\n * 1. **A refusal is honoured only for a refusable priority.** This is the\n * second of the two enforcement points described in `send-rate.ts`.\n * `emailSendRateVerdict` already cannot refuse a transactional send;\n * the governor is INJECTABLE, so a wrong one is reachable, and the send\n * path must still be unable to drop a password reset. Anything that is\n * not explicitly a campaign or a bulk sweep sends regardless of the\n * answer.\n * 2. **It fails open.** A governor that throws — Firestore unreachable, no\n * Admin app, a bug — must not stop mail. The counter being unavailable\n * is an outage on the control, and an outage on a control that turns\n * into an outage on the product is a worse bug than the burst it was\n * guarding. The same posture `sendEmail` takes everywhere else: it\n * never throws, and neither does this.\n */\n const priority = resolveSendPriority(options.context, options.priority)\n const governor = getEmailSendGovernor()\n if (governor) {\n let verdict: Awaited<ReturnType<typeof governor>> | null\n try {\n verdict = await governor({\n priority,\n count: to.length,\n context: options.context,\n })\n } catch (error) {\n console.error(`${label} send-rate governor failed — allowing`, error)\n verdict = null\n }\n if (verdict && !verdict.allowed && isRefusablePriority(priority)) {\n const retryAtMs =\n verdict.retryAtMs ?? emailSendRateWindowStartMs(Date.now())\n console.warn(\n `${label} deferred — platform send rate reached ` +\n `(${verdict.used ?? '?'}/${verdict.ceiling ?? '?'} this hour)`,\n )\n return {\n sent: false,\n reason: 'rate-limited',\n retryAtMs,\n detail:\n `Platform hourly send rate reached (${verdict.ceiling ?? '?'}/hour). ` +\n 'Transactional mail is unaffected.',\n }\n }\n }\n\n /*\n * THE VISIBLE OPT-OUT, on both parts.\n *\n * The header pair below is for the mailbox provider; this is for the person\n * — CAN-SPAM asks for a mechanism the recipient can see and use, and most\n * clients render no control for the header at all. Both helpers are\n * idempotent by URL, so a sender that placed its own link (a designed\n * template rendering `{{unsubscribeUrl}}`, the campaign body's footer)\n * keeps its own placement and does not get a second one.\n *\n * `text` first and `html` from the result, so the synthesized HTML part\n * that stands in for a text-only message carries the link as an anchor\n * rather than as characters.\n */\n const text = unsubscribeUrl\n ? appendUnsubscribeText(options.text ?? '', unsubscribeUrl)\n : options.text\n const html = unsubscribeUrl\n ? options.html\n ? appendUnsubscribeHtml(options.html, unsubscribeUrl)\n : renderTextEmailHtml(text ?? '', options.subject)\n : options.html\n\n try {\n const response = await postResendEmail(\n apiKey,\n {\n from,\n to,\n subject: options.subject,\n ...(text ? { text } : {}),\n // The HTML part, from the caller when it has one and otherwise\n // synthesized from `text`. A message with no HTML part carries no\n // anchors, so its links are not links in the inbox AND Resend has\n // nothing to rewrite for click tracking — see `text-email-html.ts`.\n // The caller always wins: this can only fill a gap, never override a\n // designed template.\n ...(() => {\n const body = html || renderTextEmailHtml(text ?? '', options.subject)\n return body ? { html: body } : {}\n })(),\n // The caller's headers plus the RFC 8058 pair for a marketing send.\n // Caller-first, so the campaign sender's own pair is the one that\n // ships and a merchant-authored header is never silently replaced.\n ...(() => {\n const headers = {\n ...unsubscribeHeaders(oneClickUrl || unsubscribeUrl),\n ...(options.headers ?? {}),\n }\n return Object.keys(headers).length ? { headers } : {}\n })(),\n // The caller's tags plus the `context` tag (AGL-2407). Caller-first\n // so a sender that stamps its own `context` keeps it: a tag list with\n // two entries of one name is not a shape worth discovering in\n // production, and the explicit one is the more specific.\n ...(() => {\n const caller = options.tags ?? []\n const derived = caller.some((tag) => tag?.name === 'context')\n ? []\n : contextTag(options.context)\n const tags = [...caller, ...derived]\n return tags.length ? { tags } : {}\n })(),\n ...(options.replyTo ? { reply_to: options.replyTo } : {}),\n },\n options.context,\n )\n\n if (!response.ok) {\n const detail = await response.text().catch(() => '')\n /*\n * A 429 IS NOT A STATEMENT ABOUT THIS RECIPIENT, so it does not report\n * as one. See the `rate-limited` member of\n * {@link SendEmailFailureReason} for why the distinction is load-bearing\n * rather than cosmetic — every caller in the tree already has a branch\n * for a deferral, and none of them has one for \"rejected, but try this\n * exact address again later\".\n *\n * A warning rather than an error: the provider asking for a slower pace\n * is a normal thing to be told, and logging it at the level a failed\n * delivery uses is what teaches an operator to skim past both.\n */\n if (response.status === 429) {\n const retryAtMs = providerRetryAtMs(response.headers)\n console.warn(\n `${label} deferred — the provider is rate limiting; retry in ` +\n `${Math.max(0, Math.round((retryAtMs - Date.now()) / 1000))}s`,\n )\n return {\n sent: false,\n reason: 'rate-limited',\n status: response.status,\n retryAtMs,\n detail: detail.slice(0, 500),\n }\n }\n console.error(`${label} failed`, response.status, detail)\n return {\n sent: false,\n reason: 'rejected',\n status: response.status,\n detail: detail.slice(0, 500),\n }\n }\n\n const body = (await response.json().catch(() => null)) as {\n id?: string\n } | null\n return { sent: true, id: body?.id ?? null }\n } catch (error) {\n console.error(`${label} failed`, error)\n return {\n sent: false,\n reason: 'network',\n detail: String((error as Error)?.message ?? error).slice(0, 500),\n }\n }\n}\n\nexport default sendEmail\n"],"names":["emailSendRateWindowStartMs","getEmailSendGovernor","isRefusablePriority","resolveSendPriority","renderTextEmailHtml","sendingIdentityRefusal","pooledMarketingRefusal","appendUnsubscribeHtml","appendUnsubscribeText","getMarketingSendGate","isMarketingMessage","unsubscribeHeaders","EMAIL_DELIVERABILITY_PREFLIGHT_TIMEOUT_MS","getEmailDeliverabilityPreflight","bareSenderAddress","screenTenantMessage","RESEND_SEND_ENDPOINT","contextTag","context","value","String","trim","replace","slice","name","rateLimitedRetryAtMs","result","failure","reason","retryAtMs","Number","isFinite","PROVIDER_RETRY_FALLBACK_MS","PROVIDER_RETRY_MAX_MS","headerSeconds","headers","raw","get","undefined","seconds","providerRetryAtMs","nowMs","Date","now","waitMs","Math","min","sendFailureReason","sent","isDeferrableSendResult","emailSendPurpose","options","priority","askDeliverabilityPreflight","request","label","preflight","timer","Promise","race","resolve","setTimeout","console","warn","unref","error","clearTimeout","askOutboundScreen","workspace","sendingIdentity","audience","hostId","refusal","subject","fromName","fromAddress","from","replyTo","bodies","text","html","owed","Boolean","owedFor","releasedReviewId","detail","getEmailConfig","apiKey","process","env","RESEND_API_KEY","USAGE_EMAIL_FROM","isEmailConfigured","applyFromName","angle","match","address","includes","normalizeRecipients","to","list","Array","isArray","map","filter","postResendEmail","payload","recipients","length","Error","fetch","method","Authorization","body","JSON","stringify","sendEmail","configuredFrom","identityRefusal","message","code","resolvedFrom","screenRefusal","sendingAddress","toLowerCase","purpose","sendingDomain","lastIndexOf","sendingSource","source","marketing","refused","held","stopped","Set","entry","email","remaining","has","unsubscribeUrl","oneClickUrl","gate","verdict","siteBase","capped","topicId","consentHostIds","consentAwaitsConfirmation","allowed","pooledRefusal","governor","count","used","ceiling","response","Object","keys","caller","tags","derived","some","tag","reply_to","ok","catch","status","max","round","json","id"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;CAMC,GACD,SAEEA,0BAA0B,EAC1BC,oBAAoB,EACpBC,mBAAmB,EACnBC,mBAAmB,QACd,iBAAa;AACpB,SAASC,mBAAmB,QAAQ,uBAAmB;AACvD,SACEC,sBAAsB,EACtBC,sBAAsB,QAGjB,sBAAkB;AACzB,SACEC,qBAAqB,EACrBC,qBAAqB,EACrBC,oBAAoB,EACpBC,kBAAkB,EAClBC,kBAAkB,QAEb,sBAAkB;AACzB,SACEC,yCAAyC,EACzCC,+BAA+B,QAG1B,4BAAwB;AAC/B,SAASC,iBAAiB,QAAQ,6BAAyB;AAC3D,SAASC,mBAAmB,QAAQ,4BAAwB;AAE5D,OAAO,MAAMC,uBAAuB,gCAA+B;AAgJnE;;;;;;;;;;;;;;;;;;;;;;;CAuBC,GACD,OAAO,SAASC,WAAWC,OAA2B;IACpD,MAAMC,QAAQC,OAAOF,kBAAAA,UAAW,IAC7BG,IAAI,GACJC,OAAO,CAAC,oBAAoB,KAC5BA,OAAO,CAAC,YAAY,IACpBC,KAAK,CAAC,GAAG;IACZ,OAAOJ,QAAQ;QAAC;YAAEK,MAAM;YAAWL;QAAM;KAAE,GAAG,EAAE;AAClD;AAqJA;;;;;;;;;;CAUC,GACD,OAAO,SAASM,qBACdC,MAA0C;IAE1C,MAAMC,UAAUD;IAChB,IAAI,CAACC,WAAWA,QAAQC,MAAM,KAAK,gBAAgB,OAAO;IAC1D,MAAMC,YAAYC,OAAOH,QAAQE,SAAS;IAC1C,OAAOC,OAAOC,QAAQ,CAACF,aAAaA,YAAY;AAClD;AAEA;;;;;CAKC,GACD,MA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AAO;gBACpD2B,QAAQC,IAAI,CACV,GAAGR,MAAM,oDAAoD,CAAC,GAC5D,GAAGV,KAAKyH,GAAG,CAAC,GAAGzH,KAAK0H,KAAK,CAAC,AAAC1I,CAAAA,YAAYa,KAAKC,GAAG,EAAC,IAAK,OAAO,CAAC,CAAC;gBAElE,OAAO;oBACLK,MAAM;oBACNpB,QAAQ;oBACRyI,QAAQX,SAASW,MAAM;oBACvBxI;oBACAwD,QAAQA,OAAO9D,KAAK,CAAC,GAAG;gBAC1B;YACF;YACAuC,QAAQG,KAAK,CAAC,GAAGV,MAAM,OAAO,CAAC,EAAEmG,SAASW,MAAM,EAAEhF;YAClD,OAAO;gBACLrC,MAAM;gBACNpB,QAAQ;gBACRyI,QAAQX,SAASW,MAAM;gBACvBhF,QAAQA,OAAO9D,KAAK,CAAC,GAAG;YAC1B;QACF;QAEA,MAAM0F,OAAQ,MAAMyC,SAASc,IAAI,GAAGJ,KAAK,CAAC,IAAM;QAGhD,OAAO;YAAEpH,MAAM;YAAMyH,EAAE,WAAExD,wBAAAA,KAAMwD,EAAE,oBAAI;QAAK;IAC5C,EAAE,OAAOxG,OAAO;;QACdH,QAAQG,KAAK,CAAC,GAAGV,MAAM,OAAO,CAAC,EAAEU;QACjC,OAAO;YACLjB,MAAM;YACNpB,QAAQ;YACRyD,QAAQjE,gBAAQ6C,yBAAD,AAACA,MAAiBsD,OAAO,oBAAItD,OAAO1C,KAAK,CAAC,GAAG;QAC9D;IACF;AACF;AAEA,eAAe6F,UAAS"}
|
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
* See the License for the specific language governing permissions and
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/
|
|
17
|
+
import type { SendingWorkspace } from './outbound-screen-gate';
|
|
17
18
|
/**
|
|
18
19
|
* CUSTOM SENDING DOMAINS — policy half.
|
|
19
20
|
*
|
|
@@ -677,7 +678,18 @@ export type SendingIdentityRefusalCode =
|
|
|
677
678
|
* On a domain the merchant owns the same message sends: there the complaint
|
|
678
679
|
* lands on their own name, and how they spend it is theirs to decide.
|
|
679
680
|
*/
|
|
680
|
-
| 'shared-identity-no-unsubscribe'
|
|
681
|
+
| 'shared-identity-no-unsubscribe'
|
|
682
|
+
/**
|
|
683
|
+
* The site or its workspace is under a FULL lockdown — a staff suspension
|
|
684
|
+
* for abuse, fraud, billing or a takedown (AGL-3356).
|
|
685
|
+
*
|
|
686
|
+
* Refused whatever the identity would otherwise have been, because a
|
|
687
|
+
* suspended workspace sending mail is exactly what the suspension exists
|
|
688
|
+
* to stop: the incident behind this code was a locked workspace whose
|
|
689
|
+
* event-triggered workflow could still mail on its behalf. Not the
|
|
690
|
+
* merchant's to fix, and not a DNS state — `domain` is null.
|
|
691
|
+
*/
|
|
692
|
+
| 'workspace-suspended';
|
|
681
693
|
export interface SendingIdentityRefusal {
|
|
682
694
|
code: SendingIdentityRefusalCode;
|
|
683
695
|
/** The domain at fault, or null for `platform-unconfigured`. */
|
|
@@ -701,6 +713,15 @@ export interface SendingIdentityVerdict {
|
|
|
701
713
|
summary: string;
|
|
702
714
|
/** Null on success. Both keys always present — `strictNullChecks` is off. */
|
|
703
715
|
refusal: SendingIdentityRefusal | null;
|
|
716
|
+
/**
|
|
717
|
+
* The workspace this identity was resolved for, stamped by
|
|
718
|
+
* `hostSendingIdentity` from the documents it already read (AGL-3356).
|
|
719
|
+
* `sendEmail` hands it to the outbound phishing screen, which is how one
|
|
720
|
+
* check covers every tenant sender without any of them passing anything.
|
|
721
|
+
* Absent on a platform identity and on any resolution that did not start
|
|
722
|
+
* from a host.
|
|
723
|
+
*/
|
|
724
|
+
workspace?: SendingWorkspace | null;
|
|
704
725
|
}
|
|
705
726
|
/**
|
|
706
727
|
* Choose the identity a message leaves on, or refuse.
|