Skip to content

Set up SMTP from Settings, and check the connection before a signer misses an email - #269

Open
adryserage wants to merge 15 commits into
NYLLON-SOFTWARE:mainfrom
adryserage:smtp-settings
Open

adryserage wants to merge 15 commits into
NYLLON-SOFTWARE:mainfrom
adryserage:smtp-settings

Conversation

@adryserage

@adryserage adryserage commented Nov 25, 2026 •

Copy link
Copy Markdown

Builds on #253 and should merge after it.

With #253, an SMTP server can only be set through environment variables, and Settings, Organization counts email as working as soon as a sender address is chosen, before anything has reached the server. A wrong host or password shows up only when a signer never gets their email.

This lets an administrator enter the SMTP server under Settings, Organization, Email setup, and check it:

  • Server, port, encryption, user name and password can be saved in the app. Each SMTP_* variable that is set still wins, and the page shows that field read-only with the variable's name. EMAIL_DRIVER=smtp still chooses the driver.
  • The password is stored in app_settings, encrypted with a key derived from BETTER_AUTH_SECRET through secretKeyFor in seal-identity.ts (context signudoc-email-smtp), as discussed in "Connect to Microsoft 365" in Settings, without granting tenant-wide Mail.Send #76. It is never sent back to the browser; the page only says that one is saved, or that it has to be entered again after BETTER_AUTH_SECRET changes.
  • A saved password is only sent to the server it was saved for: changing the server, port, encryption or user name asks for the password again. When SMTP_PASSWORD is set in the environment, the other SMTP fields come from the environment too, so a password from the environment never goes to a server entered in the app.
  • "Check connection" connects and logs in with nodemailer's verify() and shows the server's own answer, with the password removed. It gives up after 10 seconds.
  • Email counts as working only once "Send me a test email" gets through. Saving a different server or password asks for a new test.
  • Changes are audited as settings_changed in the same transaction, with the password recorded only as "replaced".
  • The driver reads the server for each message, so a saved change applies without a restart. Sending a draft, sending a reminder and the sign-up page still refuse before changing anything when no server is set up (fix(email): sending without a provider returns a generic HTTP 500 #53, fix(auth): signup tells senders to check their email when no provider is configured #95).

One migration adds five nullable columns to app_settings.

Checks

  • src/lib/smtp-settings.test.ts (new), plus SMTP cases in src/lib/services/email.test.ts and src/lib/email-status.test.ts: all pass. npm run typecheck and npm run lint pass.
  • *.dbtest.ts were not run (no local Postgres). The database paths were checked end to end instead, against a real Postgres with a fake SMTP server: wrong and right passwords, the password never in the page or the audit trail, a test email turning the status to working, and 401 when signed out.
  • We ran the deterministic checks of Aetheris 5.0.2 on the changed files and compared them with Add an SMTP email driver #253 alone. No new security, dependency, architecture or API finding: the secret-scan hits are field names (SMTP_PASSWORD, smtp_password) and test fixtures, and the SQL hit is Add an SMTP email driver #253's interval constant.

Complexity, and a possible split

Aetheris flags three functions over its cyclomatic complexity limit of 15: EmailSetupPanel (20 before this PR, 26 now), inspectEmail (18) and the form's handleSubmit (16). I kept them as they are to keep this diff readable, and can split them here or in a follow-up if you prefer:

  • inspectEmail would become a dispatch on the driver, { capture, smtp, resend }[resolveEmailDriver(env)](options), with inspectSmtpEmail taking the SMTP branch and inspectResendEmail the rest. Each function then holds one provider's logic.
  • EmailSetupPanel would move its loading, pendingAction and runAction state into a useEmailSetup() hook, and its buttons into an EmailSetupActions component driven by a table from status to actions (domain_missing to "Set up domain", domain_pending to "Check DNS records", a configured smtp to "Check connection" and "Send me a test email"). The panel itself would keep only the layout.

Note

Add SMTP email driver with settings UI, connection check, and test-email verification

  • Adds smtp to EMAIL_DRIVER choices, with email sending via nodemailer in email.ts. Settings can be stored in the database or set through environment variables; environment values take precedence.
  • Adds an admin SMTP settings form and endpoints in route.ts, with saved passwords sealed and never returned to the client. A check_connection action verifies SMTP connectivity and login without sending mail.
  • A successful test email records a fingerprint of the tested settings in markSmtpEmailTested; email readiness is cleared when settings change, so a signer's server is re-checked before it counts as ready. Email status in email-status.ts reports configuration, sender, and tested state.
  • Adds send idempotency via the email_idempotency_keys table (24-hour retention, 10-minute lease) and new columns on app_settings for SMTP settings and the tested fingerprint.
  • Risk: canSendEmail is now asynchronous and callers such as signup/page.tsx and draft/reminder sending now await connected-service creation; SMTP setups using the Resend test sender address are rejected.

Macroscope summarized 0ddd0af.

AirLoren and others added 11 commits November 22, 2026 23:46
Self-hosted installs can now send through their own SMTP server instead
of Resend: EMAIL_DRIVER=smtp with SMTP_HOST, SMTP_PORT, SMTP_USER,
SMTP_PASSWORD and SMTP_SECURE. Port 465 uses TLS from the start; other
ports must upgrade with STARTTLS before the password is sent.

The sender address is resolved as for Resend (RESEND_FROM_EMAIL, then the
organization settings). Settings shows email as ready once a sender at a
real domain is set, since there is no provider API to ask; "Send a test
email" checks delivery.
Address review: the settings page showed Resend setup text for SMTP
installs, and the SMTP driver ignored idempotency keys. SMTP now has an
'smtp' status with its own text, and keyed sends are claimed in a new
email_idempotency_keys table (24-hour window, as with Resend) so a retry
is not delivered twice; a failed send releases its key.
Address review: a key saved before an interrupted send was taken as proof
of delivery, so a retry could report a warning as sent without sending it.
Keys are now 'sending' until the server accepts the message, then 'sent'.
A retry skips only 'sent' keys, takes over a 'sending' key after a
10-minute lease (the earlier attempt was interrupted), and fails while
another attempt may still be sending, so callers retry instead of
recording a message that never went out.
Address review: the state column had been added to the already published
20261123100000 migration, which a database that ran its first copy would
skip. That file is back to its published content, and the column and its
check go in 20261123110000, as the repository asks for published
migrations.
An install that sends with EMAIL_DRIVER=smtp can now keep its SMTP server
in app_settings instead of the environment. Each SMTP_* variable that is
set still wins, field by field. The password is sealed with a key derived
from BETTER_AUTH_SECRET (context "signudoc-email-smtp"), as the maintainers
asked in NYLLON-SOFTWARE#76, and is never part of what the page is sent.
The SMTP driver looks the server up for each message, from the SMTP_*
variables and, for any that are not set, from Settings, so a saved change
applies to the next message without a restart. Sending a draft, sending
a reminder and the sign-up page still refuse before anything changes
when no server is set up: they now ask through createConnectedEmailService,
which reads the saved server too.
With NYLLON-SOFTWARE#253, the email status counted an SMTP install as working as soon
as a sender address was chosen, before anything had reached the server.
The status now says whether a host, a user and a password are set, and
leaves the "email works" mark to a test email that gets through.

A new "check_connection" action on /api/admin/email connects and logs in
with nodemailer's verify(), and reports the server's own answer with the
password taken out. It gives up after 10 seconds without an answer, so
the administrator is not left waiting for nodemailer's two minutes.
Email setup now shows an SMTP server form on an install that sends with
EMAIL_DRIVER=smtp: server, port, encryption, user name and password.
A field set by an SMTP_* variable is shown read-only with the variable's
name. The password field only replaces the saved one, says when one is
saved, and says when it has to be entered again after BETTER_AUTH_SECRET
changed. "Check connection" sits next to "Send me a test email".

The form saves through PUT /api/admin/email/smtp, administrators only,
rate limited like the other organization settings. A change is written
with its "settings_changed" line in the install's audit trail in one
transaction, and the password appears there only as "replaced".
Changing the server, port, encryption or user name in Settings now asks
for the password again, and a password set in SMTP_PASSWORD makes the
other SMTP fields come from the environment too. Before, an administrator
could point a saved or environment password at a server of their own and
read it from Check connection.
@vercel

vercel Bot commented Nov 25, 2026

Copy link
Copy Markdown

@adryserage is attempting to deploy a commit to the Basic Intelligence Team on Vercel.

A member of the Team first needs to authorize it.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-25T08:41:45.073937Z 0ddd0af New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@adryserage adryserage mentioned this pull request Nov 25, 2026
6 of 7 tasks
@greptile-apps

greptile-apps Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 5/5

[High impact] The migration update appears safe to merge.

Summary

The PR adds SMTP setup in Settings, encrypted password storage, connection checks, and a test email that confirms the saved settings work.

  • Admins can save an SMTP server in Organization settings.
  • Admins can check an SMTP login and see when test delivery proves it works.
  • SignuDoc can send transactional email through an SMTP server.
  • Signup, draft sending, and manual reminders check email availability first.

Reviews (3) · Last reviewed commit: "Add smtp_tested_fingerprint in a migrati..." · Reviewed by Greptile

Comment thread src/lib/email-status.ts Resolved
Comment thread src/lib/services/email.ts Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5f1339430b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/lib/services/email.ts Resolved
Comment thread src/lib/email-status.ts Resolved
"Email works" for SMTP trusted a mark that only checked the sender
address. A test still on its way through the old server could set it
again after a save of new settings had cleared it, and a mark earned with
Resend still counted after EMAIL_DRIVER became smtp.

A successful test now stores an HMAC of the SMTP settings it sent with,
keyed from BETTER_AUTH_SECRET, and only if the saved settings still give
the same value with the row locked. The status reports the setup as
tested only while the settings in use give that value.
nodemailer's limits apply to each step, so a server that answered slowly
at every step could keep the administrator waiting well past ten seconds.
The whole check now gives up after ten seconds and says so.
With SMTP set up but no sender address, sign-up and sending passed the
preflight and mail went out from Resend's test address, which an SMTP
server refuses. The SMTP preflight and every SMTP send now require an
address under Settings, Organization or in RESEND_FROM_EMAIL.
A database that already ran 20261125090000_smtp_settings.sql would never
get the column, and a test email that went through would then be reported
as failed.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0ddd0af343

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/lib/smtp-settings.ts
Comment on lines +412 to +414
JSON.stringify(
SMTP_FIELDS.map((field) => smtpEnv[SMTP_VARIABLES[field]] ?? null),
),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Include the effective sender in the SMTP test fingerprint

After a successful SMTP test, changing RESEND_FROM_EMAIL leaves emailReadyAt intact because the environment override in resolveSettings() does not reset it, while this new HMAC still matches because it covers only SMTP_FIELDS. Consequently, getEmailStatus() reports tested: true for the new, untested sender—even onboarding@resend.dev, which canSendEmail() and every SMTP send explicitly reject. Changing to a sender the relay does not authorize can therefore leave Settings declaring email working while invitations fail. Persist and compare the effective sender alongside the SMTP settings.

Useful? React with 👍 / 👎.

Comment thread src/lib/email-status.ts
Comment on lines +437 to +438
if (!configured || !hasSender) {
await smtpMarkReady(false);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Synchronize the setup warning with SMTP fingerprint mismatches

When a previously tested installation changes an SMTP_* environment value, the new fingerprint comparison correctly makes tested false, but this branch never calls smtpMarkReady(false) as long as the required fields and sender remain populated. The old email_ready_at therefore survives even after getEmailStatus(), whereas emailNeedsAttention()—used by src/app/(app)/layout.tsx:46 for the administrator's setup warning—checks only that timestamp. Administrators consequently receive no warning that the replacement configuration has never passed a test. Make the persisted readiness mark or notice predicate follow the fingerprint result.

Useful? React with 👍 / 👎.

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants