Repository navigation
feat(core): built-in SMTP email transport for generic SMTP credentials - #2156
Conversation
🦋 Changeset detectedLatest commit: 076304c The changes in this PR will be included in the next version bump. This PR includes changesets to release 12 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
Scope checkThis PR changes 842 lines across 5 files. Large PRs are harder to review and more likely to be closed without review. If this scope is intentional, no action needed. A maintainer will review it. If not, please consider splitting this into smaller PRs. See CONTRIBUTING.md for contribution guidelines. |
@emdash-cms/admin
@emdash-cms/auth
@emdash-cms/auth-atproto
@emdash-cms/blocks
@emdash-cms/cloudflare
@emdash-cms/contentful-to-portable-text
emdash
create-emdash
@emdash-cms/gutenberg-to-portable-text
@emdash-cms/plugin-cli
@emdash-cms/plugin-test
@emdash-cms/plugin-types
@emdash-cms/registry-client
@emdash-cms/registry-lexicons
@emdash-cms/registry-loader
@emdash-cms/registry-moderation
@emdash-cms/registry-verification
upgrade-emdash
@emdash-cms/sandbox-workerd
@emdash-cms/x402
@emdash-cms/plugin-ai-moderation
@emdash-cms/plugin-ai-search
@emdash-cms/plugin-atproto
@emdash-cms/plugin-audit-log
@emdash-cms/plugin-color
@emdash-cms/plugin-embeds
@emdash-cms/plugin-field-kit
@emdash-cms/plugin-forms
@emdash-cms/plugin-webhook-notifier
commit: |
b21e3c5 to
e142700
Compare
Overlapping PRsThis PR modifies files that are also changed by other open PRs:
This may cause merge conflicts or duplicated work. A maintainer will coordinate. |
There was a problem hiding this comment.
The approach is sound: a built-in SMTP transport is the right way to give operators generic SMTP credentials on Cloudflare Workers, and it fits the existing exclusive email:deliver hook model alongside the dev console and Cloudflare Email providers. The PR references the approved discussion and adds a proper changeset.
Static review found several real issues, though:
- Admin UI labels are not localized. Hard-coded English provider names and security-mode labels in
EmailSettings.tsxviolate the Lingui/i18n convention. - SMTP configured via the admin UI does not become active until the runtime restarts. The SMTP built-in is registered only at cold-start when a complete config is already present. The settings route saves the DB record and sets the exclusive selection, but the current pipeline has no SMTP handler, so
isAvailable()returnstruewhilesend()throwsEmailNotConfiguredError. - The admin API allows saving port 25. The PR claims port 25 is refused with a clear error, but that refusal only lives in
loadSmtpConfigFromEnv(). The Zod schema used by the settings route accepts any port 1–65535. - SMTP MIME is not safe for non-ASCII content. Headers (
Subject,From,Reply-To) are emitted as raw UTF-8 and the body is declaredContent-Transfer-Encoding: 7bit, which will mojibake or be rejected for localized/RTL content. - Stale/narrative comments. The SMTP plugin header still says "env-only … no admin UI yet", and tests reference issue numbers in comments.
I did not run the test suite, linter, or builds; the findings below are based on reading the diff, tracing call sites, and checking the repo conventions in AGENTS.md.
| const PROVIDER_OPTIONS: { value: EmailProviderChoice; label: string }[] = [ | ||
| { value: "none", label: "None" }, | ||
| { value: "smtp", label: "SMTP" }, | ||
| { value: "cloudflare", label: "Cloudflare Email" }, |
There was a problem hiding this comment.
[needs fixing] These select labels are user-facing English strings rendered in the DOM, but they bypass Lingui. Per AGENTS.md every admin UI string must go through @lingui/react/macro / @lingui/core/macro.
Use msg descriptors at module scope and resolve them with t() when rendering the Select items:
| const PROVIDER_OPTIONS: { value: EmailProviderChoice; label: string }[] = [ | |
| { value: "none", label: "None" }, | |
| { value: "smtp", label: "SMTP" }, | |
| { value: "cloudflare", label: "Cloudflare Email" }, | |
| import { msg } from "@lingui/core/macro"; | |
| import type { MessageDescriptor } from "@lingui/core"; | |
| const PROVIDER_OPTIONS: { value: EmailProviderChoice; label: MessageDescriptor }[] = [ | |
| { value: "none", label: msg`None` }, | |
| { value: "smtp", label: msg`SMTP` }, | |
| { value: "cloudflare", label: msg`Cloudflare Email` }, | |
| ]; |
Then map with label: t(opt.label) in the <Select items={...}> call on line 263.
| { value: "starttls", label: "STARTTLS (port 587)" }, | ||
| { value: "tls", label: "Implicit TLS (port 465)" }, |
There was a problem hiding this comment.
[needs fixing] The STARTTLS / implicit TLS option labels are hard-coded English. They are user-visible strings in the security <Select> and must be localized.
| { value: "starttls", label: "STARTTLS (port 587)" }, | |
| { value: "tls", label: "Implicit TLS (port 465)" }, | |
| items={[ | |
| { value: "starttls", label: t`STARTTLS (port 587)` }, | |
| { value: "tls", label: t`Implicit TLS (port 465)` }, | |
| ]} |
| // Persist and activate SMTP as the selected provider | ||
| await optionsRepo.set(optionKey, SMTP_EMAIL_PLUGIN_ID); | ||
| emdash.hooks.setExclusiveSelection(EMAIL_DELIVER_HOOK, SMTP_EMAIL_PLUGIN_ID); | ||
|
|
There was a problem hiding this comment.
[needs fixing] This saves the SMTP config to the DB and immediately sets it as the selected exclusive provider, but nothing rebuilds the hook pipeline. EmDashRuntime only registers the built-in SMTP plugin at cold-start when loadSmtpConfig() already returns a complete config (emdash-runtime.ts:1359). If the worker started without SMTP env vars or an existing DB config, the SMTP handler is not in the current pipeline, so emdash.email.isAvailable() will report true while send() later throws EmailNotConfiguredError.
Fix by making the SMTP provider available immediately after admin configuration. The cleanest path is to register the built-in SMTP plugin unconditionally (like Cloudflare Email) and have its handler reject an incomplete config with a clear message, or expose a hook-pipeline rebuild that this route can invoke after persisting a new provider.
| const smtpConfigSchema = z.object({ | ||
| host: z.string().min(1), | ||
| port: z.number().int().min(1).max(65535), | ||
| secure: z.enum(["starttls", "tls"]), |
There was a problem hiding this comment.
[needs fixing] The PR description says port 25 is refused with a clear error because Cloudflare blocks it, but this Zod schema accepts any port 1–65535. A user can save port 25 through the admin UI, after which delivery will hang/fail at runtime.
Add a refine so the API rejects port 25 at the same place it rejects other invalid values:
| secure: z.enum(["starttls", "tls"]), | |
| const smtpConfigSchema = z.object({ | |
| host: z.string().min(1), | |
| port: z.number().int().min(1).max(65535), | |
| secure: z.enum(["starttls", "tls"]), | |
| user: z.string().min(1), | |
| pass: z.string().min(1).optional(), // undefined = keep existing password | |
| fromName: z.string().optional(), | |
| fromEmail: z.string().email().optional(), | |
| replyTo: z.string().email().optional(), | |
| }).refine((v) => v.port !== 25, { | |
| message: "Port 25 is not supported on Cloudflare Workers; use 587 (STARTTLS) or 465 (implicit TLS).", | |
| }); |
| ].join("\r\n"); | ||
| } else { | ||
| headers.push(`Content-Type: text/plain; charset=utf-8`); | ||
| headers.push(`Content-Transfer-Encoding: 7bit`); |
There was a problem hiding this comment.
[needs fixing] The MIME body is declared Content-Transfer-Encoding: 7bit and Subject / From / Reply-To headers are emitted as raw UTF-8. That violates RFC 5322/2047 and will mojibake or be rejected for any non-ASCII content, including localized site names, RTL text, or sender names.
At minimum, encode non-ASCII headers per RFC 2047 and switch the body transfer encoding to quoted-printable or base64 (or negotiate BODY=8BITMIME and use 8bit). As written, a user-visible <strong>${siteName}</strong> from the test email or any localized subject will be corrupted.
| * uses `node:net` / `node:tls`. Configuration is env-only for the first | ||
| * iteration — no admin UI yet. |
There was a problem hiding this comment.
[suggestion] This header comment is stale: it says the SMTP config is "env-only" and that "no admin UI yet" exists, but this PR adds exactly that admin UI. Update or remove the outdated line so future readers don't believe the feature is CLI/env-only.
| * uses `node:net` / `node:tls`. Configuration is env-only for the first | |
| * iteration — no admin UI yet. | |
| * via raw TCP — the one network primitive sandboxed plugins cannot use. | |
| * | |
| * Registered as a built-in `email:deliver` provider when SMTP is configured, | |
| * either via env vars or via Settings → Email in the admin UI. |
| }); | ||
| }); | ||
|
|
||
| describe("Cloudflare socket edge cases (regression #1541)", () => { |
There was a problem hiding this comment.
[suggestion] AGENTS.md says comments should never reference issues/PRs; that context belongs in commit messages. The describe block name and the inline // Regression #1541 comment both violate this. Rename the suite to something descriptive (e.g., Cloudflare socket edge cases) and delete the issue-number comment on line 462.
| } | ||
| }); | ||
|
|
||
| it("uses 25s timeout so hook timeout (30s) does not swallow the error", async () => { |
There was a problem hiding this comment.
[suggestion] The test name claims to verify that the default 25s timeout is shorter than the 30s hook timeout, but it actually passes timeoutMs: 50 and only asserts the configurable timeout is used. It cannot fail on the real regression it claims to guard against (someone changing the default 25s value). Either drop the test or mock timers and assert the actual default.
There was a problem hiding this comment.
Re-review summary
The approach is still sound: a built-in SMTP transport is the right way to unblock operators with generic SMTP credentials on Cloudflare Workers, and adding Settings → Email UI support fits EmDash’s exclusive-hook email model. However, this revision does not resolve the main blockers from the first review. I checked the diff, the full changed files, cross-references to EmailPipeline/HookPipeline, and the repo conventions in AGENTS.md.
What changed since first review
- The admin settings route now persists SMTP config to the DB and sets the exclusive provider selection.
- Cloudflare Email also gained a DB-backed config path.
- New tests cover DB save/load and Cloudflare Email.
What is still broken / unaddressed
- Admin UI labels are still hard-coded English (
PROVIDER_OPTIONS, security-mode labels, placeholders) — a directAGENTS.md/Localize everything user-facingviolation. - Success toasts display raw server English messages (
"SMTP configured and activated", etc.) instead of localized text. - SMTP configured via the admin UI does not actually deliver email until the runtime restarts. The plugin is only registered at cold-start when a complete config already exists; the settings route can set the exclusive selection, but the hook pipeline has no
email:deliverhandler foremdash-smtp. - Port 25 is still accepted by the admin API. The only refusal is in
loadSmtpConfigFromEnv(); the Zod schema andloadSmtpConfigFromDballow port 25, defeating the documented guarantee. - SMTP MIME is not safe for non-ASCII / RTL content. Headers are emitted raw and the body is declared
Content-Transfer-Encoding: 7bit. - Stale/narrative comments remain. The SMTP module header still says “env-only … no admin UI yet”, and tests reference issue numbers.
I did not run the test suite, linter, or build; the findings below are based on static reading and tracing call sites.
| const PROVIDER_OPTIONS: { value: EmailProviderChoice; label: string }[] = [ | ||
| { value: "none", label: "None" }, | ||
| { value: "smtp", label: "SMTP" }, | ||
| { value: "cloudflare", label: "Cloudflare Email" }, |
There was a problem hiding this comment.
[needs fixing] Provider and security-mode labels are still hard-coded English: "None", "SMTP", "Cloudflare Email", "STARTTLS (port 587)", "Implicit TLS (port 465)", and all the SMTP form placeholders. AGENTS.md requires every admin UI string to go through Lingui.
| const PROVIDER_OPTIONS: { value: EmailProviderChoice; label: string }[] = [ | |
| { value: "none", label: "None" }, | |
| { value: "smtp", label: "SMTP" }, | |
| { value: "cloudflare", label: "Cloudflare Email" }, | |
| import { msg } from "@lingui/core/macro"; | |
| import type { MessageDescriptor } from "@lingui/core"; | |
| const PROVIDER_OPTIONS: { value: EmailProviderChoice; label: MessageDescriptor }[] = [ | |
| { value: "none", label: msg`None` }, | |
| { value: "smtp", label: msg`SMTP` }, | |
| { value: "cloudflare", label: msg`Cloudflare Email` }, | |
| ]; | |
| // inside the component, render with t(opt.label) |
| }, [settings]); | ||
|
|
||
| const saveMutation = useMutation({ | ||
| mutationFn: saveEmailSettings, |
There was a problem hiding this comment.
[needs fixing] The save-success toast shows result.message directly. The API returns English strings like "SMTP configured and activated", so non-English admins will see untranslated text. The same pattern is used for testMutation and bindingMutation success toasts.
| mutationFn: saveEmailSettings, | |
| onSuccess: () => { | |
| toastManager.add({ title: t`Email settings saved`, variant: "success", timeout: 5000 }); | |
| setSmtpPass(""); // clear password field after save | |
| void queryClient.invalidateQueries({ queryKey: ["email-settings"] }); | |
| }, |
If the message needs to vary by provider, return a stable code from the API and map it to a localized string on the client.
| // WP Mail SMTP's is_mailer_complete(): a half-saved config (host but no | ||
| // password) must not register a provider — the resulting 535 on send is | ||
| // more confusing than a clean "not configured" state. | ||
| if (isSmtpConfigComplete(smtpConfig)) { |
There was a problem hiding this comment.
[needs fixing] The SMTP built-in is registered only when isSmtpConfigComplete(loadSmtpConfig(...)) is true at cold start. The settings route (packages/core/src/astro/routes/api/settings/email.ts:337) can save DB config and call emdash.hooks.setExclusiveSelection(EMAIL_DELIVER_HOOK, SMTP_EMAIL_PLUGIN_ID), but if the plugin was never registered (because no SMTP config existed at startup), the pipeline has no email:deliver handler for it. EmailPipeline.isAvailable() will return true while send() throws EmailNotConfiguredError.
The Cloudflare Email built-in is always registered (emdash-runtime.ts, just below this block); SMTP should be registered the same way, with its handler loading the latest DB config on demand and failing cleanly when the config is incomplete.
|
|
||
| const smtpConfigSchema = z.object({ | ||
| host: z.string().min(1), | ||
| port: z.number().int().min(1).max(65535), |
There was a problem hiding this comment.
[needs fixing] The PR states that port 25 is refused, but the admin API schema accepts any port from 1–65535. The only port-25 refusal is in loadSmtpConfigFromEnv(); a config saved through the admin UI will bypass that check both at validation time and in loadSmtpConfigFromDb().
| port: z.number().int().min(1).max(65535), | |
| const smtpConfigSchema = z.object({ | |
| host: z.string().min(1), | |
| port: z.number() | |
| .int() | |
| .min(1) | |
| .max(65535) | |
| .refine((p) => p !== 25, { | |
| message: "Port 25 is not supported; use 587 (STARTTLS) or 465 (implicit TLS).", | |
| }), | |
| secure: z.enum(["starttls", "tls"]), | |
| user: z.string().min(1), | |
| pass: z.string().min(1).optional(), | |
| fromName: z.string().optional(), | |
| fromEmail: z.string().email().optional(), | |
| replyTo: z.string().email().optional(), | |
| }); |
The same refusal should also be added to loadSmtpConfigFromDb() and to the client-side handleSave port check.
| `Subject: ${sanitizeHeader(subject)}`, | ||
| `Date: ${new Date().toUTCString()}`, | ||
| `Message-ID: <${crypto.randomUUID()}@emdash>`, | ||
| `MIME-Version: 1.0`, | ||
| ]; | ||
| if (replyTo) { | ||
| headers.push(`Reply-To: ${sanitizeHeader(replyTo)}`); | ||
| } | ||
|
|
||
| let body: string; | ||
| if (html) { | ||
| const boundary = `----=_emdash_${crypto.randomUUID()}`; | ||
| headers.push(`Content-Type: multipart/alternative; boundary="${boundary}"`); | ||
| body = [ | ||
| `--${boundary}`, | ||
| `Content-Type: text/plain; charset=utf-8`, | ||
| `Content-Transfer-Encoding: 7bit`, |
There was a problem hiding this comment.
[needs fixing] buildMime emits raw UTF-8 in Subject, From, and Reply-To headers and declares Content-Transfer-Encoding: 7bit for both plain-text and HTML parts. For localized or RTL content this will mojibake or be rejected by strict SMTP servers. Headers should be RFC 2047 encoded and the transfer encoding should be base64/quoted-printable when non-ASCII bytes are present.
| * Registered as a built-in `email:deliver` provider when SMTP env vars are | ||
| * present. On Cloudflare Workers it uses `cloudflare:sockets`; on Node it | ||
| * uses `node:net` / `node:tls`. Configuration is env-only for the first | ||
| * iteration — no admin UI yet. |
There was a problem hiding this comment.
[needs fixing] The module header is stale: it says the config is "env-only … no admin UI yet", but this PR adds exactly that. There are also issue-number references in the new test comments (packages/core/tests/unit/plugins/email-smtp.test.ts:453, :462). AGENTS.md prohibits issue/PR references in comments and narrative/stale documentation.
| * iteration — no admin UI yet. | |
| * Registered as a built-in `email:deliver` provider when SMTP is configured | |
| * via environment variables or the Settings → Email admin UI. |
|
Thanks @ascorbic, this was really helpful, and the workerd details saved a lot of guessing. I reworked the PR along your notes:
We didn't need your example code in the end, but thanks for offering it. ~ 🤖 Claude Opus 5.5 |
There was a problem hiding this comment.
This is the right change for #1541. A built-in raw-TCP SMTP transport is the cleanest way to unblock operators who only have generic SMTP credentials on Cloudflare Workers, and registering SMTP unconditionally while resolving it through the existing exclusive-hook machinery keeps the admin-saved-settings workflow intact. The implementation now covers the blockers from the previous pass: SMTP is registered unconditionally in emdash-runtime.ts, dot-stuffing is applied to the full DATA content, non-ASCII headers are split into RFC 2047 encoded-words, port 25 is refused at every boundary (env parsing, DB loading, delivery, admin API schema, and client form), the admin API preserves the stored password when a later save omits it, the admin UI strings are wrapped with Lingui, and the stale doc/module-comment references are gone.
The one remaining concern is the D1 query-count snapshot. Static re-review did not run the test suite or harness, but the committed snapshot diff shows that GET / (cold) now performs a delete from "options" where "name" = ?, raising the cold-start query count from 24 to 25. AGENTS.md treats any new query on a logged-out route as a finding unless it is unavoidable, and the PR description explicitly claims that email:deliver joins the existing batched cold-start read "so logged-out routes get no extra query." A DELETE is a state-changing write, not a read, and it is not accounted for in that claim. The SQLite snapshot is unchanged, which points to a D1-fixture-specific stale option left by the dev-only seed path; that still needs to be fixed or explicitly accepted before merge.
| { | ||
| "GET / (cold)": { | ||
| "delete from \"_emdash_redirect_generation_artifacts\" where \"generation\" = ? and \"position\" >= ?": 1, | ||
| "delete from \"options\" where \"name\" = ?": 1, |
There was a problem hiding this comment.
[needs fixing] This PR adds a delete from "options" where "name" = ? query to the GET / (cold) D1 query-count fixture. AGENTS.md's performance conventions treat any new query on a logged-out route as a finding unless it is unavoidable, and the PR description explicitly states that email:deliver joins the existing batched cold-start read "so logged-out routes get no extra query." A DELETE is a state-changing write, not a read, and it raises the cold-start query budget for / from 24 to 25 (see query-counts.snapshot.d1.json:2).
The SQLite snapshot is unchanged, which suggests the extra query is D1-fixture-specific: the D1 seed path runs through the dev-only POST /_emdash/api/setup/dev-bypass endpoint, where the dev-console email provider is the sole email:deliver provider and gets auto-selected and persisted to the options table. In a production build the dev-console provider is not registered, so the new built-in SMTP registration causes resolveExclusiveHooks to process email:deliver and delete that stale selection on the first cold start.
Even if it only affects seeded fixture state, the committed snapshot now documents a state-changing query on an anonymous cold-start path. Please either eliminate the stale option from the fixture state before re-measuring, make the dev-console selection non-persistent (for example by treating it as a fallback or manual provider so its auto-selection is not stored), or update the PR's query-count claim to explain why this DELETE is necessary and acceptable.
|
@emdashbot The extra ~ 🤖 Claude Opus 5.5 |
There was a problem hiding this comment.
This is the right change for #1541: a built-in raw-TCP SMTP transport keeps operators with only SMTP credentials from needing a separate email API plugin, and wiring it through the existing exclusive-hook resolution preserves the Settings → Email workflow without a public hook API change.
Most of the earlier blockers are now resolved in the code I reviewed:
- SMTP is registered unconditionally in
emdash-runtime.ts, so a DB save made after startup always has a handler. - Dot-stuffing is applied to the full DATA content (
dotStuff(mime)) and has its own direct unit test. - Non-ASCII headers are split into RFC 2047 encoded-words with a per-chunk length limit, and a test verifies multi-word decoding round-trips.
- Port 25 is refused consistently:
loadSmtpConfigFromEnv,loadSmtpConfigFromDb, the admin Zod schema, and the client-sidehandleSavecheck. - The admin API preserves the stored password when a later save omits it and requires re-entry when host or username changes.
- Admin UI strings and placeholders are wrapped with Lingui, and save/test success toasts use translated titles instead of raw
result.message. - The stale module-header comment and dead
createSmtpPluginreference are gone.
The one remaining issue is the D1 query-count snapshot. The committed fixture still shows a DELETE FROM "options" WHERE "name" = ? on the anonymous cold-start path GET /, raising the cold-start budget from 24 to 25 queries. The PR description explains that this happens because the D1 seed path runs through astro dev, where the dev-only console email provider is auto-selected and persisted to options, and the production runtime then deletes that stale row on its first cold start. AGENTS.md treats any new query on a logged-out route as a finding unless it is unavoidable ("the snapshot diff makes it visible, it does not make it acceptable"), and a DELETE is a state-changing write, not a read. This needs to be fixed in the fixture or avoided by not persisting the dev-console auto-selection, rather than accepted in the snapshot.
Other than that, the diff is clean, well-tested, and consistent with the accepted Discussion #2157.
| { | ||
| "GET / (cold)": { | ||
| "delete from \"_emdash_redirect_generation_artifacts\" where \"generation\" = ? and \"position\" >= ?": 1, | ||
| "delete from \"options\" where \"name\" = ?": 1, |
There was a problem hiding this comment.
[needs fixing] The D1 cold-start fixture still records delete from "options" where "name" = ? on an anonymous route (GET / (cold)). AGENTS.md considers any new query on a logged-out route a finding unless it is truly unavoidable, and the PR description acknowledges this DELETE is caused by the D1 seed path running through astro dev and persisting a dev-only provider selection that the production runtime then cleans up.
That explanation identifies a fixture/seed problem, not a load-bearing cold-start write. Please eliminate the stale row from the seeded fixture, or make the dev-console provider auto-selection non-persistent (e.g. treat it as a fallback/manual provider), and re-measure so the snapshot does not document a state-changing query on an unauthenticated cold path.
| @@ -1,5 +1,5 @@ | |||
| { | |||
| "GET / (cold)": 24, | |||
| "GET / (cold)": 25, | |||
There was a problem hiding this comment.
[needs fixing] Matches the extra options delete query above: the GET / (cold) budget went from 24 to 25. This should come back down once the stale dev-console selection is removed from the D1 fixture seed or the auto-selection is no longer persisted.
|
This PR is waiting on its author because it has merge conflicts with |
There was a problem hiding this comment.
Thanks Kevin! 5 points I have on my mind:
- A tie-break for fallback providers would help. #4312 makes the dev console a fallback too. When more than one fallback is left, the resolver drops all of them. So with both PRs in,
astro devwithEMAIL_SMTP_*set and no email plugin has no email provider. Picking the first one infallbackProvidersorder would fix that, with SMTP listed before the console. Then it works whichever PR lands first. A test for this case would be great. parseAddresscould use a length check before its regex runs. The regex gets very slow on long input. A plugin can pass areplyToof a few thousand spaces, and the server then can't do anything else for seconds. Rejecting anything over 256 characters first would avoid that.- Errors from
QUITcan probably be ignored once the server has accepted the message with 250. Right nowdeliverSmtpstill throws whenQUITfails. The email was delivered, but the caller sees a failure and may send it again. - The sender email might need to be required when the SMTP username isn't an email address. Without a sender, the username is used instead. For Amazon SES or SendGrid the username is a key, not an address, so every send fails. A check in the PUT route would catch this when the settings are saved.
- The branch conflicts with
main, but only in the two D1 query-count files. Could you mergemainin? Taking main's version of both files should do.
~ 🤖 Claude Code (Claude Opus 5.5)
# Conflicts: # packages/core/src/emdash-runtime.ts # scripts/query-counts.queries.d1.json # scripts/query-counts.snapshot.d1.json
- Pick the first fallback provider when only fallbacks are active - Cap address length before parsing to avoid regex backtracking - Treat a failed QUIT after acceptance as delivered - Require a sender email when the SMTP username is not an address
|
Thanks @danielmlr, all five are in:
~ 🤖 Claude Opus 5.5 |
There was a problem hiding this comment.
The approach is right: a built-in raw-TCP SMTP email:deliver provider wired into the existing exclusive-hook resolution fixes #1541 without changing the public hook API. Both reviewers found the earlier registration, MIME encoding, password-preservation, port-validation and localization fixes in place, and accept the author's explanation of the separate dot-stuffing and base64-body tests. One issue remains open and both reviewers raised it. The D1 fixture still records a delete from "options" where "name" = ? on the anonymous GET / (cold) path, raising the cold-start query count by one (22 to 23 after rebasing). The extra query comes from stale dev-console selection state that the D1 seed path persists through astro dev. AGENTS.md treats a new query on a logged-out route as a finding unless it is unavoidable, and this one is a write that a fixture fix or non-persistent dev selection would remove.
Reviewed by anthropic/claude-opus-5-5 and openai/gpt-6.1-sol. The change since the last review (1171 lines) was too large for a scoped follow-up, so this is a full review.
| "GET / (cold)": { | ||
| "delete from \"_emdash_redirect_generation_artifacts\" where \"generation\" <> (select \"generation\" from \"_emdash_redirect_state\" where \"id\" = ?)": 1, | ||
| "delete from \"_emdash_redirect_generation_artifacts\" where \"generation\" = ? and \"position\" >= ?": 1, | ||
| "delete from \"options\" where \"name\" = ?": 1, |
There was a problem hiding this comment.
[needs fixing] The D1 cold-start fixture still records delete from "options" where "name" = ? on GET / (cold), an anonymous route. SMTP is now always registered, so email:deliver always goes through resolveExclusiveHooks in production. The dev-console provider selection, auto-selected and persisted while seeding through astro dev, is stale in the production build and gets deleted on the first anonymous cold start. AGENTS.md treats a new query on a logged-out route as a finding unless it is unavoidable. This is a state-changing write caused by the fixture, not a query production needs. Fix it by clearing the stale emdash:exclusive_hook:email:deliver option in the D1 seed step, by not persisting the dev-console auto-selection (for example by treating it as a fallback provider), or by moving the cleanup off the anonymous request path. Then re-measure instead of accepting the extra write in the snapshot.
| @@ -1,5 +1,5 @@ | |||
| { | |||
| "GET / (cold)": 22, | |||
| "GET / (cold)": 23, | |||
There was a problem hiding this comment.
[needs fixing] The GET / (cold) budget goes up by one query (22 to 23 after rebasing) because of the extra options delete recorded in query-counts.queries.d1.json. This should come back down once the stale dev-console selection is removed from the D1 seed or its auto-selection is no longer persisted.
There was a problem hiding this comment.
The follow-up takes the right approach: treating the development console mailer as a non-persistent fallback fixes the cold-start query regression through the existing provider-resolution mechanism.
I checked the changed runtime selection, regression tests, changeset, and D1 query-count updates. Console auto-selection is no longer persisted, configured SMTP takes precedence over the console, and the recorded anonymous cold-start options deletion is gone; the D1 count returns from 23 to 22. The previously open finding is addressed, and I found no new issues in the follow-up changes.
Review was static; I did not run tests or tooling.
Follow-up review by openai/gpt-6.1-sol, scoped to the changes since the last review.
There was a problem hiding this comment.
The follow-up takes the right approach: explicitly selecting the development console mailer makes the invite tests independent of automatic provider selection when the shared fixture also registers an email plugin.
I checked the complete follow-up diff, the invite helper and its callers, the exclusive-provider selection endpoint, development-provider registration, and the serial Playwright configuration. The new request uses the existing authenticated selection API and preserves the end-to-end invite flow. The previously resolved findings remain addressed; I found no new issues in these changes.
Review was static; I did not run tests or tooling.
Follow-up review by openai/gpt-6.1-sol, scoped to the changes since the last review.
danielmlr
left a comment
There was a problem hiding this comment.
Thanks Kevin! All five look good now. I spotted a few more things in the SMTP code. The first one should be fixed before merging, the others aren't blocking.
- Sending fails if the subject or text ends with half an emoji. That can happen on its own: comment notifications cut the comment off at 500 characters, and sometimes the cut lands in the middle of an emoji. Then the email just doesn't go out. If
b64()andencodedWord()usedencodeBase64fromutils/base64.ts, the broken emoji would turn into a placeholder character and the email would still be sent. A test with half an emoji would be great. - The recipient regex has the same slow case
parseAddresshad. Only plugin code could hit it, but leaving@out of the part before the real@would close it. - If
EMAIL_SMTP_SECUREis set but empty, the SMTP env settings are ignored completely. Using||instead of??, like the port does, would fix it. - The PR description still says the dev-console changes were dropped and that D1 goes from 24 to 25 queries, and neither is true anymore.
Use encodeBase64 for bodies, encoded-words and AUTH so a lone surrogate becomes U+FFFD instead of throwing. Exclude @ from the local part of the envelope regex to avoid quadratic backtracking, and treat an empty EMAIL_SMTP_SECURE like an unset one.
|
Thanks Daniel! All four are in.
~ 🤖 Claude Opus 5.5 |
There was a problem hiding this comment.
The follow-up takes the right approach: reusing the shared UTF-8 base64 utility handles truncated surrogate pairs without failing delivery, tightening the envelope regex removes ambiguous backtracking, and treating an empty security variable as unset matches the existing port-default behavior.
I checked every follow-up hunk, the shared encoder, envelope validation and delivery paths, and the added regression tests. Previously resolved findings and the author's explanations remain accepted; I found no new issues to fix within this follow-up's scope.
Review was static; I did not run tests or tooling.
Follow-up review by openai/gpt-6.1-sol, scoped to the changes since the last review.
What does this PR do?
Adds a built-in
email:deliverprovider that sends through any standard SMTP server (Brevo, Office 365, Google Workspace, Fastmail, Amazon SES, self-hosted Postfix). Sites that only have SMTP credentials can then send magic links, invites and recovery emails without an HTTP email API or a third-party plugin. It follows the approved Discussion #2157. This PR was opened before the design PR process, so it links that Discussion instead of a design PR.Transport
node:netandnode:tls, used on Node and on Cloudflare Workers withnodejs_compat. There is no separate Cloudflare path or virtual module.STARTTLSand upgrades synchronously in thedatahandler that delivers the 220, which workerd requires. On workerd it passeshost(notservername); on Node it also setsservernameso SNI is sent. Bytes sent after the 220 are rejected.AbortSignalfrom the timeout is passed into connect, so a stalled handshake closes the socket. Sockets are always closed withdestroy(), so a failed upgrade no longer hangs.STARTTLSandAUTH, prefersAUTH PLAINand falls back toAUTH LOGIN. It never authenticates before TLS and verifies the server certificate. Port 25 is refused.Configuration
EMAIL_SMTP_HOST,EMAIL_SMTP_USERandEMAIL_SMTP_PASS(plus optional port, security, sender and reply-to), or Settings → Email in the admin.EMDASH_ENCRYPTION_KEY). Host and username are bound into the encryption context, and changing either requires entering the password again.Provider selection (internal only, no public hook API change)
resolveExclusiveHooksgets an internalmanualProvidersset next tofallbackProviders. Without env config, SMTP is a manual provider: it is never auto-selected and does not stop a single email plugin from being auto-selected. With env config, SMTP is a fallback provider, so it serves email until an email plugin is active or another provider is selected.fallbackProvidersorder serves the hook, and SMTP comes before the console. Soastro devwithEMAIL_SMTP_*set and no email plugin sends through SMTP.email:deliverjoins the existing batched cold-start read of stored selections, so reading the selection adds no query. If the database holds a selection for an email provider that is no longer active, the first cold start deletes it once, ascomment:moderatealready does. The query-count snapshots are unchanged.API and admin
GET /_emdash/api/settings/emailreports the SMTP settings (never the password) and the in-memory selection.PUTsaves SMTP settings or selects a plugin provider. A test send that fails with an SMTP error returns 502 with the server's reply.Docs:
guides/email.mdxdocuments the transport.deployment/cloudflare.mdxhas a short section with the Workers requirements, anddeployment/secrets.mdxlists the variables.Compared with the earlier revision, this drops
email-cloudflare.ts, the Cloudflare "Test Binding" route, the publicautoSelecthook option, the__none__sentinel and stale-selection keeping.Closes #1541
Type of change
Your connection to this change
Checklist
pnpm typecheckpassespnpm lintpassespnpm testpasses (or targeted tests for my change)pnpm formathas been runmessages.pochanges except in translation PRs — a workflow extracts catalogs on merge tomain.AI assistance disclosure
Screenshots / test output
Live sends from a deployed Worker (
nodejs_compat, compatibility date 2026-02-24) through Brevo: 4 of 4 delivered on port 587 (STARTTLS) and 4 of 4 on port 465 (implicit TLS).New tests:
email-smtp-socket.test.tsruns against real local sockets: the STARTTLS upgrade (SNI, EHLO name, AUTH PLAIN), a failed upgrade that fails fast instead of hanging, bytes injected after STARTTLS, an untrusted certificate, and a stalled 465 handshake that closes the socket. The upgrade, failed-upgrade and stalled-handshake tests fail against the previous revision.email-provider-selection.test.tsboots the runtime and checks which provider is selected, with and without env config, with and without an email plugin.manualProviderscases inexclusive-hooks.test.ts.