Diffinery

homeflare/diffinerypublic

Open-source, agent-first GitHub and GitHub Actions alternative that runs on your own Cloudflare account: git hosting, pull requests, code review and drop-in GitHub Actions YAML on Workers, Durable Objects, R2 and Containers.

Merge pull request #8 from alankernel67/claude/objective-brattain-ddafb9

Email without Cloudflare Email Sending: an SMTP transport (SMTP_URL, SMTP_PASSWORD)
altugank authored · GitHub committed 2 parents ae5059edfdc5e6commit c969fbb3a29c3a0b8e099ff5c0c1e9769bcc5334Browse files
13 files changed+814−29
Files (13)
modifiedapps/diffinery/docs/accounts/notifications.md+1−1View file
@@ -381,7 +381,7 @@
381381 | `turned off <group> emails` | You turned off that group (for example `turned off watching emails`). |
382382 | `no email address` | Your account has no email address. |
383383 | `account disabled` | Disabled accounts only get the email saying they were disabled or enabled. |
384-| `email sending is not configured (no EMAIL binding)` | The instance can't send email; ask a site administrator. |
384+| `email sending is not configured (no EMAIL binding or SMTP_URL)` | The instance can't send email; ask a site administrator. |
385385 | `address is suppressed: ...` | Email to your address bounced or was reported as spam, or a site administrator suppressed it. See [When Diffinery stops emailing you](#when-diffinery-stops-emailing-you). |
386386
387387 ## How notifications differ from GitHub
modifiedapps/diffinery/docs/admin/site-administration.md+10−6View file
@@ -300,7 +300,7 @@
300300
301301 | Item | What it shows |
302302 | --- | --- |
303-| **Sending** | "Cloudflare Email Sending is bound", or "not configured (no EMAIL binding): emails are logged, not sent" |
303+| **Sending** | "Cloudflare Email Sending is bound"; "over SMTP: smtps://user@host:465", the server in `SMTP_URL` (never the password); "SMTP_URL is set but can't be used: ..." with the reason; or "not configured (no EMAIL binding or SMTP_URL): emails are logged, not sent". See [SMTP](/docs/self-hosting/configuration#smtp). |
304304 | **Queue** | `diffinery-mail`, or "not bound: emails are dropped" |
305305 | **From** | The address emails are sent from: `MAIL_FROM`, or `notifications@<your hostname>` when it is empty (see [Configuration](/docs/self-hosting/configuration)) |
306306 | **Bounces and complaints** | Where they come from: the `diffinery-mail-events` queue, and whether the signed endpoint is on (`MAIL_EVENTS_SECRET` set) |
@@ -315,7 +315,7 @@
315315
316316 **Suppressed addresses** lists every address Diffinery sends nothing to, newest first, with why (`hard-bounce`, `complaint` or `manual`), where that came from and since when. **Remove** sends email to the address again; **Suppress an address** adds one by hand, with an optional note. Both are recorded in the audit log. See [Bounces, complaints and the suppression list](#bounces-complaints-and-the-suppression-list).
317317
318-**Recent emails** lists the last 100 emails sent to anyone, with the time, recipient address, subject, template kind, Cloudflare's message ID, the status (`sent`, `failed` or `skipped`) and the reason when it wasn't sent. The log keeps 90 days.
318+**Recent emails** lists the last 100 emails sent to anyone, with the time, recipient address, subject, template kind, the message ID (Cloudflare's, or the `Message-ID` Diffinery gave an email sent over SMTP), the status (`sent`, `failed` or `skipped`) and the reason when it wasn't sent. The log keeps 90 days.
319319
320320 See [Notifications](/docs/accounts/notifications#every-email-diffinery-sends) for when each email is sent.
321321
@@ -323,7 +323,7 @@
323323
324324 | Method and path | Description | Needs |
325325 | --- | --- | --- |
326-| `GET /api/v3/diffinery/admin/email` | `sending` and `queue` (whether they are configured), `from` (the sender address: `MAIL_FROM`, or `notifications@<your hostname>` when it is empty), `last_24h` counts (`sent`, `failed`, `skipped`) and the `last` email logged | site administrator, any token scope |
326+| `GET /api/v3/diffinery/admin/email` | `sending` and `queue` (whether they are configured), `transport` (`email-sending`, `smtp` or `null`), `smtp` (`url`, the server without the password, and `error`, why `SMTP_URL` can't be used; `null` unless `transport` is `smtp`), `from` (the sender address: `MAIL_FROM`, or `notifications@<your hostname>` when it is empty), `last_24h` counts (`sent`, `failed`, `skipped`) and the `last` email logged | site administrator, any token scope |
327327 | `POST /api/v3/diffinery/admin/emails/samples` | Send every template to yourself now, or only some with `{"only": ["signin", "invite-org"]}`. Returns `to`, `sent`, `total` and each result. | site administrator, with an `admin` token for all repositories or a browser session |
328328 | `GET /api/v3/diffinery/admin/email/suppressions` | The suppression list, newest first: `email`, `reason`, `detail`, `source` (`cloudflare`, `webhook`, `send` or `admin`), `created_by`, `created_at` and `owner_can_lift` | site administrator, any token scope |
329329 | `PUT /api/v3/diffinery/admin/email/suppressions/{email}` | Suppress an address by hand, with an optional `{"note": "..."}`. Audited as `email.suppression.add`. | site administrator, with an `admin` token or a browser session |
@@ -338,7 +338,7 @@
338338
339339 | Reason | How |
340340 | --- | --- |
341-| `hard-bounce` | Email to it bounced permanently (the mailbox or domain doesn't exist, or the receiving server refuses it for good), or Email Sending refused to send to it for good (`E_RECIPIENT_SUPPRESSED`, source `send`). Soft bounces, delays and temporary send errors (rate and daily limits, delivery errors) change nothing. |
341+| `hard-bounce` | Email to it bounced permanently (the mailbox or domain doesn't exist, or the receiving server refuses it for good), or Email Sending refused to send to it for good (`E_RECIPIENT_SUPPRESSED`, source `send`), or the SMTP server refused the recipient for good (`E_SMTP_RECIPIENT_REJECTED`, source `send`). Soft bounces, delays and temporary send errors (rate and daily limits, delivery errors) change nothing. |
342342 | `complaint` | Its owner marked an email from Diffinery as spam. |
343343 | `manual` | A site administrator added it, under **Suppress an address** or with the API. |
344344
@@ -515,8 +515,12 @@
515515 | "enable this account first" | Sign-in links can't be created for disabled accounts. Set the status to `active`, then create the link. |
516516 | "enter a valid email address" | The invite form needs an address like `[email protected]`. |
517517 | `403 only site admins can invite people without an organization` | Instance invites from the CLI or API need a site administrator; others must pass `--org`. |
518-| **Sending** says "not configured" | The Worker has no `send_email` binding, so emails are logged as skipped. See [Configuration](/docs/self-hosting/configuration). |
519-| Emails show as `failed` | The **Recent emails** detail has Cloudflare's error. Check the sending domain's DNS records and the queue. |
518+| **Sending** says "not configured" | The Worker has neither a `send_email` binding nor `SMTP_URL`, so emails are logged as skipped. See [Configuration](/docs/self-hosting/configuration) and [SMTP](/docs/self-hosting/configuration#smtp). |
519+| **Sending** says "SMTP_URL is set but can't be used" | Fix what it names, such as a password in the URL (it belongs in the `SMTP_PASSWORD` secret) or a missing `SMTP_PASSWORD`. Until then emails fail with `E_SMTP_CONFIG`. |
520+| `E_SMTP_REJECTED: SMTP AUTH: 535 ...` | The SMTP server refused the user or password. Check the user in `SMTP_URL` and the `SMTP_PASSWORD` secret. |
521+| `E_SMTP_REJECTED: SMTP MAIL FROM: 5...` | The SMTP user may not send from `MAIL_FROM`. Use an address the server allows. |
522+| `gave up after 6 attempts: SMTP ...` | The SMTP server kept answering `4xx`, or couldn't be reached in time. Check the host and port in `SMTP_URL`; port 25 is blocked on Cloudflare. |
523+| Emails show as `failed` | The **Recent emails** detail has Cloudflare's or the SMTP server's error. Check the sending domain's DNS records and the queue. |
520524 | Emails show as `skipped` with "address is suppressed" | The address bounced, reported spam or was suppressed by hand. See [Bounces, complaints and the suppression list](#bounces-complaints-and-the-suppression-list). |
521525 | `E_RECIPIENT_SUPPRESSED` | The address is on Cloudflare's own suppression list. Remove it in the Cloudflare dashboard. |
522526 | `401 missing or bad signature` from `/-/email/events` | The `X-Diffinery-Signature` header is missing, signed with another secret, or more than 5 minutes old. |
modifiedapps/diffinery/docs/self-hosting/configuration.md+37−2View file
@@ -22,7 +22,8 @@
2222 | Variable | Production value in the repository | Required | What it does |
2323 | --- | --- | --- | --- |
2424 | `PUBLIC_URL` | `https://diffinery.com` | Yes | The canonical origin of the instance. See [PUBLIC_URL](#public_url). On deploy, `scripts/bootstrap.sh` replaces it with `https://$DIFFINERY_DOMAIN` (default `https://diffinery.com`), whatever `wrangler.jsonc` says. |
25-| `MAIL_FROM` | `[email protected]` | No | Sender address of every email. The display name is "Diffinery", or `<actor> (Diffinery)` for emails about someone's action. On deploy, `scripts/bootstrap.sh` replaces it with `notifications@$MAIL_DOMAIN` (default `notifications@$DIFFINERY_DOMAIN`). When empty, Diffinery sends from `notifications@<hostname of PUBLIC_URL>`. The domain must be onboarded to Email Sending. |
25+| `MAIL_FROM` | `[email protected]` | No | Sender address of every email. The display name is "Diffinery", or `<actor> (Diffinery)` for emails about someone's action. On deploy, `scripts/bootstrap.sh` replaces it with `notifications@$MAIL_DOMAIN` (default `notifications@$DIFFINERY_DOMAIN`). When empty, Diffinery sends from `notifications@<hostname of PUBLIC_URL>`. The domain must be onboarded to Email Sending, or, with `SMTP_URL`, be one your SMTP server lets you send from. |
26+| `SMTP_URL` | Not set | No | The SMTP server email goes through when the Worker has no `EMAIL` binding, such as an instance outside Cloudflare: `smtps://<user>@<host>:465` or `smtp://<user>@<host>:587`. The password goes in the `SMTP_PASSWORD` secret. See [SMTP](#smtp). |
2627 | `BOOTSTRAP_ADMINS` | Empty (set on deploy) | For the first sign-in | Emails (case-insensitive) that become site administrators. On deploy, `scripts/bootstrap.sh` sets it from the `BOOTSTRAP_ADMINS` environment variable, else keeps the deployed Worker's list. See [BOOTSTRAP_ADMINS](#bootstrap_admins). |
2728 | `ACCESS_TEAM_DOMAIN` | Empty (filled in on deploy) | For email sign-in | Your Cloudflare Zero Trust team domain, like `example.cloudflareaccess.com`. Used to fetch the Access signing keys and to check the token issuer. |
2829 | `ACCESS_AUD` | Empty (filled in on deploy) | For email sign-in | The audience tag of the Access application that guards `/auth/access`. |
@@ -163,6 +164,39 @@
163164
164165 To use a widget of your own instead, add `"TURNSTILE_SITE_KEY": "<site key>"` under `vars` in `wrangler.jsonc` and store its secret key with `printf '%s' "$TURNSTILE_SECRET" | pnpm exec wrangler secret put TURNSTILE_SECRET -c wrangler.deploy.jsonc`. The deploy then creates no widget and never replaces your secret; it only fills in a missing `TURNSTILE_SECRET` when your widget is in the same Cloudflare account. If you rotate the secret key of the deploy's widget in the dashboard, run `pnpm exec wrangler secret delete TURNSTILE_SECRET -c wrangler.deploy.jsonc` and deploy again, so the deploy stores the new one.
165166
167+### SMTP
168+
169+Without an `EMAIL` binding, Diffinery can send email through any SMTP server that speaks TLS: your mail provider's submission server, Amazon SES, Postmark, Mailgun or your own. This is how an instance outside Cloudflare, which has no Email Sending, sends sign-up codes, invitations and notifications. When the `EMAIL` binding is there, it is used and `SMTP_URL` is ignored.
170+
171+1. Add `SMTP_URL` under `vars` in `wrangler.jsonc`; the deploy keeps it.
172+ - `smtps://<user>@<host>:465` uses TLS from the start. The port defaults to 465.
173+ - `smtp://<user>@<host>:587` starts plain and upgrades with STARTTLS. The port defaults to 587. If the server doesn't offer STARTTLS, Diffinery sends nothing (`E_SMTP_REJECTED: SMTP: the server doesn't offer STARTTLS, and Diffinery doesn't send without TLS`), so the password never crosses the network in the clear.
174+ - Write an `@` in the user as `%40`: `smtps://notifications%[email protected]`.
175+ - Leave the user out (`smtps://relay.internal:465`) for a relay that needs no sign-in.
176+ - Cloudflare Workers can't open connections to port 25, so use 465 or 587.
177+2. Store the password as a secret. Never put it in `SMTP_URL`: Diffinery refuses such a URL.
178+
179+ ```sh
180+ cd apps/diffinery
181+ printf '%s' "$SMTP_PASSWORD" | pnpm exec wrangler secret put SMTP_PASSWORD -c wrangler.deploy.jsonc
182+ ```
183+
184+3. Make sure `MAIL_FROM` is an address the SMTP user may send from. It is both the `From` header and the envelope sender.
185+4. Check it: **Settings → Email** shows **Sending** as "over SMTP: smtps://...", and **Send me a test email** sends one.
186+
187+Diffinery signs in with AUTH PLAIN, or AUTH LOGIN when the server offers only that. Each email is one connection, and each reply has 30 seconds to arrive. What happens to the email depends on the server's answer:
188+
189+| Answer | Result |
190+| --- | --- |
191+| `2xx` | `sent`. **Recent emails** shows the `Message-ID` Diffinery gave the email. |
192+| `4xx`, a timeout or a dropped connection | `E_SMTP_TRANSIENT`. The queue tries again later, up to 6 times. |
193+| `5xx` to `RCPT TO` that says the address doesn't exist (enhanced status `5.1.1`, `5.1.2`, `5.1.3`, `5.1.6`, `5.1.10` or `5.2.1`, or `550`, `551` or `553` without one) | `failed` with `E_SMTP_RECIPIENT_REJECTED`, and the address goes on the [suppression list](/docs/admin/site-administration#bounces-complaints-and-the-suppression-list) as a `hard-bounce` with source `send`. |
194+| Any other `5xx`, such as `535` for a wrong password or `5.7.1` for a sender the server won't relay for | `failed` with `E_SMTP_REJECTED`. Nothing else changes. |
195+
196+Most submission servers accept every recipient and report a bounce later, by email to `MAIL_FROM`. Diffinery doesn't read that mailbox. To suppress those addresses too, have your provider post bounces and complaints to the signed intake, `POST /-/email/events` (see `MAIL_EVENTS_SECRET`).
197+
198+Diffinery never logs the password or the content of an email. Errors quote the server's reply, never the commands sent.
199+
166200 ### DEV_AUTH
167201
168202 When `DEV_AUTH` is set, `ACCESS_AUD` is empty and both `PUBLIC_URL` and the request's own address are on the local machine (`localhost`, `127.x.x.x` or `[::1]`), every request without credentials (no token, no session) acts as the account with the email in `DEV_AUTH`, with full access. That account is created on first use and is a site administrator if the email is also in `BOOTSTRAP_ADMINS`. While `DEV_AUTH` is set, the email log also keeps each whole message, and `GET /api/v3/diffinery/emails` returns it, so tests can read emails without delivering them.
@@ -181,6 +215,7 @@
181215 | `GITHUB_OAUTH_CLIENT_SECRET` | The client secret of a GitHub OAuth app | You, optionally | With `GITHUB_OAUTH_CLIENT_ID`, turns on the **Link with GitHub** option on **Settings → Linked accounts**. | People link GitHub accounts with the gist code only. |
182216 | `GITHUB_APP_CLIENT_SECRET`, `GITHUB_APP_PRIVATE_KEY`, `GITHUB_APP_WEBHOOK_SECRET` | The GitHub App's client secret, its private key (the PEM file GitHub gives, as it is) and its webhook secret | You, optionally | With `GITHUB_APP_ID`, `GITHUB_APP_SLUG` and `GITHUB_APP_CLIENT_ID`, turns on [GitHub runners](#github-runners). | **Settings → GitHub runners** says the instance has no GitHub App, and `POST /-/github/webhook` answers 404. |
183217 | `MAIL_EVENTS_SECRET` | A random string, at least 32 characters | You, optionally | Turns on `POST /-/email/events`, the signed intake for bounces and complaints from anything other than Cloudflare's own event subscriptions. See [Bounces, complaints and the suppression list](/docs/admin/site-administration#bounces-complaints-and-the-suppression-list). | The endpoint answers 404. Bounces and complaints still arrive through the `diffinery-mail-events` queue. |
218+| `SMTP_PASSWORD` | The password of the user in `SMTP_URL` | You, optionally | Signs in to the SMTP server in `SMTP_URL`. See [SMTP](#smtp). | With a user in `SMTP_URL`, nothing is sent: every email fails with `E_SMTP_CONFIG: SMTP_URL names a user but the SMTP_PASSWORD secret is not set`. |
184219 | `TURNSTILE_SECRET` | The secret key of a Cloudflare Turnstile widget | The deploy, from its widget (see [Turnstile](#turnstile)) | With `TURNSTILE_SITE_KEY`, checks that whoever asks for a sign-up code (with `SIGNUP=open`), or sends a security report, an early access request or a contact message without signing in, passed the Turnstile widget. See [SIGNUP](#signup) and [Security contact](#security-contact). | With `SIGNUP=open`, sign-up answers `503` "Sign-up needs Turnstile configured", the security report and contact forms take reports and messages only from people who are signed in, and the early access form is closed (local development skips the check). The next deploy sets it when the token has **Account → Turnstile → Edit**. |
185220
186221 None of these secrets is rotated automatically, and `ensure-secrets.sh` never replaces one that exists. Keep a copy of `MASTER_KEY` somewhere safe: replacing it without keeping the old one as `MASTER_KEY_PREV` makes every stored secret undecryptable and invalidates unsubscribe links already sent, along with the runtime tokens of running jobs and cache and artifact links already handed out. To rotate it, follow [Rotating MASTER_KEY](#rotating-master_key). To rotate the OIDC key, delete `OIDC_PRIVATE_KEY` and deploy: a new key with a new `kid` (`diffinery-<date>`) is generated, and relying parties pick it up from `/.well-known/jwks`.
@@ -236,7 +271,7 @@
236271 | `BUCKET` | R2 bucket | `diffinery-data` | Large git objects, LFS objects, archived job logs, caches, artifacts, container image layers and manifests, the event archive, release assets, cached source archives (zipball and tarball downloads) and profile pictures. |
237272 | `EVENTS` | Queue producer, with a consumer on the same Worker | `diffinery-events`, dead-letter queue `diffinery-events-dlq` | Repository events for webhooks, notifications and the audit log. Consumer: batches of up to 50, waiting up to 2 seconds, 8 retries. |
238273 | `MAIL` | Queue producer, with a consumer on the same Worker | `diffinery-mail`, dead-letter queue `diffinery-mail-dlq` | Email jobs. Consumer: batches of up to 20, waiting up to 2 seconds, 8 retries. Optional: without it emails are dropped with a warning in the logs. |
239-| `EMAIL` | `send_email` (Email Sending) | Your onboarded domain | Sending email. Optional: without it every email is logged as `skipped`. |
274+| `EMAIL` | `send_email` (Email Sending) | Your onboarded domain | Sending email. Optional: without it email goes to the SMTP server in `SMTP_URL`, and without that too every email is logged as `skipped`. |
240275 | (none) | Queue consumer | `diffinery-mail-events` | Bounces and complaints from Email Sending's event subscriptions; the deploy subscribes this queue to your sending domain's events (see [Site administration](/docs/admin/site-administration#where-bounces-and-complaints-come-from)). Consumer: batches of up to 50, waiting up to 5 seconds, 8 retries. |
241276 | `RL_AUTH`, `RL_ANON`, `RL_ACCOUNT`, `RL_CREATE`, `RL_MODEL` | Rate limiting (`ratelimits`) | Namespaces `1001` to `1005`; 20, 300, 2,000, 60 and 600 requests per 60 seconds | [Request rate limits](/docs/reference/rest-api#rate-limits): sign-in and security reports per IP address, anonymous requests per IP address, signed-in requests per account, new content per account, and agents' model requests per paying person (`MODEL_RATE_LIMIT` in `src/lib/rate-limit.ts`). Optional: a missing binding (the `dev` environment declares none) or one that fails lets requests through. If you change a limit, change `RATE_LIMITS` (or `MODEL_RATE_LIMIT`) in `src/lib/rate-limit.ts` to match, since the 429 messages quote it. Namespace IDs are shared across your Cloudflare account, so pick others if another Worker already uses these. Where these bindings don't exist, set `RATE_LIMITS` to `durable` to count in `RATE_LIMITER` instead. |
242277 | `REPO` | Durable Object namespace | Class `RepoDO` (SQLite) | One object per repository. |
modifiedapps/diffinery/src/docs/api-meta.ts+1−1View file
@@ -1590,7 +1590,7 @@
15901590 description: "When your address is suppressed by a bounce or complaint, sends one email to it, past the suppression list; following its link while signed in lifts the suppression. 409 when it isn't suppressed, 403 for a suppression a site administrator added, at most 3 an hour.",
15911591 access: "account",
15921592 },
1593- "GET /diffinery/admin/email": { summary: "Email delivery status", description: "Whether sending is configured, whether the signed bounce and complaint endpoint is on (`event_intake`), and counts for the last 24 hours.", access: "site-admin" },
1593+ "GET /diffinery/admin/email": { summary: "Email delivery status", description: "Whether sending is configured and how (`transport`: Cloudflare Email Sending or SMTP, with `smtp` naming the server), whether the signed bounce and complaint endpoint is on (`event_intake`), and counts for the last 24 hours.", access: "site-admin" },
15941594 "GET /diffinery/admin/email/suppressions": { summary: "List suppressed email addresses", description: "Newest first: `email`, `reason` (`hard-bounce`, `complaint` or `manual`), `detail`, `source` (`cloudflare`, `webhook`, `send` or `admin`), `created_by` and `created_at`.", access: "site-admin" },
15951595 "PUT /diffinery/admin/email/suppressions/{email}": { summary: "Suppress an email address", description: "Diffinery sends nothing to it until it is removed. Recorded in the audit log.", access: "site-admin", body: { note: ["string", "Why, kept with the entry."] } },
15961596 "DELETE /diffinery/admin/email/suppressions/{email}": { summary: "Remove an address from the suppression list", description: "Whatever put it there. 404 when it isn't suppressed. Recorded in the audit log.", access: "site-admin", status: 204 },
modifiedapps/diffinery/src/env.ts+8−1View file
@@ -51,7 +51,7 @@
5151 MODEL_UPSTREAM_OPENAI?: string;
5252 MODEL_UPSTREAM_OPENROUTER?: string;
5353 RUN_WORKFLOW: Workflow<{ repoId: string; runId: string }>;
54- /** Cloudflare Email Sending. Missing when sending isn't set up; emails are then logged as skipped. */
54+ /** Cloudflare Email Sending. Missing when sending isn't set up; emails then go over SMTP_URL, or are logged as skipped. */
5555 EMAIL?: SendEmail;
5656 /** Request rate limits (lib/rate-limit.ts); none in local development. */
5757 RL_AUTH?: RateLimit;
@@ -109,6 +109,11 @@
109109 /** Sender address for every email, e.g. [email protected]. */
110110 MAIL_FROM?: string;
111111 /**
112+ * SMTP server for email when there is no EMAIL binding (mail/smtp.ts), e.g. on celld:
113+ * `smtps://user@host:465` (TLS) or `smtp://user@host:587` (STARTTLS). The password is SMTP_PASSWORD.
114+ */
115+ SMTP_URL?: string;
116+ /**
112117 * More places security researchers can report vulnerabilities, served in /.well-known/security.txt
113118 * after the instance's own report form (/security/report): an email address or an https URL, several
114119 * separated by commas.
@@ -160,6 +165,8 @@
160165 OIDC_PRIVATE_KEY?: string;
161166 /** Secret: signs bounce and complaint events posted to /-/email/events (mail/events.ts); unset, that endpoint is off. */
162167 MAIL_EVENTS_SECRET?: string;
168+ /** Secret: the password for the user in SMTP_URL. */
169+ SMTP_PASSWORD?: string;
163170 /** Secret: Cloudflare Turnstile secret key, to check the widget on the sign-up page and the security report form (siteverify). */
164171 TURNSTILE_SECRET?: string;
165172 /** Secret: the GitHub App's client secret, to check who links an installation. */
modifiedapps/diffinery/src/mail/api.ts+14−2View file
@@ -7,7 +7,8 @@
77 import { HttpError, now } from "../lib/util.js";
88 import { MailStore, isDigestHour, isTimeZone, mergePrefs, type WatchLevel } from "./prefs.js";
99 import { sampleJobs } from "./samples.js";
10-import { deliver, senderAddress } from "./send.js";
10+import { deliver, mailTransport, senderAddress } from "./send.js";
11+import { smtpLabel } from "./smtp.js";
1112 import { Suppressions } from "./suppression.js";
1213 import { adminSuppress, adminUnsuppress, sendDigestNow, sendTest, sendVerification, suppressionJson } from "./web.js";
1314
@@ -176,7 +177,18 @@
176177 siteAdmin(c, "read");
177178 const store = new MailStore(c.env.DB);
178179 const [day, last] = await Promise.all([store.counts(new Date(Date.now() - 86400_000).toISOString()), store.recent({ limit: 1 })]);
179- return c.json({ sending: !!c.env.EMAIL, queue: !!c.env.MAIL, from: senderAddress(c.env), event_intake: !!c.env.MAIL_EVENTS_SECRET, last_24h: day, last: last[0] ? { ...last[0], dev_copy: undefined } : null });
180+ const t = mailTransport(c.env);
181+ const smtp = t?.kind === "smtp" ? ("error" in t ? { url: null, error: t.error } : { url: smtpLabel(t.config), error: null }) : null;
182+ return c.json({
183+ sending: !!t && !(t.kind === "smtp" && "error" in t),
184+ transport: t?.kind ?? null,
185+ smtp,
186+ queue: !!c.env.MAIL,
187+ from: senderAddress(c.env),
188+ event_intake: !!c.env.MAIL_EVENTS_SECRET,
189+ last_24h: day,
190+ last: last[0] ? { ...last[0], dev_copy: undefined } : null,
191+ });
180192 });
181193
182194 /**
modifiedapps/diffinery/src/mail/send.ts+27−9View file
@@ -4,6 +4,7 @@
44 import { MailStore, wantsEmail } from "./prefs.js";
55 import { compose, toHtml, toText, type RenderCtx } from "./templates.js";
66 import { categoryOf, isMandatory, type MailJob } from "./types.js";
7+import { SmtpError, sendSmtp, smtpConfig, type SmtpConfig } from "./smtp.js";
78 import { REASON_TEXT, Suppressions, sendSuppression } from "./suppression.js";
89 import { unsubUrl } from "./unsubscribe.js";
910
@@ -11,8 +12,9 @@
1112 * Sending: jobs go on the `diffinery-mail` queue (so a slow or failing send
1213 * never holds up a request, and failures retry with backoff), and the queue
1314 * consumer checks the recipient's settings, renders and sends each one through
14- * Cloudflare Email Sending. Nothing goes to an address on the suppression list
15- * (suppression.ts), and an address Email Sending refuses for good goes on it.
15+ * Cloudflare Email Sending, or over SMTP (smtp.ts) where there is no EMAIL binding.
16+ * Nothing goes to an address on the suppression list (suppression.ts), and an
17+ * address Email Sending or the SMTP server refuses for good goes on it.
1618 */
1719
1820 /**
@@ -74,10 +76,23 @@
7476 }
7577 }
7678
77-const RETRYABLE = new Set(["E_RATE_LIMIT_EXCEEDED", "E_INTERNAL_SERVER_ERROR", "E_DELIVERY_FAILED"]);
79+const RETRYABLE = new Set(["E_RATE_LIMIT_EXCEEDED", "E_INTERNAL_SERVER_ERROR", "E_DELIVERY_FAILED", "E_SMTP_TRANSIENT"]);
7880
7981 export class RetryableMailError extends Error {}
8082
83+/**
84+ * How this instance sends email: Cloudflare Email Sending when the EMAIL binding is there, else
85+ * the SMTP server in SMTP_URL (with what is wrong with it, if anything); null when neither is set.
86+ */
87+export type MailTransport = { kind: "email-sending"; binding: SendEmail } | { kind: "smtp"; config: SmtpConfig } | { kind: "smtp"; error: string };
88+
89+export function mailTransport(env: Pick<Env, "EMAIL" | "SMTP_URL" | "SMTP_PASSWORD">): MailTransport | null {
90+ if (env.EMAIL) return { kind: "email-sending", binding: env.EMAIL };
91+ const smtp = smtpConfig(env);
92+ if (!smtp) return null;
93+ return "error" in smtp ? { kind: "smtp", error: smtp.error } : { kind: "smtp", config: smtp };
94+}
95+
8196 /** The address every email is sent from: MAIL_FROM, or notifications@ the public host. */
8297 export const senderAddress = (env: Pick<Env, "MAIL_FROM" | "PUBLIC_URL">): string => env.MAIL_FROM || `notifications@${new URL(env.PUBLIC_URL).hostname}`;
8398
@@ -205,18 +220,21 @@
205220 const msg = await buildMessage(env, job, to);
206221 const devCopy = devAuth(env) ? JSON.stringify(msg) : null;
207222 const base = { account_id: to.accountId ?? null, to_addr: to.email, kind: job.kind, subject: msg.subject, dev_copy: devCopy };
208- if (!env.EMAIL) {
209- await store.log({ ...base, status: "skipped", detail: "email sending is not configured (no EMAIL binding)", message_id: null });
210- return { status: "skipped", detail: "no EMAIL binding" };
223+ const transport = mailTransport(env);
224+ if (!transport) {
225+ await store.log({ ...base, status: "skipped", detail: "email sending is not configured (no EMAIL binding or SMTP_URL)", message_id: null });
226+ return { status: "skipped", detail: "no EMAIL binding or SMTP_URL" };
211227 }
212228 let res: { messageId?: string };
213229 try {
214- res = await env.EMAIL.send(msg);
230+ if (transport.kind === "email-sending") res = await transport.binding.send(msg);
231+ else if ("error" in transport) throw new SmtpError("E_SMTP_CONFIG", transport.error);
232+ else res = await sendSmtp(transport.config, msg, { ehlo: new URL(env.PUBLIC_URL).hostname });
215233 } catch (e) {
216234 const code = (e as { code?: string }).code ?? "";
217235 const detail = `${code ? `${code}: ` : ""}${(e as Error).message ?? String(e)}`;
218236 if (RETRYABLE.has(code)) throw new RetryableMailError(detail);
219- // A permanent failure for this recipient (it's on Cloudflare's suppression list) puts it on ours.
237+ // A permanent failure for this recipient (it's on Cloudflare's suppression list, or the SMTP server has no such mailbox) puts it on ours.
220238 const s = sendSuppression(to.email, { error: e });
221239 if (s) await suppressFromSend(env, s);
222240 await store.log({ ...base, status: "failed", detail, message_id: null });
@@ -234,7 +252,7 @@
234252 return { status: "sent", messageId: res.messageId };
235253 }
236254
237-/** Suppress an address Email Sending refused for good (source `send`), audited like any other addition. Never throws. */
255+/** Suppress an address Email Sending or the SMTP server refused for good (source `send`), audited like any other addition. Never throws. */
238256 async function suppressFromSend(env: Env, s: NonNullable<ReturnType<typeof sendSuppression>>): Promise<void> {
239257 try {
240258 await new Suppressions(env.DB).add({ ...s, source: "send" });
addedapps/diffinery/src/mail/smtp.ts+316−0View file
@@ -1,0 +1,316 @@
1+import { connect } from "cloudflare:sockets";
2+import type { Env } from "../env.js";
3+import type { Outgoing } from "./send.js";
4+
5+/**
6+ * Sending over SMTP, for an instance without Cloudflare Email Sending (the EMAIL binding), such as
7+ * one on celld. SMTP_URL names the server and the user and SMTP_PASSWORD (a secret) the password:
8+ * `smtps://user@host:465` is TLS from the first byte, and `smtp://user@host:587` upgrades with
9+ * STARTTLS and refuses to go on without it, so the password never crosses the network in the clear.
10+ * Each email is one TCP connection (`cloudflare:sockets`, which celld provides too). Nothing of the
11+ * conversation is logged; errors carry the server's replies, never the commands sent.
12+ */
13+
14+export interface SmtpConfig {
15+ host: string;
16+ port: number;
17+ /** `implicit`: TLS from the start (smtps://). `starttls`: plain until STARTTLS, which is required (smtp://). */
18+ tls: "implicit" | "starttls";
19+ user: string | null;
20+ password: string | null;
21+}
22+
23+/**
24+ * E_SMTP_TRANSIENT (a 4xx reply, a timeout or a dropped connection) is retried. E_SMTP_RECIPIENT_REJECTED
25+ * (the server refused the recipient for good) suppresses the address. E_SMTP_REJECTED (any other 5xx,
26+ * such as a wrong password) and E_SMTP_CONFIG fail the email and change nothing else.
27+ */
28+export type SmtpErrorCode = "E_SMTP_CONFIG" | "E_SMTP_TRANSIENT" | "E_SMTP_REJECTED" | "E_SMTP_RECIPIENT_REJECTED";
29+
30+export class SmtpError extends Error {
31+ constructor(
32+ readonly code: SmtpErrorCode,
33+ message: string,
34+ ) {
35+ super(message);
36+ this.name = "SmtpError";
37+ }
38+}
39+
40+/** The SMTP settings, null when SMTP_URL is unset, or what is wrong with them. */
41+export function smtpConfig(env: Pick<Env, "SMTP_URL" | "SMTP_PASSWORD">): SmtpConfig | { error: string } | null {
42+ const raw = env.SMTP_URL?.trim();
43+ if (!raw) return null;
44+ let u: URL;
45+ try {
46+ u = new URL(raw);
47+ } catch {
48+ return { error: "SMTP_URL is not a URL" };
49+ }
50+ const tls = u.protocol === "smtps:" ? "implicit" : u.protocol === "smtp:" ? "starttls" : null;
51+ if (!tls) return { error: "SMTP_URL must start with smtps:// or smtp://" };
52+ if (u.password) return { error: "the password goes in the SMTP_PASSWORD secret, not in SMTP_URL" };
53+ const host = u.hostname.replace(/^\[(.*)\]$/, "$1");
54+ if (!host) return { error: "SMTP_URL has no host" };
55+ if ((u.pathname && u.pathname !== "/") || u.search || u.hash) return { error: "SMTP_URL takes no path or query" };
56+ let user: string | null;
57+ try {
58+ user = u.username ? decodeURIComponent(u.username) : null;
59+ } catch {
60+ return { error: "SMTP_URL has a badly escaped user" };
61+ }
62+ const password = env.SMTP_PASSWORD || null;
63+ if (user && !password) return { error: "SMTP_URL names a user but the SMTP_PASSWORD secret is not set" };
64+ if (password && !user) return { error: "SMTP_PASSWORD is set but SMTP_URL names no user" };
65+ return { host, port: u.port ? Number(u.port) : tls === "implicit" ? 465 : 587, tls, user, password };
66+}
67+
68+/** SMTP_URL as an administrator may see it: scheme, user, host and port. */
69+export const smtpLabel = (c: SmtpConfig): string =>
70+ `${c.tls === "implicit" ? "smtps" : "smtp"}://${c.user ? `${encodeURIComponent(c.user)}@` : ""}${c.host.includes(":") ? `[${c.host}]` : c.host}:${c.port}${c.tls === "starttls" ? " (STARTTLS)" : ""}`;
71+
72+/** How long to wait for each reply, and for each write. */
73+export const SMTP_TIMEOUT_MS = 30_000;
74+
75+const enc = new TextEncoder();
76+
77+function b64(s: string): string {
78+ let bin = "";
79+ for (const b of enc.encode(s)) bin += String.fromCharCode(b);
80+ return btoa(bin);
81+}
82+
83+/** Base64 in lines of 76 characters (RFC 2045). */
84+const b64Lines = (s: string): string => b64(s).replace(/.{76}/g, "$&\r\n");
85+
86+const ASCII = /^[\x20-\x7e]*$/;
87+
88+/** A header value with non-ASCII text as RFC 2047 encoded words of at most 39 bytes of UTF-8 each, so a folded line stays under 78 characters. */
89+function encodeWords(s: string): string {
90+ if (ASCII.test(s)) return s;
91+ const words: string[] = [];
92+ let cur = "";
93+ for (const ch of s) {
94+ if (cur && enc.encode(cur + ch).length > 39) {
95+ words.push(cur);
96+ cur = "";
97+ }
98+ cur += ch;
99+ }
100+ if (cur) words.push(cur);
101+ return words.map((w) => `=?UTF-8?B?${b64(w)}?=`).join("\r\n ");
102+}
103+
104+const oneLine = (s: string): string => s.replace(/[\r\n]+/g, " ");
105+
106+function mailbox(m: { name: string; email: string } | string): string {
107+ if (typeof m === "string") return oneLine(m);
108+ const name = oneLine(m.name).trim();
109+ if (!name) return oneLine(m.email);
110+ return `${ASCII.test(name) ? `"${name.replace(/[\\"]/g, "\\$&")}"` : encodeWords(name)} <${oneLine(m.email)}>`;
111+}
112+
113+/** Headers formatMessage writes itself; the same names in Outgoing.headers are left out. */
114+const OWN_HEADERS = new Set(["from", "to", "cc", "bcc", "reply-to", "subject", "date", "message-id", "mime-version", "content-type", "content-transfer-encoding"]);
115+
116+/** The email as RFC 5322 text with CRLF line ends: text and HTML as multipart/alternative, each in base64. */
117+export function formatMessage(msg: Outgoing, o: { messageId: string; date: Date; boundary?: string }): string {
118+ const boundary = o.boundary ?? `=_diffinery_${crypto.randomUUID().replace(/-/g, "")}`;
119+ const headers: Array<[string, string]> = [
120+ ["From", mailbox(msg.from)],
121+ ["To", mailbox(msg.to)],
122+ ...(msg.replyTo ? [["Reply-To", mailbox(msg.replyTo)] as [string, string]] : []),
123+ ["Subject", encodeWords(oneLine(msg.subject))],
124+ ["Date", o.date.toUTCString().replace(/GMT$/, "+0000")],
125+ ["Message-ID", o.messageId],
126+ ["MIME-Version", "1.0"],
127+ ...Object.entries(msg.headers)
128+ .filter(([k]) => /^[A-Za-z0-9-]+$/.test(k) && !OWN_HEADERS.has(k.toLowerCase()))
129+ .map(([k, v]) => [k, encodeWords(oneLine(v))] as [string, string]),
130+ ["Content-Type", `multipart/alternative; boundary="${boundary}"`],
131+ ];
132+ const part = (type: string, body: string) => `--${boundary}\r\nContent-Type: ${type}; charset=utf-8\r\nContent-Transfer-Encoding: base64\r\n\r\n${b64Lines(body)}\r\n`;
133+ return `${headers.map(([k, v]) => `${k}: ${v}\r\n`).join("")}\r\n${part("text/plain", msg.text)}${part("text/html", msg.html)}--${boundary}--\r\n`;
134+}
135+
136+/** Enhanced status codes (RFC 3463) that mean the recipient's address is bad for good: no such mailbox or domain, or a disabled mailbox. */
137+const BAD_RECIPIENT = new Set(["5.1.1", "5.1.2", "5.1.3", "5.1.6", "5.1.10", "5.2.1"]);
138+
139+interface Reply {
140+ code: number;
141+ text: string;
142+}
143+
144+/** Whether a 5xx reply to RCPT TO is about the address rather than the sender, the relay or the message. */
145+function recipientGone(r: Reply): boolean {
146+ const enhanced = /^5\.\d{1,3}\.\d{1,3}\b/.exec(r.text)?.[0];
147+ return enhanced ? BAD_RECIPIENT.has(enhanced) : r.code === 550 || r.code === 551 || r.code === 553;
148+}
149+
150+function failure(stage: string, r: Reply): SmtpError {
151+ const detail = `SMTP ${stage}: ${r.code} ${r.text}`.slice(0, 300);
152+ if (r.code >= 400 && r.code < 500) return new SmtpError("E_SMTP_TRANSIENT", detail);
153+ if (r.code >= 500) return new SmtpError(stage === "RCPT TO" && recipientGone(r) ? "E_SMTP_RECIPIENT_REJECTED" : "E_SMTP_REJECTED", detail);
154+ return new SmtpError("E_SMTP_TRANSIENT", `${detail} (unexpected reply)`);
155+}
156+
157+/** One SMTP connection: reads replies line by line and writes commands, each within the timeout. */
158+class Session {
159+ private reader!: ReadableStreamDefaultReader<Uint8Array>;
160+ private writer!: WritableStreamDefaultWriter<Uint8Array>;
161+ private decoder = new TextDecoder();
162+ private buf = "";
163+
164+ constructor(
165+ private socket: Socket,
166+ private timeoutMs: number,
167+ ) {
168+ this.attach(socket);
169+ }
170+
171+ private attach(socket: Socket): void {
172+ this.socket = socket;
173+ // A connection that fails shows up in the next read; these would otherwise be unhandled rejections.
174+ socket.opened.catch(() => {});
175+ socket.closed.catch(() => {});
176+ this.reader = socket.readable.getReader();
177+ this.writer = socket.writable.getWriter();
178+ this.decoder = new TextDecoder();
179+ this.buf = "";
180+ }
181+
182+ private async within<T>(p: Promise<T>, what: string): Promise<T> {
183+ let timer: ReturnType<typeof setTimeout> | null = null;
184+ const timeout = new Promise<never>((_, reject) => {
185+ timer = setTimeout(() => reject(new SmtpError("E_SMTP_TRANSIENT", `SMTP ${what}: no answer from the server in ${this.timeoutMs / 1000} seconds`)), this.timeoutMs);
186+ });
187+ try {
188+ return await Promise.race([p, timeout]);
189+ } finally {
190+ clearTimeout(timer);
191+ }
192+ }
193+
194+ private async line(stage: string): Promise<string> {
195+ for (;;) {
196+ const nl = this.buf.indexOf("\n");
197+ if (nl >= 0) {
198+ const l = this.buf.slice(0, nl).replace(/\r$/, "");
199+ this.buf = this.buf.slice(nl + 1);
200+ return l;
201+ }
202+ if (this.buf.length > 64_000) throw new SmtpError("E_SMTP_TRANSIENT", `SMTP ${stage}: reply line too long`);
203+ const { value, done } = await this.within(this.reader.read(), stage);
204+ if (done) throw new SmtpError("E_SMTP_TRANSIENT", `SMTP ${stage}: the server closed the connection`);
205+ this.buf += this.decoder.decode(value, { stream: true });
206+ }
207+ }
208+
209+ /** One reply, all lines of a multiline one (`250-...` up to `250 ...`) joined. */
210+ async reply(stage: string): Promise<Reply> {
211+ const lines: string[] = [];
212+ for (;;) {
213+ const l = await this.line(stage);
214+ const m = /^(\d{3})([ -]|$)(.*)$/.exec(l);
215+ if (!m) throw new SmtpError("E_SMTP_TRANSIENT", `SMTP ${stage}: not an SMTP reply`);
216+ lines.push(m[3]!);
217+ if (m[2] !== "-") return { code: Number(m[1]), text: lines.join("\n") };
218+ }
219+ }
220+
221+ async write(data: string, stage: string): Promise<void> {
222+ await this.within(this.writer.write(enc.encode(data)), stage);
223+ }
224+
225+ /** Send a command and expect one of the codes. `stage` names it in errors, so a command with a password in it never shows up. */
226+ async command(line: string, ok: number[], stage: string): Promise<Reply> {
227+ await this.write(`${line}\r\n`, stage);
228+ return this.expect(ok, stage);
229+ }
230+
231+ async expect(ok: number[], stage: string): Promise<Reply> {
232+ const r = await this.reply(stage);
233+ if (!ok.includes(r.code)) throw failure(stage, r);
234+ return r;
235+ }
236+
237+ /** EHLO, and the extensions the server lists (keyword → parameters). */
238+ async ehlo(name: string): Promise<Map<string, string>> {
239+ const r = await this.command(`EHLO ${name}`, [250], "EHLO");
240+ const caps = new Map<string, string>();
241+ for (const l of r.text.split("\n").slice(1)) {
242+ const [k, ...rest] = l.trim().split(/\s+/);
243+ if (k) caps.set(k.toUpperCase(), rest.join(" ").toUpperCase());
244+ }
245+ return caps;
246+ }
247+
248+ /** Switch to TLS after the server's 220 to STARTTLS. Anything it sent before is dropped, so it can't be injected into the TLS session. */
249+ startTls(): void {
250+ this.reader.releaseLock();
251+ this.writer.releaseLock();
252+ this.attach(this.socket.startTls());
253+ }
254+
255+ async close(): Promise<void> {
256+ await this.socket.close().catch(() => {});
257+ }
258+}
259+
260+const ADDRESS = /^[^\s<>()[\],;:"\\@]+@[^\s<>()[\],;:"\\@]+$/;
261+
262+/**
263+ * Send one email over SMTP. Resolves with the Message-ID it gave the email; throws SmtpError.
264+ * `ehlo` is the name Diffinery greets the server with (its own hostname).
265+ */
266+export async function sendSmtp(cfg: SmtpConfig, msg: Outgoing, opts: { ehlo: string; timeoutMs?: number; now?: Date }): Promise<{ messageId: string }> {
267+ const from = msg.from.email;
268+ const to = typeof msg.to === "string" ? msg.to : msg.to.email;
269+ for (const a of [from, to]) if (!ADDRESS.test(a)) throw new SmtpError("E_SMTP_REJECTED", `not an address SMTP can send to: ${oneLine(a).slice(0, 100)}`);
270+ const messageId = `<${crypto.randomUUID()}@${from.slice(from.lastIndexOf("@") + 1)}>`;
271+ const data = formatMessage(msg, { messageId, date: opts.now ?? new Date() });
272+
273+ let session: Session;
274+ try {
275+ session = new Session(connect({ hostname: cfg.host, port: cfg.port }, { secureTransport: cfg.tls === "implicit" ? "on" : "starttls", allowHalfOpen: false }), opts.timeoutMs ?? SMTP_TIMEOUT_MS);
276+ } catch (e) {
277+ throw new SmtpError("E_SMTP_TRANSIENT", `SMTP connect: ${(e as Error).message ?? String(e)}`);
278+ }
279+ try {
280+ await session.expect([220], "greeting");
281+ let caps = await session.ehlo(opts.ehlo);
282+ if (cfg.tls === "starttls") {
283+ if (!caps.has("STARTTLS")) throw new SmtpError("E_SMTP_REJECTED", "SMTP: the server doesn't offer STARTTLS, and Diffinery doesn't send without TLS");
284+ await session.command("STARTTLS", [220], "STARTTLS");
285+ session.startTls();
286+ caps = await session.ehlo(opts.ehlo);
287+ }
288+ if (cfg.user && cfg.password) {
289+ const mechanisms = (caps.get("AUTH") ?? "").split(" ");
290+ if (mechanisms.includes("PLAIN")) {
291+ await session.command(`AUTH PLAIN ${b64(`\0${cfg.user}\0${cfg.password}`)}`, [235], "AUTH");
292+ } else if (mechanisms.includes("LOGIN")) {
293+ await session.command("AUTH LOGIN", [334], "AUTH");
294+ await session.command(b64(cfg.user), [334], "AUTH");
295+ await session.command(b64(cfg.password), [235], "AUTH");
296+ } else {
297+ throw new SmtpError("E_SMTP_REJECTED", "SMTP: the server offers neither AUTH PLAIN nor AUTH LOGIN");
298+ }
299+ }
300+ const utf8 = !ASCII.test(from + to);
301+ if (utf8 && !caps.has("SMTPUTF8")) throw new SmtpError("E_SMTP_REJECTED", "SMTP: the address isn't ASCII and the server doesn't offer SMTPUTF8");
302+ await session.command(`MAIL FROM:<${from}>${utf8 ? " SMTPUTF8" : ""}`, [250], "MAIL FROM");
303+ await session.command(`RCPT TO:<${to}>`, [250, 251], "RCPT TO");
304+ await session.command("DATA", [354], "DATA");
305+ // A line that starts with a dot gets another (RFC 5321 4.5.2); a dot alone ends the message.
306+ await session.write(`${data.replace(/^\./gm, "..")}.\r\n`, "DATA");
307+ await session.expect([250], "DATA");
308+ await session.write("QUIT\r\n", "QUIT").catch(() => {});
309+ return { messageId };
310+ } catch (e) {
311+ if (e instanceof SmtpError) throw e;
312+ throw new SmtpError("E_SMTP_TRANSIENT", `SMTP: ${(e as Error).message ?? String(e)}`);
313+ } finally {
314+ await session.close();
315+ }
316+}
modifiedapps/diffinery/src/mail/suppression.ts+7−5View file
@@ -12,7 +12,7 @@
1212 *
1313 * Bounces and complaints come from Cloudflare Email Sending's Event Subscriptions (a queue,
1414 * mail/events.ts), from a signed POST to /-/email/events for anything else, and from Email
15- * Sending's own answer to a send that it refuses for good (sendSuppression, used by deliver()).
15+ * Sending's or the SMTP server's own answer to a send it refuses for good (sendSuppression, used by deliver()).
1616 */
1717
1818 export type SuppressionReason = "hard-bounce" | "complaint" | "manual";
@@ -103,11 +103,13 @@
103103 /**
104104 * Error codes with which Email Sending's send() refuses a recipient for good: it is on Cloudflare's
105105 * own suppression list (after a bounce or complaint there), so every later send fails the same way.
106- * Everything else (rate limits, the daily limit, delivery and internal errors, a bad message or
107- * sender) is about the send, not the address, and changes nothing.
106+ * Over SMTP (smtp.ts), E_SMTP_RECIPIENT_REJECTED: the server answered RCPT TO with a permanent
107+ * "no such mailbox or domain". Everything else (rate limits, the daily limit, delivery and internal
108+ * errors, a bad message or sender, a wrong SMTP password) is about the send, not the address, and
109+ * changes nothing.
108110 * https://developers.cloudflare.com/email-service/api/send-emails/workers-api/
109111 */
110-export const PERMANENT_SEND_CODES: ReadonlySet<string> = new Set(["E_RECIPIENT_SUPPRESSED"]);
112+export const PERMANENT_SEND_CODES: ReadonlySet<string> = new Set(["E_RECIPIENT_SUPPRESSED", "E_SMTP_RECIPIENT_REJECTED"]);
111113
112114 /**
113115 * What Email Sending's answer to one send means for the list: a permanent failure for the
@@ -122,7 +124,7 @@
122124 const e = answer.error as { code?: unknown; message?: unknown };
123125 const code = typeof e.code === "string" ? e.code : "";
124126 if (!PERMANENT_SEND_CODES.has(code)) return null;
125- return { email, reason: "hard-bounce", detail: clip(`Email Sending refused it: ${code}${typeof e.message === "string" && e.message ? `: ${e.message}` : ""}`) };
127+ return { email, reason: "hard-bounce", detail: clip(`${code.startsWith("E_SMTP_") ? "The SMTP server" : "Email Sending"} refused it: ${code}${typeof e.message === "string" && e.message ? `: ${e.message}` : ""}`) };
126128 }
127129 const r = answer.result && typeof answer.result === "object" ? (answer.result as { permanent_bounces?: unknown }) : null;
128130 const bounced = Array.isArray(r?.permanent_bounces) ? r.permanent_bounces : [];
modifiedapps/diffinery/src/mail/web.tsx+12−2View file
@@ -12,7 +12,8 @@
1212 import { Form, Time, WATCH_OPTIONS, act, flash, post, prm, render, repoUrl, type WebApp } from "../web/ui.js";
1313 import { MailStore, WATCH_LEVELS, type EmailLogRow, type NotificationPrefs, type WatchLevel } from "./prefs.js";
1414 import { sampleJobs } from "./samples.js";
15-import { buildMessage, deliver, enqueueMail, senderAddress } from "./send.js";
15+import { buildMessage, deliver, enqueueMail, mailTransport, senderAddress } from "./send.js";
16+import { smtpLabel } from "./smtp.js";
1617 import type { Category, MailJob } from "./types.js";
1718 import { readUnsubToken, type UnsubScope, type UnsubToken } from "./unsubscribe.js";
1819 import { normalEmail } from "../auth/signup.js";
@@ -60,6 +61,15 @@
6061 return me;
6162 };
6263
64+/** The Sending line on Settings → Email: which transport sends, or why nothing does. */
65+function sendingStatus(env: AppContext["env"]): Child {
66+ const t = mailTransport(env);
67+ if (!t) return <span class="bad">not configured (no EMAIL binding or SMTP_URL): emails are logged, not sent</span>;
68+ if (t.kind === "email-sending") return <span class="ok">Cloudflare Email Sending is bound</span>;
69+ if ("error" in t) return <span class="bad">SMTP_URL is set but can't be used: {t.error}</span>;
70+ return <span class="ok">over SMTP: {smtpLabel(t.config)}</span>;
71+}
72+
6373 /** One-line description of what an unsubscribe link changes. */
6474 function scopeText(s: UnsubScope): string {
6575 if (s.t === "thread") return `Mute ${s.repo}#${s.number}`;
@@ -631,7 +641,7 @@
631641 <div class="body">
632642 <dl class="kv m0">
633643 <dt>Sending</dt>
634- <dd>{c.env.EMAIL ? <span class="ok">Cloudflare Email Sending is bound</span> : <span class="bad">not configured (no EMAIL binding): emails are logged, not sent</span>}</dd>
644+ <dd>{sendingStatus(c.env)}</dd>
635645 <dt>Queue</dt>
636646 <dd>{c.env.MAIL ? "diffinery-mail" : <span class="bad">not bound: emails are dropped</span>}</dd>
637647 <dt>From</dt>
addedapps/diffinery/test/unit/smtp.test.ts+367−0View file
@@ -1,0 +1,367 @@
1+import { afterEach, describe, expect, it, vi } from "vitest";
2+import type { Env } from "../../src/env.js";
3+import { deliver, mailTransport, RetryableMailError, type Outgoing } from "../../src/mail/send.js";
4+import { formatMessage, sendSmtp, SmtpError, smtpConfig, smtpLabel, type SmtpConfig } from "../../src/mail/smtp.js";
5+import { Suppressions } from "../../src/mail/suppression.js";
6+import type { MailJob } from "../../src/mail/types.js";
7+import { setConnect } from "./stubs/cloudflare-sockets.js";
8+import { testD1 } from "./stubs/d1.js";
9+
10+const enc = new TextEncoder();
11+const PASSWORD = "hunter2-very-secret";
12+const b64 = (s: string) => Buffer.from(s, "utf8").toString("base64");
13+
14+type Verb = "STARTTLS" | "AUTH" | "MAIL" | "RCPT" | "DATA" | "END";
15+
16+/**
17+ * A fake SMTP server behind a fake socket: it answers each command as a submission server would,
18+ * or with the reply a test sets for that step ("CLOSE" hangs up instead), and records the commands
19+ * and the message. Replies go out as soon as a command is written, so nothing here waits on time.
20+ */
21+class FakeSmtp {
22+ commands: string[] = [];
23+ data = "";
24+ connects: Array<{ address: unknown; options: unknown }> = [];
25+ upgrades = 0;
26+ private out: (s: string) => void = () => {};
27+ private hangUp: () => void = () => {};
28+ private buf = "";
29+ private inData = false;
30+ private loginStep = 0;
31+ private tls = false;
32+
33+ constructor(
34+ private s: {
35+ silent?: boolean;
36+ /** Extensions after TLS (default PIPELINING, AUTH PLAIN LOGIN, ENHANCEDSTATUSCODES) and before it (default STARTTLS). */
37+ ehlo?: string[];
38+ ehloPlain?: string[];
39+ reply?: Partial<Record<Verb, string>>;
40+ } = {},
41+ ) {}
42+
43+ connect = (address: unknown, options?: { secureTransport?: string }): Socket => {
44+ this.connects.push({ address, options });
45+ this.tls = options?.secureTransport === "on";
46+ const socket = this.socket();
47+ if (!this.s.silent) this.send("220 smtp.example ESMTP");
48+ return socket;
49+ };
50+
51+ private socket(): Socket {
52+ const dec = new TextDecoder();
53+ let ctrl!: ReadableStreamDefaultController<Uint8Array>;
54+ const readable = new ReadableStream<Uint8Array>({ start: (c) => void (ctrl = c) });
55+ this.out = (s) => ctrl.enqueue(enc.encode(s));
56+ this.hangUp = () => {
57+ try {
58+ ctrl.close();
59+ } catch {
60+ // already closed
61+ }
62+ };
63+ const writable = new WritableStream<Uint8Array>({ write: (chunk) => this.receive(dec.decode(chunk, { stream: true })) });
64+ const startTls = () => {
65+ this.upgrades++;
66+ this.tls = true;
67+ return this.socket();
68+ };
69+ return { readable, writable, opened: Promise.resolve({}), closed: Promise.resolve(), close: async () => this.hangUp(), startTls } as unknown as Socket;
70+ }
71+
72+ private send(s: string): void {
73+ if (s === "CLOSE") this.hangUp();
74+ else this.out(`${s}\r\n`);
75+ }
76+
77+ private receive(text: string): void {
78+ this.buf += text;
79+ for (let i = this.buf.indexOf("\r\n"); i >= 0; i = this.buf.indexOf("\r\n")) {
80+ const line = this.buf.slice(0, i);
81+ this.buf = this.buf.slice(i + 2);
82+ if (this.inData) {
83+ if (line === ".") {
84+ this.inData = false;
85+ this.send(this.s.reply?.END ?? "250 2.0.0 Ok: queued as ABC123");
86+ } else this.data += `${line.startsWith(".") ? line.slice(1) : line}\r\n`;
87+ } else this.command(line);
88+ }
89+ }
90+
91+ private command(line: string): void {
92+ this.commands.push(line);
93+ const r = this.s.reply ?? {};
94+ if (this.loginStep === 1) {
95+ this.loginStep = 2;
96+ return this.send("334 UGFzc3dvcmQ6");
97+ }
98+ if (this.loginStep === 2) {
99+ this.loginStep = 0;
100+ return this.send(r.AUTH ?? "235 2.7.0 Authentication successful");
101+ }
102+ const verb = line.split(" ")[0]!.toUpperCase();
103+ if (verb === "EHLO") {
104+ const ext = this.tls ? (this.s.ehlo ?? ["PIPELINING", "AUTH PLAIN LOGIN", "ENHANCEDSTATUSCODES"]) : (this.s.ehloPlain ?? ["STARTTLS", "ENHANCEDSTATUSCODES"]);
105+ const lines = ["smtp.example Hello", ...ext];
106+ return this.send(lines.map((l, i) => `250${i === lines.length - 1 ? " " : "-"}${l}`).join("\r\n"));
107+ }
108+ if (verb === "STARTTLS") return this.send(r.STARTTLS ?? "220 2.0.0 Ready to start TLS");
109+ if (line === "AUTH LOGIN") {
110+ this.loginStep = 1;
111+ return this.send("334 VXNlcm5hbWU6");
112+ }
113+ if (verb === "AUTH") return this.send(r.AUTH ?? "235 2.7.0 Authentication successful");
114+ if (verb === "MAIL") return this.send(r.MAIL ?? "250 2.1.0 Ok");
115+ if (verb === "RCPT") return this.send(r.RCPT ?? "250 2.1.5 Ok");
116+ if (verb === "DATA") {
117+ const reply = r.DATA ?? "354 End data with <CR><LF>.<CR><LF>";
118+ this.inData = reply.startsWith("354");
119+ return this.send(reply);
120+ }
121+ if (verb === "QUIT") return this.send("221 2.0.0 Bye");
122+ this.send("500 5.5.2 Unknown command");
123+ }
124+
125+ /** The decoded text/plain or text/html part of the message the server received. */
126+ part(type: "plain" | "html"): string {
127+ const m = new RegExp(`Content-Type: text/${type}; charset=utf-8\\r\\nContent-Transfer-Encoding: base64\\r\\n\\r\\n([\\s\\S]*?)\\r\\n--`).exec(this.data);
128+ return Buffer.from(m![1]!.replace(/\r\n/g, ""), "base64").toString("utf8");
129+ }
130+}
131+
132+const msg = (over: Partial<Outgoing> = {}): Outgoing => ({
133+ from: { name: "Ann (Diffinery)", email: "[email protected]" },
134+ to: { name: "Bob", email: "[email protected]" },
135+ subject: "Your test email",
136+ html: "<p>Hello <b>Bob</b></p>",
137+ text: "Hello Bob\n.a line that starts with a dot",
138+ headers: { "X-Diffinery-Reason": "account", "List-Unsubscribe": "<https://diffinery.example/u/x>" },
139+ ...over,
140+});
141+
142+const implicit: SmtpConfig = { host: "smtp.example", port: 465, tls: "implicit", user: "[email protected]", password: PASSWORD };
143+const starttls: SmtpConfig = { ...implicit, port: 587, tls: "starttls" };
144+
145+function server(s: ConstructorParameters<typeof FakeSmtp>[0] = {}): FakeSmtp {
146+ const f = new FakeSmtp(s);
147+ setConnect(f.connect);
148+ return f;
149+}
150+
151+afterEach(() => {
152+ setConnect(null);
153+ vi.restoreAllMocks();
154+});
155+
156+describe("SMTP settings", () => {
157+ it("reads SMTP_URL and SMTP_PASSWORD", () => {
158+ expect(smtpConfig({})).toBeNull();
159+ expect(smtpConfig({ SMTP_URL: "smtps://ann%[email protected]", SMTP_PASSWORD: PASSWORD })).toEqual(implicit);
160+ expect(smtpConfig({ SMTP_URL: "smtp://ann%[email protected]", SMTP_PASSWORD: PASSWORD })).toEqual(starttls);
161+ expect(smtpConfig({ SMTP_URL: "smtps://relay.example:2465" })).toEqual({ host: "relay.example", port: 2465, tls: "implicit", user: null, password: null });
162+ expect(smtpConfig({ SMTP_URL: "smtp://[::1]:1587" })).toMatchObject({ host: "::1", port: 1587 });
163+ });
164+
165+ it("says what is wrong, and never takes a password from the URL", () => {
166+ expect(smtpConfig({ SMTP_URL: "smtps://ann:[email protected]" })).toEqual({ error: "the password goes in the SMTP_PASSWORD secret, not in SMTP_URL" });
167+ expect(smtpConfig({ SMTP_URL: "https://smtp.example" })).toEqual({ error: "SMTP_URL must start with smtps:// or smtp://" });
168+ expect(smtpConfig({ SMTP_URL: "smtps://[email protected]" })).toEqual({ error: "SMTP_URL names a user but the SMTP_PASSWORD secret is not set" });
169+ expect(smtpConfig({ SMTP_URL: "smtps://smtp.example", SMTP_PASSWORD: PASSWORD })).toEqual({ error: "SMTP_PASSWORD is set but SMTP_URL names no user" });
170+ expect(smtpConfig({ SMTP_URL: "smtps://smtp.example/x?y" })).toEqual({ error: "SMTP_URL takes no path or query" });
171+ });
172+
173+ it("shows administrators the server but not the password", () => {
174+ expect(smtpLabel(implicit)).toBe("smtps://ann%[email protected]:465");
175+ expect(smtpLabel(starttls)).toBe("smtp://ann%[email protected]:587 (STARTTLS)");
176+ });
177+
178+ it("prefers the EMAIL binding when both are there", () => {
179+ const EMAIL = { send: async () => ({ messageId: "x" }) } as unknown as SendEmail;
180+ expect(mailTransport({ EMAIL, SMTP_URL: "smtps://smtp.example" })?.kind).toBe("email-sending");
181+ expect(mailTransport({ SMTP_URL: "smtps://smtp.example" })?.kind).toBe("smtp");
182+ expect(mailTransport({})).toBeNull();
183+ });
184+});
185+
186+describe("the MIME message", () => {
187+ const date = new Date("2026-10-30T12:00:00Z");
188+
189+ it("has the headers, and the text and HTML parts in base64, with CRLF line ends", () => {
190+ const m = formatMessage(msg({ replyTo: "[email protected]" }), { messageId: "<[email protected]>", date, boundary: "b" });
191+ expect(m.replace(/\r\n/g, "")).not.toMatch(/[\r\n]/);
192+ const [head] = m.split("\r\n\r\n");
193+ expect(head!.split("\r\n")).toEqual([
194+ 'From: "Ann (Diffinery)" <[email protected]>',
195+ 'To: "Bob" <[email protected]>',
196+ "Reply-To: [email protected]",
197+ "Subject: Your test email",
198+ "Date: Fri, 30 Oct 2026 12:00:00 +0000",
199+ "Message-ID: <[email protected]>",
200+ "MIME-Version: 1.0",
201+ "X-Diffinery-Reason: account",
202+ "List-Unsubscribe: <https://diffinery.example/u/x>",
203+ 'Content-Type: multipart/alternative; boundary="b"',
204+ ]);
205+ expect(m).toContain(`Content-Type: text/plain; charset=utf-8\r\nContent-Transfer-Encoding: base64\r\n\r\n${b64(msg().text)}\r\n--b\r\n`);
206+ expect(m).toContain(`Content-Type: text/html; charset=utf-8\r\nContent-Transfer-Encoding: base64\r\n\r\n${b64(msg().html)}\r\n--b--\r\n`);
207+ });
208+
209+ it("encodes non-ASCII names and subjects, and keeps out injected headers", () => {
210+ const m = formatMessage(
211+ msg({ subject: "Ünal commented on acme/website#12 — a long subject that needs more than one encoded word", to: { name: "Bob Ünal", email: "[email protected]" }, headers: { "X-Evil\r\nBcc": "x", "X-Ok": "a\r\nBcc: [email protected]", Subject: "twice" } }),
212+ { messageId: "<id@x>", date },
213+ );
214+ const head = m.split("\r\n\r\n")[0]!;
215+ const decode = (s: string) => s.replace(/\r\n /g, "").replace(/=\?UTF-8\?B\?([^?]*)\?=/g, (_, w: string) => Buffer.from(w, "base64").toString("utf8"));
216+ expect(decode(/^Subject: (.*(?:\r\n .*)*)/m.exec(head)![1]!)).toBe("Ünal commented on acme/website#12 — a long subject that needs more than one encoded word");
217+ expect(/^Subject: .*(?:\r\n .*)*/m.exec(head)![0].split("\r\n").every((l) => l.length <= 78)).toBe(true);
218+ expect(decode(/^To: (.*)/m.exec(head)![1]!)).toBe("Bob Ünal <[email protected]>");
219+ expect(head).toContain("X-Ok: a Bcc: [email protected]");
220+ expect(head).not.toMatch(/^Bcc/m);
221+ expect(head.match(/^Subject:/gm)).toHaveLength(1);
222+ });
223+});
224+
225+describe("sending over SMTP", () => {
226+ it("sends over implicit TLS with AUTH PLAIN", async () => {
227+ const f = server();
228+ const r = await sendSmtp(implicit, msg(), { ehlo: "diffinery.example" });
229+ expect(f.connects).toEqual([{ address: { hostname: "smtp.example", port: 465 }, options: { secureTransport: "on", allowHalfOpen: false } }]);
230+ expect(f.commands).toEqual(["EHLO diffinery.example", `AUTH PLAIN ${b64(`\0[email protected]\0${PASSWORD}`)}`, "MAIL FROM:<[email protected]>", "RCPT TO:<[email protected]>", "DATA", "QUIT"]);
231+ expect(r.messageId).toMatch(/^<[0-9a-f-]{36}@diffinery\.example>$/);
232+ expect(f.data).toContain(`Message-ID: ${r.messageId}\r\n`);
233+ expect(f.part("plain")).toBe(msg().text);
234+ expect(f.part("html")).toBe(msg().html);
235+ });
236+
237+ it("upgrades with STARTTLS before anything else, and falls back to AUTH LOGIN", async () => {
238+ const f = server({ ehlo: ["AUTH LOGIN"] });
239+ await sendSmtp(starttls, msg(), { ehlo: "diffinery.example" });
240+ expect(f.connects[0]).toEqual({ address: { hostname: "smtp.example", port: 587 }, options: { secureTransport: "starttls", allowHalfOpen: false } });
241+ expect(f.upgrades).toBe(1);
242+ expect(f.commands.slice(0, 6)).toEqual(["EHLO diffinery.example", "STARTTLS", "EHLO diffinery.example", "AUTH LOGIN", b64("[email protected]"), b64(PASSWORD)]);
243+ });
244+
245+ it("won't send the password without TLS", async () => {
246+ const f = server({ ehloPlain: ["AUTH PLAIN LOGIN"] });
247+ const err = await sendSmtp(starttls, msg(), { ehlo: "diffinery.example" }).catch((e: SmtpError) => e);
248+ expect(err).toMatchObject({ code: "E_SMTP_REJECTED", message: "SMTP: the server doesn't offer STARTTLS, and Diffinery doesn't send without TLS" });
249+ expect(f.commands).toEqual(["EHLO diffinery.example"]);
250+ });
251+
252+ it("ignores anything the server sent before TLS started", async () => {
253+ // A man in the middle appends a reply to the 220; read after the upgrade, it would answer the second EHLO.
254+ const f = server({ reply: { STARTTLS: "220 2.0.0 go ahead\r\n250 injected" } });
255+ await sendSmtp(starttls, msg(), { ehlo: "diffinery.example" });
256+ expect(f.commands.slice(2, 4)).toEqual(["EHLO diffinery.example", `AUTH PLAIN ${b64(`\0[email protected]\0${PASSWORD}`)}`]);
257+ });
258+
259+ it("sends without AUTH when SMTP_URL names no user", async () => {
260+ const f = server();
261+ await sendSmtp({ ...implicit, user: null, password: null }, msg(), { ehlo: "diffinery.example" });
262+ expect(f.commands[1]).toBe("MAIL FROM:<[email protected]>");
263+ });
264+
265+ it.each([
266+ ["RCPT", "550 5.1.1 <[email protected]>: Recipient address rejected: User unknown", "E_SMTP_RECIPIENT_REJECTED"],
267+ ["RCPT", "550 Mailbox not found", "E_SMTP_RECIPIENT_REJECTED"],
268+ ["RCPT", "550 5.7.1 Relaying denied", "E_SMTP_REJECTED"],
269+ ["RCPT", "552 5.2.2 Mailbox full", "E_SMTP_REJECTED"],
270+ ["RCPT", "451 4.3.0 Try again later", "E_SMTP_TRANSIENT"],
271+ ["MAIL", "550 5.1.8 Sender address rejected", "E_SMTP_REJECTED"],
272+ ["MAIL", "421 4.7.0 Too many connections", "E_SMTP_TRANSIENT"],
273+ ["END", "554 5.6.0 Message rejected", "E_SMTP_REJECTED"],
274+ ["DATA", "CLOSE", "E_SMTP_TRANSIENT"],
275+ ] as const)("maps %s %s to %s", async (verb, reply, code) => {
276+ server({ reply: { [verb]: reply } });
277+ const err = await sendSmtp(implicit, msg(), { ehlo: "diffinery.example" }).catch((e: unknown) => e);
278+ expect(err).toBeInstanceOf(SmtpError);
279+ expect((err as SmtpError).code).toBe(code);
280+ });
281+
282+ it("never puts the password in an error", async () => {
283+ server({ reply: { AUTH: "535 5.7.8 Authentication credentials invalid" } });
284+ const err = (await sendSmtp(implicit, msg(), { ehlo: "diffinery.example" }).catch((e: unknown) => e)) as SmtpError;
285+ expect(err).toMatchObject({ code: "E_SMTP_REJECTED", message: "SMTP AUTH: 535 5.7.8 Authentication credentials invalid" });
286+ const login = server({ ehlo: ["AUTH LOGIN"], reply: { AUTH: "535 5.7.8 nope" } });
287+ const err2 = (await sendSmtp(implicit, msg(), { ehlo: "diffinery.example" }).catch((e: unknown) => e)) as SmtpError;
288+ expect(login.commands).toContain(b64(PASSWORD));
289+ for (const e of [err, err2]) for (const secret of [PASSWORD, b64(PASSWORD), b64(`\0[email protected]\0${PASSWORD}`)]) expect(`${e.message} ${e.stack}`).not.toContain(secret);
290+ });
291+
292+ it("gives up on a server that doesn't answer", async () => {
293+ server({ silent: true });
294+ const err = await sendSmtp(implicit, msg(), { ehlo: "diffinery.example", timeoutMs: 5 }).catch((e: unknown) => e);
295+ expect(err).toMatchObject({ code: "E_SMTP_TRANSIENT", message: "SMTP greeting: no answer from the server in 0.005 seconds" });
296+ });
297+
298+ it("refuses an address that would break the command", async () => {
299+ const f = server();
300+ const err = await sendSmtp(implicit, msg({ to: "[email protected]>\r\nRCPT TO:<[email protected]" }), { ehlo: "diffinery.example" }).catch((e: unknown) => e);
301+ expect(err).toMatchObject({ code: "E_SMTP_REJECTED" });
302+ expect(f.connects).toEqual([]);
303+ });
304+});
305+
306+describe("deliver() over SMTP", () => {
307+ const at = "2026-10-01T00:00:00.000Z";
308+ const job: MailJob = { kind: "test", data: { by: "ann" }, to: { accountId: "ann" }, reason: "account", at } as MailJob;
309+
310+ function setup(vars: Partial<Env> = { SMTP_URL: "smtps://ann%[email protected]", SMTP_PASSWORD: PASSWORD }) {
311+ const DB = testD1();
312+ DB.sqlite.prepare("INSERT INTO accounts (id, login, kind, email, status, created_at) VALUES ('ann', 'ann', 'user', '[email protected]', 'active', ?)").run(at);
313+ const env = { DB, PUBLIC_URL: "https://diffinery.example", MASTER_KEY: "test-master-key", MAIL_FROM: "[email protected]", ...vars } as unknown as Env;
314+ const log = () => DB.sqlite.prepare("SELECT to_addr, status, detail, message_id FROM email_log ORDER BY rowid").all() as Array<{ to_addr: string; status: string; detail: string | null; message_id: string | null }>;
315+ return { env, log };
316+ }
317+
318+ it("sends through SMTP_URL when there is no EMAIL binding", async () => {
319+ const f = server();
320+ const { env, log } = setup();
321+ const r = await deliver(env, job);
322+ expect(r.status).toBe("sent");
323+ expect(f.commands).toContain("RCPT TO:<[email protected]>");
324+ expect(log()).toEqual([{ to_addr: "[email protected]", status: "sent", detail: null, message_id: r.messageId }]);
325+ });
326+
327+ it("suppresses an address the server says doesn't exist", async () => {
328+ server({ reply: { RCPT: "550 5.1.1 User unknown" } });
329+ const { env, log } = setup();
330+ expect(await deliver(env, job)).toEqual({ status: "failed", detail: "E_SMTP_RECIPIENT_REJECTED: SMTP RCPT TO: 550 5.1.1 User unknown" });
331+ expect(await new Suppressions(env.DB).get("[email protected]")).toMatchObject({ reason: "hard-bounce", source: "send", detail: "The SMTP server refused it: E_SMTP_RECIPIENT_REJECTED: SMTP RCPT TO: 550 5.1.1 User unknown" });
332+ expect(log()[0]).toMatchObject({ status: "failed" });
333+ });
334+
335+ it("retries a temporary failure, and suppresses nothing", async () => {
336+ server({ reply: { MAIL: "421 4.7.0 Try again later" } });
337+ const { env, log } = setup();
338+ await expect(deliver(env, job)).rejects.toBeInstanceOf(RetryableMailError);
339+ expect(await new Suppressions(env.DB).get("[email protected]")).toBeNull();
340+ expect(log()).toEqual([]);
341+ });
342+
343+ it("fails a wrong password without suppressing the recipient or logging the password", async () => {
344+ server({ reply: { AUTH: "535 5.7.8 Authentication credentials invalid" } });
345+ const errors = vi.spyOn(console, "error").mockImplementation(() => {});
346+ const { env, log } = setup();
347+ expect((await deliver(env, job)).status).toBe("failed");
348+ expect(await new Suppressions(env.DB).get("[email protected]")).toBeNull();
349+ const logged = JSON.stringify([errors.mock.calls, log()]);
350+ expect(logged).toContain("535 5.7.8");
351+ for (const secret of [PASSWORD, b64(PASSWORD), b64(`\0[email protected]\0${PASSWORD}`)]) expect(logged).not.toContain(secret);
352+ });
353+
354+ it("fails without connecting when SMTP_URL can't be used", async () => {
355+ const f = server();
356+ vi.spyOn(console, "error").mockImplementation(() => {});
357+ const { env } = setup({ SMTP_URL: "smtps://ann:[email protected]" });
358+ expect(await deliver(env, job)).toEqual({ status: "failed", detail: "E_SMTP_CONFIG: the password goes in the SMTP_PASSWORD secret, not in SMTP_URL" });
359+ expect(f.connects).toEqual([]);
360+ });
361+
362+ it("skips when neither EMAIL nor SMTP_URL is set", async () => {
363+ const { env, log } = setup({});
364+ expect(await deliver(env, job)).toEqual({ status: "skipped", detail: "no EMAIL binding or SMTP_URL" });
365+ expect(log()[0]).toMatchObject({ status: "skipped", detail: "email sending is not configured (no EMAIL binding or SMTP_URL)" });
366+ });
367+});
addedapps/diffinery/test/unit/stubs/cloudflare-sockets.ts+13−0View file
@@ -1,0 +1,13 @@
1+/** Stand-in for the Workers runtime's `cloudflare:sockets` module: a unit test sets what connect() returns with setConnect. */
2+type Connect = (address: { hostname: string; port: number } | string, options?: { secureTransport?: string; allowHalfOpen: boolean }) => Socket;
3+
4+let fake: Connect | null = null;
5+
6+export function setConnect(fn: Connect | null): void {
7+ fake = fn;
8+}
9+
10+export const connect: Connect = (address, options) => {
11+ if (!fake) throw new Error("this test set no fake connect()");
12+ return fake(address, options);
13+};
modifiedapps/diffinery/vitest.config.ts+1−0View file
@@ -11,6 +11,7 @@
1111 alias: {
1212 "cloudflare:workflows": fileURLToPath(new URL("./test/unit/stubs/cloudflare-workflows.ts", import.meta.url)),
1313 "cloudflare:workers": fileURLToPath(new URL("./test/unit/stubs/cloudflare-workers.ts", import.meta.url)),
14+ "cloudflare:sockets": fileURLToPath(new URL("./test/unit/stubs/cloudflare-sockets.ts", import.meta.url)),
1415 },
1516 },
1617 plugins: [