feat(email): remove Gmail OAuth2, put SMTP behind a transport registry

Engagement Phase 1 (docs/website/ENGAGEMENT.md §1.2a, §3.1, §3.2). A
subtraction and a replacement in one commit, because leaving the OAuth2
flow half-wired across a release is worse than either end state.

Deleted, per the §1.2a inventory: GET /admin/email/connect/start and
/connect/callback, the connectStart/connectCallback controllers with the
email_oauth_tx signed cookie, the PKCE verifier and CSRF nonce plumbing,
the https://mail.google.com/ scope, the borrowed `google` auth-providers
client, the OAuth2 nodemailer transport with its smtp.gmail.com:465
literals, the refresh-token decrypt in the model, and the client's
Connect Gmail button, redirect banner and six Gmail error strings.
`provider` and `refresh_token_enc` stay as columns under the
additive-only discipline, unread.

Added: a mail transport registry (server/src/engagement/transports) with
`smtp` as the sole registration. `credentialFields` is the single
declaration the admin form renders, the sanitizer filters against, and
the "is it secret" answer comes from, so adding a transport is a
registration rather than four edits. email_config gains transport /
credential_enc (one encrypted JSON blob, since the field list is the
transport's to declare) / reply_to.

All six call sites keep their exact failure contracts: the contact
form's mailto fallback, the invite's copyable link, the reset's generic
200, and sendTeamNotification's never-throws. One deliberate behaviour
change: `enabled` now gates every sender rather than only isConfigured()
— the connect flow used to set it as a side effect, and with a credential
form the toggle has to mean what it says.

Send-test becomes the real verification. Under OAuth2 the sender came
back from Google and was guaranteed to belong to the credential;
operator-typed, it can be refused, so failures name the sender and the
SPF/DMARC reason (§1.2a consequence 2).

G22, the silent degradation: an upgraded deployment backfills to smtp
with no credentials and every sink politely does nothing. The admin
dashboard now warns when the deprecated Gmail token is present and no
replacement credential is, so the one deployment this happens to is told.
A fresh install has never had mail and is not nagged.

Guardrails: new `npm run check:hosts` (§3.2 rule 4) with its own
self-test, wired into pr-checks before the install; routes.manifest and
routes.guards regenerated (-2 routes).

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2026-08-28 20:41:43 -05:00
parent e25e7ade80
commit 47c8b37d45
26 changed files with 1535 additions and 461 deletions

View File

@@ -0,0 +1,22 @@
// ── The engagement subsystem — one door ────────────────────────────────────
//
// ENGAGEMENT.md Phase 1. Today this is the mail transport registry and core's
// own transports; the trigger registry, the rules engine and the delivery
// channels arrive in later phases and hang here too.
//
// **Core's transports register through the same door a module's would**, and
// they register HERE rather than at the bottom of the registry file. That keeps
// the registry free of any knowledge of its registrants — the same reason
// `registerCore()` is called from app.js rather than from inside
// `modules/registries.js` (MODULE_API.md §7.6) — and it means requiring the
// registry never has the side effect of populating it.
//
// Requiring this module is what makes `smtp` available. Everything that resolves
// a transport goes through here, so there is exactly one place a transport can
// come into existence.
require('./transports/smtp')
const transports = require('./transports')
module.exports = { transports }

View File

@@ -0,0 +1,195 @@
// ── The mail transport registry ────────────────────────────────────────────
//
// ENGAGEMENT.md §3.1, Phase 1. A **channel** is what kind of sink this is (email,
// push, in-app); a **transport** is how one channel actually delivers. This file
// is the second half only. The channel registry arrives with the engine that
// consumes it — registering a channel nothing calls would be a shape frozen
// before anything had tried to use it.
//
// What this replaces: `mailer.buildTransport()` had Gmail's host, port and
// OAuth2 auth type as literals, so "which provider" was a code edit. Now the
// stored `email_config.transport` names a registration, and the registration
// declares its own credential fields — which drives the admin form, the encrypted
// blob's shape and the validation, from one place.
//
// **`credentialFields` is the contract.** It is read by three consumers that
// would otherwise drift: the admin form renders it, `sanitizeCredential()` below
// filters a submitted body through it, and `describe()` tells the client which
// values are secret so they are never sent back. Adding a field to a transport is
// therefore one edit, not four.
//
// **No transport may carry a default host, endpoint or sender** (§3.2 rule 1). A
// transport with no operator configuration is `unconfigured` and its channel is
// off — it never falls back to somewhere we chose. `scripts/checkNoExternalHosts.js`
// is the CI backstop for that rule; this file is where it would be broken first.
//
// Nothing here touches the database or the network at require time.
const log = require('../../utils/logger')('mailer')
// id → transport definition
const transports = new Map()
// Field kinds the admin form knows how to render. `secret` is the only one that
// changes behaviour server-side: it is write-only, so an unchanged value arrives
// as '' and must be read from the stored credential rather than overwritten.
const FIELD_KINDS = new Set(['text', 'number', 'secret', 'boolean'])
/**
* Register a mail transport. Shape-checked at the call and collision-checked
* here, the same validate-then-commit discipline `modules/registries.js` uses.
*
* @param {object} def
* @param {string} def.id stable id stored in email_config.transport
* @param {string} def.label human name for the admin form
* @param {Array} def.credentialFields [{ key, label, kind, required, help, default }]
* @param {Function} def.build (credential, config) → a nodemailer-shaped transport
* @param {Function} def.isComplete (credential) → boolean; are the required fields present
*/
function registerMailTransport(def) {
if (!def || typeof def !== 'object') throw new Error('registerMailTransport: definition required')
const { id, label, credentialFields, build, isComplete } = def
if (typeof id !== 'string' || !/^[a-z][a-z0-9_-]*$/.test(id)) {
throw new Error(`registerMailTransport: invalid id ${JSON.stringify(id)}`)
}
if (transports.has(id)) throw new Error(`registerMailTransport: ${id} is already registered`)
if (typeof label !== 'string' || !label) throw new Error(`registerMailTransport(${id}): label required`)
if (!Array.isArray(credentialFields) || credentialFields.length === 0) {
throw new Error(`registerMailTransport(${id}): credentialFields required`)
}
for (const f of credentialFields) {
if (!f || typeof f.key !== 'string' || !f.key) {
throw new Error(`registerMailTransport(${id}): every credential field needs a key`)
}
if (!FIELD_KINDS.has(f.kind)) {
throw new Error(`registerMailTransport(${id}): field ${f.key} has unknown kind ${f.kind}`)
}
}
if (typeof build !== 'function') throw new Error(`registerMailTransport(${id}): build() required`)
if (typeof isComplete !== 'function') throw new Error(`registerMailTransport(${id}): isComplete() required`)
transports.set(id, { ...def, credentialFields: credentialFields.map((f) => ({ ...f })) })
return id
}
/** The registered transport, or null. Callers must handle null — a stored id can
* name a transport that no longer exists (a downgrade, a removed provider), and
* that must degrade to "unconfigured", never throw at send time. */
function get(id) {
return transports.get(id) || null
}
function has(id) {
return transports.has(id)
}
/** Every transport, as the admin form needs it: no functions, secrets flagged. */
function describe() {
return [...transports.values()].map((t) => ({
id: t.id,
label: t.label,
help: t.help || null,
credentialFields: t.credentialFields.map((f) => ({
key: f.key,
label: f.label || f.key,
kind: f.kind,
required: Boolean(f.required),
help: f.help || null,
default: f.default === undefined ? null : f.default,
placeholder: f.placeholder || null,
})),
}))
}
/**
* Filter a submitted credential body down to the transport's declared fields,
* coercing each to its declared kind. Anything not declared is dropped — the
* blob that reaches `secretBox.encrypt` only ever holds fields a transport asked
* for, so a client cannot smuggle extra keys into stored ciphertext.
*
* `secret` fields submitted empty are OMITTED rather than blanked, which is the
* "leave the existing one alone" convention `botConfig.save`/`emailConfig.save`
* already use; `mergeCredential()` is what puts the stored value back.
*/
function sanitizeCredential(id, body) {
const t = get(id)
if (!t) return {}
const out = {}
for (const f of t.credentialFields) {
if (!(f.key in (body || {}))) continue
const raw = body[f.key]
if (f.kind === 'secret') {
if (raw === undefined || raw === null || raw === '') continue
out[f.key] = String(raw)
} else if (f.kind === 'number') {
const n = Number(raw)
if (Number.isFinite(n)) out[f.key] = n
} else if (f.kind === 'boolean') {
out[f.key] = Boolean(raw)
} else {
out[f.key] = raw === null || raw === undefined ? '' : String(raw)
}
}
return out
}
/** Stored credential + the submitted patch. Omitted secrets keep their stored value. */
function mergeCredential(id, stored, patch) {
return { ...(stored || {}), ...(patch || {}) }
}
/** Non-secret fields only — safe to return over the admin API. */
function publicCredential(id, credential) {
const t = get(id)
if (!t || !credential) return {}
const out = {}
for (const f of t.credentialFields) {
if (f.kind === 'secret') continue
if (credential[f.key] !== undefined) out[f.key] = credential[f.key]
}
return out
}
/** Which declared secrets are actually held, so the form can say "set" without
* ever returning the value. */
function secretsPresent(id, credential) {
const t = get(id)
if (!t) return {}
const out = {}
for (const f of t.credentialFields) {
if (f.kind !== 'secret') continue
out[f.key] = Boolean(credential && credential[f.key])
}
return out
}
/** Does this credential have everything its transport needs to send? */
function isComplete(id, credential) {
const t = get(id)
if (!t) return false
try {
return Boolean(t.isComplete(credential || {}))
} catch (err) {
log.warn('transport isComplete threw', { transport: id, message: err.message })
return false
}
}
// Test-only: the registry is module-level state and a suite that registers a
// fake transport must be able to undo it.
function _reset() {
transports.clear()
}
module.exports = {
registerMailTransport,
get,
has,
describe,
sanitizeCredential,
mergeCredential,
publicCredential,
secretsPresent,
isComplete,
_reset,
}

View File

@@ -0,0 +1,96 @@
// ── SMTP — the baseline mail transport ─────────────────────────────────────
//
// ENGAGEMENT.md decision 4: Gmail OAuth2 is removed, SMTP is the baseline. This
// is the only registered transport, and it is deliberately plain SMTP rather than
// anything provider-shaped — a relay (Mailgun, SES, Postmark), a self-hosted MTA
// and Gmail-with-an-app-password are all reachable through these five fields, so
// one transport covers all three postures §7.1 Q5 asks to document.
//
// **No defaults for host, port, user or sender.** §3.2 rule 1: a transport with
// no operator configuration is unconfigured, never pointed at somewhere we chose.
// `secure` gets a default because it is a protocol choice, not a destination — and
// even that is only a form default, not a fallback applied to a stored blank.
//
// **`secure` is the field operators get wrong**, so its help text says which port
// each setting means: `secure: true` is implicit TLS on 465, `secure: false` is
// plaintext-then-STARTTLS on 587 (which nodemailer upgrades automatically). The
// combination that silently fails is 587 with secure on — the handshake hangs
// rather than erroring cleanly — which is exactly why "Send test" is the real
// verification path now (§1.2a consequence 2).
const nodemailer = require('nodemailer')
const registry = require('./index')
const CREDENTIAL_FIELDS = [
{
key: 'host',
label: 'SMTP host',
kind: 'text',
required: true,
placeholder: 'smtp.example.com',
help: 'Your relay or mail server. No default — nothing is sent until you set this.',
},
{
key: 'port',
label: 'Port',
kind: 'number',
required: true,
default: 587,
help: '587 for STARTTLS (most relays), 465 for implicit TLS, 25 for an unauthenticated local MTA.',
},
{
key: 'secure',
label: 'Implicit TLS',
kind: 'boolean',
required: false,
default: false,
help: 'On for port 465. Leave off for 587 — the connection still upgrades to TLS via STARTTLS.',
},
{
key: 'user',
label: 'Username',
kind: 'text',
required: false,
help: 'Leave blank for an unauthenticated local relay.',
},
{
key: 'password',
label: 'Password / API key',
kind: 'secret',
required: false,
help: 'Stored encrypted and never returned. For Gmail this is an app password, not the account password.',
},
]
// Authentication is optional (a local MTA on port 25 needs none), so the only
// hard requirement is a destination. A username without a password is not
// "complete" — that combination authenticates as nobody and fails at the server.
function isComplete(credential) {
const c = credential || {}
if (!c.host || !Number(c.port)) return false
if (c.user && !c.password) return false
return true
}
function build(credential) {
const c = credential || {}
const options = {
host: String(c.host),
port: Number(c.port),
secure: Boolean(c.secure),
}
if (c.user) options.auth = { user: String(c.user), pass: String(c.password || '') }
return nodemailer.createTransport(options)
}
registry.registerMailTransport({
id: 'smtp',
label: 'SMTP',
help: 'Any SMTP relay or mail server. See the operator guide for the three supported postures.',
credentialFields: CREDENTIAL_FIELDS,
isComplete,
build,
})
module.exports = { CREDENTIAL_FIELDS, isComplete, build }

View File

@@ -1,7 +1,8 @@
const singletonConfigDb = require('../singletonConfigDb')
const COLS =
'id, provider, enabled, sender_email, sender_name, refresh_token_enc, status, status_detail, last_verified_at, updated_by, created_at, updated_at'
'id, provider, transport, enabled, sender_email, sender_name, reply_to, credential_enc, refresh_token_enc, ' +
'status, status_detail, last_verified_at, updated_by, created_at, updated_at'
// Singleton row (id = 1). See ../singletonConfigDb for the get/upsert contract.
module.exports = singletonConfigDb('email_config', COLS)

View File

@@ -1,30 +1,69 @@
// Outbound email config store (Gmail OAuth2). Mirrors the botConfig model split:
// the DB layer only ever sees ciphertext, and only getWithSecret() (used by the
// mailer at send time) decrypts the refresh token. The admin-facing getSafe()
// never includes it — callers see only `hasRefreshToken`.
// Outbound email config store. Mirrors the botConfig model split: the DB layer
// only ever sees ciphertext, and only getWithSecret() (used by the mailer at send
// time) decrypts the credential. The admin-facing getSafe() never includes it —
// callers see the non-secret fields plus which secrets are set.
//
// The credential is ONE encrypted JSON blob, not a column per field, because the
// field list belongs to the transport (ENGAGEMENT.md §3.1). `credential_enc`
// holds `{ host, port, secure, user, password }` for `smtp`; a future relay's
// blob would hold different keys against the same column.
//
// `provider` and `refresh_token_enc` are the removed Gmail OAuth2 connection
// (§1.2a). They are no longer read as configuration — `hadLegacyConnection`
// exposes the token column's presence for one purpose only: telling an upgraded
// deployment that its mail just stopped.
const db = require('./emailConfig.db')
const secretBox = require('../../utils/secretBox')
const { transports } = require('../../engagement')
function toSafe(row) {
const DEFAULT_TRANSPORT = 'smtp'
// A stored blob that will not parse is treated as ABSENT, never as an error —
// the same fail-safe rule utils/settingsJson.js applies. A deployment whose
// SECRET_ENC_KEY was rotated must degrade to "unconfigured" and say so on the
// admin screen, not 500 the settings page and the contact form with it.
function readCredential(row) {
if (!row || !row.credential_enc) return null
try {
const parsed = JSON.parse(secretBox.decrypt(row.credential_enc))
return parsed && typeof parsed === 'object' ? parsed : null
} catch {
return null
}
}
function toSafe(row, credential) {
const transport = (row && row.transport) || DEFAULT_TRANSPORT
if (!row) {
return {
provider: 'gmail_oauth2',
transport: DEFAULT_TRANSPORT,
enabled: false,
senderEmail: null,
senderName: null,
hasRefreshToken: false,
replyTo: null,
credential: {},
secretsSet: transports.secretsPresent(DEFAULT_TRANSPORT, null),
hasCredential: false,
hadLegacyConnection: false,
status: 'unconfigured',
statusDetail: null,
lastVerifiedAt: null,
}
}
return {
provider: row.provider || 'gmail_oauth2',
transport,
enabled: Boolean(row.enabled),
senderEmail: row.sender_email || null,
senderName: row.sender_name || null,
hasRefreshToken: Boolean(row.refresh_token_enc),
replyTo: row.reply_to || null,
credential: transports.publicCredential(transport, credential),
secretsSet: transports.secretsPresent(transport, credential),
hasCredential: transports.isComplete(transport, credential),
// Deliberately the raw column, not "is Gmail configured": nothing reads the
// token any more. It answers "did this deployment have working mail before
// the upgrade?", which is the G22 warning's whole condition.
hadLegacyConnection: Boolean(row.refresh_token_enc),
status: row.status || 'unconfigured',
statusDetail: row.status_detail || null,
lastVerifiedAt: row.last_verified_at || null,
@@ -32,38 +71,53 @@ function toSafe(row) {
}
async function getSafe() {
return toSafe(await db.get())
const row = await db.get()
return toSafe(row, readCredential(row))
}
// Decrypted refresh token included — server-side only (building the mailer's
// OAuth2 transport). Returns null when no row exists yet.
// Decrypted credential included — server-side only (building the transport at
// send time). Returns null when no row exists yet.
async function getWithSecret() {
const row = await db.get()
if (!row) return null
return {
...toSafe(row),
refreshToken: row.refresh_token_enc ? secretBox.decrypt(row.refresh_token_enc) : null,
}
const credential = readCredential(row)
return { ...toSafe(row, credential), credentialSecret: credential || {} }
}
// Save admin-supplied / connect-flow config. `refreshToken` undefined or '' means
// "leave the existing token unchanged" (same convention as botConfig.save).
async function save({ senderEmail, senderName, refreshToken, enabled, status, statusDetail, updatedBy }) {
// Save admin-supplied config. `credential` is a PATCH, merged over the stored
// blob: a secret field submitted empty is omitted by the registry's sanitizer and
// therefore keeps its stored value (same convention as botConfig.save).
async function save({ transport, senderEmail, senderName, replyTo, credential, enabled, status, statusDetail, updatedBy }) {
const row = await db.get()
const fields = {}
const nextTransport = transport !== undefined ? transport : (row && row.transport) || DEFAULT_TRANSPORT
if (transport !== undefined) fields.transport = transport
if (senderEmail !== undefined) fields.sender_email = senderEmail
if (senderName !== undefined) fields.sender_name = senderName
if (refreshToken) fields.refresh_token_enc = secretBox.encrypt(refreshToken)
if (replyTo !== undefined) fields.reply_to = replyTo
if (credential !== undefined) {
// Changing transport starts from an empty credential rather than merging one
// transport's fields into another's — an SMTP password left inside a relay's
// blob is a stored secret nobody can see and nothing will ever use.
const base = row && row.transport === nextTransport ? readCredential(row) : null
const merged = transports.mergeCredential(nextTransport, base, transports.sanitizeCredential(nextTransport, credential))
fields.credential_enc = Object.keys(merged).length ? secretBox.encrypt(JSON.stringify(merged)) : null
}
if (enabled !== undefined) fields.enabled = enabled ? 1 : 0
if (status !== undefined) fields.status = status
if (statusDetail !== undefined) fields.status_detail = statusDetail
if (updatedBy !== undefined) fields.updated_by = updatedBy
const row = await db.upsert(fields)
return toSafe(row)
const saved = await db.upsert(fields)
return toSafe(saved, readCredential(saved))
}
// Clear the stored credential and disable sending (admin "Disconnect").
// Clear the stored credential and disable sending (admin "Clear credentials").
// The legacy Gmail token goes too: this is the operator saying "there is no
// mailbox here", and leaving the deprecated column set would keep the G22 warning
// on screen for a deployment that has deliberately turned mail off.
async function disconnect(updatedBy) {
const row = await db.upsert({
credential_enc: null,
refresh_token_enc: null,
sender_email: null,
enabled: 0,
@@ -72,7 +126,7 @@ async function disconnect(updatedBy) {
last_verified_at: null,
updated_by: updatedBy ?? null,
})
return toSafe(row)
return toSafe(row, readCredential(row))
}
// Record the outcome of the last send / verification so the admin panel has
@@ -86,7 +140,7 @@ async function recordStatus({ status, statusDetail, lastVerifiedAt } = {}) {
}
if (Object.keys(fields).length === 0) return getSafe()
const row = await db.upsert(fields)
return toSafe(row)
return toSafe(row, readCredential(row))
}
module.exports = { getSafe, getWithSecret, save, disconnect, recordStatus }
module.exports = { getSafe, getWithSecret, save, disconnect, recordStatus, DEFAULT_TRANSPORT }

View File

@@ -5,8 +5,8 @@
// Push is opt-out: a user in one Team must never have to configure anything to be
// tickled about it, and the per-Team mute is how they stop. Email is opt-IN
// (`email_mode` defaults to `'off'`, deviating from §6.4 on the org lead's call):
// turning on Gmail in the admin panel must not start sending daily mail to every
// member of every Team on the deployment.
// configuring a mail transport in the admin panel must not start sending daily
// mail to every member of every Team on the deployment.
//
// Both are read the same way — COALESCE to the column default, never treat a
// missing row as "unknown" — so the asymmetry lives in ONE place, the schema, and

View File

@@ -9,6 +9,7 @@ const trustedDevices = require('../../../model/trustedDevices/trustedDevices.mod
const recoveryCodes = require('../../../model/recoveryCodes/recoveryCodes.model')
const registries = require('../../../modules/registries')
const announceJobs = require('../../../model/announceJobs/announceJobs.model')
const emailConfig = require('../../../model/emailConfig/emailConfig.model')
const forumSettings = require('../../../model/teams/teamForumSettings.model')
const pushDispatch = require('../../../utils/pushDispatch')
const { cleanBody } = require('../../../utils/sanitizeHtml')
@@ -55,6 +56,39 @@ async function announceIfNewlyPublished(post, transition) {
}
// ── Dashboard & site mode ─────────────────────────────────────────────
// G22 — the Gmail removal degrades SILENTLY (ENGAGEMENT.md §1.2a consequence 3).
// On upgrade, `transport` backfills to `smtp` with no credentials, so every sink
// politely does nothing: the contact form falls back to `mailto`, invites surface
// a copyable link, password resets still answer a generic 200. Nothing breaks
// loudly, which is exactly the risk — email stops and nobody is told.
//
// So something has to say it. The condition is deliberately narrow: a deployment
// that still holds the deprecated Gmail refresh token (it had working mail) and
// has no replacement credential (it does not any more). A fresh install has never
// had mail and is not warned — a nag about a capability nobody asked for is a
// banner people learn to ignore, and this one has to be believed exactly once.
//
// Never fails the dashboard. A warning that can 500 the admin landing page is a
// worse bug than the one it reports.
async function emailWarning() {
try {
const c = await emailConfig.getSafe()
if (!c.hadLegacyConnection || c.hasCredential) return null
return {
code: 'EMAIL_TRANSPORT_MIGRATION',
message:
'Outbound email is not configured. This deployment used the Gmail connect flow, which has been ' +
'removed — mail is no longer being sent. Add SMTP credentials under Settings → Email. Gmail still ' +
'works as an ordinary SMTP relay with an app password.',
href: '/admin/settings',
}
} catch (err) {
log.warn('dashboard email warning check failed', { message: err.message })
return null
}
}
async function dashboard(req, res) {
try {
return res.json({
@@ -67,6 +101,7 @@ async function dashboard(req, res) {
posts: await posts.counts(),
users: await users.count(),
},
warnings: [await emailWarning()].filter(Boolean),
recent_activity: await activity.list({ limit: 10 }),
})
} catch (err) {

View File

@@ -12,7 +12,7 @@
// through toward another mount and 403 an editor on an unrelated route. Keep
// gates per-route in this file.
//
// GET /dashboard — stats overview, any staff role.
// GET /dashboard — stats overview + operator warnings, any staff role.
// PUT /site-mode — live ↔ maintenance, admin only.
//
// Neither is the audit log (/activity) nor the bot-scoring state
@@ -34,7 +34,7 @@ dashboardRouter.get(
// #swagger.tags = ['Admin · Dashboard']
// #swagger.summary = 'Dashboard summary counts'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.responses[200] = { description: 'Summary: site mode, last change, post/user counts and recent activity', content: { "application/json": { schema: { type: "object", properties: { site_mode: { type: "string", example: "live" }, last_change: { type: "object", properties: { at: { type: "string", nullable: true }, by: { type: "string", nullable: true } } }, counts: { type: "object", properties: { posts: { type: "object", additionalProperties: true }, users: { type: "integer" } } }, recent_activity: { type: "array", items: { type: "object", additionalProperties: true } } } } } } } */
/* #swagger.responses[200] = { description: 'Summary: site mode, last change, post/user counts and recent activity', content: { "application/json": { schema: { type: "object", properties: { site_mode: { type: "string", example: "live" }, last_change: { type: "object", properties: { at: { type: "string", nullable: true }, by: { type: "string", nullable: true } } }, counts: { type: "object", properties: { posts: { type: "object", additionalProperties: true }, users: { type: "integer" } } }, warnings: { type: "array", description: "Operator warnings needing action; empty when there is nothing to say", items: { type: "object", properties: { code: { type: "string", example: "EMAIL_TRANSPORT_MIGRATION" }, message: { type: "string" }, href: { type: "string" } } } }, recent_activity: { type: "array", items: { type: "object", additionalProperties: true } } } } } } } */
/* #swagger.responses[401] = { description: 'Not authenticated', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
ctrl.dashboard,
)

View File

@@ -1,9 +1,13 @@
// Admin · Email — outbound mail delivery via Gmail OAuth2.
// Admin · Email — outbound mail delivery.
//
// Mounted at /api/v1/admin/email by admin/index.js, which already applied
// `noindex, isLoggedIn, staffOnly`. The modern replacement for env SMTP: the
// refresh token is captured by the connect flow below and is write-only over
// this API (stored encrypted by utils/secretBox.js, never returned).
// `noindex, isLoggedIn, staffOnly`. The credential for the selected transport is
// captured by PUT /config below and is write-only over this API (stored encrypted
// by utils/secretBox.js, never returned).
//
// Four routes. `/connect/start` and `/connect/callback` were deleted with the
// Gmail OAuth2 flow in engagement Phase 1 (ENGAGEMENT.md §1.2a) — SMTP has no
// redirect to bounce through, so a credential form is the whole of it.
//
// Admin-only, and kept as a per-route gate rather than a router-level `use` so
// the middleware chain each route carries is unchanged by the move.
@@ -21,9 +25,10 @@ const adminOnly = requireRole('admin')
emailRouter.get(
'/config',
// #swagger.tags = ['Admin · Email']
// #swagger.summary = 'Get email delivery config + status (admin only)'
// #swagger.summary = 'Get email delivery config, status and the transport catalog (admin only)'
// #swagger.description = 'Credentials are write-only: secret fields are never returned, only a per-field `secretsSet` flag. `transports` carries each registered transport&#39;s declared credential fields, which is what the admin form renders.'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.responses[200] = { description: 'Config (refresh token stripped) + status', content: { "application/json": { schema: { type: "object", additionalProperties: true } } } } */
/* #swagger.responses[200] = { description: 'Config (secrets stripped) + status + transport catalog', content: { "application/json": { schema: { type: "object", additionalProperties: true } } } } */
/* #swagger.responses[401] = { description: 'Not authenticated', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
/* #swagger.responses[403] = { description: 'Admin role required', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
adminOnly,
@@ -33,45 +38,32 @@ emailRouter.put(
'/config',
// #swagger.tags = ['Admin · Email']
// #swagger.summary = 'Update email delivery config (admin only)'
// #swagger.description = 'Set the From display name and enabled toggle. Enabling requires a connected Gmail account.'
// #swagger.description = 'Set the transport, sender identity, credentials and enabled toggle. `credential` is a patch against the stored blob — a secret field submitted empty keeps its stored value. Enabling requires complete credentials and a sender address.'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.requestBody = { content: { "application/json": { schema: { type: "object", properties: { senderName: { type: "string" }, enabled: { type: "boolean" } } } } } } */
/* #swagger.requestBody = { content: { "application/json": { schema: { type: "object", properties: { transport: { type: "string", example: "smtp" }, senderEmail: { type: "string", format: "email" }, senderName: { type: "string" }, replyTo: { type: "string", format: "email" }, credential: { type: "object", additionalProperties: true }, enabled: { type: "boolean" } } } } } } */
/* #swagger.responses[200] = { description: 'Updated config', content: { "application/json": { schema: { type: "object", additionalProperties: true } } } } */
/* #swagger.responses[400] = { description: 'Cannot enable before connecting a mailbox', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
/* #swagger.responses[400] = { description: 'Unknown transport, or cannot enable without complete credentials and a sender address', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
/* #swagger.responses[401] = { description: 'Not authenticated', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
/* #swagger.responses[403] = { description: 'Admin role required', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
adminOnly,
body('transport').optional().isString().trim().isLength({ min: 1, max: 32 }),
body('senderEmail').optional({ values: 'falsy' }).isEmail().isLength({ max: 255 }),
body('senderName').optional({ values: 'null' }).isString().trim().isLength({ max: 120 }),
body('replyTo').optional({ values: 'falsy' }).isEmail().isLength({ max: 255 }),
// The credential's SHAPE is the transport's to declare, so it is validated by
// the registry's sanitizer (which drops anything undeclared) rather than by a
// field list duplicated here that would drift the first time a transport is
// added. All this asserts is that it is an object at all.
body('credential').optional().isObject(),
body('enabled').optional().isBoolean(),
validate,
emailConfig.saveConfig,
)
emailRouter.get(
'/connect/start',
// #swagger.tags = ['Admin · Email']
// #swagger.summary = 'Begin the Gmail OAuth2 connect flow (admin only)'
// #swagger.description = 'Returns { url } to redirect the browser to Google. Reuses the google SSO OAuth client.'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.responses[200] = { description: 'Authorization URL', content: { "application/json": { schema: { type: "object", properties: { url: { type: "string" } } } } } } */
/* #swagger.responses[400] = { description: 'Google OAuth client not configured', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
/* #swagger.responses[401] = { description: 'Not authenticated', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
/* #swagger.responses[403] = { description: 'Admin role required', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
adminOnly,
emailConfig.connectStart,
)
emailRouter.get(
'/connect/callback',
// #swagger.tags = ['Admin · Email']
// #swagger.summary = 'OAuth2 callback — stores the refresh token, redirects to Settings'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.responses[302] = { description: 'Redirect back to /admin/settings' } */
adminOnly,
emailConfig.connectCallback,
)
emailRouter.post(
'/test',
// #swagger.tags = ['Admin · Email']
// #swagger.summary = 'Send a test email (admin only)'
// #swagger.description = 'The real verification of the configuration — host, port, TLS mode, credentials, and whether the relay accepts the configured sender. Failures return a specific diagnostic.'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.requestBody = { content: { "application/json": { schema: { type: "object", properties: { to: { type: "string", format: "email" } } } } } } */
/* #swagger.responses[200] = { description: 'Sent', content: { "application/json": { schema: { type: "object", properties: { sent: { type: "boolean" }, to: { type: "string" } } } } } } */
@@ -84,9 +76,9 @@ emailRouter.post(
emailRouter.post(
'/disconnect',
// #swagger.tags = ['Admin · Email']
// #swagger.summary = 'Disconnect Gmail and disable email (admin only)'
// #swagger.summary = 'Clear the stored credentials and disable email (admin only)'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.responses[200] = { description: 'Disconnected config', content: { "application/json": { schema: { type: "object", additionalProperties: true } } } } */
/* #swagger.responses[200] = { description: 'Cleared config', content: { "application/json": { schema: { type: "object", additionalProperties: true } } } } */
/* #swagger.responses[401] = { description: 'Not authenticated', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
/* #swagger.responses[403] = { description: 'Admin role required', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
adminOnly,

View File

@@ -1,67 +1,37 @@
// ── Admin: outbound email configuration (Gmail OAuth2) ─────────────────────
// ── Admin: outbound email configuration ────────────────────────────────────
//
// Modern replacement for env-var SMTP. Sending goes through Gmail over OAuth2;
// the admin connects the mailbox with an in-app consent flow that captures a
// refresh token. We reuse the existing `google` SSO OAuth client (its id/secret)
// rather than a second app — so the only per-mailbox secret is the refresh token,
// stored AES-GCM-encrypted and write-only over this API (never returned).
// Email is configured here, not via env vars. The admin picks a registered mail
// transport and fills in the fields that transport declares; the whole set is
// stored as one AES-GCM-encrypted blob and is write-only over this API — secret
// fields are never returned, only a per-field "is it set" flag.
//
// The connect flow mirrors sso.controller.js: a signed httpOnly tx cookie carries
// the CSRF nonce + PKCE verifier across the redirect to Google and back. It differs
// only in scope (https://mail.google.com/ for SMTP XOAUTH2) and access_type=offline
// + prompt=consent, which guarantee a refresh token even on reconnect.
// Gmail OAuth2 and its consent flow were removed in engagement Phase 1
// (ENGAGEMENT.md §1.2a). What went with it: two routes, the `email_oauth_tx`
// signed cookie, the PKCE verifier and CSRF nonce plumbing, the
// `https://mail.google.com/` scope, and the borrowed `google` auth-providers
// client. That last one was a real coupling — an admin rotating the Google SSO
// secret silently broke outbound mail, with nothing on either screen relating the
// two — and removing it is one of the better side effects of the decision.
//
// **The form is driven by the transport's `credentialFields`, not by this file.**
// getConfig ships the declarations to the client, saveConfig hands the submitted
// body to the registry's sanitizer, and neither one names a field. Adding a
// transport is a registration, not an edit here.
const emailConfig = require('../../../model/emailConfig/emailConfig.model')
const authProviders = require('../../../model/authProviders/authProviders.model')
const activity = require('../../../model/activity/activity.model')
const mailer = require('../../../utils/mailer')
const GoogleProvider = require('../../../auth/providers/google.provider')
const ssoState = require('../../../auth/ssoState')
const token = require('../../../auth/token')
const { transports } = require('../../../engagement')
const log = require('../../../utils/logger')('admin')
// Gmail scope grants SMTP (XOAUTH2) access; openid+email let us read back which
// address was connected. The narrower gmail.send scope only works via the Gmail
// API, not SMTP, so we need the full-access scope here.
const EMAIL_SCOPE = 'https://mail.google.com/ openid email'
const TX_COOKIE = 'email_oauth_tx'
// Public base URL for the OAuth redirect_uri — same fallback pattern as
// sso.controller.js. Must be identical between start and callback.
function appBaseUrl(req) {
const configured = process.env.APP_BASE_URL
if (configured) return configured.replace(/\/+$/, '')
const derived = `${req.protocol}://${req.get('host')}`
log.warn('APP_BASE_URL not set — deriving email redirect_uri from the request', { derived })
return derived
}
function redirectUri(req) {
return `${appBaseUrl(req)}/api/v1/admin/email/connect/callback`
}
function txCookieOptions(req) {
return { ...token.cookieOptions(req), maxAge: 10 * 60 * 1000 }
}
// Front-end redirect targets after the callback resolves.
const CONNECTED_URL = '/admin/settings?email_connected=1'
const errorUrl = (code) => `/admin/settings?email_error=${code}`
// Load the Google OAuth client (id + decrypted secret) reused for email. Returns
// null when the google provider hasn't been configured with credentials yet.
async function googleClient() {
const row = await authProviders.getWithSecret('google')
if (!row || !row.client_id || !row.client_secret) return null
return { clientId: row.client_id, clientSecret: row.client_secret }
}
// GET /admin/email/config
async function getConfig(req, res) {
try {
const config = await emailConfig.getSafe()
// Surface whether the Google client email can borrow is configured, so the
// UI can explain why Connect is unavailable.
config.googleConfigured = Boolean(await googleClient())
// The transport catalog rides with the config so the client renders the
// credential form from the same declarations the server validates against.
config.transports = transports.describe()
return res.json(config)
} catch (err) {
log.error('emailConfig.getConfig', err)
@@ -69,23 +39,50 @@ async function getConfig(req, res) {
}
}
// PUT /admin/email/config — sender name + enabled toggle. Enabling requires a
// connected mailbox (a stored refresh token).
// PUT /admin/email/config — transport, sender identity, credentials, enabled.
//
// Enabling requires a complete credential AND a sender address, checked against
// the state as it will be AFTER this save rather than before it: the admin fills
// the whole form and ticks Enable in one submit, and refusing that because the
// credential was absent a moment ago would make the screen impossible to use.
async function saveConfig(req, res) {
const { senderName, enabled } = req.body
const { transport, senderEmail, senderName, replyTo, credential, enabled } = req.body
try {
const current = await emailConfig.getSafe()
if (enabled && !current.hasRefreshToken) {
return res.status(400).json({ message: 'Connect a Gmail account before enabling email.' })
const nextTransport = transport === undefined ? current.transport : transport
if (!transports.has(nextTransport)) {
return res.status(400).json({ message: `Unknown mail transport "${nextTransport}".` })
}
const saved = await emailConfig.save({
transport: transport !== undefined ? nextTransport : undefined,
senderEmail: senderEmail !== undefined ? senderEmail || null : undefined,
senderName: senderName !== undefined ? senderName || null : undefined,
enabled,
replyTo: replyTo !== undefined ? replyTo || null : undefined,
credential,
// Enabling is applied only once the saved row can actually support it, so
// the response tells the truth about what is stored rather than echoing the
// request. The re-read below is what decides.
enabled: enabled === undefined ? undefined : Boolean(enabled),
updatedBy: req.user.id,
})
saved.googleConfigured = Boolean(await googleClient())
await activity.log({ req, action: 'email.config.update', detail: { enabled: saved.enabled } })
log.info('email config updated', { by: req.user.username, enabled: saved.enabled })
if (saved.enabled && !(saved.hasCredential && saved.senderEmail)) {
const reverted = await emailConfig.save({ enabled: false, updatedBy: req.user.id })
reverted.transports = transports.describe()
return res.status(400).json({
message: 'Add complete credentials and a sender address before enabling email.',
config: reverted,
})
}
saved.transports = transports.describe()
await activity.log({
req,
action: 'email.config.update',
detail: { transport: saved.transport, enabled: saved.enabled, hasCredential: saved.hasCredential },
})
log.info('email config updated', { by: req.user.username, transport: saved.transport, enabled: saved.enabled })
return res.json(saved)
} catch (err) {
log.error('emailConfig.saveConfig', err)
@@ -93,96 +90,14 @@ async function saveConfig(req, res) {
}
}
// GET /admin/email/connect/start — returns { url } for the browser to navigate to.
async function connectStart(req, res) {
try {
const client = await googleClient()
if (!client) {
return res.status(400).json({
message: 'Configure the Google authentication provider (client id + secret) before connecting email.',
})
}
const provider = new GoogleProvider({ clientId: client.clientId, clientSecret: client.clientSecret })
const tx = ssoState.createTx({ flow: 'email' })
res.cookie(TX_COOKIE, tx.txToken, txCookieOptions(req))
const params = new URLSearchParams({
client_id: client.clientId,
redirect_uri: redirectUri(req),
response_type: 'code',
scope: EMAIL_SCOPE,
access_type: 'offline',
prompt: 'consent',
include_granted_scopes: 'true',
state: tx.nonce,
code_challenge: tx.codeChallenge,
code_challenge_method: 'S256',
})
const url = `${provider.authEndpoint()}?${params.toString()}`
return res.json({ url })
} catch (err) {
log.error('emailConfig.connectStart', err)
return res.status(500).json({ message: 'Internal Server Error' })
}
}
// GET /admin/email/connect/callback — exchange the code, capture the refresh
// token + connected address, store encrypted, and redirect back to Settings.
async function connectCallback(req, res) {
const txToken = req.cookies && req.cookies[TX_COOKIE]
const { code, state, error: oauthError } = req.query
res.clearCookie(TX_COOKIE, token.cookieOptions(req)) // single-use
if (oauthError) {
log.warn('email connect: provider returned error', { error: String(oauthError).slice(0, 60) })
return res.redirect(errorUrl('denied'))
}
const tx = ssoState.verifyTx(txToken, state)
if (!tx || tx.flow !== 'email' || !code) {
log.warn('email connect: bad state')
return res.redirect(errorUrl('bad_state'))
}
try {
const client = await googleClient()
if (!client) return res.redirect(errorUrl('no_client'))
const provider = new GoogleProvider({ clientId: client.clientId, clientSecret: client.clientSecret })
const tokenSet = await provider.exchangeCode({
code,
redirectUri: redirectUri(req),
codeVerifier: tx.verifier,
})
if (!tokenSet.refresh_token) {
// Google only returns a refresh token when it hasn't already granted one
// for this client+scope. prompt=consent should force it; if it's still
// missing the admin can revoke the app's access and retry.
log.warn('email connect: no refresh_token returned')
return res.redirect(errorUrl('no_refresh_token'))
}
const profile = await provider.getUserProfile(tokenSet.access_token)
const senderEmail = profile.email || null
if (!senderEmail) return res.redirect(errorUrl('no_email'))
await emailConfig.save({
senderEmail,
refreshToken: tokenSet.refresh_token,
enabled: true,
status: 'connected',
statusDetail: 'Connected',
updatedBy: req.user.id,
})
await emailConfig.recordStatus({ status: 'connected', statusDetail: 'Connected', lastVerifiedAt: new Date() })
await activity.log({ req, action: 'email.connect', detail: { senderEmail } })
log.info('email connected', { senderEmail, by: req.user.username })
return res.redirect(CONNECTED_URL)
} catch (err) {
log.error('emailConfig.connectCallback', err)
return res.redirect(errorUrl('error'))
}
}
// POST /admin/email/test — send a test message (to the given address, or the
// contact recipient by default).
//
// This is the only verification the configuration gets. Under the removed consent
// flow the sending address came back from Google and was guaranteed to belong to
// the credential; an operator-typed sender the relay will not accept is a silent
// deliverability failure, so mailer.describeSendError puts the sender in the
// message and this hands it through verbatim.
async function testSend(req, res) {
try {
const result = await mailer.sendTest(req.body.to)
@@ -198,9 +113,9 @@ async function testSend(req, res) {
async function disconnect(req, res) {
try {
const config = await emailConfig.disconnect(req.user.id)
config.googleConfigured = Boolean(await googleClient())
config.transports = transports.describe()
await activity.log({ req, action: 'email.disconnect' })
log.info('email disconnected', { by: req.user.username })
log.info('email credentials cleared', { by: req.user.username })
return res.json(config)
} catch (err) {
log.error('emailConfig.disconnect', err)
@@ -208,4 +123,4 @@ async function disconnect(req, res) {
}
}
module.exports = { getConfig, saveConfig, connectStart, connectCallback, testSend, disconnect }
module.exports = { getConfig, saveConfig, testSend, disconnect }

View File

@@ -43,7 +43,7 @@ async function start() {
logFile: createLogger.logFilePath || 'disabled (console only)',
db: `${process.env.DB_HOST || '127.0.0.1'}:${process.env.DB_PORT || 3306}/${process.env.DB_NAME || 'runic_gateway'}`,
cookieSecure: process.env.COOKIE_SECURE || 'auto',
email: 'gmail-oauth2 (configured in admin → settings)',
email: 'smtp (configured in admin → settings)',
})
// Fail fast if the server<->bot shared secret is weak/placeholder. Fatal in

View File

@@ -1,65 +1,93 @@
// ── Outbound mail (Gmail over OAuth2 / SMTP XOAUTH2) ───────────────────────
// ── Outbound mail ──────────────────────────────────────────────────────────
//
// Email is configured in Admin → Settings → Email, not via env vars. The
// connection (enabled flag, connected Gmail address, encrypted refresh token)
// lives in the email_config singleton; the OAuth client id/secret are reused
// from the `google` auth_providers row. nodemailer takes the refresh token and
// auto-mints short-lived access tokens for each send.
// `email_config` singleton holds the enabled flag, the sender identity and the
// AES-GCM-encrypted credential for whichever transport is selected; the transport
// itself is a registration in `src/engagement/transports` (ENGAGEMENT.md §3.1),
// so which provider is used is DATA, not a code path in this file.
//
// When email is not configured, sendContactMessage does NOT throw — it signals
// the caller to fall back to a mailto: link (the contact form relies on this).
const nodemailer = require('nodemailer')
// Gmail OAuth2 was removed in engagement Phase 1 (§1.2a). Gmail is still reachable
// as an ordinary SMTP relay (`smtp.gmail.com:587` with an app password) — the
// operator types those in like any other host; nothing in here knows about it.
//
// **The failure contracts are the point of this file.** Six call sites, five
// senders, and each one degrades a specific way when mail is unconfigured. Those
// contracts are unchanged by the transport rewrite and are asserted in
// test/mailer.test.js: sendContactMessage returns a mailto fallback, sendInvite
// and sendPasswordReset return { sent: false, reason: 'NOT_CONFIGURED' } so their
// callers can surface a link / answer a generic 200, sendTeamNotification never
// throws at all, and only sendTest throws — because only sendTest has an admin
// waiting to be told why.
const emailConfig = require('../model/emailConfig/emailConfig.model')
const authProviders = require('../model/authProviders/authProviders.model')
const settings = require('../model/settings/settings.model')
const { transports } = require('../engagement')
const brand = require('../config/brand')
const log = require('./logger')('mailer')
// Ready to send only when enabled, connected (has a refresh token), and we know
// which address to send as.
// Ready to send only when enabled, holding a complete credential for a
// registered transport, and knowing which address to send as.
async function isConfigured() {
const c = await emailConfig.getSafe()
return Boolean(c.enabled && c.hasRefreshToken && c.senderEmail)
return Boolean(c.enabled && c.hasCredential && c.senderEmail)
}
// Recipient for the contact form: the admin-editable contact_email setting, or
// the connected sending address as a last resort.
// the configured sending address as a last resort.
async function contactRecipient(senderEmail) {
const to = await settings.get('contact_email')
return to || senderEmail || null
}
// Build a nodemailer OAuth2 transport from the stored config + reused Google
// client credentials. Returns { transport, config } or null when unconfigured.
/**
* Build a transport from the stored config. Returns { transport, config } or
* null when unconfigured — every sender handles null itself.
*
* Null, never a throw, for all five ways this can fail: no row, disabled, no
* sender address, an incomplete credential, or a stored transport id that is not
* registered (a downgrade, or a provider removed from the build). The last one is
* the reason `transports.get()` is checked rather than assumed: a send-time
* exception from an unknown id would break the contact form for a reason the
* admin screen already shows.
*
* **`enabled` is checked here now, and it was not before.** Under the connect
* flow this function tested only "is there a refresh token and a sender", so the
* contact form kept sending after an admin unticked "Enable email sending" —
* `isConfigured()` honoured the toggle but the direct senders bypassed it. With
* the toggle no longer set as a side effect of a consent redirect it has to mean
* what it says, so the gate lives on the one path every sender shares.
*/
async function buildTransport() {
const config = await emailConfig.getWithSecret()
if (!config || !config.refreshToken || !config.senderEmail) return null
const google = await authProviders.getWithSecret('google')
if (!google || !google.client_id || !google.client_secret) {
log.warn('email send skipped: Google OAuth client is not configured')
if (!config || !config.enabled || !config.senderEmail) return null
const def = transports.get(config.transport)
if (!def) {
log.warn('email send skipped: no such transport', { transport: config.transport })
return null
}
if (!transports.isComplete(config.transport, config.credentialSecret)) {
log.warn('email send skipped: transport credentials are incomplete', { transport: config.transport })
return null
}
try {
return { transport: def.build(config.credentialSecret, config), config }
} catch (err) {
log.error('could not build the mail transport', err)
return null
}
const transport = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
type: 'OAuth2',
user: config.senderEmail,
clientId: google.client_id,
clientSecret: google.client_secret,
refreshToken: config.refreshToken,
},
})
return { transport, config }
}
function fromHeader(config) {
return config.senderName ? `"${config.senderName}" <${config.senderEmail}>` : config.senderEmail
}
// Reply-To is the operator's optional override; the contact form's per-message
// replyTo (the visitor's address) wins over it, which is the whole reason the
// contact form has one.
function replyToFor(config, override) {
return override || config.replyTo || undefined
}
/**
* Send a contact message. If email is not configured/enabled, signals the caller
* to fall back to a mailto: link instead of throwing.
@@ -76,7 +104,7 @@ async function sendContactMessage({ name, email, message }) {
await transport.sendMail({
from: fromHeader(config),
to,
replyTo: email,
replyTo: replyToFor(config, email),
subject: `${brand.name} contact from ${name || 'a visitor'}`,
text: `From: ${name || 'unknown'} <${email || 'no email'}>\n\n${message}`,
})
@@ -84,19 +112,49 @@ async function sendContactMessage({ name, email, message }) {
return { sent: true }
} catch (err) {
log.error('contact send failed', err)
await emailConfig.recordStatus({ status: 'error', statusDetail: err.message })
await emailConfig.recordStatus({ status: 'error', statusDetail: describeSendError(err) })
throw err
}
}
/**
* Turn a transport error into something an operator can act on.
*
* This matters more than it used to. Under Gmail OAuth2 the sending address came
* back from Google's userinfo and was guaranteed to be a mailbox the credential
* owned. Under SMTP `sender_email` is operator-typed, so a relay rejecting the
* envelope From is now a live failure mode (§1.2a consequence 2) — and it arrives
* as a bare "550 5.7.1" that means nothing without the sender in front of it.
*/
function describeSendError(err, config) {
const code = err && (err.responseCode || err.code)
const base = (err && (err.response || err.message)) || 'Send failed'
const sender = config && config.senderEmail
if (sender && (code === 550 || code === 553 || code === 554 || code === 'EENVELOPE')) {
return `${base} — the server refused "${sender}" as the sender. It must be an address this account is allowed to send as (SPF/DMARC).`
}
if (code === 'EAUTH') return `${base} — the username or password was rejected.`
if (code === 'ESOCKET' || code === 'ECONNECTION') {
return `${base} — could not connect. Check the host, the port, and whether "Implicit TLS" matches it (on for 465, off for 587).`
}
if (code === 'ETIMEDOUT') {
return `${base} — the connection timed out. A common cause is "Implicit TLS" left on for port 587.`
}
return String(base)
}
/**
* Send a test email to `to`, used by the admin "Send test" button. Throws on
* failure; records the outcome either way. Returns { sent: true } on success.
*
* **This is now the real verification of the whole configuration** — host, port,
* TLS mode, credentials AND whether the relay will accept the operator-typed
* sender. There is no consent flow left to prove any of it beforehand.
*/
async function sendTest(to) {
const built = await buildTransport()
if (!built) {
const err = new Error('Email is not configured. Connect Gmail first.')
const err = new Error('Email is not configured. Set a transport, its credentials and a sender address first.')
err.code = 'NOT_CONFIGURED'
throw err
}
@@ -111,15 +169,19 @@ async function sendTest(to) {
await transport.sendMail({
from: fromHeader(config),
to: recipient,
replyTo: replyToFor(config),
subject: `${brand.name} email test`,
text: 'This is a test message confirming Gmail OAuth2 email delivery is working.',
text: `This is a test message confirming ${config.transport} email delivery is working.`,
})
await emailConfig.recordStatus({ status: 'connected', statusDetail: 'Test send OK', lastVerifiedAt: new Date() })
return { sent: true, to: recipient }
} catch (err) {
const detail = describeSendError(err, config)
log.error('test send failed', err)
await emailConfig.recordStatus({ status: 'error', statusDetail: err.message })
throw err
await emailConfig.recordStatus({ status: 'error', statusDetail: detail })
const wrapped = new Error(detail)
wrapped.code = err.code || 'SEND_FAILED'
throw wrapped
}
}
@@ -140,6 +202,7 @@ async function sendInvite({ to, acceptUrl, role, invitedByName }) {
await transport.sendMail({
from: fromHeader(config),
to,
replyTo: replyToFor(config),
subject: `Your ${brand.name} invitation`,
text:
`You have been invited${by} to join ${brand.name}${roleLabel}.\n\n` +
@@ -150,7 +213,7 @@ async function sendInvite({ to, acceptUrl, role, invitedByName }) {
return { sent: true }
} catch (err) {
log.error('invite send failed', err)
await emailConfig.recordStatus({ status: 'error', statusDetail: err.message })
await emailConfig.recordStatus({ status: 'error', statusDetail: describeSendError(err, config) })
throw err
}
}
@@ -171,6 +234,7 @@ async function sendPasswordReset({ to, resetUrl, username }) {
await transport.sendMail({
from: fromHeader(config),
to,
replyTo: replyToFor(config),
subject: `Reset your ${brand.name} password`,
text:
`We received a request to reset the password${forWhom} at ${brand.name}.\n\n` +
@@ -182,7 +246,7 @@ async function sendPasswordReset({ to, resetUrl, username }) {
return { sent: true }
} catch (err) {
log.error('password reset send failed', err)
await emailConfig.recordStatus({ status: 'error', statusDetail: err.message })
await emailConfig.recordStatus({ status: 'error', statusDetail: describeSendError(err, config) })
throw err
}
}
@@ -234,6 +298,7 @@ async function sendTeamNotification({ to, subject, intro, items, teamUrl, unsubs
await transport.sendMail({
from: fromHeader(config),
to,
replyTo: replyToFor(config),
subject,
text: lines.join('\n'),
// The header carries the API url, not the one in the body: a one-click
@@ -252,7 +317,7 @@ async function sendTeamNotification({ to, subject, intro, items, teamUrl, unsubs
// called by a request that can report the failure to whoever caused it; this
// one is not, and recordStatus already puts the error where an admin reads it.
log.warn('team notification send failed', { message: err.message })
await emailConfig.recordStatus({ status: 'error', statusDetail: err.message }).catch(() => {})
await emailConfig.recordStatus({ status: 'error', statusDetail: describeSendError(err, config) }).catch(() => {})
return { sent: false, reason: 'SEND_FAILED' }
}
}

View File

@@ -211,8 +211,8 @@ async function forumPost({ team, threadId, threadTitle, type, authorUserId, auth
* exactly that.
*
* Skipped entirely when no email is configured — §6.4's "off unless configured"
* — and checked BEFORE the recipient query so a deployment with no Gmail
* connected pays nothing for the sink it does not have.
* — and checked BEFORE the recipient query so a deployment with no mail
* transport configured pays nothing for the sink it does not have.
*/
async function emailImmediate({ team, threadId, threadTitle, type, exclude, authorName, bodyHtml }) {
if (!(await mailer.isConfigured())) return 0
@@ -227,8 +227,8 @@ async function emailImmediate({ team, threadId, threadTitle, type, exclude, auth
for (const r of recipients) {
// Serial rather than Promise.all: this is an SMTP conversation per recipient
// against a provider with its own rate limits, and a burst of them from a
// busy thread is how a Gmail sender gets throttled. The loop is also why the
// against a relay with its own rate limits, and a burst of them from a
// busy thread is how a sending account gets throttled. The loop is also why the
// send below is fire-and-report rather than fire-and-throw.
// eslint-disable-next-line no-await-in-loop
const res = await mailer.sendTeamNotification({