@fabrika/email 0.9.0-dev.4 → 0.9.0-dev.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/directory.ts CHANGED
@@ -9,7 +9,7 @@ import { z } from 'zod'
9
9
  import { type EmailProvider, parseProviderVariables } from './config.js'
10
10
  import { emailContentOf, sameEmailContent } from './content.js'
11
11
  import { EmailDeliveryError, type EmailDeliveryResult, type EmailMessage, type EmailSender, type EmailSenderCapabilities } from './email.js'
12
- import { validateEmailAttachments, validateEmailMessage } from './validation.js'
12
+ import { validateEmailAttachments, validateEmailBroadcast, validateEmailMessage } from './validation.js'
13
13
 
14
14
  /** Resend's bound, so a local composition meets the limit a production transport has. */
15
15
  const DIRECTORY_MAX_ATTACHMENT_BYTES = 25 * 1024 * 1024
@@ -24,6 +24,7 @@ const capturedEmailSchema = z.object({
24
24
  replyTo: z.string().optional(),
25
25
  fromName: z.string().optional(),
26
26
  unsubscribeUrl: z.string().optional(),
27
+ broadcast: z.literal(true).optional(),
27
28
  attachments: z.array(z.object({ filename: z.string(), contentType: z.string(), content: z.string() })).readonly().optional(),
28
29
  capturedAt: z.number().int(),
29
30
  })
@@ -43,6 +44,7 @@ export class DirectoryEmailSender implements EmailSender {
43
44
  maxBatch: 1,
44
45
  listUnsubscribe: true,
45
46
  maxAttachmentBytes: DIRECTORY_MAX_ATTACHMENT_BYTES,
47
+ broadcast: true,
46
48
  }
47
49
  readonly #directory: string
48
50
  readonly #now: () => number
@@ -59,6 +61,7 @@ export class DirectoryEmailSender implements EmailSender {
59
61
  async send(message: EmailMessage, signal: AbortSignal): Promise<EmailDeliveryResult> {
60
62
  validateEmailMessage(message)
61
63
  validateEmailAttachments(message, this.capabilities, 'The mail capture')
64
+ validateEmailBroadcast(message, this.capabilities, 'The mail capture')
62
65
  if (signal.aborted) throw new EmailDeliveryError('The mail capture was aborted by the caller', { code: 'aborted' })
63
66
  const messageId = createHash('sha256').update(message.idempotencyKey).digest('hex')
64
67
  const captured: CapturedEmail = { messageId, idempotencyKey: message.idempotencyKey, ...emailContentOf(message), capturedAt: this.#now() }
package/src/email.ts CHANGED
@@ -23,6 +23,12 @@ export interface EmailMessage {
23
23
  * <url>` and `List-Unsubscribe-Post: List-Unsubscribe=One-Click`. A transport without `listUnsubscribe` refuses it.
24
24
  */
25
25
  readonly unsubscribeUrl?: string
26
+ /**
27
+ * One message of a send to many recipients (a newsletter, an announcement), not a reply to what the recipient did.
28
+ * A provider keeps such mail apart from transactional mail, and the law and the mailbox providers ask it to carry
29
+ * an unsubscribe, so it needs `unsubscribeUrl`. A transport without `broadcast` refuses it.
30
+ */
31
+ readonly broadcast?: boolean
26
32
  /**
27
33
  * Files the message carries, at most `MAX_EMAIL_ATTACHMENTS`, together at most the transport's `maxAttachmentBytes`.
28
34
  * A transport without `maxAttachmentBytes` refuses a message that has any; an empty list is none.
@@ -47,6 +53,14 @@ export interface EmailSenderCapabilities {
47
53
  readonly listUnsubscribe?: boolean
48
54
  /** The most attachment bytes one message carries, every file together; absent: it sends no attachments. */
49
55
  readonly maxAttachmentBytes?: number
56
+ /** File extensions it refuses an attachment for, lowercase and without the dot; absent: none. */
57
+ readonly refusedAttachmentExtensions?: readonly string[]
58
+ /** The only file extensions it sends an attachment with, lowercase and without the dot; absent: any. */
59
+ readonly attachmentExtensions?: readonly string[]
60
+ /** The fewest characters a text or HTML body has once trimmed; absent: any body that is not blank. */
61
+ readonly minBodyLength?: number
62
+ /** Whether it sends a `broadcast` message, on its provider's channel for them where it has one; absent is no. */
63
+ readonly broadcast?: boolean
50
64
  }
51
65
 
52
66
  export interface EmailSender {
@@ -0,0 +1,138 @@
1
+ // What every HTTP provider adapter shares, so an adapter holds only its provider's mapping: the request it sends for a
2
+ // message, the message id of an accepted answer, and the answers it tells apart beyond the HTTP status. The base
3
+ // validates the message against the adapter's capabilities before any I/O and classifies the rest.
4
+
5
+ import { z } from 'zod'
6
+ import type { EmailSenderIdentity } from './config.js'
7
+ import {
8
+ EmailDeliveryError,
9
+ type EmailDeliveryResult,
10
+ type EmailFetch,
11
+ type EmailMessage,
12
+ type EmailSender,
13
+ type EmailSenderCapabilities,
14
+ } from './email.js'
15
+ import { parseTimeout, postToProvider, type ProviderResponse } from './http.js'
16
+ import {
17
+ isValidEmailSenderIdentity,
18
+ isVisibleAscii,
19
+ validateEmailAttachments,
20
+ validateEmailBodies,
21
+ validateEmailBroadcast,
22
+ validateEmailMessage,
23
+ } from './validation.js'
24
+
25
+ /** The options every HTTP adapter takes beside its credentials. */
26
+ export interface HttpEmailSenderOptions {
27
+ readonly from: EmailSenderIdentity
28
+ readonly fetch?: EmailFetch
29
+ readonly timeoutMs?: number
30
+ }
31
+
32
+ export interface HttpEmailRequest {
33
+ readonly url: string
34
+ readonly headers: Readonly<Record<string, string>>
35
+ readonly body: unknown
36
+ }
37
+
38
+ export abstract class HttpEmailSender implements EmailSender {
39
+ abstract readonly capabilities: EmailSenderCapabilities
40
+ protected readonly from: EmailSenderIdentity
41
+ readonly #label: string
42
+ readonly #provider: string
43
+ readonly #fetch: EmailFetch
44
+ readonly #timeoutMs: number
45
+
46
+ /** `label` names the provider in every message, `provider` in every result. An adapter checks its credentials first. */
47
+ protected constructor(names: { readonly label: string; readonly provider: string }, options: HttpEmailSenderOptions) {
48
+ if (!isValidEmailSenderIdentity(options.from)) {
49
+ throw new EmailDeliveryError(`${names.label} sender is invalid`, { code: 'invalid_configuration' })
50
+ }
51
+ this.from = options.from
52
+ this.#label = names.label
53
+ this.#provider = names.provider
54
+ this.#fetch = options.fetch ?? ((input, init) => globalThis.fetch(input, init))
55
+ this.#timeoutMs = parseTimeout(names.label, options.timeoutMs)
56
+ }
57
+
58
+ /** The request for a message that passed validation. */
59
+ protected abstract request(message: EmailMessage): HttpEmailRequest | Promise<HttpEmailRequest>
60
+
61
+ /** The message id of a 2xx answer to `message`; undefined when the answer is not a valid success. May throw a refusal. */
62
+ protected abstract messageId(response: ProviderResponse, message: EmailMessage): string | undefined
63
+
64
+ /** A failed answer to the message the provider tells apart beyond its status; undefined leaves it to `refusalByStatus`. */
65
+ protected refusal(_response: ProviderResponse, _message: EmailMessage): EmailDeliveryError | undefined {
66
+ return undefined
67
+ }
68
+
69
+ async send(message: EmailMessage, signal: AbortSignal): Promise<EmailDeliveryResult> {
70
+ validateEmailMessage(message)
71
+ if (message.unsubscribeUrl !== undefined && this.capabilities.listUnsubscribe !== true) {
72
+ throw new EmailDeliveryError(`${this.#label} cannot write the List-Unsubscribe headers`, { code: 'invalid_message' })
73
+ }
74
+ validateEmailAttachments(message, this.capabilities, this.#label)
75
+ validateEmailBodies(message, this.capabilities, this.#label)
76
+ validateEmailBroadcast(message, this.capabilities, this.#label)
77
+
78
+ const request = await this.request(message)
79
+ const response = await postToProvider({ label: this.#label, fetch: this.#fetch, ...request, signal, timeoutMs: this.#timeoutMs })
80
+ if (!response.ok) throw this.refusal(response, message) ?? refusalByStatus(this.#label, response.status)
81
+
82
+ const messageId = this.messageId(response, message)
83
+ if (messageId === undefined || messageId === '') {
84
+ throw new EmailDeliveryError(`${this.#label} returned an invalid success response`, {
85
+ code: 'malformed_response',
86
+ httpStatus: response.status,
87
+ })
88
+ }
89
+ return { status: 'accepted', provider: this.#provider, messageId }
90
+ }
91
+ }
92
+
93
+ /** The classification of a failed answer by its status alone, for every answer an adapter does not tell apart. */
94
+ export function refusalByStatus(label: string, status: number): EmailDeliveryError {
95
+ if (status === 401 || status === 403) {
96
+ return new EmailDeliveryError(`${label} refused the credentials (${status})`, { code: 'provider_unauthorized', httpStatus: status })
97
+ }
98
+ if (status === 429) return new EmailDeliveryError(`${label} rate limit exceeded`, { code: 'rate_limited', httpStatus: status })
99
+ if (status >= 500) return new EmailDeliveryError(`${label} is unavailable`, { code: 'provider_unavailable', httpStatus: status })
100
+ return new EmailDeliveryError(`${label} rejected the request (${status})`, { code: 'provider_rejected', httpStatus: status })
101
+ }
102
+
103
+ /** RFC 5322 specials a display name may still hold after validation; any of them makes the name a quoted string. */
104
+ const DISPLAY_NAME_SPECIALS = /[()[\]:;@,.]/
105
+
106
+ /** `Name <address>` for an API that takes the sender as one header value; validation keeps the name quotable. */
107
+ export function formatMailbox(address: string, name: string | undefined): string {
108
+ if (name === undefined) return address
109
+ return DISPLAY_NAME_SPECIALS.test(name) ? `"${name}" <${address}>` : `${name} <${address}>`
110
+ }
111
+
112
+ /** An API key or token: non-empty visible ASCII, so it fits a header unchanged. */
113
+ export function isCredential(value: string): boolean {
114
+ return value.length > 0 && isVisibleAscii(value)
115
+ }
116
+
117
+ /** The name of a provider's stream or route: 1..64 letters, digits, `_` and `-`. */
118
+ export function isChannelName(value: string): boolean {
119
+ return /^[A-Za-z0-9_-]{1,64}$/.test(value)
120
+ }
121
+
122
+ /** A provider variable that holds a credential. */
123
+ export const credentialVariable = z.string().refine(isCredential)
124
+
125
+ /** An optional provider variable: empty is absent, and a present value must pass `valid`. */
126
+ export function optionalVariable(valid: (value: string) => boolean) {
127
+ return z.string().optional().transform((value) => (value === '' ? undefined : value)).refine((value) => value === undefined || valid(value))
128
+ }
129
+
130
+ /**
131
+ * The message's key as a provider that takes at most `maxLength` characters sends it. A longer key is sent as its
132
+ * SHA-256, which keeps one key one key: a retry sends the same digest, another message another.
133
+ */
134
+ export async function providerIdempotencyKey(key: string, maxLength: number): Promise<string> {
135
+ if (key.length <= maxLength) return key
136
+ const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(key)))
137
+ return `sha256:${Array.from(digest, (byte) => byte.toString(16).padStart(2, '0')).join('')}`
138
+ }
package/src/http.ts CHANGED
@@ -1,5 +1,5 @@
1
- // The request half both HTTP adapters share: the caller's signal, the adapter's own timeout, and how a thrown fetch
2
- // is classified. Messages name the provider and nothing the request carried.
1
+ // The request half both HTTP adapters share: the caller's signal, the adapter's own timeout, how a thrown fetch is
2
+ // classified, and a redirect that is never followed. Messages name the provider and nothing the request carried.
3
3
 
4
4
  import { EmailDeliveryError, type EmailFetch } from './email.js'
5
5
 
@@ -21,7 +21,10 @@ export interface ProviderResponse {
21
21
  readonly body: unknown
22
22
  }
23
23
 
24
- /** The answer with its body already read, so an abort or a timeout while the body arrives is classified as one. */
24
+ /**
25
+ * The answer with its body already read, so an abort or a timeout while the body arrives is classified as one. A redirect
26
+ * is never followed: a followed one would send the credential headers and the message to wherever it points.
27
+ */
25
28
  export async function postToProvider(request: ProviderRequest): Promise<ProviderResponse> {
26
29
  if (request.signal.aborted) throw abortedError(request.label)
27
30
  const timeout = AbortSignal.timeout(request.timeoutMs)
@@ -32,16 +35,39 @@ export async function postToProvider(request: ProviderRequest): Promise<Provider
32
35
  headers: { ...request.headers, 'Content-Type': 'application/json' },
33
36
  signal,
34
37
  body: JSON.stringify(request.body),
38
+ redirect: 'manual',
35
39
  })
40
+ if (isRedirect(response)) {
41
+ void response.body?.cancel().catch(() => undefined)
42
+ throw redirectError(request.label, response.status)
43
+ }
36
44
  const text = await untilAborted(response.text(), signal)
37
45
  return { ok: response.ok, status: response.status, body: parseJson(text) }
38
- } catch {
46
+ } catch (error) {
47
+ if (error instanceof EmailDeliveryError) throw error
39
48
  if (request.signal.aborted) throw abortedError(request.label)
40
49
  if (timeout.aborted) throw new EmailDeliveryError(`${request.label} request timed out`, { code: 'request_timeout' })
41
50
  throw new EmailDeliveryError(`${request.label} request failed`, { code: 'network_error' })
42
51
  }
43
52
  }
44
53
 
54
+ /**
55
+ * A 3xx, or the opaque answer a browser-like runtime gives for one under `redirect: 'manual'`. The endpoint answered
56
+ * without taking the message, and the same request gets the same answer, so it is a permanent `provider_rejected`: the
57
+ * configured URL is not the provider's API, and a person fixes it.
58
+ */
59
+ function isRedirect(response: Response): boolean {
60
+ return response.type === 'opaqueredirect' || (response.status >= 300 && response.status < 400)
61
+ }
62
+
63
+ function redirectError(label: string, status: number): EmailDeliveryError {
64
+ const shown = status === 0 ? '' : ` (HTTP ${status})`
65
+ return new EmailDeliveryError(`${label} answered with a redirect${shown}, which is not followed`, {
66
+ code: 'provider_rejected',
67
+ ...(status === 0 ? {} : { httpStatus: status }),
68
+ })
69
+ }
70
+
45
71
  export function parseTimeout(label: string, value: number | undefined): number {
46
72
  const timeoutMs = value ?? 10_000
47
73
  if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 120_000) {
package/src/index.ts CHANGED
@@ -36,5 +36,7 @@ export {
36
36
  MAX_EMAIL_SUBJECT_LENGTH,
37
37
  MAX_UNSUBSCRIBE_URL_LENGTH,
38
38
  validateEmailAttachments,
39
+ validateEmailBodies,
40
+ validateEmailBroadcast,
39
41
  validateEmailMessage,
40
42
  } from './validation.js'
@@ -0,0 +1,153 @@
1
+ // Lettermint's Sending API (https://lettermint.co/docs/api-reference/sending), built from its OpenAPI document and
2
+ // verified on a live project in October 2026. It keeps an idempotency key for 24 hours, and a 202 means it took the
3
+ // message.
4
+
5
+ import { z } from 'zod'
6
+ import { type EmailProvider, parseProviderVariables } from './config.js'
7
+ import { base64Of } from './content.js'
8
+ import { EmailDeliveryError, type EmailMessage, type EmailSenderCapabilities, oneClickUnsubscribeHeaders } from './email.js'
9
+ import {
10
+ credentialVariable,
11
+ formatMailbox,
12
+ type HttpEmailRequest,
13
+ HttpEmailSender,
14
+ type HttpEmailSenderOptions,
15
+ isChannelName,
16
+ isCredential,
17
+ optionalVariable,
18
+ providerIdempotencyKey,
19
+ } from './http-sender.js'
20
+ import type { ProviderResponse } from './http.js'
21
+
22
+ const LETTERMINT_SEND_URL = 'https://api.lettermint.co/v1/send'
23
+ /** The slug Lettermint gives a new project's broadcast route. */
24
+ const DEFAULT_BROADCAST_ROUTE = 'broadcast'
25
+ const MAX_IDEMPOTENCY_KEY_LENGTH = 255
26
+ /** `pending` and `scheduled` are documented; the id is what counts, so a new status is no failure. */
27
+ const lettermintSuccessSchema = z.object({ message_id: z.string() })
28
+ /** Lettermint refuses a text or HTML body shorter than this with a 422, counting characters once trimmed. */
29
+ const LETTERMINT_MIN_BODY_LENGTH = 3
30
+ /** A 409 carries only a `message`; the one for a key reused with another body says so in these words. */
31
+ const lettermintErrorSchema = z.object({ message: z.string() })
32
+ const OTHER_PAYLOAD = /payload/i
33
+ /** A structured refusal, whose message names a route the project lacks; read only to say so, never put into the error. */
34
+ const lettermintApiErrorSchema = z.object({ error: z.object({ message: z.string() }) })
35
+ const UNKNOWN_ROUTE = /route/i
36
+ /** Lettermint refuses a request over 25 MB with its attachments base64; 15 MiB of bytes leaves room for the bodies. */
37
+ const LETTERMINT_MAX_ATTACHMENT_BYTES = 15 * 1024 * 1024
38
+
39
+ export interface LettermintEmailSenderOptions extends HttpEmailSenderOptions {
40
+ /** A project API token: it sends through that project's default route. */
41
+ readonly projectToken: string
42
+ /** The slug of the project's broadcast route, which a `broadcast` message goes through; `broadcast` by default. */
43
+ readonly broadcastRoute?: string
44
+ }
45
+
46
+ export class LettermintEmailSender extends HttpEmailSender {
47
+ readonly capabilities: EmailSenderCapabilities = {
48
+ idempotent: true,
49
+ confirmation: 'sync',
50
+ maxBatch: 1,
51
+ listUnsubscribe: true,
52
+ maxAttachmentBytes: LETTERMINT_MAX_ATTACHMENT_BYTES,
53
+ minBodyLength: LETTERMINT_MIN_BODY_LENGTH,
54
+ broadcast: true,
55
+ }
56
+ readonly #projectToken: string
57
+ readonly #broadcastRoute: string
58
+
59
+ constructor(options: LettermintEmailSenderOptions) {
60
+ if (!isCredential(options.projectToken)) {
61
+ throw new EmailDeliveryError('Lettermint project token is invalid', { code: 'invalid_configuration' })
62
+ }
63
+ const broadcastRoute = options.broadcastRoute ?? DEFAULT_BROADCAST_ROUTE
64
+ if (!isChannelName(broadcastRoute)) {
65
+ throw new EmailDeliveryError('Lettermint broadcast route is invalid', { code: 'invalid_configuration' })
66
+ }
67
+ super({ label: 'Lettermint', provider: 'lettermint' }, options)
68
+ this.#projectToken = options.projectToken
69
+ this.#broadcastRoute = broadcastRoute
70
+ }
71
+
72
+ protected async request(message: EmailMessage): Promise<HttpEmailRequest> {
73
+ const attachments = message.attachments ?? []
74
+ return {
75
+ url: LETTERMINT_SEND_URL,
76
+ headers: {
77
+ 'x-lettermint-token': this.#projectToken,
78
+ 'Idempotency-Key': await providerIdempotencyKey(message.idempotencyKey, MAX_IDEMPOTENCY_KEY_LENGTH),
79
+ },
80
+ body: {
81
+ from: formatMailbox(this.from.address, message.fromName ?? this.from.name),
82
+ to: [message.to],
83
+ // Lettermint keeps broadcast mail on infrastructure apart from the transactional route.
84
+ ...(message.broadcast === true ? { route: this.#broadcastRoute } : {}),
85
+ subject: message.subject,
86
+ text: message.text,
87
+ ...(message.html === undefined ? {} : { html: message.html }),
88
+ ...(message.replyTo === undefined ? {} : { reply_to: [message.replyTo] }),
89
+ ...(message.unsubscribeUrl === undefined ? {} : { headers: oneClickUnsubscribeHeaders(message.unsubscribeUrl) }),
90
+ ...(attachments.length === 0
91
+ ? {}
92
+ : {
93
+ attachments: attachments.map((attachment) => ({
94
+ filename: attachment.filename,
95
+ content: base64Of(attachment.content),
96
+ content_type: attachment.contentType,
97
+ })),
98
+ }),
99
+ },
100
+ }
101
+ }
102
+
103
+ protected messageId(response: ProviderResponse): string | undefined {
104
+ return lettermintSuccessSchema.safeParse(response.body).data?.message_id
105
+ }
106
+
107
+ protected override refusal(response: ProviderResponse, message: EmailMessage): EmailDeliveryError | undefined {
108
+ const status = response.status
109
+ // Only a broadcast message names a route; a transactional one takes the project's default, so its 422 is another.
110
+ if (
111
+ status === 422 && message.broadcast === true && UNKNOWN_ROUTE.test(lettermintApiErrorSchema.safeParse(response.body).data?.error.message ?? '')
112
+ ) {
113
+ return new EmailDeliveryError(
114
+ 'Lettermint knows no such route in the project: create its broadcast route, or name it in FABRIKA_EMAIL_LETTERMINT_BROADCAST_ROUTE (422)',
115
+ { code: 'provider_rejected', httpStatus: status },
116
+ )
117
+ }
118
+ if (status !== 409) return undefined
119
+ // The 409 has no code, so its text is read, and only to tell the two apart; it never reaches the error. A wording
120
+ // that no longer names the payload reads as in progress, which a retry cannot turn into a second delivery.
121
+ const text = lettermintErrorSchema.safeParse(response.body).data?.message
122
+ if (text !== undefined && OTHER_PAYLOAD.test(text)) {
123
+ return new EmailDeliveryError('Lettermint already took a different request under this idempotency key', {
124
+ code: 'idempotency_conflict',
125
+ httpStatus: status,
126
+ })
127
+ }
128
+ // Every other 409 is a request under the key still in progress, or one whose outcome is unknown, which Lettermint
129
+ // answers the same way until the key expires. A retry cannot deliver twice, so it is retried.
130
+ return new EmailDeliveryError('A matching Lettermint request is still in progress', { code: 'request_in_progress', httpStatus: status })
131
+ }
132
+ }
133
+
134
+ const lettermintVariablesSchema = z.object({
135
+ FABRIKA_EMAIL_LETTERMINT_PROJECT_TOKEN: credentialVariable,
136
+ FABRIKA_EMAIL_LETTERMINT_BROADCAST_ROUTE: optionalVariable(isChannelName),
137
+ })
138
+
139
+ export const lettermintEmailProvider: EmailProvider = {
140
+ variables: [
141
+ { name: 'FABRIKA_EMAIL_LETTERMINT_PROJECT_TOKEN', secret: true, required: true },
142
+ { name: 'FABRIKA_EMAIL_LETTERMINT_BROADCAST_ROUTE', secret: false, required: false },
143
+ ],
144
+ create({ from, env, fetch }) {
145
+ const variables = parseProviderVariables(lettermintVariablesSchema, env)
146
+ return new LettermintEmailSender({
147
+ projectToken: variables.FABRIKA_EMAIL_LETTERMINT_PROJECT_TOKEN,
148
+ broadcastRoute: variables.FABRIKA_EMAIL_LETTERMINT_BROADCAST_ROUTE,
149
+ from,
150
+ fetch,
151
+ })
152
+ },
153
+ }
package/src/memory.ts CHANGED
@@ -11,7 +11,7 @@ import {
11
11
  type EmailSender,
12
12
  type EmailSenderCapabilities,
13
13
  } from './email.js'
14
- import { validateEmailAttachments, validateEmailMessage } from './validation.js'
14
+ import { validateEmailAttachments, validateEmailBroadcast, validateEmailMessage } from './validation.js'
15
15
 
16
16
  export interface MemoryEmail {
17
17
  readonly message: EmailMessage
@@ -82,6 +82,7 @@ export class MemoryEmailSender implements EmailSender {
82
82
  maxBatch: 1,
83
83
  listUnsubscribe: true,
84
84
  maxAttachmentBytes: MEMORY_MAX_ATTACHMENT_BYTES,
85
+ broadcast: true,
85
86
  ...options.capabilities,
86
87
  }
87
88
  if (!Number.isSafeInteger(this.capabilities.maxBatch) || this.capabilities.maxBatch < 1) {
@@ -138,6 +139,7 @@ export class MemoryEmailSender implements EmailSender {
138
139
  throw new EmailDeliveryError('The memory sender writes no List-Unsubscribe header', { code: 'invalid_message' })
139
140
  }
140
141
  validateEmailAttachments(message, this.capabilities, 'The memory sender')
142
+ validateEmailBroadcast(message, this.capabilities, 'The memory sender')
141
143
  if (signal.aborted) throw failure('aborted')
142
144
  const handoff: MutableHandoff = { message, at: this.#now(), taken: false, answer: 'network_error' }
143
145
  this.#handoffs.push(handoff)
@@ -17,6 +17,8 @@ export const PLATFORM_MAIL_CAPABILITIES: EmailSenderCapabilities = {
17
17
  maxBatch: 1,
18
18
  listUnsubscribe: true,
19
19
  maxAttachmentBytes: 10 * 1024 * 1024,
20
+ // Control refuses one at once when its own transport sends none, and dispatches it on the provider's channel.
21
+ broadcast: true,
20
22
  }
21
23
 
22
24
  const LABEL = 'Platform mail'
@@ -38,6 +40,8 @@ interface PlatformMailRequest {
38
40
  readonly replyTo?: string
39
41
  readonly fromName?: string
40
42
  readonly unsubscribeUrl?: string
43
+ /** Present only when true, so a transactional message encodes, and fingerprints, as it did before the field. */
44
+ readonly broadcast?: true
41
45
  readonly attachments?: readonly PlatformMailAttachment[]
42
46
  }
43
47
 
@@ -52,6 +56,7 @@ function platformMailRequestOf(message: EmailMessage): PlatformMailRequest {
52
56
  ...(message.replyTo === undefined ? {} : { replyTo: message.replyTo }),
53
57
  ...(message.fromName === undefined ? {} : { fromName: message.fromName }),
54
58
  ...(message.unsubscribeUrl === undefined ? {} : { unsubscribeUrl: message.unsubscribeUrl }),
59
+ ...(message.broadcast === true ? { broadcast: true } : {}),
55
60
  ...(attachments.length === 0
56
61
  ? {}
57
62
  : {
@@ -118,6 +123,7 @@ const requestSchema = z.object({
118
123
  replyTo: z.string().optional(),
119
124
  fromName: z.string().optional(),
120
125
  unsubscribeUrl: z.string().optional(),
126
+ broadcast: z.literal(true).optional(),
121
127
  attachments: z.array(attachmentSchema).optional(),
122
128
  }).strict()
123
129
 
package/src/platform.ts CHANGED
@@ -7,8 +7,14 @@ import {
7
7
  type EmailSenderCapabilities,
8
8
  } from './email.js'
9
9
  import { parseTimeout, postToProvider } from './http.js'
10
- import { encodePlatformMailRequest, parsePlatformMailAnswer, PLATFORM_MAIL_CAPABILITIES, PLATFORM_MAIL_SEND_PATH } from './platform-wire.js'
11
- import { isVisibleAscii, validateEmailAttachments, validateEmailMessage } from './validation.js'
10
+ import {
11
+ encodePlatformMailRequest,
12
+ installationMailKey,
13
+ parsePlatformMailAnswer,
14
+ PLATFORM_MAIL_CAPABILITIES,
15
+ PLATFORM_MAIL_SEND_PATH,
16
+ } from './platform-wire.js'
17
+ import { isVisibleAscii, validateEmailAttachments, validateEmailBroadcast, validateEmailMessage } from './validation.js'
12
18
 
13
19
  export {
14
20
  encodePlatformMailRequest,
@@ -68,6 +74,7 @@ export class PlatformEmailSender implements EmailSender {
68
74
  async send(message: EmailMessage, signal: AbortSignal): Promise<EmailDeliveryResult> {
69
75
  validateEmailMessage(message)
70
76
  validateEmailAttachments(message, this.capabilities, LABEL)
77
+ validateEmailBroadcast(message, this.capabilities, LABEL)
71
78
 
72
79
  // postToProvider serializes the body itself; the canonical text survives the round trip unchanged.
73
80
  const body: unknown = JSON.parse(encodePlatformMailRequest(message))
@@ -98,8 +105,48 @@ export class PlatformEmailSender implements EmailSender {
98
105
  }
99
106
  }
100
107
 
101
- /** `http(s)://host[:port]` exactly as written: no path, query, fragment or credentials. */
102
- function isHttpOrigin(value: string): boolean {
108
+ export interface InstallationMailSenderOptions {
109
+ /** Control's http(s) origin; the send path is appended to it. */
110
+ readonly url: string
111
+ /** The secret the service shares with Control, which its key derives from (`installationMailKey`). */
112
+ readonly secret: string
113
+ readonly fetch?: EmailFetch
114
+ readonly timeoutMs?: number
115
+ }
116
+
117
+ /**
118
+ * An installation service's sender to Control's relay: a `PlatformEmailSender` under `installationMailKey(secret)`,
119
+ * built at the first send because deriving the key is asynchronous. A send that cannot build it (a URL that is not an
120
+ * origin, a secret that is not usable) throws and keeps nothing, so the next send builds it again.
121
+ */
122
+ export function installationMailSender(options: InstallationMailSenderOptions): EmailSender {
123
+ let sender: Promise<PlatformEmailSender> | undefined
124
+ return {
125
+ capabilities: PLATFORM_MAIL_CAPABILITIES,
126
+ async send(message, signal) {
127
+ const pending = sender ??= installationMailKey(options.secret).then((key) =>
128
+ new PlatformEmailSender({
129
+ url: options.url,
130
+ key,
131
+ ...(options.fetch === undefined ? {} : { fetch: options.fetch }),
132
+ ...(options.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs }),
133
+ })
134
+ )
135
+ const ready = await pending.catch((error: unknown) => {
136
+ // Only the build that failed is dropped; a send that started a newer one keeps it.
137
+ if (sender === pending) sender = undefined
138
+ throw error
139
+ })
140
+ return ready.send(message, signal)
141
+ },
142
+ }
143
+ }
144
+
145
+ /**
146
+ * `http(s)://host[:port]` exactly as written: no path, query, fragment or credentials. The one check of a relay's origin,
147
+ * for the sender, IAM's boot and IAM's Cloudflare deploy (which also requires `https:`).
148
+ */
149
+ export function isHttpOrigin(value: string): boolean {
103
150
  try {
104
151
  const url = new URL(value)
105
152
  return (url.protocol === 'http:' || url.protocol === 'https:') && url.origin === value