Skip to content

feat(core): built-in SMTP email transport for generic SMTP credentials - #2156

Merged
swissky merged 19 commits into
emdash-cms:mainfrom
swissky:feat/smtp-transport
Nov 5, 2026
Merged

swissky merged 19 commits into
emdash-cms:mainfrom
swissky:feat/smtp-transport

Conversation

@swissky

@swissky swissky commented Jul 20, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

Adds a built-in email:deliver provider 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

  • One implementation on node:net and node:tls, used on Node and on Cloudflare Workers with nodejs_compat. There is no separate Cloudflare path or virtual module.
  • STARTTLS: the client sends STARTTLS and upgrades synchronously in the data handler that delivers the 220, which workerd requires. On workerd it passes host (not servername); on Node it also sets servername so SNI is sent. Bytes sent after the 220 are rejected.
  • Port 465 uses implicit TLS. An AbortSignal from the timeout is passed into connect, so a stalled handshake closes the socket. Sockets are always closed with destroy(), so a failed upgrade no longer hangs.
  • The EHLO name is the sender's domain. The client checks the EHLO reply for STARTTLS and AUTH, prefers AUTH PLAIN and falls back to AUTH LOGIN. It never authenticates before TLS and verifies the server certificate. Port 25 is refused.

Configuration

  • Env vars EMAIL_SMTP_HOST, EMAIL_SMTP_USER and EMAIL_SMTP_PASS (plus optional port, security, sender and reply-to), or Settings → Email in the admin.
  • Admin-saved settings take precedence over env vars. The password is stored with the plugin-setting encryption envelope (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)

  • resolveExclusiveHooks gets an internal manualProviders set next to fallbackProviders. 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.
  • The dev console mailer becomes a fallback provider too. When only fallbacks are active, the first one in fallbackProviders order serves the hook, and SMTP comes before the console. So astro dev with EMAIL_SMTP_* set and no email plugin sends through SMTP.
  • email:deliver joins 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, as comment:moderate already does. The query-count snapshots are unchanged.

API and admin

  • GET /_emdash/api/settings/email reports the SMTP settings (never the password) and the in-memory selection. PUT saves SMTP settings or selects a plugin provider. A test send that fails with an SMTP error returns 502 with the server's reply.
  • Settings → Email has a provider dropdown (SMTP plus installed email plugins) and the SMTP form.

Docs: guides/email.mdx documents the transport. deployment/cloudflare.mdx has a short section with the Workers requirements, and deployment/secrets.mdx lists the variables.

Compared with the earlier revision, this drops email-cloudflare.ts, the Cloudflare "Test Binding" route, the public autoSelect hook option, the __none__ sentinel and stale-selection keeping.

Closes #1541

Type of change

  • Bug fix
  • Feature (requires an accepted feature plan or RFC)
  • Refactor (no behavior change)
  • Translation
  • Documentation
  • Performance improvement
  • Tests
  • Chore (dependencies, CI, tooling)

Your connection to this change

  • I use EmDash and ran into the problem this PR addresses
  • I maintain a tool, dependency, or service that EmDash uses, and this change concerns that integration
  • A Maintainer approved this specific change before I opened the PR

Checklist

AI assistance disclosure

  • This PR includes AI-generated code or text — model/tool: Kimi K3, Claude Opus 5.5

Screenshots / test output

Settings → Email with the provider dropdown open, listing SMTP and the console email provider

Settings → Email with SMTP selected, showing host, port, security, username, password and optional sender fields

The same SMTP form in the Arabic admin, laid out right to left

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.ts runs 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.ts boots the runtime and checks which provider is selected, with and without env config, with and without an email plugin.
  • Route tests for GET, PUT and the 502 test-send error, plus manualProviders cases in exclusive-hooks.test.ts.
packages/core: Test Files  802 passed | 2 skipped (804)
               Tests  9673 passed | 11 skipped (9684)
packages/admin EmailSettings.test.tsx: Tests  11 passed (11)

@changeset-bot

changeset-bot Bot commented Jul 20, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 076304c

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 12 packages
Name Type
emdash Minor
@emdash-cms/admin Minor
@emdash-cms/cloudflare Minor
@emdash-cms/plugin-test Patch
@emdash-cms/sandbox-workerd Patch
@emdash-cms/auth Minor
@emdash-cms/blocks Minor
create-emdash Minor
@emdash-cms/gutenberg-to-portable-text Minor
@emdash-cms/x402 Minor
@emdash-cms/auth-atproto Patch
@emdash-cms/plugin-embeds Patch

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

@github-actions

Copy link
Copy Markdown
Contributor

Scope check

This 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.

@pkg-pr-new

pkg-pr-new Bot commented Jul 20, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@emdash-cms/admin

npm i https://pkg.pr.new/@emdash-cms/admin@2156

@emdash-cms/auth

npm i https://pkg.pr.new/@emdash-cms/auth@2156

@emdash-cms/auth-atproto

npm i https://pkg.pr.new/@emdash-cms/auth-atproto@2156

@emdash-cms/blocks

npm i https://pkg.pr.new/@emdash-cms/blocks@2156

@emdash-cms/cloudflare

npm i https://pkg.pr.new/@emdash-cms/cloudflare@2156

@emdash-cms/contentful-to-portable-text

npm i https://pkg.pr.new/@emdash-cms/contentful-to-portable-text@2156

emdash

npm i https://pkg.pr.new/emdash@2156

create-emdash

npm i https://pkg.pr.new/create-emdash@2156

@emdash-cms/gutenberg-to-portable-text

npm i https://pkg.pr.new/@emdash-cms/gutenberg-to-portable-text@2156

@emdash-cms/plugin-cli

npm i https://pkg.pr.new/@emdash-cms/plugin-cli@2156

@emdash-cms/plugin-test

npm i https://pkg.pr.new/@emdash-cms/plugin-test@2156

@emdash-cms/plugin-types

npm i https://pkg.pr.new/@emdash-cms/plugin-types@2156

@emdash-cms/registry-client

npm i https://pkg.pr.new/@emdash-cms/registry-client@2156

@emdash-cms/registry-lexicons

npm i https://pkg.pr.new/@emdash-cms/registry-lexicons@2156

@emdash-cms/registry-loader

npm i https://pkg.pr.new/@emdash-cms/registry-loader@2156

@emdash-cms/registry-moderation

npm i https://pkg.pr.new/@emdash-cms/registry-moderation@2156

@emdash-cms/registry-verification

npm i https://pkg.pr.new/@emdash-cms/registry-verification@2156

upgrade-emdash

npm i https://pkg.pr.new/upgrade-emdash@2156

@emdash-cms/sandbox-workerd

npm i https://pkg.pr.new/@emdash-cms/sandbox-workerd@2156

@emdash-cms/x402

npm i https://pkg.pr.new/@emdash-cms/x402@2156

@emdash-cms/plugin-ai-moderation

npm i https://pkg.pr.new/@emdash-cms/plugin-ai-moderation@2156

@emdash-cms/plugin-ai-search

npm i https://pkg.pr.new/@emdash-cms/plugin-ai-search@2156

@emdash-cms/plugin-atproto

npm i https://pkg.pr.new/@emdash-cms/plugin-atproto@2156

@emdash-cms/plugin-audit-log

npm i https://pkg.pr.new/@emdash-cms/plugin-audit-log@2156

@emdash-cms/plugin-color

npm i https://pkg.pr.new/@emdash-cms/plugin-color@2156

@emdash-cms/plugin-embeds

npm i https://pkg.pr.new/@emdash-cms/plugin-embeds@2156

@emdash-cms/plugin-field-kit

npm i https://pkg.pr.new/@emdash-cms/plugin-field-kit@2156

@emdash-cms/plugin-forms

npm i https://pkg.pr.new/@emdash-cms/plugin-forms@2156

@emdash-cms/plugin-webhook-notifier

npm i https://pkg.pr.new/@emdash-cms/plugin-webhook-notifier@2156

commit: 076304c

@swissky swissky added the bot:review Trigger an emdashbot code review on this PR label Jul 20, 2026
@emdashbot emdashbot Bot removed the bot:review Trigger an emdashbot code review on this PR label Jul 20, 2026
@swissky
swissky force-pushed the feat/smtp-transport branch 2 times, most recently from b21e3c5 to e142700 Compare July 20, 2026 21:35
@swissky
swissky marked this pull request as draft July 21, 2026 05:06
@github-actions github-actions Bot added area/admin and removed review/needs-review No maintainer or bot review yet labels Jul 21, 2026
github-actions Bot pushed a commit that referenced this pull request Jul 21, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Overlapping PRs

This PR modifies files that are also changed by other open PRs:

This may cause merge conflicts or duplicated work. A maintainer will coordinate.

@github-actions github-actions Bot mentioned this pull request Jul 22, 2026
@swissky
swissky marked this pull request as ready for review July 22, 2026 04:30
@github-actions github-actions Bot added the review/needs-review No maintainer or bot review yet label Jul 22, 2026

@emdashbot emdashbot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.tsx violate 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() returns true while send() throws EmailNotConfiguredError.
  • 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 declared Content-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.

Comment on lines +32 to +35
const PROVIDER_OPTIONS: { value: EmailProviderChoice; label: string }[] = [
{ value: "none", label: "None" },
{ value: "smtp", label: "SMTP" },
{ value: "cloudflare", label: "Cloudflare Email" },

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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:

Suggested change
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.

Comment on lines +304 to +305
{ value: "starttls", label: "STARTTLS (port 587)" },
{ value: "tls", label: "Implicit TLS (port 465)" },

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Suggested change
{ 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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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"]),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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:

Suggested change
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).",
});

Comment thread packages/core/src/plugins/email-smtp.ts Outdated
].join("\r\n");
} else {
headers.push(`Content-Type: text/plain; charset=utf-8`);
headers.push(`Content-Transfer-Encoding: 7bit`);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Comment thread packages/core/src/plugins/email-smtp.ts Outdated
Comment on lines +10 to +11
* uses `node:net` / `node:tls`. Configuration is env-only for the first
* iteration — no admin UI yet.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Suggested change
* 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)", () => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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 () => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

@github-actions github-actions Bot added review/awaiting-author Reviewed; waiting on the author to respond and removed needs-rebase review/needs-review No maintainer or bot review yet labels Jul 22, 2026
@swissky swissky added the bot:review Trigger an emdashbot code review on this PR label Jul 22, 2026

@emdashbot emdashbot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 direct AGENTS.md/Localize everything user-facing violation.
  • 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:deliver handler for emdash-smtp.
  • Port 25 is still accepted by the admin API. The only refusal is in loadSmtpConfigFromEnv(); the Zod schema and loadSmtpConfigFromDb allow 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.

Comment on lines +32 to +35
const PROVIDER_OPTIONS: { value: EmailProviderChoice; label: string }[] = [
{ value: "none", label: "None" },
{ value: "smtp", label: "SMTP" },
{ value: "cloudflare", label: "Cloudflare Email" },

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Suggested change
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,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Suggested change
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.

Comment thread packages/core/src/emdash-runtime.ts Outdated
// 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)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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().

Suggested change
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.

Comment thread packages/core/src/plugins/email-smtp.ts Outdated
Comment on lines +229 to +245
`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`,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Comment thread packages/core/src/plugins/email-smtp.ts Outdated
* 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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Suggested change
* 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.

@swissky

swissky commented Oct 9, 2026

Copy link
Copy Markdown
Member Author

Thanks @ascorbic, this was really helpful, and the workerd details saved a lot of guessing. I reworked the PR along your notes:

  • Only node:net and node:tls now. The Cloudflare socket path, the virtual module and email-cloudflare.ts are gone.
  • startTls() sends STARTTLS itself and upgrades synchronously in the data handler that delivers the 220. On workerd it passes host and no servername. On Node it still sets servername, because Node sends no SNI otherwise.
  • Sockets are closed with destroy(), and the timeout's AbortSignal goes into connect, so a failed upgrade or a stalled 465 handshake no longer hangs or leaks.
  • AUTH PLAIN, with LOGIN as the fallback. The EHLO reply is checked for STARTTLS and AUTH, and the EHLO name is the sender's domain.
  • The public autoSelect, __none__, stale-selection keeping and the dev-console changes are out. Instead there is an internal manualProviders set next to fallbackProviders in resolveExclusiveHooks. Unconfigured SMTP is never auto-selected. With env config it acts as a fallback, so a single email plugin still wins.
  • New Node tests run against real local sockets: the STARTTLS upgrade, a failed upgrade, data sent after the 220, an untrusted certificate and a stalled 465 handshake. The upgrade, failed-upgrade and stalled-handshake tests fail on the previous revision.
  • Live sends from a deployed Worker (nodejs_compat) through Brevo: 4 of 4 on 587 and 4 of 4 on 465.

We didn't need your example code in the end, but thanks for offering it.

~ 🤖 Claude Opus 5.5

@emdashbot emdashbot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread scripts/query-counts.queries.d1.json Outdated
{
"GET / (cold)": {
"delete from \"_emdash_redirect_generation_artifacts\" where \"generation\" = ? and \"position\" >= ?": 1,
"delete from \"options\" where \"name\" = ?": 1,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

@swissky

swissky commented Oct 9, 2026

Copy link
Copy Markdown
Member Author

@emdashbot The extra delete on GET / (cold) is a one-time cleanup of a stale email:deliver selection (the D1 fixture seeds via astro dev, which stores the dev console mailer). Later cold starts, warm requests and SQLite are unchanged. Avoiding it would mean keeping stale selections, which the maintainer review asked to keep out of this PR. We accept the trade-off; the PR description explains it.

~ 🤖 Claude Opus 5.5

@emdashbot emdashbot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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-side handleSave check.
  • 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 createSmtpPlugin reference 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.

Comment thread scripts/query-counts.queries.d1.json Outdated
{
"GET / (cold)": {
"delete from \"_emdash_redirect_generation_artifacts\" where \"generation\" = ? and \"position\" >= ?": 1,
"delete from \"options\" where \"name\" = ?": 1,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Comment thread scripts/query-counts.snapshot.d1.json Outdated
@@ -1,5 +1,5 @@
{
"GET / (cold)": 24,
"GET / (cold)": 25,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

@github-actions

Copy link
Copy Markdown
Contributor

This PR is waiting on its author because it has merge conflicts with main, and it has had no activity for 14 days. It will be closed in 7 days unless there is activity: push an update or leave a comment to keep it open.

@danielmlr danielmlr left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks Kevin! 5 points I have on my mind:

  1. 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 dev with EMAIL_SMTP_* set and no email plugin has no email provider. Picking the first one in fallbackProviders order would fix that, with SMTP listed before the console. Then it works whichever PR lands first. A test for this case would be great.
  2. parseAddress could use a length check before its regex runs. The regex gets very slow on long input. A plugin can pass a replyTo of a few thousand spaces, and the server then can't do anything else for seconds. Rejecting anything over 256 characters first would avoid that.
  3. Errors from QUIT can probably be ignored once the server has accepted the message with 250. Right now deliverSmtp still throws when QUIT fails. The email was delivered, but the caller sees a failure and may send it again.
  4. 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.
  5. The branch conflicts with main, but only in the two D1 query-count files. Could you merge main in? 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
@swissky

swissky commented Nov 3, 2026

Copy link
Copy Markdown
Member Author

Thanks @danielmlr, all five are in:

  1. When only fallback providers are active, the first one in fallbackProviders order is used, without storing it. SMTP is listed right after the comment moderator, so with docs: say when the dev console email provider runs #4312 it comes before the dev console. Tests cover both the only-fallbacks case and a plugin still winning over several fallbacks.
  2. parseAddress rejects input over 256 characters before the regex runs. 5000 spaces as replyTo took 26 s before; the new test fails if that comes back.
  3. A failed QUIT after the 250 is logged as a warning and the send counts as delivered.
  4. The PUT route requires a sender email when the SMTP username is not an email address; the admin shows the validation message. The changeset and email guide mention it.
  5. Merged main, taking main's D1 query-count files. emdash-runtime.ts also needed a manual merge after the cold-start read refactor; only the SMTP registration and selection hunks are re-applied on top.

~ 🤖 Claude Opus 5.5

@emdashbot emdashbot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread scripts/query-counts.queries.d1.json Outdated
"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,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Comment thread scripts/query-counts.snapshot.d1.json Outdated
@@ -1,5 +1,5 @@
{
"GET / (cold)": 22,
"GET / (cold)": 23,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

@emdashbot emdashbot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@emdashbot emdashbot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 danielmlr left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

  1. 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() and encodedWord() used encodeBase64 from utils/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.
  2. The recipient regex has the same slow case parseAddress had. Only plugin code could hit it, but leaving @ out of the part before the real @ would close it.
  3. If EMAIL_SMTP_SECURE is set but empty, the SMTP env settings are ignored completely. Using || instead of ??, like the port does, would fix it.
  4. 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.
@swissky

swissky commented Nov 5, 2026

Copy link
Copy Markdown
Member Author

Thanks Daniel! All four are in.

  1. Bodies, encoded-words and AUTH now use encodeBase64, and a test sends a subject and body ending in half an emoji (it failed with a URIError before).
  2. The local part now excludes @. The test with 50,000 @ signs took seconds before.
  3. Switched to ||, with a test for an empty EMAIL_SMTP_SECURE on port 465.
  4. Description updated.

~ 🤖 Claude Opus 5.5

@emdashbot emdashbot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature request: built-in SMTP email transport in core

3 participants