@fabrika/email 0.9.0-dev.2 → 0.9.0-dev.21

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/email",
3
- "version": "0.9.0-dev.2",
3
+ "version": "0.9.0-dev.21",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -26,6 +26,31 @@
26
26
  "types": "./types/src/resend.d.ts",
27
27
  "default": "./src/resend.ts"
28
28
  },
29
+ "./postmark": {
30
+ "bun": "./src/postmark.ts",
31
+ "types": "./types/src/postmark.d.ts",
32
+ "default": "./src/postmark.ts"
33
+ },
34
+ "./ahasend": {
35
+ "bun": "./src/ahasend.ts",
36
+ "types": "./types/src/ahasend.d.ts",
37
+ "default": "./src/ahasend.ts"
38
+ },
39
+ "./brevo": {
40
+ "bun": "./src/brevo.ts",
41
+ "types": "./types/src/brevo.d.ts",
42
+ "default": "./src/brevo.ts"
43
+ },
44
+ "./cloudflare": {
45
+ "bun": "./src/cloudflare.ts",
46
+ "types": "./types/src/cloudflare.d.ts",
47
+ "default": "./src/cloudflare.ts"
48
+ },
49
+ "./lettermint": {
50
+ "bun": "./src/lettermint.ts",
51
+ "types": "./types/src/lettermint.d.ts",
52
+ "default": "./src/lettermint.ts"
53
+ },
29
54
  "./directory": {
30
55
  "bun": "./src/directory.ts",
31
56
  "types": "./types/src/directory.d.ts",
@@ -58,7 +83,7 @@
58
83
  }
59
84
  },
60
85
  "scripts": {
61
- "typecheck": "tsc --noEmit",
86
+ "typecheck": "tsrs --build tsconfig.test.json",
62
87
  "test": "bun test src/__tests__"
63
88
  },
64
89
  "dependencies": {
package/src/ahasend.ts ADDED
@@ -0,0 +1,172 @@
1
+ // AhaSend's API v2 (https://ahasend.com/docs/api-reference/messages/create-message), built from its documentation and
2
+ // verified on a live account in October 2026. It keeps an idempotency key for 24 hours, and a 202 carries one result
3
+ // per recipient, which can itself be a refusal. It renders a message's content as a template only when the request
4
+ // carries substitutions, which this adapter never sends, so `{{` in a message reaches the recipient as written.
5
+
6
+ import { z } from 'zod'
7
+ import { type EmailProvider, parseProviderVariables } from './config.js'
8
+ import { base64Of } from './content.js'
9
+ import { EmailDeliveryError, type EmailMessage, type EmailSenderCapabilities, oneClickUnsubscribeHeaders } from './email.js'
10
+ import {
11
+ credentialVariable,
12
+ type HttpEmailRequest,
13
+ HttpEmailSender,
14
+ type HttpEmailSenderOptions,
15
+ isCredential,
16
+ optionalVariable,
17
+ providerIdempotencyKey,
18
+ } from './http-sender.js'
19
+ import type { ProviderResponse } from './http.js'
20
+ import { isValidEmailAddress } from './validation.js'
21
+
22
+ const AHASEND_API_URL = 'https://api.ahasend.com/v2/accounts'
23
+ const ACCOUNT_ID_PATTERN = /^[A-Za-z0-9-]{1,64}$/
24
+ /** A refusal carries only a free-text `message`, read here to tell a reused key from another 422 and never put into an error. */
25
+ const ahaSendErrorSchema = z.object({ message: z.string() })
26
+ const KEY_REUSED = /idempotency key/i
27
+ const MAX_IDEMPOTENCY_KEY_LENGTH = 255
28
+ const ahaSendResultSchema = z.object({
29
+ // `queued` and `scheduled` are documented; any status but `error` with an id is taken, so a new one is no failure.
30
+ data: z.tuple([z.object({ status: z.string(), id: z.string().nullable() })]),
31
+ })
32
+ /**
33
+ * AhaSend refuses a message over 20 MiB with its attachments base64 and MIME-wrapped; 12 MiB of bytes leaves room for
34
+ * the bodies, and its body stays under the 30 MB request bound.
35
+ */
36
+ const AHASEND_MAX_ATTACHMENT_BYTES = 12 * 1024 * 1024
37
+
38
+ export interface AhaSendEmailSenderOptions extends HttpEmailSenderOptions {
39
+ /** An API key v2, scoped to `messages:send:{domain}` at least. */
40
+ readonly apiKey: string
41
+ /** The account the key belongs to: the path of every request. */
42
+ readonly accountId: string
43
+ /**
44
+ * The address a `broadcast` message is sent from, on a domain the account has configured as a Marketing domain:
45
+ * AhaSend's terms allow marketing mail through the API from such a domain only. Without it, a broadcast is refused.
46
+ */
47
+ readonly broadcastFrom?: string
48
+ }
49
+
50
+ /** A refusal's body is one free-text `message`, so only the status is read. */
51
+ export class AhaSendEmailSender extends HttpEmailSender {
52
+ /** `broadcast` only with `broadcastFrom`. */
53
+ readonly capabilities: EmailSenderCapabilities
54
+ readonly #apiKey: string
55
+ readonly #messagesUrl: string
56
+ readonly #broadcastFrom: string | undefined
57
+
58
+ constructor(options: AhaSendEmailSenderOptions) {
59
+ if (!isCredential(options.apiKey)) {
60
+ throw new EmailDeliveryError('AhaSend API key is invalid', { code: 'invalid_configuration' })
61
+ }
62
+ if (!ACCOUNT_ID_PATTERN.test(options.accountId)) {
63
+ throw new EmailDeliveryError('AhaSend account ID is invalid', { code: 'invalid_configuration' })
64
+ }
65
+ if (options.broadcastFrom !== undefined && !isValidEmailAddress(options.broadcastFrom)) {
66
+ throw new EmailDeliveryError('AhaSend broadcast sender is invalid', { code: 'invalid_configuration' })
67
+ }
68
+ super({ label: 'AhaSend', provider: 'ahasend' }, options)
69
+ this.#apiKey = options.apiKey
70
+ this.#messagesUrl = `${AHASEND_API_URL}/${options.accountId}/messages`
71
+ this.#broadcastFrom = options.broadcastFrom
72
+ this.capabilities = {
73
+ idempotent: true,
74
+ confirmation: 'sync',
75
+ maxBatch: 1,
76
+ listUnsubscribe: true,
77
+ maxAttachmentBytes: AHASEND_MAX_ATTACHMENT_BYTES,
78
+ ...(options.broadcastFrom === undefined ? {} : { broadcast: true }),
79
+ }
80
+ }
81
+
82
+ protected async request(message: EmailMessage): Promise<HttpEmailRequest> {
83
+ const senderName = message.fromName ?? this.from.name
84
+ // `send` refused a broadcast message without `broadcastFrom`; never send one from the transactional domain.
85
+ const fromAddress = message.broadcast === true ? this.#broadcastFrom : this.from.address
86
+ if (fromAddress === undefined) throw new EmailDeliveryError('AhaSend sends no broadcast email', { code: 'invalid_message' })
87
+ const attachments = message.attachments ?? []
88
+ return {
89
+ url: this.#messagesUrl,
90
+ headers: {
91
+ Authorization: `Bearer ${this.#apiKey}`,
92
+ 'Idempotency-Key': await providerIdempotencyKey(message.idempotencyKey, MAX_IDEMPOTENCY_KEY_LENGTH),
93
+ },
94
+ body: {
95
+ from: {
96
+ email: fromAddress,
97
+ ...(senderName === undefined ? {} : { name: senderName }),
98
+ },
99
+ recipients: [{ email: message.to }],
100
+ subject: message.subject,
101
+ text_content: message.text,
102
+ ...(message.html === undefined ? {} : { html_content: message.html }),
103
+ ...(message.replyTo === undefined ? {} : { reply_to: { email: message.replyTo } }),
104
+ ...(message.unsubscribeUrl === undefined ? {} : { headers: oneClickUnsubscribeHeaders(message.unsubscribeUrl) }),
105
+ ...(attachments.length === 0
106
+ ? {}
107
+ : {
108
+ attachments: attachments.map((attachment) => ({
109
+ base64: true,
110
+ data: base64Of(attachment.content),
111
+ content_type: attachment.contentType,
112
+ file_name: attachment.filename,
113
+ })),
114
+ }),
115
+ },
116
+ }
117
+ }
118
+
119
+ protected messageId(response: ProviderResponse): string | undefined {
120
+ const result = ahaSendResultSchema.safeParse(response.body).data?.data[0]
121
+ if (result === undefined) return undefined
122
+ // The item's `error` is free text about the recipient, so it stays out of the refusal.
123
+ if (result.status === 'error') {
124
+ throw new EmailDeliveryError(`AhaSend refused the recipient (${response.status})`, { code: 'provider_rejected', httpStatus: response.status })
125
+ }
126
+ return result.id ?? undefined
127
+ }
128
+
129
+ protected override refusal(response: ProviderResponse): EmailDeliveryError | undefined {
130
+ const status = response.status
131
+ // Documented for an unknown account; a key of another account answers 401.
132
+ if (status === 404) {
133
+ return new EmailDeliveryError('AhaSend knows no such account (404)', { code: 'provider_unauthorized', httpStatus: status })
134
+ }
135
+ // Live, a concurrent request under the key waited for the first and replayed its answer; 409 is documented.
136
+ if (status === 409) {
137
+ return new EmailDeliveryError('A matching AhaSend request is still in progress', { code: 'request_in_progress', httpStatus: status })
138
+ }
139
+ // A malformed body is a 400; a 422 names the key reused for another request, and any other is a rejection.
140
+ if (status === 422 && KEY_REUSED.test(ahaSendErrorSchema.safeParse(response.body).data?.message ?? '')) {
141
+ return new EmailDeliveryError('AhaSend refused the idempotency key for this request (422)', {
142
+ code: 'idempotency_conflict',
143
+ httpStatus: status,
144
+ })
145
+ }
146
+ return undefined
147
+ }
148
+ }
149
+
150
+ const ahaSendVariablesSchema = z.object({
151
+ FABRIKA_EMAIL_AHASEND_API_KEY: credentialVariable,
152
+ FABRIKA_EMAIL_AHASEND_ACCOUNT_ID: z.string().regex(ACCOUNT_ID_PATTERN),
153
+ FABRIKA_EMAIL_AHASEND_BROADCAST_FROM: optionalVariable(isValidEmailAddress),
154
+ })
155
+
156
+ export const ahaSendEmailProvider: EmailProvider = {
157
+ variables: [
158
+ { name: 'FABRIKA_EMAIL_AHASEND_API_KEY', secret: true, required: true },
159
+ { name: 'FABRIKA_EMAIL_AHASEND_ACCOUNT_ID', secret: false, required: true },
160
+ { name: 'FABRIKA_EMAIL_AHASEND_BROADCAST_FROM', secret: false, required: false },
161
+ ],
162
+ create({ from, env, fetch }) {
163
+ const variables = parseProviderVariables(ahaSendVariablesSchema, env)
164
+ return new AhaSendEmailSender({
165
+ apiKey: variables.FABRIKA_EMAIL_AHASEND_API_KEY,
166
+ accountId: variables.FABRIKA_EMAIL_AHASEND_ACCOUNT_ID,
167
+ broadcastFrom: variables.FABRIKA_EMAIL_AHASEND_BROADCAST_FROM,
168
+ from,
169
+ fetch,
170
+ })
171
+ },
172
+ }
package/src/brevo.ts ADDED
@@ -0,0 +1,158 @@
1
+ // Brevo's transactional email API (https://developers.brevo.com/reference/sendtransacemail), built from its
2
+ // documentation in November 2026 and checked only against a stubbed fetch (backlog 290). A 201 carries the message id.
3
+ // Brevo dedupes a repeated `idempotencyKey` for 30 minutes only, while a relay or an outbox retries for hours, so the
4
+ // adapter sends the key but does not report itself idempotent: an unknown outcome over Brevo waits for a person.
5
+
6
+ import { z } from 'zod'
7
+ import { type EmailProvider, parseProviderVariables } from './config.js'
8
+ import { base64Of } from './content.js'
9
+ import { EmailDeliveryError, type EmailMessage, type EmailSenderCapabilities } from './email.js'
10
+ import { credentialVariable, type HttpEmailRequest, HttpEmailSender, type HttpEmailSenderOptions, isCredential } from './http-sender.js'
11
+ import type { ProviderResponse } from './http.js'
12
+
13
+ const BREVO_SEND_URL = 'https://api.brevo.com/v3/smtp/email'
14
+ const brevoSuccessSchema = z.object({ messageId: z.string() })
15
+ /** A refusal's `code` is one of a documented set; its `message` is free text and is never read. */
16
+ const brevoErrorSchema = z.object({ code: z.string() })
17
+ /** Brevo bounds a sender's or a recipient's display name at 70 characters; the contract allows 128. */
18
+ const BREVO_MAX_NAME_LENGTH = 70
19
+ /**
20
+ * Brevo bounds a transactional message at 20 MB with its attachments base64; 10 MiB of bytes leaves room for the
21
+ * bodies. Its help center also mentions 4 MB per file, which is not enforced here (backlog 290).
22
+ */
23
+ const BREVO_MAX_ATTACHMENT_BYTES = 10 * 1024 * 1024
24
+ /**
25
+ * The extensions Brevo takes an attachment with, from its API reference. It takes no media type: it derives it from the
26
+ * file name, so the adapter refuses any other file before the request instead of losing the message to a 400.
27
+ */
28
+ const BREVO_ATTACHMENT_EXTENSIONS: readonly string[] = (
29
+ 'xlsx xls ods docx docm doc csv pdf txt gif jpg jpeg png tif tiff rtf bmp cgm css shtml html htm zip xml ppt pptx tar ez ics mobi msg pub '
30
+ + 'eps odt mp3 m4a m4v wma ogg flac wav aif aifc aiff mp4 mov avi mkv mpeg mpg wmv pkpass xlsm'
31
+ ).split(' ')
32
+ /**
33
+ * A repeated idempotency key (`duplicate_parameter`), an identical request too soon (`duplicate_request`), or a request
34
+ * the reference's error codes call already processed: each says an earlier request may have sent the message.
35
+ */
36
+ const DUPLICATE_CODES: ReadonlySet<string> = new Set(['duplicate_parameter', 'duplicate_request', 'Request already processed'])
37
+ /** The account has no credits left (402 `not_enough_credits`; the reference also lists `Insufficient credits`). */
38
+ const NO_CREDITS_CODES: ReadonlySet<string> = new Set(['not_enough_credits', 'Insufficient credits'])
39
+ /**
40
+ * The key or the account may not send: a failed authentication, an unknown key, a missing permission, an account still
41
+ * validated. The reference lists `Authentication failed` and `api-key not found` beside the snake_case codes.
42
+ */
43
+ const NOT_ALLOWED_CODES: ReadonlySet<string> = new Set([
44
+ 'unauthorized',
45
+ 'Authentication failed',
46
+ 'api-key not found',
47
+ 'permission_denied',
48
+ 'account_under_validation',
49
+ ])
50
+
51
+ export interface BrevoEmailSenderOptions extends HttpEmailSenderOptions {
52
+ /** An API key (v3) of the account. */
53
+ readonly apiKey: string
54
+ }
55
+
56
+ export class BrevoEmailSender extends HttpEmailSender {
57
+ readonly capabilities: EmailSenderCapabilities = {
58
+ // Brevo keeps a key for 30 minutes, shorter than any retry horizon here, so a late retry could deliver twice.
59
+ idempotent: false,
60
+ confirmation: 'sync',
61
+ maxBatch: 1,
62
+ maxAttachmentBytes: BREVO_MAX_ATTACHMENT_BYTES,
63
+ attachmentExtensions: BREVO_ATTACHMENT_EXTENSIONS,
64
+ // No `listUnsubscribe`, and so no `broadcast`: Brevo takes no standard header in `headers`, so `List-Unsubscribe`
65
+ // is not known to reach the recipient.
66
+ }
67
+ readonly #apiKey: string
68
+
69
+ constructor(options: BrevoEmailSenderOptions) {
70
+ if (!isCredential(options.apiKey)) {
71
+ throw new EmailDeliveryError('Brevo API key is invalid', { code: 'invalid_configuration' })
72
+ }
73
+ if (options.from.name !== undefined && options.from.name.length > BREVO_MAX_NAME_LENGTH) {
74
+ throw new EmailDeliveryError(`Brevo sender name is longer than ${BREVO_MAX_NAME_LENGTH} characters`, { code: 'invalid_configuration' })
75
+ }
76
+ super({ label: 'Brevo', provider: 'brevo' }, options)
77
+ this.#apiKey = options.apiKey
78
+ }
79
+
80
+ protected async request(message: EmailMessage): Promise<HttpEmailRequest> {
81
+ const name = message.fromName ?? this.from.name
82
+ if (name !== undefined && name.length > BREVO_MAX_NAME_LENGTH) {
83
+ throw new EmailDeliveryError(`Brevo sends no sender name longer than ${BREVO_MAX_NAME_LENGTH} characters`, { code: 'invalid_message' })
84
+ }
85
+ const attachments = message.attachments ?? []
86
+ return {
87
+ url: BREVO_SEND_URL,
88
+ headers: { 'api-key': this.#apiKey, Accept: 'application/json' },
89
+ body: {
90
+ sender: { email: this.from.address, ...(name === undefined ? {} : { name }) },
91
+ to: [{ email: message.to }],
92
+ subject: message.subject,
93
+ // Brevo requires an HTML body without a template; a message without one, or with a blank one, gets its text
94
+ // as HTML, so the recipient never sees an empty message.
95
+ htmlContent: message.html === undefined || message.html.trim() === '' ? brevoHtmlOfText(message.text) : message.html,
96
+ textContent: message.text,
97
+ ...(message.replyTo === undefined ? {} : { replyTo: { email: message.replyTo } }),
98
+ headers: { idempotencyKey: await brevoIdempotencyKey(message.idempotencyKey) },
99
+ ...(attachments.length === 0
100
+ ? {}
101
+ : { attachment: attachments.map((attachment) => ({ name: attachment.filename, content: base64Of(attachment.content) })) }),
102
+ },
103
+ }
104
+ }
105
+
106
+ protected messageId(response: ProviderResponse): string | undefined {
107
+ return brevoSuccessSchema.safeParse(response.body).data?.messageId
108
+ }
109
+
110
+ protected override refusal(response: ProviderResponse): EmailDeliveryError | undefined {
111
+ const status = response.status
112
+ const code = brevoErrorSchema.safeParse(response.body).data?.code
113
+ if (status === 402 || (code !== undefined && NO_CREDITS_CODES.has(code))) {
114
+ return new EmailDeliveryError(`Brevo account has no credits left (${status})`, { code: 'quota_exceeded', httpStatus: status })
115
+ }
116
+ // A 429 or a 5xx keeps the meaning of its status whatever its code.
117
+ if (code === undefined || status >= 500 || status === 429) return undefined
118
+ if (DUPLICATE_CODES.has(code)) {
119
+ // Brevo took a request under this key, or an identical one, and does not say whether its content matched.
120
+ return new EmailDeliveryError(`Brevo already took a request under this idempotency key (${status})`, {
121
+ code: 'idempotency_conflict',
122
+ httpStatus: status,
123
+ })
124
+ }
125
+ if (NOT_ALLOWED_CODES.has(code)) {
126
+ return new EmailDeliveryError(`Brevo refused the key or the account (${status})`, { code: 'provider_unauthorized', httpStatus: status })
127
+ }
128
+ return undefined
129
+ }
130
+ }
131
+
132
+ /**
133
+ * The message's key as Brevo takes it, a UUID: the first 16 bytes of its SHA-256 with the version 4 and variant bits
134
+ * set. One key is always one UUID, so a retry sends the same one; Brevo recommends a version 4 UUID.
135
+ */
136
+ async function brevoIdempotencyKey(key: string): Promise<string> {
137
+ const bytes = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(key))).slice(0, 16)
138
+ bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40
139
+ bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80
140
+ const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('')
141
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`
142
+ }
143
+
144
+ /** A plain text as the HTML body Brevo requires: every character escaped, each line break a `<br>`. */
145
+ export function brevoHtmlOfText(text: string): string {
146
+ const escaped = text.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;').replaceAll("'", '&#39;')
147
+ return escaped.replace(/\r\n|\r|\n/g, '<br>\n')
148
+ }
149
+
150
+ const brevoVariablesSchema = z.object({ FABRIKA_EMAIL_BREVO_API_KEY: credentialVariable })
151
+
152
+ export const brevoEmailProvider: EmailProvider = {
153
+ variables: [{ name: 'FABRIKA_EMAIL_BREVO_API_KEY', secret: true, required: true }],
154
+ create({ from, env, fetch }) {
155
+ const variables = parseProviderVariables(brevoVariablesSchema, env)
156
+ return new BrevoEmailSender({ apiKey: variables.FABRIKA_EMAIL_BREVO_API_KEY, from, fetch })
157
+ },
158
+ }
@@ -0,0 +1,144 @@
1
+ // Cloudflare Email Service's Email Sending REST API (https://developers.cloudflare.com/email-service/api/send-emails/rest-api/),
2
+ // built from its documentation in October 2026. Only the accepted answer is checked live (2026-10-25): a 200 counts by its
3
+ // `message_id`, or without one by a delivered or queued recipient; the refusals follow the documentation (backlog 241).
4
+ // It has no idempotency key, and Cloudflare takes transactional mail only. The REST API, not the Workers `send_email`
5
+ // binding, so the transport is one set of `FABRIKA_EMAIL_*` on every runtime that sends: a Worker, a Bun process on
6
+ // Zerops, an application.
7
+
8
+ import { z } from 'zod'
9
+ import { type EmailProvider, parseProviderVariables } from './config.js'
10
+ import { base64Of } from './content.js'
11
+ import { EmailDeliveryError, type EmailMessage, type EmailSenderCapabilities, oneClickUnsubscribeHeaders } from './email.js'
12
+ import { credentialVariable, type HttpEmailRequest, HttpEmailSender, type HttpEmailSenderOptions, isCredential } from './http-sender.js'
13
+ import type { ProviderResponse } from './http.js'
14
+
15
+ const CLOUDFLARE_ACCOUNTS_URL = 'https://api.cloudflare.com/client/v4/accounts'
16
+ /** A Cloudflare account ID: 32 hexadecimal digits, the path of every request. */
17
+ const ACCOUNT_ID_PATTERN = /^[0-9a-fA-F]{32}$/
18
+ const cloudflareSuccessSchema = z.object({
19
+ success: z.literal(true),
20
+ result: z.object({
21
+ message_id: z.string().optional(),
22
+ delivered: z.array(z.string()).optional(),
23
+ queued: z.array(z.string()).optional(),
24
+ permanent_bounces: z.array(z.string()).optional(),
25
+ suppressed_recipients: z.array(z.string()).optional(),
26
+ }),
27
+ })
28
+ /** Cloudflare bounds a custom header's value at 2,048 bytes; the URL travels inside `<…>`. */
29
+ const MAX_HEADER_VALUE_BYTES = 2048
30
+ /**
31
+ * Cloudflare counts the whole message, attachments base64 and MIME-wrapped, against 5 MiB; 3 MiB of bytes leaves
32
+ * about a mebibyte for the bodies and the headers.
33
+ */
34
+ const CLOUDFLARE_MAX_ATTACHMENT_BYTES = 3 * 1024 * 1024
35
+
36
+ export interface CloudflareEmailSenderOptions extends HttpEmailSenderOptions {
37
+ /** An account API token with the Email Sending Write permission and nothing else. */
38
+ readonly apiToken: string
39
+ /** The account the token sends for: the path of every request. */
40
+ readonly accountId: string
41
+ }
42
+
43
+ /** A refusal's body carries numeric codes and machine-readable messages; only the status is read. */
44
+ export class CloudflareEmailSender extends HttpEmailSender {
45
+ readonly capabilities: EmailSenderCapabilities = {
46
+ idempotent: false,
47
+ confirmation: 'sync',
48
+ maxBatch: 1,
49
+ listUnsubscribe: true,
50
+ maxAttachmentBytes: CLOUDFLARE_MAX_ATTACHMENT_BYTES,
51
+ // Cloudflare Email Service takes transactional mail only, so it sends no broadcast.
52
+ }
53
+ readonly #apiToken: string
54
+ readonly #sendUrl: string
55
+
56
+ constructor(options: CloudflareEmailSenderOptions) {
57
+ if (!isCredential(options.apiToken)) {
58
+ throw new EmailDeliveryError('Cloudflare API token is invalid', { code: 'invalid_configuration' })
59
+ }
60
+ if (!ACCOUNT_ID_PATTERN.test(options.accountId)) {
61
+ throw new EmailDeliveryError('Cloudflare account ID is invalid', { code: 'invalid_configuration' })
62
+ }
63
+ super({ label: 'Cloudflare', provider: 'cloudflare' }, options)
64
+ this.#apiToken = options.apiToken
65
+ this.#sendUrl = `${CLOUDFLARE_ACCOUNTS_URL}/${options.accountId}/email/sending/send`
66
+ }
67
+
68
+ protected request(message: EmailMessage): HttpEmailRequest {
69
+ if (message.unsubscribeUrl !== undefined && new TextEncoder().encode(`<${message.unsubscribeUrl}>`).byteLength > MAX_HEADER_VALUE_BYTES) {
70
+ throw new EmailDeliveryError('Email unsubscribe URL is invalid', { code: 'invalid_message' })
71
+ }
72
+ const senderName = message.fromName ?? this.from.name
73
+ const attachments = message.attachments ?? []
74
+ return {
75
+ url: this.#sendUrl,
76
+ headers: { Authorization: `Bearer ${this.#apiToken}` },
77
+ body: {
78
+ from: { address: this.from.address, ...(senderName === undefined ? {} : { name: senderName }) },
79
+ to: message.to,
80
+ subject: message.subject,
81
+ text: message.text,
82
+ ...(message.html === undefined ? {} : { html: message.html }),
83
+ ...(message.replyTo === undefined ? {} : { reply_to: message.replyTo }),
84
+ ...(message.unsubscribeUrl === undefined ? {} : { headers: oneClickUnsubscribeHeaders(message.unsubscribeUrl) }),
85
+ ...(attachments.length === 0
86
+ ? {}
87
+ : {
88
+ attachments: attachments.map((attachment) => ({
89
+ content: base64Of(attachment.content),
90
+ filename: attachment.filename,
91
+ type: attachment.contentType,
92
+ disposition: 'attachment',
93
+ })),
94
+ }),
95
+ },
96
+ }
97
+ }
98
+
99
+ protected messageId(response: ProviderResponse, message: EmailMessage): string | undefined {
100
+ const result = cloudflareSuccessSchema.safeParse(response.body).data?.result
101
+ if (result === undefined) return undefined
102
+ const listed = (addresses: readonly string[] | undefined): boolean =>
103
+ (addresses ?? []).some((address) => address.toLowerCase() === message.to.toLowerCase())
104
+ // A 200 groups the recipients by outcome; the one recipient listed as bounced or suppressed got nothing. The
105
+ // lists name the address, so they stay out of the refusal.
106
+ if (listed(result.permanent_bounces) || listed(result.suppressed_recipients)) {
107
+ throw new EmailDeliveryError(`Cloudflare refused the recipient (${response.status})`, { code: 'provider_rejected', httpStatus: response.status })
108
+ }
109
+ if (result.message_id !== undefined && result.message_id !== '') return result.message_id
110
+ // The REST guide documents a 200 with the recipients' status and no `message_id`. A recipient delivered or queued
111
+ // was taken, and the message's own key names that send, the same on every retry of it.
112
+ if (listed(result.delivered) || listed(result.queued)) return `cloudflare:${message.idempotencyKey}`
113
+ return undefined
114
+ }
115
+
116
+ protected override refusal(response: ProviderResponse): EmailDeliveryError | undefined {
117
+ // Documented as a resource not found: under this path, an account the token cannot reach.
118
+ if (response.status === 404) {
119
+ return new EmailDeliveryError('Cloudflare knows no such account (404)', { code: 'provider_unauthorized', httpStatus: response.status })
120
+ }
121
+ return undefined
122
+ }
123
+ }
124
+
125
+ const cloudflareVariablesSchema = z.object({
126
+ FABRIKA_EMAIL_CLOUDFLARE_API_TOKEN: credentialVariable,
127
+ FABRIKA_EMAIL_CLOUDFLARE_ACCOUNT_ID: z.string().regex(ACCOUNT_ID_PATTERN),
128
+ })
129
+
130
+ export const cloudflareEmailProvider: EmailProvider = {
131
+ variables: [
132
+ { name: 'FABRIKA_EMAIL_CLOUDFLARE_API_TOKEN', secret: true, required: true },
133
+ { name: 'FABRIKA_EMAIL_CLOUDFLARE_ACCOUNT_ID', secret: false, required: true },
134
+ ],
135
+ create({ from, env, fetch }) {
136
+ const variables = parseProviderVariables(cloudflareVariablesSchema, env)
137
+ return new CloudflareEmailSender({
138
+ apiToken: variables.FABRIKA_EMAIL_CLOUDFLARE_API_TOKEN,
139
+ accountId: variables.FABRIKA_EMAIL_CLOUDFLARE_ACCOUNT_ID,
140
+ from,
141
+ fetch,
142
+ })
143
+ },
144
+ }
@@ -26,6 +26,8 @@ export interface WireMessage {
26
26
  readonly unsubscribeUrl?: string
27
27
  /** Each attachment with its bytes as base64. */
28
28
  readonly attachments?: readonly EmailAttachmentContent[]
29
+ /** Whether the provider got it as broadcast mail, on its channel for them where it has one. */
30
+ readonly broadcast?: boolean
29
31
  }
30
32
 
31
33
  /** A stored or sent message in wire terms: what a local harness answers for an `EmailMessage` it kept. */
@@ -99,6 +101,8 @@ const UNSUBSCRIBE_MESSAGE: EmailMessage = {
99
101
  unsubscribeUrl: 'https://app.example.test/api/mail.unsubscribe?t=conformance-token-6c2e',
100
102
  }
101
103
 
104
+ const BROADCAST_MESSAGE: EmailMessage = { ...UNSUBSCRIBE_MESSAGE, idempotencyKey: 'conformance/broadcast-1', broadcast: true }
105
+
102
106
  const ATTACHMENT_MESSAGE: EmailMessage = {
103
107
  ...MINIMAL_MESSAGE,
104
108
  idempotencyKey: 'conformance/attachment-1',
@@ -134,6 +138,7 @@ const INVALID_MESSAGES: readonly { readonly problem: string; readonly message: E
134
138
  { problem: 'a sender name over 128 characters', message: { ...MINIMAL_MESSAGE, fromName: 'x'.repeat(129) } },
135
139
  { problem: 'an unsubscribe URL over http', message: { ...MINIMAL_MESSAGE, unsubscribeUrl: 'http://app.example.test/u' } },
136
140
  { problem: 'an unsubscribe URL with a bracket', message: { ...MINIMAL_MESSAGE, unsubscribeUrl: 'https://app.example.test/u>x' } },
141
+ { problem: 'a broadcast without an unsubscribe URL', message: { ...MINIMAL_MESSAGE, broadcast: true } },
137
142
  {
138
143
  problem: 'an attachment name with a path',
139
144
  message: { ...MINIMAL_MESSAGE, attachments: [{ filename: '../etc/passwd', contentType: 'text/plain', content: ONE_BYTE }] },
@@ -231,6 +236,19 @@ function describeHttpSender(harness: EmailSenderHttpHarness): void {
231
236
  expect(current.requests).toHaveLength(0)
232
237
  })
233
238
 
239
+ test('hands a broadcast message to the provider as one when it says it sends them, and refuses it otherwise', async () => {
240
+ const current = httpCase(async (request) => harness.answers.accepted(request))
241
+ if (current.sender.capabilities.broadcast === true) {
242
+ await current.sender.send(BROADCAST_MESSAGE, new AbortController().signal)
243
+ const wire = await harness.readRequest(only(current.requests))
244
+ expect(wire).toMatchObject({ ...contentOf(BROADCAST_MESSAGE), unsubscribeUrl: BROADCAST_MESSAGE.unsubscribeUrl })
245
+ expect(wire.broadcast).toBe(true)
246
+ return
247
+ }
248
+ await expectRejection(() => current.sender.send(BROADCAST_MESSAGE, new AbortController().signal), 'invalid_message', () => MESSAGE_MARKERS)
249
+ expect(current.requests).toHaveLength(0)
250
+ })
251
+
234
252
  test('hands the attachments it says it sends to the provider, and refuses them otherwise', async () => {
235
253
  const current = httpCase(async (request) => harness.answers.accepted(request))
236
254
  if (current.sender.capabilities.maxAttachmentBytes !== undefined) {
@@ -250,6 +268,45 @@ function describeHttpSender(harness: EmailSenderHttpHarness): void {
250
268
  expect(current.requests).toHaveLength(0)
251
269
  })
252
270
 
271
+ test('refuses an attachment of a file type it says it refuses, without a request', async () => {
272
+ const current = httpCase(async (request) => harness.answers.accepted(request))
273
+ const extension = current.sender.capabilities.refusedAttachmentExtensions?.[0]
274
+ if (extension === undefined || current.sender.capabilities.maxAttachmentBytes === undefined) return
275
+ const message: EmailMessage = {
276
+ ...ATTACHMENT_MESSAGE,
277
+ attachments: [{ filename: `report.${extension.toUpperCase()}`, contentType: 'application/octet-stream', content: ONE_BYTE }],
278
+ }
279
+ await expectRejection(() => current.sender.send(message, new AbortController().signal), 'invalid_message', () => MESSAGE_MARKERS)
280
+ expect(current.requests).toHaveLength(0)
281
+ })
282
+
283
+ test('refuses an attachment of a file type outside the ones it says it sends, without a request', async () => {
284
+ const current = httpCase(async (request) => harness.answers.accepted(request))
285
+ const allowed = current.sender.capabilities.attachmentExtensions
286
+ if (allowed === undefined || current.sender.capabilities.maxAttachmentBytes === undefined) return
287
+ const extension = ['json', 'svg', 'webp', 'bin'].find((candidate) => !allowed.includes(candidate))
288
+ if (extension === undefined) throw new Error('every probe extension is allowed: pick another')
289
+ const message: EmailMessage = {
290
+ ...ATTACHMENT_MESSAGE,
291
+ attachments: [{ filename: `report.${extension}`, contentType: 'application/octet-stream', content: ONE_BYTE }],
292
+ }
293
+ await expectRejection(() => current.sender.send(message, new AbortController().signal), 'invalid_message', () => MESSAGE_MARKERS)
294
+ expect(current.requests).toHaveLength(0)
295
+ })
296
+
297
+ test('refuses a body shorter than it says it sends, counted in characters once trimmed, without a request', async () => {
298
+ const current = httpCase(async (request) => harness.answers.accepted(request))
299
+ const min = current.sender.capabilities.minBodyLength
300
+ if (min === undefined) return
301
+ const short = ` ${'😀'.repeat(min - 1)} `
302
+ for (const message of [{ ...MINIMAL_MESSAGE, text: short }, { ...MINIMAL_MESSAGE, html: short }]) {
303
+ await expectRejection(() => current.sender.send(message, new AbortController().signal), 'invalid_message', () => MESSAGE_MARKERS)
304
+ }
305
+ expect(current.requests).toHaveLength(0)
306
+ await current.sender.send({ ...MINIMAL_MESSAGE, text: '😀'.repeat(min) }, new AbortController().signal)
307
+ expect(current.requests).toHaveLength(1)
308
+ })
309
+
253
310
  test.each(INVALID_MESSAGES)('refuses $problem as invalid_message without a request', async ({ message }) => {
254
311
  const current = httpCase(async (request) => harness.answers.accepted(request))
255
312
  await expectRejection(() => current.sender.send(message, new AbortController().signal), 'invalid_message', forbidden(current))
@@ -382,6 +439,16 @@ function describeLocalSender(harness: EmailSenderLocalHarness): void {
382
439
  expect(await harness.stored()).toHaveLength(0)
383
440
  })
384
441
 
442
+ test('stores a broadcast message as one when it says it sends them, and refuses it otherwise', async () => {
443
+ if (current().capabilities.broadcast === true) {
444
+ await current().send(BROADCAST_MESSAGE, new AbortController().signal)
445
+ expect(only(await harness.stored()).broadcast).toBe(true)
446
+ return
447
+ }
448
+ await expectRejection(() => current().send(BROADCAST_MESSAGE, new AbortController().signal), 'invalid_message', () => MESSAGE_MARKERS)
449
+ expect(await harness.stored()).toHaveLength(0)
450
+ })
451
+
385
452
  test('stores the attachments it says it sends, and refuses them otherwise', async () => {
386
453
  const limit = current().capabilities.maxAttachmentBytes
387
454
  if (limit !== undefined) {
@@ -448,6 +515,7 @@ function expectOptionalFieldsAbsent(wire: WireMessage): void {
448
515
  expect(wire.fromName).toBeUndefined()
449
516
  expect(wire.unsubscribeUrl).toBeUndefined()
450
517
  expect(wire.attachments).toBeUndefined()
518
+ expect(wire.broadcast ?? false).toBe(false)
451
519
  }
452
520
 
453
521
  function contentOf(message: EmailMessage): WireMessage {
package/src/content.ts CHANGED
@@ -16,13 +16,14 @@ export interface EmailContent {
16
16
  readonly replyTo?: string
17
17
  readonly fromName?: string
18
18
  readonly unsubscribeUrl?: string
19
+ readonly broadcast?: true
19
20
  readonly attachments?: readonly EmailAttachmentContent[]
20
21
  }
21
22
 
22
23
  export function sameEmailContent(left: EmailContent, right: EmailContent): boolean {
23
24
  return left.to === right.to && left.subject === right.subject && left.text === right.text && left.html === right.html
24
25
  && left.replyTo === right.replyTo && left.fromName === right.fromName && left.unsubscribeUrl === right.unsubscribeUrl
25
- && sameAttachments(left.attachments ?? [], right.attachments ?? [])
26
+ && left.broadcast === right.broadcast && sameAttachments(left.attachments ?? [], right.attachments ?? [])
26
27
  }
27
28
 
28
29
  export function emailContentOf(message: EmailMessage): EmailContent {
@@ -35,6 +36,7 @@ export function emailContentOf(message: EmailMessage): EmailContent {
35
36
  ...(message.replyTo === undefined ? {} : { replyTo: message.replyTo }),
36
37
  ...(message.fromName === undefined ? {} : { fromName: message.fromName }),
37
38
  ...(message.unsubscribeUrl === undefined ? {} : { unsubscribeUrl: message.unsubscribeUrl }),
39
+ ...(message.broadcast === true ? { broadcast: true } : {}),
38
40
  ...(attachments.length === 0
39
41
  ? {}
40
42
  : {