Multiplayer agent harness for work.
Send mail through Nodemailer and one Resend client (#2480)
Regan Bell0905136ed2e7
diff --git a/cli/README.md b/cli/README.mdindex a4728925e..36c1ff47c 100644--- a/cli/README.md+++ b/cli/README.md@@ -239,5 +239,5 @@ Incompatible directorychanges increment the contract major; optional fields may be added within amajor.-The package has no runtime dependencies. It shells out to Docker with Buildx, Flyctl,+Its one runtime dependency is Nodemailer, which `qm check` uses to verify SMTP credentials. It shells out to Docker with Buildx, Flyctl,the AWS CLI, and Git. Terraform is operator-run against the module generated by `init`.diff --git a/cli/package-lock.json b/cli/package-lock.jsonindex 8b469f6a2..6540577b4 100644--- a/cli/package-lock.json+++ b/cli/package-lock.json@@ -8,6 +8,9 @@"name": "@yc-software/qm","version": "0.1.6","license": "MIT",+ "dependencies": {+ "nodemailer": "^10.1.0"+ },"bin": {"qm": "dist/bin/qm.js"},@@ -29,6 +32,15 @@"undici-types": "~7.18.0"}},+ "node_modules/nodemailer": {+ "version": "10.1.0",+ "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.1.0.tgz",+ "integrity": "sha512-fXW8AulB25aOTuwfRYV6lqHyfz2VM4rr4SGXH03mE7x5znEUpzL5mu6anARUpZN7744Ziwkmr4AxSLPJsBQspg==",+ "license": "MIT-0",+ "engines": {+ "node": ">=20.0.0"+ }+ },"node_modules/typescript": {"version": "5.9.3","resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",diff --git a/cli/package.json b/cli/package.jsonindex 4fbc357d4..ee7e10856 100644--- a/cli/package.json+++ b/cli/package.json@@ -46,5 +46,8 @@"devDependencies": {"@types/node": "^24.0.0","typescript": "^5.8.2"+ },+ "dependencies": {+ "nodemailer": "^10.1.0"}}diff --git a/cli/src/backends/doctor.ts b/cli/src/backends/doctor.tsindex af245728c..fb5d4c0c2 100644--- a/cli/src/backends/doctor.ts+++ b/cli/src/backends/doctor.ts@@ -12,7 +12,7 @@ import {import { CliError, errMessage, step, warn } from "../log.ts";import { capture, deploymentSecretValue, flyBin, isInvalidSecret, readEnvFile, which } from "../util.ts";import { computedSecrets, serviceSecretValue } from "../secrets.ts";-import { emailTransportConfigured } from "../preflight.ts";+import { emailTransportConfigured, smtpTlsMode, smtpTransport } from "../preflight.ts";export function slackManifestBotScopes(manifest: string): string[] {try {@@ -279,21 +279,6 @@ async function resendCheck(apiKey: string): Promise<void> {if (!res.ok) throw new CliError(`the Resend API returned HTTP ${res.status}; retry when it recovers`);}-async function smtpReachable(host: string, port: number): Promise<string> {- const { connect } = await import("node:net");- return new Promise<string>((resolve, reject) => {- const socket = connect({ host, port });- const done = (error?: Error, greeting?: string): void => {- socket.destroy();- if (error) reject(error);- else resolve(greeting ?? "");- };- socket.setTimeout(10_000, () => done(new Error("connection timed out")));- socket.once("error", (e: Error) => done(e));- socket.once("data", (chunk: Buffer) => done(undefined, chunk.toString("utf8").split("\r\n")[0] ?? ""));- });-}-async function authBrokerCheck(config: QmConfig, secrets: Map<string, string>, haveValues: boolean): Promise<void> {if (haveValues && !emailTransportConfigured(config, secrets)) {step("sign-in email: disabled; use qm admin-login for administrator access");@@ -327,13 +312,13 @@ async function authBrokerCheck(config: QmConfig, secrets: Map<string, string>, hreturn;}const port = Number(config.env.auth?.SMTP_PORT ?? 587);- let greeting: string;+ const implicit = smtpTlsMode(config.env.auth?.SMTP_TLS, port) === "implicit";try {- greeting = await smtpReachable(host, port);+ await smtpTransport(host, port, implicit ? "implicit" : "none").verify();} catch (e) {throw new CliError(`SMTP relay ${host}:${port} is unreachable: ${errMessage(e)} — the broker cannot send sign-in links`,);}- step(`SMTP relay ${host}:${port}: reachable (${greeting || "no greeting"})`);+ step(`SMTP relay ${host}:${port}: reachable`);}diff --git a/cli/src/preflight.ts b/cli/src/preflight.tsindex 7ec998e69..9c09403fa 100644--- a/cli/src/preflight.ts+++ b/cli/src/preflight.ts@@ -1,8 +1,7 @@import { existsSync, readFileSync } from "node:fs";-import { connect as netConnect, type Socket } from "node:net";-import { connect as tlsConnect } from "node:tls";import { join } from "node:path";import { fileURLToPath } from "node:url";+import { createTransport } from "nodemailer";import type { QmConfig } from "./config.ts";import { CliError, errMessage, step, warn } from "./log.ts";import { deploymentSecretValue } from "./util.ts";@@ -112,156 +111,39 @@ export interface SmtpVerifyOptions {username: string;password: string;tls: SmtpTlsMode;- timeoutMs?: number;}export class SmtpRejectedError extends Error {}-function smtpTlsMode(declared: string | undefined, port: number): SmtpTlsMode {+export function smtpTlsMode(declared: string | undefined, port: number): SmtpTlsMode {const mode = declared?.trim().toLowerCase();if (mode === "implicit" || mode === "none" || mode === "starttls") return mode;return port === 465 ? "implicit" : "starttls";}-class SmtpProbe {- private buffer = "";- private waiter: { resolve: (reply: { code: number; text: string }) => void; reject: (e: Error) => void } | null =- null;- private failure: Error | null = null;-- private socket: Socket;-- constructor(socket: Socket, timeoutMs: number) {- this.socket = socket;- socket.setTimeout(timeoutMs, () => this.fail(new Error("SMTP timed out")));- this.attach(socket);- }-- private attach(socket: Socket): void {- socket.on("data", (chunk: Buffer) => this.onData(chunk.toString("utf8")));- socket.on("error", (e: Error) => this.fail(e));- socket.on("close", () => this.fail(new Error("SMTP connection closed")));- }-- private fail(e: Error): void {- this.failure ??= e;- const waiter = this.waiter;- this.waiter = null;- waiter?.reject(e);- }-- private onData(chunk: string): void {- this.buffer += chunk;- const lines = this.buffer.split("\r\n");- let text = "";- for (let i = 0; i < lines.length - 1; i++) {- const line = lines[i]!;- if (!/^\d{3}[ -]/.test(line)) {- this.fail(new Error(`SMTP sent an unparseable reply: ${line}`));- return;- }- text += line.slice(4);- if (line[3] === " ") {- this.buffer = lines.slice(i + 1).join("\r\n");- const waiter = this.waiter;- this.waiter = null;- waiter?.resolve({ code: Number(line.slice(0, 3)), text });- return;- }- text += "\n";- }- }-- read(): Promise<{ code: number; text: string }> {- if (this.failure) return Promise.reject(this.failure);- return new Promise((resolve, reject) => {- this.waiter = { resolve, reject };- });- }-- command(line: string): Promise<{ code: number; text: string }> {- this.socket.write(`${line}\r\n`);- return this.read();- }-- async upgrade(host: string): Promise<void> {- const plain = this.socket;- for (const event of ["data", "error", "close"]) plain.removeAllListeners(event);- const secure = tlsConnect({ socket: plain, servername: host }) as unknown as Socket;- secure.on("error", () => undefined);- await new Promise<void>((resolve, reject) => {- secure.once("secureConnect", () => resolve());- secure.once("error", reject);- });- secure.removeAllListeners("error");- this.socket = secure;- this.attach(secure);- }-- close(): void {- for (const event of ["data", "error", "close"]) this.socket.removeAllListeners(event);- this.socket.on("error", () => undefined);- this.socket.destroy();- }-}--async function openSmtpSocket(options: SmtpVerifyOptions, timeoutMs: number): Promise<Socket> {- const socket =- options.tls === "implicit"- ? (tlsConnect({ host: options.host, port: options.port, servername: options.host }) as unknown as Socket)- : netConnect({ host: options.host, port: options.port });- return new Promise<Socket>((resolve, reject) => {- const timer = setTimeout(- () => reject(new Error(`SMTP connect to ${options.host}:${options.port} timed out`)),- timeoutMs,- );- socket.once(options.tls === "implicit" ? "secureConnect" : "connect", () => {- clearTimeout(timer);- socket.removeAllListeners("error");- resolve(socket);- });- socket.once("error", (e: Error) => {- clearTimeout(timer);- socket.destroy();- reject(e);- });+export function smtpTransport(host: string, port: number, tls: SmtpTlsMode, auth?: { user: string; pass: string }) {+ return createTransport({+ host,+ port,+ secure: tls === "implicit",+ requireTLS: tls === "starttls",+ ignoreTLS: tls === "none",+ ...(auth ? { auth } : {}),+ connectionTimeout: PROBE_TIMEOUT_MS,+ greetingTimeout: PROBE_TIMEOUT_MS,+ socketTimeout: PROBE_TIMEOUT_MS,});}export async function smtpVerify(options: SmtpVerifyOptions): Promise<void> {- const timeoutMs = options.timeoutMs ?? PROBE_TIMEOUT_MS;- const probe = new SmtpProbe(await openSmtpSocket(options, timeoutMs), timeoutMs);- const expect = (reply: { code: number; text: string }, codes: readonly number[], what: string): void => {- if (codes.includes(reply.code)) return;- const detail = `${what}: ${reply.code} ${reply.text.split("\n")[0] ?? ""}`;- if (reply.code >= 500) throw new SmtpRejectedError(`SMTP rejected ${detail}`);- throw new Error(`SMTP did not accept ${detail}`);- };try {- expect(await probe.read(), [220], "greeting");- let ehlo = await probe.command(`EHLO qm-check`);- expect(ehlo, [250], "EHLO");- if (options.tls === "starttls") {- if (!/\bSTARTTLS\b/i.test(ehlo.text))- throw new Error("SMTP server does not offer STARTTLS — refusing to send credentials in cleartext");- expect(await probe.command("STARTTLS"), [220], "STARTTLS");- await probe.upgrade(options.host);- ehlo = await probe.command(`EHLO qm-check`);- expect(ehlo, [250], "EHLO");- }- const steps = /\bPLAIN\b/.test(ehlo.text)- ? [`AUTH PLAIN ${Buffer.from(`\0${options.username}\0${options.password}`, "utf8").toString("base64")}`]- : [- "AUTH LOGIN",- Buffer.from(options.username, "utf8").toString("base64"),- Buffer.from(options.password, "utf8").toString("base64"),- ];- for (const [index, line] of steps.entries()) {- expect(await probe.command(line), index === steps.length - 1 ? [235] : [334], "AUTH");- }- await probe.command("QUIT").catch(() => undefined);- } finally {- probe.close();+ await smtpTransport(options.host, options.port, options.tls, {+ user: options.username,+ pass: options.password,+ }).verify();+ } catch (e) {+ if ((e as { code?: unknown }).code === "EAUTH") throw new SmtpRejectedError(errMessage(e));+ throw e;}}diff --git a/cli/test/package.test.ts b/cli/test/package.test.tsindex 782d99396..b6b62724b 100644--- a/cli/test/package.test.ts+++ b/cli/test/package.test.ts@@ -44,27 +44,45 @@ test(const packed = JSON.parse(execFileSync("npm", ["pack", "--json", "--pack-destination", dir], { cwd: cliDir, encoding: "utf8", env }),) as Array<{ filename: string; files: Array<{ path: string }> }>;- const tarball = join(dir, packed[0]!.filename);const deployment = join(dir, "deployment");const awsDeployment = join(dir, "aws-deployment");- const tarballBytes = readFileSync(tarball);const packageManifest = JSON.parse(readFileSync(join(cliDir, "package.json"), "utf8")) as Record<string, unknown>;const version = packageManifest["version"] as string;+ const published = new Map([+ ["@yc-software/qm", { manifest: packageManifest, bytes: readFileSync(join(dir, packed[0]!.filename)) }],+ ]);+ for (const name of Object.keys(packageManifest["dependencies"] as Record<string, string>)) {+ const source = join(cliDir, "node_modules", name);+ const [dependency] = JSON.parse(+ execFileSync("npm", ["pack", "--json", "--ignore-scripts", "--pack-destination", dir], {+ cwd: source,+ encoding: "utf8",+ env,+ }),+ ) as Array<{ filename: string }>;+ published.set(name, {+ manifest: JSON.parse(readFileSync(join(source, "package.json"), "utf8")) as Record<string, unknown>,+ bytes: readFileSync(join(dir, dependency!.filename)),+ });+ }registry = createServer((request, response) => {const origin = `http://${request.headers.host}`;- if (request.url && decodeURIComponent(request.url) === "/@yc-software/qm") {+ const path = decodeURIComponent(request.url ?? "").slice(1);+ const metadata = published.get(path);+ if (metadata) {+ const release = metadata.manifest["version"] as string;response.setHeader("content-type", "application/json");response.end(JSON.stringify({- name: "@yc-software/qm",- "dist-tags": { latest: version },+ name: path,+ "dist-tags": { latest: release },versions: {- [version]: {- ...packageManifest,+ [release]: {+ ...metadata.manifest,dist: {- tarball: `${origin}/@yc-software/qm/-/qm-${version}.tgz`,- shasum: createHash("sha1").update(tarballBytes).digest("hex"),- integrity: `sha512-${createHash("sha512").update(tarballBytes).digest("base64")}`,+ tarball: `${origin}/${path}/-/package-${release}.tgz`,+ shasum: createHash("sha1").update(metadata.bytes).digest("hex"),+ integrity: `sha512-${createHash("sha512").update(metadata.bytes).digest("base64")}`,},},},@@ -72,9 +90,11 @@ test();return;}- if (request.url === `/@yc-software/qm/-/qm-${version}.tgz`) {+ const tarball = /^(.+)\/-\/package-[^/]+\.tgz$/.exec(path);+ const archive = tarball && published.get(tarball[1]!);+ if (archive) {response.setHeader("content-type", "application/octet-stream");- response.end(tarballBytes);+ response.end(archive.bytes);return;}response.statusCode = 404;@@ -141,7 +161,7 @@ test(registry = undefined;const bin = join(deployment, "node_modules", ".bin", "qm");const awsBin = join(awsDeployment, "node_modules", ".bin", "qm");- rmSync(tarball);+ rmSync(join(dir, packed[0]!.filename));assert.ok(existsSync(join(deployment, "deployment.md")));assert.ok(existsSync(join(deployment, ".codex", "skills", "deploy-qm", "SKILL.md")));diff --git a/cli/test/preflight.test.ts b/cli/test/preflight.test.tsindex 0f1cd3b52..110aeea12 100644--- a/cli/test/preflight.test.ts+++ b/cli/test/preflight.test.ts@@ -1,6 +1,7 @@import { test } from "node:test";import assert from "node:assert/strict";import { createServer, type Server, type Socket } from "node:net";+import { doctorCommon } from "../src/backends/doctor.ts";import type { QmConfig } from "../src/config.ts";import { CliError } from "../src/log.ts";import {@@ -185,6 +186,50 @@ test("email preflight fails check on rejected SMTP credentials and warns on stra}});+test("email preflight warns instead of failing when a STARTTLS relay does not offer STARTTLS", async () => {+ const smtp = await fakeSmtp("right");+ const config = {+ ...CONFIG,+ env: { auth: { AUTH_EMAIL_TRANSPORT: "smtp", SMTP_PORT: String(smtp.port), SMTP_TLS: "starttls" } },+ };+ try {+ const lines = await quietAsync(() =>+ emailTransportPreflight(+ config,+ new Map([+ ["AUTH_EMAIL_FROM", "QM <[email protected]>"],+ ["SMTP_HOST", "127.0.0.1"],+ ["SMTP_USERNAME", "user"],+ ["SMTP_PASSWORD", "right"],+ ]),+ ),+ );+ assert.ok(lines.some((line) => line.includes("could not verify the SMTP credentials")));+ assert.ok(!lines.some((line) => line.includes("credentials accepted")));+ } finally {+ await smtp.close();+ }+});++test("doctor reports an SMTP relay reachable when it answers and unreachable when it does not", async () => {+ const smtp = await fakeSmtp("right");+ const relay = (port: number): QmConfig => ({+ ...CONFIG,+ env: { auth: { AUTH_EMAIL_TRANSPORT: "smtp", SMTP_PORT: String(port) } },+ });+ const secrets = new Map([["SMTP_HOST", "127.0.0.1"]]);+ try {+ const lines = await quietAsync(() => doctorCommon(relay(smtp.port), secrets));+ assert.ok(lines.some((line) => line.includes(`SMTP relay 127.0.0.1:${smtp.port}: reachable`)));+ } finally {+ await smtp.close();+ }+ await assert.rejects(+ quietAsync(() => doctorCommon(relay(smtp.port), secrets)),+ (e: unknown) => e instanceof CliError && e.message.includes("is unreachable"),+ );+});+test("email preflight warns when SMTP values are set but the transport is resend", async () => {const config = { ...CONFIG, env: { auth: { AUTH_EMAIL_TRANSPORT: "resend" } } };const lines = await quietAsync(() =>diff --git a/knip.json b/knip.jsonindex 3564f74bc..9bb846a22 100644--- a/knip.json+++ b/knip.json@@ -47,6 +47,9 @@"entry": ["bin/qm.ts", "src/contract.ts"]},"plugins/*": {},+ "plugins/portal": {+ "ignoreDependencies": ["nodemailer"]+ },"plugins/web-ui": {"entry": ["src/shared-session.ts",diff --git a/package-lock.json b/package-lock.jsonindex 6edaeb526..b794bec2f 100644--- a/package-lock.json+++ b/package-lock.json@@ -38,6 +38,7 @@"jose": "^6.2.3","lru-cache": "^11.5.2","modal": "^0.10.1",+ "nodemailer": "^10.1.0","officeparser": "^8.0.0","pg": "^8.13.1","pg-boss": "^12.26.1",@@ -79,6 +80,9 @@"version": "0.1.6","dev": true,"license": "MIT",+ "dependencies": {+ "nodemailer": "^10.1.0"+ },"bin": {"qm": "dist/bin/qm.js"},@@ -7531,6 +7535,15 @@"node-gyp-build-test": "build-test.js"}},+ "node_modules/nodemailer": {+ "version": "10.1.0",+ "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.1.0.tgz",+ "integrity": "sha512-fXW8AulB25aOTuwfRYV6lqHyfz2VM4rr4SGXH03mE7x5znEUpzL5mu6anARUpZN7744Ziwkmr4AxSLPJsBQspg==",+ "license": "MIT-0",+ "engines": {+ "node": ">=20.0.0"+ }+ },"node_modules/non-error": {"version": "0.1.0","resolved": "https://registry.npmjs.org/non-error/-/non-error-0.1.0.tgz",diff --git a/package.json b/package.jsonindex 703d91842..088f2370e 100644--- a/package.json+++ b/package.json@@ -96,6 +96,7 @@"jose": "^6.2.3","lru-cache": "^11.5.2","modal": "^0.10.1",+ "nodemailer": "^10.1.0","officeparser": "^8.0.0","pg": "^8.13.1","pg-boss": "^12.26.1",diff --git a/plugins/auth/package-lock.json b/plugins/auth/package-lock.jsonindex 1669f44f3..03b3ee974 100644--- a/plugins/auth/package-lock.json+++ b/plugins/auth/package-lock.json@@ -9,7 +9,8 @@"version": "0.1.0","dependencies": {"@sentry/node": "10.75.0",- "jose": "^6.2.3"+ "jose": "^6.2.3",+ "nodemailer": "^10.1.0"},"devDependencies": {"@types/node": "^24.0.0",@@ -321,6 +322,15 @@"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==","license": "MIT"},+ "node_modules/nodemailer": {+ "version": "10.1.0",+ "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.1.0.tgz",+ "integrity": "sha512-fXW8AulB25aOTuwfRYV6lqHyfz2VM4rr4SGXH03mE7x5znEUpzL5mu6anARUpZN7744Ziwkmr4AxSLPJsBQspg==",+ "license": "MIT-0",+ "engines": {+ "node": ">=20.0.0"+ }+ },"node_modules/require-in-the-middle": {"version": "8.0.1","resolved": "https://registry.npmjs.org/require-in-the-middle/-/require-in-the-middle-8.0.1.tgz",diff --git a/plugins/auth/package.json b/plugins/auth/package.jsonindex 281803258..6ed3d1575 100644--- a/plugins/auth/package.json+++ b/plugins/auth/package.json@@ -19,6 +19,7 @@},"dependencies": {"@sentry/node": "10.75.0",- "jose": "^6.2.3"+ "jose": "^6.2.3",+ "nodemailer": "^10.1.0"}}diff --git a/plugins/auth/src/config.ts b/plugins/auth/src/config.tsindex 82171af98..89d2c63ce 100644--- a/plugins/auth/src/config.ts+++ b/plugins/auth/src/config.ts@@ -1,9 +1,10 @@-import type { SmtpTlsMode } from "./smtp.ts";import { isMissingOrPlaceholder } from "../../chassis/src/env.ts";import { parsePasswordHash } from "./password.ts";type EmailTransportKind = "resend" | "smtp";+type SmtpTlsMode = "starttls" | "implicit" | "none";+interface SmtpSettings {host: string;port: number;diff --git a/plugins/auth/src/email.ts b/plugins/auth/src/email.tsindex 745d1e2e1..28a1cbf77 100644--- a/plugins/auth/src/email.ts+++ b/plugins/auth/src/email.ts@@ -1,117 +1,39 @@-import { randomBytes } from "node:crypto";+import { createTransport } from "nodemailer";import { escapeHtml } from "../../chassis/src/http.ts";-import { emailConfigured, senderAddress, type AuthConfig } from "./config.ts";-import { smtpDeliver } from "./smtp.ts";+import { resendMailer, type Mailer, type OutgoingEmail } from "../../chassis/src/resend.ts";+import { emailConfigured, type AuthConfig } from "./config.ts";-export interface OutgoingEmail {- to: string;- subject: string;- text: string;- html: string;-}--export interface Mailer {- send(message: OutgoingEmail): Promise<string>;- verify(): Promise<string>;-}--const RESEND_ENDPOINT = "https://api.resend.com/emails";-const RESEND_VERIFY_ENDPOINT = "https://api.resend.com/domains";-const RESEND_TIMEOUT_MS = 15_000;--export function resendMailer(cfg: AuthConfig, fetchImpl: typeof fetch = fetch): Mailer {- const authorization = `Bearer ${cfg.resendApiKey}`;- return {- async send(message) {- const r = await fetchImpl(RESEND_ENDPOINT, {- method: "POST",- headers: { authorization, "content-type": "application/json" },- body: JSON.stringify({- from: cfg.emailFrom,- to: [message.to],- subject: message.subject,- text: message.text,- html: message.html,- }),- signal: AbortSignal.timeout(RESEND_TIMEOUT_MS),- });- const body = (await r.json().catch(() => ({}))) as { id?: string; message?: string; name?: string };- if (!r.ok)- throw new Error(`Resend rejected the message: HTTP ${r.status} ${body.message ?? body.name ?? ""}`.trim());- return body.id ?? "accepted";- },- async verify() {- const r = await fetchImpl(RESEND_VERIFY_ENDPOINT, {- headers: { authorization },- signal: AbortSignal.timeout(RESEND_TIMEOUT_MS),- });- if (r.status === 401 || r.status === 403) throw new Error("Resend rejected RESEND_API_KEY");- if (!r.ok) throw new Error(`Resend API returned HTTP ${r.status}`);- return "Resend API key accepted";- },- };-}+const SMTP_TIMEOUT_MS = 15_000;function smtpMailer(cfg: AuthConfig): Mailer {- const options = { ...cfg.smtp };- const from = senderAddress(cfg.emailFrom);+ const { host, port, username, password, tls } = cfg.smtp;+ const transport = createTransport({+ host,+ port,+ secure: tls === "implicit",+ requireTLS: tls === "starttls",+ ignoreTLS: tls === "none",+ auth: { user: username, pass: password },+ connectionTimeout: SMTP_TIMEOUT_MS,+ greetingTimeout: SMTP_TIMEOUT_MS,+ socketTimeout: SMTP_TIMEOUT_MS,+ });return {async send(message) {- return smtpDeliver(options, { from, to: message.to, data: renderMessage(cfg, message) });- },- async verify() {- return `SMTP ${cfg.smtp.host}:${cfg.smtp.port} ${await smtpDeliver(options, null)}`;+ const info = await transport.sendMail({+ from: cfg.emailFrom,+ ...message,+ textEncoding: "base64",+ headers: { "Auto-Submitted": "auto-generated" },+ });+ return info.response;},};}export function mailerFor(cfg: AuthConfig): Mailer | null {if (!emailConfigured(cfg)) return null;- return cfg.transport === "smtp" ? smtpMailer(cfg) : resendMailer(cfg);-}--function encodeHeader(value: string): string {- const clean = value.replace(/[\r\n]+/g, " ").trim();- return /^[\x20-\x7E]*$/.test(clean) ? clean : `=?UTF-8?B?${Buffer.from(clean, "utf8").toString("base64")}?=`;-}--function base64Body(value: string): string {- return (- Buffer.from(value.replace(/\r?\n/g, "\r\n"), "utf8")- .toString("base64")- .match(/.{1,76}/g) ?? []- ).join("\r\n");-}--export function renderMessage(cfg: AuthConfig, message: OutgoingEmail, nowMs = Date.now()): string {- const boundary = `qm-${randomBytes(12).toString("hex")}`;- const domain = senderAddress(cfg.emailFrom).split("@")[1] ?? "localhost";- const headers = [- `From: ${encodeHeader(cfg.emailFrom)}`,- `To: ${encodeHeader(message.to)}`,- `Subject: ${encodeHeader(message.subject)}`,- `Date: ${new Date(nowMs).toUTCString()}`,- `Message-ID: <${randomBytes(16).toString("hex")}@${domain}>`,- "MIME-Version: 1.0",- "Auto-Submitted: auto-generated",- `Content-Type: multipart/alternative; boundary="${boundary}"`,- ];- return [- headers.join("\r\n"),- "",- `--${boundary}`,- "Content-Type: text/plain; charset=utf-8",- "Content-Transfer-Encoding: base64",- "",- base64Body(message.text),- `--${boundary}`,- "Content-Type: text/html; charset=utf-8",- "Content-Transfer-Encoding: base64",- "",- base64Body(message.html),- `--${boundary}--`,- "",- ].join("\r\n");+ return cfg.transport === "smtp" ? smtpMailer(cfg) : resendMailer(cfg.resendApiKey, cfg.emailFrom);}export function renderSignInEmail(args: {diff --git a/plugins/auth/src/server.ts b/plugins/auth/src/server.tsindex 68c2124e2..87369df3d 100644--- a/plugins/auth/src/server.ts+++ b/plugins/auth/src/server.ts@@ -11,7 +11,8 @@ import { claimOnce, withinRateLimit, ClaimStoreUnavailableError, type ClaimStoreimport { coreEmailAllowed } from "../../chassis/src/external-members.ts";import { mintIdToken, pkceMatches, safeEqual, subjectFor, TokenSigner, type AuthRequest } from "./tokens.ts";import { ID_TOKEN_ALG, type SigningKey } from "./keys.ts";-import { renderSignInEmail, type Mailer } from "./email.ts";+import type { Mailer } from "../../chassis/src/resend.ts";+import { renderSignInEmail } from "./email.ts";import { confirmSignInPage, signInPage, linkSentPage, problemPage, CONFIRM_PAGE_CSP, PAGE_CSP } from "./pages.ts";const MAX_FORM_BYTES = 8 * 1024;diff --git a/plugins/auth/src/smtp.ts b/plugins/auth/src/smtp.tsdeleted file mode 100644index 6d7225feb..000000000--- a/plugins/auth/src/smtp.ts+++ /dev/null@@ -1,207 +0,0 @@-import { connect as netConnect, type Socket } from "node:net";-import { connect as tlsConnect } from "node:tls";--export type SmtpTlsMode = "starttls" | "implicit" | "none";--export interface SmtpOptions {- host: string;- port: number;- username: string;- password: string;- tls: SmtpTlsMode;- timeoutMs?: number;-}--interface SmtpReply {- code: number;- text: string;-}--export interface SmtpDelivery {- from: string;- to: string;- data: string;-}--const CRLF = "\r\n";--export function takeReply(buffer: string): { code: number; text: string; rest: string } | null {- const lines: string[] = [];- let cursor = 0;- for (;;) {- const end = buffer.indexOf(CRLF, cursor);- if (end === -1) return null;- const line = buffer.slice(cursor, end);- cursor = end + CRLF.length;- if (!/^\d{3}[ -]/.test(line)) return null;- lines.push(line.slice(4));- if (line[3] === " ") return { code: Number(line.slice(0, 3)), text: lines.join("\n"), rest: buffer.slice(cursor) };- }-}--export function dotStuff(data: string): string {- return data.replace(/\r\n/g, "\n").replace(/\n/g, CRLF).replace(/^\./gm, "..");-}--class SmtpSession {- private buffer = "";- private waiter: { resolve: (reply: SmtpReply) => void; reject: (e: Error) => void } | null = null;- private failure: Error | null = null;- private socket: Socket;- private readonly timeoutMs: number;-- constructor(socket: Socket, timeoutMs: number) {- this.socket = socket;- this.timeoutMs = timeoutMs;- this.attach(socket);- }-- private attach(socket: Socket): void {- socket.setTimeout(this.timeoutMs);- socket.on("data", (chunk: Buffer) => this.onData(chunk.toString("utf8")));- socket.on("error", (e: Error) => this.fail(e));- socket.on("timeout", () => this.fail(new Error("SMTP timed out")));- socket.on("close", () => this.fail(new Error("SMTP connection closed")));- }-- private detach(socket: Socket): void {- for (const event of ["data", "error", "timeout", "close"]) socket.removeAllListeners(event);- }-- private fail(e: Error): void {- this.failure ??= e;- const waiter = this.waiter;- this.waiter = null;- waiter?.reject(e);- }-- private onData(chunk: string): void {- this.buffer += chunk;- const reply = takeReply(this.buffer);- if (!reply) return;- this.buffer = reply.rest;- const waiter = this.waiter;- this.waiter = null;- waiter?.resolve({ code: reply.code, text: reply.text });- }-- private read(): Promise<SmtpReply> {- if (this.failure) return Promise.reject(this.failure);- return new Promise((resolve, reject) => {- this.waiter = { resolve, reject };- });- }-- async expect(expected: readonly number[], what: string): Promise<SmtpReply> {- const reply = await this.read();- if (!expected.includes(reply.code))- throw new Error(`SMTP ${what} rejected: ${reply.code} ${reply.text.split("\n")[0] ?? ""}`);- return reply;- }-- async command(- line: string,- expected: readonly number[],- label = line.split(" ")[0] ?? "command",- ): Promise<SmtpReply> {- this.socket.write(`${line}${CRLF}`);- return this.expect(expected, label);- }-- write(payload: string): void {- this.socket.write(payload);- }-- async upgrade(host: string): Promise<void> {- if (this.buffer.length > 0) throw new Error("SMTP server sent data before the TLS handshake, refusing to continue");- const plain = this.socket;- this.detach(plain);- const secure = tlsConnect({ socket: plain, servername: host }) as unknown as Socket;- secure.on("error", () => undefined);- await new Promise<void>((resolve, reject) => {- secure.once("secureConnect", () => resolve());- secure.once("error", reject);- });- this.socket = secure;- this.attach(secure);- }-- close(): void {- this.detach(this.socket);- this.socket.on("error", () => undefined);- this.socket.destroy();- }-}--async function openSocket(options: SmtpOptions, timeoutMs: number): Promise<Socket> {- const socket =- options.tls === "implicit"- ? (tlsConnect({ host: options.host, port: options.port, servername: options.host }) as unknown as Socket)- : netConnect({ host: options.host, port: options.port });- socket.on("error", () => undefined);- await new Promise<void>((resolve, reject) => {- const timer = setTimeout(- () => reject(new Error(`SMTP connect to ${options.host}:${options.port} timed out`)),- timeoutMs,- );- socket.once(options.tls === "implicit" ? "secureConnect" : "connect", () => {- clearTimeout(timer);- resolve();- });- socket.once("error", (e: Error) => {- clearTimeout(timer);- reject(e);- });- });- socket.removeAllListeners("error");- return socket;-}--function authSteps(mechanisms: string, username: string, password: string): string[] {- if (/\bPLAIN\b/.test(mechanisms))- return [`AUTH PLAIN ${Buffer.from(`\0${username}\0${password}`, "utf8").toString("base64")}`];- return [- "AUTH LOGIN",- Buffer.from(username, "utf8").toString("base64"),- Buffer.from(password, "utf8").toString("base64"),- ];-}--function clientName(host: string): string {- return /^[A-Za-z0-9.-]+$/.test(host) ? host : "localhost";-}--export async function smtpDeliver(options: SmtpOptions, delivery: SmtpDelivery | null): Promise<string> {- const timeoutMs = options.timeoutMs ?? 15_000;- const session = new SmtpSession(await openSocket(options, timeoutMs), timeoutMs);- try {- await session.expect([220], "greeting");- let ehlo = await session.command(`EHLO ${clientName(options.host)}`, [250]);- if (options.tls === "starttls") {- if (!/\bSTARTTLS\b/i.test(ehlo.text))- throw new Error("SMTP server does not offer STARTTLS, refusing to send credentials in cleartext");- await session.command("STARTTLS", [220]);- await session.upgrade(options.host);- ehlo = await session.command(`EHLO ${clientName(options.host)}`, [250]);- }- if (options.username || options.password) {- const steps = authSteps(ehlo.text, options.username, options.password);- for (const [index, step] of steps.entries()) {- await session.command(step, index === steps.length - 1 ? [235] : [334], "AUTH");- }- }- if (!delivery) {- await session.command("QUIT", [221]).catch(() => undefined);- return "authenticated";- }- await session.command(`MAIL FROM:<${delivery.from}>`, [250]);- await session.command(`RCPT TO:<${delivery.to}>`, [250, 251]);- await session.command("DATA", [354]);- session.write(`${dotStuff(delivery.data)}${CRLF}.${CRLF}`);- const accepted = await session.expect([250], "message");- await session.command("QUIT", [221]).catch(() => undefined);- return accepted.text.split("\n")[0] ?? "accepted";- } finally {- session.close();- }-}diff --git a/plugins/auth/test/email.test.ts b/plugins/auth/test/email.test.tsindex 86bcb8261..4b7363403 100644--- a/plugins/auth/test/email.test.ts+++ b/plugins/auth/test/email.test.ts@@ -1,7 +1,8 @@import test from "node:test";import assert from "node:assert/strict";import { readConfig } from "../src/config.ts";-import { mailerFor, renderMessage, renderSignInEmail, resendMailer } from "../src/email.ts";+import { resendMailer } from "../../chassis/src/resend.ts";+import { mailerFor, renderSignInEmail } from "../src/email.ts";import { testEnv } from "./helpers.ts";const cfg = readConfig(testEnv());@@ -52,51 +53,9 @@ test("the link is HTML-escaped so a crafted token cannot break out of the anchorassert.match(message.html, /<script>/);});-test("the MIME message is a well-formed multipart/alternative", () => {- const raw = renderMessage(- cfg,- { to: "[email protected]", subject: "Sign in to qm", text: "plain", html: "<p>rich</p>" },- Date.UTC(2026, 0, 2, 3, 4, 5),- );- const boundary = /boundary="([^"]+)"/.exec(raw)![1]!;- assert.match(raw, /^From: qm <no-reply@example\.com>\r\n/);- assert.match(raw, /\r\nTo: admin@example\.com\r\n/);- assert.match(raw, /\r\nDate: Fri, 02 Jan 2026 03:04:05 GMT\r\n/);- assert.match(raw, /\r\nMessage-ID: <[0-9a-f]{32}@example\.com>\r\n/);- assert.equal(raw.split(`--${boundary}`).length, 4);- assert.equal(- Buffer.from(- /text\/plain; charset=utf-8\r\nContent-Transfer-Encoding: base64\r\n\r\n([^\r]+)/.exec(raw)![1]!,- "base64",- ).toString("utf8"),- "plain",- );- assert.ok(raw.endsWith(`--${boundary}--\r\n`));-});--test("header injection through the subject or recipient is neutralised", () => {- const raw = renderMessage(cfg, {- to: "[email protected]\r\nBcc: [email protected]",- subject: "Sign in\r\nBcc: [email protected]",- text: "plain",- html: "<p>rich</p>",- });- const headers = raw.split("\r\n\r\n")[0]!.split("\r\n");- assert.deepEqual(- headers.map((line) => line.split(":")[0]),- ["From", "To", "Subject", "Date", "Message-ID", "MIME-Version", "Auto-Submitted", "Content-Type"],- "a CRLF in a header value must not fold into a new header line",- );-});--test("a non-ASCII subject is RFC 2047 encoded", () => {- const raw = renderMessage(cfg, { to: "[email protected]", subject: "Se connecter à qm", text: "x", html: "<p>x</p>" });- assert.match(raw, /\r\nSubject: =\?UTF-8\?B\?[A-Za-z0-9+/=]+\?=\r\n/);-});-test("the Resend transport reports the provider's message id and surfaces refusals", async () => {const calls: Array<{ url: string; init: RequestInit }> = [];- const ok = resendMailer(cfg, (async (url: string, init: RequestInit) => {+ const ok = resendMailer(cfg.resendApiKey, cfg.emailFrom, (async (url: string, init: RequestInit) => {calls.push({ url, init });return new Response(JSON.stringify({ id: "re_123" }), {status: 200,@@ -106,10 +65,17 @@ test("the Resend transport reports the provider's message id and surfaces refusaassert.equal(await ok.send({ to: "[email protected]", subject: "s", text: "t", html: "<p>h</p>" }), "re_123");assert.equal(calls[0]!.url, "https://api.resend.com/emails");assert.equal((calls[0]!.init.headers as Record<string, string>).authorization, "Bearer re_test_key");- assert.deepEqual((JSON.parse(String(calls[0]!.init.body)) as { to: string[] }).to, ["[email protected]"]);+ assert.deepEqual(JSON.parse(String(calls[0]!.init.body)), {+ from: "qm <[email protected]>",+ to: ["[email protected]"],+ subject: "s",+ text: "t",+ html: "<p>h</p>",+ });const refused = resendMailer(- cfg,+ cfg.resendApiKey,+ cfg.emailFrom,(async () =>new Response(JSON.stringify({ message: "domain not verified" }), {status: 403,@@ -120,7 +86,4 @@ test("the Resend transport reports the provider's message id and surfaces refusa() => refused.send({ to: "[email protected]", subject: "s", text: "t", html: "h" }),/domain not verified/,);-- const badKey = resendMailer(cfg, (async () => new Response("{}", { status: 401 })) as unknown as typeof fetch);- await assert.rejects(() => badKey.verify(), /rejected RESEND_API_KEY/);});diff --git a/plugins/auth/test/helpers.ts b/plugins/auth/test/helpers.tsindex 9b9af431d..15bd7fd16 100644--- a/plugins/auth/test/helpers.ts+++ b/plugins/auth/test/helpers.ts@@ -3,7 +3,7 @@ import { createServer, type Server } from "node:http";import { createHash, generateKeyPairSync, randomBytes } from "node:crypto";import { emailConfigured, readConfig, type AuthConfig } from "../src/config.ts";import type { ClaimStore } from "../../chassis/src/claims.ts";-import type { Mailer, OutgoingEmail } from "../src/email.ts";+import type { Mailer, OutgoingEmail } from "../../chassis/src/resend.ts";import { loadSigningKey } from "../src/keys.ts";import { TokenSigner } from "../src/tokens.ts";import { createAuthHandler } from "../src/server.ts";@@ -74,9 +74,6 @@ export function captureMailer(): Mailer & { sent: OutgoingEmail[]; failNext: boostate.sent.push(message);return "test-message-id";},- async verify(): Promise<string> {- return "ok";- },};return state;}diff --git a/plugins/auth/test/smtp.test.ts b/plugins/auth/test/smtp.test.tsindex 2975f8859..934eb2577 100644--- a/plugins/auth/test/smtp.test.ts+++ b/plugins/auth/test/smtp.test.ts@@ -1,7 +1,9 @@import test from "node:test";import assert from "node:assert/strict";import { createServer, type Server, type Socket } from "node:net";-import { dotStuff, smtpDeliver, takeReply } from "../src/smtp.ts";+import { readConfig } from "../src/config.ts";+import { mailerFor, renderSignInEmail } from "../src/email.ts";+import { testEnv } from "./helpers.ts";interface FakeSmtp {port: number;@@ -70,84 +72,102 @@ async function fakeSmtp(};}-const options = (port: number, over: Record<string, unknown> = {}) => ({- host: "127.0.0.1",- port,- username: "apikey",- password: "s3cret",- tls: "none" as const,- timeoutMs: 4000,- ...over,-});+function smtpMailer(port: number, overrides: Record<string, string> = {}) {+ const mailer = mailerFor(+ readConfig(+ testEnv({+ AUTH_EMAIL_TRANSPORT: "smtp",+ SMTP_HOST: "127.0.0.1",+ SMTP_PORT: String(port),+ SMTP_TLS: "none",+ SMTP_USERNAME: "apikey",+ SMTP_PASSWORD: "s3cret",+ ...overrides,+ }),+ ),+ );+ assert.ok(mailer);+ return mailer;+}-test("takeReply reassembles a multi-line reply and leaves the remainder", () => {- const reply = takeReply("250-one\r\n250 two\r\n334 next\r\n");- assert.deepEqual(reply, { code: 250, text: "one\ntwo", rest: "334 next\r\n" });- assert.equal(takeReply("250-partial\r\n"), null);- assert.equal(takeReply("garbage\r\n"), null);-});+function part(raw: string, type: string): string {+ const body = new RegExp(+ `Content-Type: ${type}; charset=utf-8\nContent-Transfer-Encoding: base64\n\n([A-Za-z0-9+/=\n]+)`,+ ).exec(raw);+ assert.ok(body, `no base64 ${type} part`);+ return Buffer.from(body[1]!.replaceAll("\n", ""), "base64").toString("utf8");+}-test("dotStuff escapes a leading dot and normalises line endings", () => {- assert.equal(dotStuff("a\n.b\nc"), "a\r\n..b\r\nc");- assert.equal(dotStuff("a\r\n.\r\nb"), "a\r\n..\r\nb");+function headerNames(raw: string): string[] {+ return raw+ .split("\n\n")[0]!+ .split("\n")+ .filter((line) => !/^\s/.test(line))+ .map((line) => line.split(":")[0]!);+}++const signIn = renderSignInEmail({+ to: "[email protected]",+ brandName: "qm",+ link: "https://agent.example.test/idp/verify#token=abc.def.ghi",+ ttlMinutes: 15,});-test("a message is delivered over the full SMTP conversation", async (t) => {+test("the sign-in email is delivered as multipart/alternative over the full SMTP conversation", async (t) => {const server = await fakeSmtp();t.after(() => server.close());- const receipt = await smtpDeliver(options(server.port), {- from: "[email protected]",- to: "[email protected]",- data: "Subject: hi\r\n\r\n.leading dot survives",- });+ const receipt = await smtpMailer(server.port).send(signIn);assert.match(receipt, /queued as FAKE1/);assert.deepEqual(- server.transcript.map((line) => line.split(" ")[0]),- ["EHLO", "AUTH", "MAIL", "RCPT", "DATA", "QUIT"],+ server.transcript.slice(0, 5).map((line) => line.split(" ")[0]),+ ["EHLO", "AUTH", "MAIL", "RCPT", "DATA"],);- assert.match(server.transcript[1]!, /^AUTH PLAIN /);assert.equal(Buffer.from(server.transcript[1]!.slice("AUTH PLAIN ".length), "base64").toString("utf8"),"\0apikey\0s3cret",);- assert.match(server.messages[0]!, /^\.leading dot survives$/m);+ assert.equal(server.transcript[2], "MAIL FROM:<[email protected]>");+ assert.equal(server.transcript[3], "RCPT TO:<[email protected]>");+ const raw = server.messages[0]!;+ assert.match(raw, /^From: qm <no-reply@example\.com>$/m);+ assert.match(raw, /^To: admin@example\.com$/m);+ assert.match(raw, /^Subject: Sign in to qm$/m);+ assert.match(raw, /^Auto-Submitted: auto-generated$/m);+ assert.match(raw, /^Message-ID: <[^>]+@example\.com>$/m);+ assert.match(raw, /^Content-Type: multipart\/alternative;/m);+ assert.equal(part(raw, "text/plain"), signIn.text);+ assert.equal(part(raw, "text/html"), signIn.html);+});++test("a CRLF in the subject cannot add a header and a non-ASCII subject is RFC 2047 encoded", async (t) => {+ const server = await fakeSmtp();+ t.after(() => server.close());+ const mailer = smtpMailer(server.port);+ await mailer.send({ ...signIn, subject: "Sign in\r\nBcc: [email protected]" });+ await mailer.send({ ...signIn, subject: "Se connecter à qm" });+ assert.ok(!headerNames(server.messages[0]!).includes("Bcc"));+ assert.deepEqual(+ server.transcript.filter((line) => line.startsWith("RCPT")),+ ["RCPT TO:<[email protected]>", "RCPT TO:<[email protected]>"],+ );+ const subject = /^Subject: (.+)$/m.exec(server.messages[1]!)![1]!;+ assert.match(subject, /^=\?UTF-8\?[BQ]\?[\x21-\x7e]+\?=$/);});test("a rejected recipient and rejected credentials both surface as errors", async (t) => {const rejecting = await fakeSmtp({ rejectRecipient: true });t.after(() => rejecting.close());- await assert.rejects(- () =>- smtpDeliver(options(rejecting.port), {- from: "[email protected]",- to: "[email protected]",- data: "Subject: hi\r\n\r\nbody",- }),- /SMTP RCPT rejected: 550/,- );+ await assert.rejects(() => smtpMailer(rejecting.port).send(signIn), /550 5\.1\.1 no such user/);const unauthorized = await fakeSmtp({ rejectAuth: true });t.after(() => unauthorized.close());- await assert.rejects(() => smtpDeliver(options(unauthorized.port), null), /SMTP AUTH rejected: 535/);-});--test("verification authenticates without sending a message", async (t) => {- const server = await fakeSmtp();- t.after(() => server.close());- assert.equal(await smtpDeliver(options(server.port), null), "authenticated");- assert.deepEqual(- server.transcript.map((line) => line.split(" ")[0]),- ["EHLO", "AUTH", "QUIT"],- );- assert.equal(server.messages.length, 0);+ await assert.rejects(() => smtpMailer(unauthorized.port).send(signIn), /535 5\.7\.8 bad credentials/);+ assert.equal(unauthorized.messages.length, 0);});-test("STARTTLS mode refuses a server that does not advertise STARTTLS", async (t) => {+test("STARTTLS mode refuses a server that does not advertise STARTTLS before sending credentials", async (t) => {const server = await fakeSmtp({ offerStartTls: false });t.after(() => server.close());- await assert.rejects(() => smtpDeliver(options(server.port, { tls: "starttls" }), null), /does not offer STARTTLS/);-});--test("a connection refusal is reported rather than hanging", async () => {- await assert.rejects(() => smtpDeliver(options(1, { timeoutMs: 2000 }), null));+ await assert.rejects(() => smtpMailer(server.port, { SMTP_TLS: "starttls" }).send(signIn), /STARTTLS/);+ assert.ok(!server.transcript.some((line) => line.startsWith("AUTH")));});diff --git a/plugins/chassis/src/resend.ts b/plugins/chassis/src/resend.tsnew file mode 100644index 000000000..7adb2a0e3--- /dev/null+++ b/plugins/chassis/src/resend.ts@@ -0,0 +1,36 @@+export interface OutgoingEmail {+ to: string;+ subject: string;+ text: string;+ html: string;+}++export interface Mailer {+ send(message: OutgoingEmail): Promise<string>;+}++const RESEND_ENDPOINT = "https://api.resend.com/emails";+const RESEND_TIMEOUT_MS = 15_000;++export function resendMailer(apiKey: string, from: string, fetchImpl: typeof fetch = fetch): Mailer {+ return {+ async send(message) {+ const r = await fetchImpl(RESEND_ENDPOINT, {+ method: "POST",+ headers: { authorization: `Bearer ${apiKey}`, "content-type": "application/json" },+ body: JSON.stringify({+ from,+ to: [message.to],+ subject: message.subject,+ text: message.text,+ html: message.html,+ }),+ signal: AbortSignal.timeout(RESEND_TIMEOUT_MS),+ });+ const body = (await r.json().catch(() => ({}))) as { id?: string; message?: string; name?: string };+ if (!r.ok)+ throw new Error(`Resend rejected the message: HTTP ${r.status} ${body.message ?? body.name ?? ""}`.trim());+ return body.id ?? "accepted";+ },+ };+}diff --git a/plugins/portal/package-lock.json b/plugins/portal/package-lock.jsonindex 8957db40b..2f322d89c 100644--- a/plugins/portal/package-lock.json+++ b/plugins/portal/package-lock.json@@ -10,7 +10,8 @@"dependencies": {"@sentry/node": "10.75.0","jose": "^6.2.3",- "lru-cache": "^11.5.2"+ "lru-cache": "^11.5.2",+ "nodemailer": "^10.1.0"},"devDependencies": {"@types/node": "^24.0.0",@@ -331,6 +332,15 @@"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==","license": "MIT"},+ "node_modules/nodemailer": {+ "version": "10.1.0",+ "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.1.0.tgz",+ "integrity": "sha512-fXW8AulB25aOTuwfRYV6lqHyfz2VM4rr4SGXH03mE7x5znEUpzL5mu6anARUpZN7744Ziwkmr4AxSLPJsBQspg==",+ "license": "MIT-0",+ "engines": {+ "node": ">=20.0.0"+ }+ },"node_modules/require-in-the-middle": {"version": "8.0.1","resolved": "https://registry.npmjs.org/require-in-the-middle/-/require-in-the-middle-8.0.1.tgz",diff --git a/plugins/portal/package.json b/plugins/portal/package.jsonindex 5325e93b2..10cc19142 100644--- a/plugins/portal/package.json+++ b/plugins/portal/package.json@@ -19,6 +19,7 @@"dependencies": {"@sentry/node": "10.75.0","jose": "^6.2.3",- "lru-cache": "^11.5.2"+ "lru-cache": "^11.5.2",+ "nodemailer": "^10.1.0"}}diff --git a/src/admin/invite-email.ts b/src/admin/invite-email.tsindex 2a18a8a06..cd1a27b50 100644--- a/src/admin/invite-email.ts+++ b/src/admin/invite-email.ts@@ -1,38 +1,8 @@import { escapeHtml } from "../../plugins/chassis/src/http.ts";-export interface InviteMailer {- send(message: { to: string; subject: string; text: string; html: string }): Promise<string>;-}-export const INVITE_EMAIL_NOT_CONFIGURED ="invitation emails are not configured — set RESEND_API_KEY and AUTH_EMAIL_FROM on core (the same Resend key and verified sender the sign-in broker uses)";-const RESEND_ENDPOINT = "https://api.resend.com/emails";-const RESEND_TIMEOUT_MS = 15_000;--export function createResendMailer(apiKey: string, from: string, fetchImpl: typeof fetch = fetch): InviteMailer {- return {- async send(message) {- const r = await fetchImpl(RESEND_ENDPOINT, {- method: "POST",- headers: { authorization: `Bearer ${apiKey}`, "content-type": "application/json" },- body: JSON.stringify({- from,- to: [message.to],- subject: message.subject,- text: message.text,- html: message.html,- }),- signal: AbortSignal.timeout(RESEND_TIMEOUT_MS),- });- const body = (await r.json().catch(() => ({}))) as { id?: string; message?: string; name?: string };- if (!r.ok)- throw new Error(`Resend rejected the message: HTTP ${r.status} ${body.message ?? body.name ?? ""}`.trim());- return body.id ?? "accepted";- },- };-}-export function renderInviteEmail(a: {to: string;brandName: string;diff --git a/src/api/app-types.ts b/src/api/app-types.tsindex 2cab2140d..7357c8b31 100644--- a/src/api/app-types.ts+++ b/src/api/app-types.ts@@ -1,6 +1,6 @@import type { TeamStore } from "../teams/teams.ts";import type { ExternalSlackPolicies } from "../resolution/external-slack.ts";-import type { InviteMailer } from "../admin/invite-email.ts";+import type { Mailer } from "../../plugins/chassis/src/resend.ts";import type { DeploymentInvitation } from "../deploy/email-access.ts";import type { AdmittedWork } from "../util/admitted-work.ts";import type { EventBus } from "../util/event-bus.ts";@@ -638,7 +638,7 @@ export interface AppDeps {swarms?: SwarmService;identity: IdentityService;publicWebUrl?: string;- inviteMailer?: InviteMailer;+ inviteMailer?: Mailer;sessions: SessionStore;screenSecurity?: SecurityScreenProbe;orchestrator: Orchestrator;diff --git a/src/api/deps.ts b/src/api/deps.tsindex fb214fa72..67aa61f4e 100644--- a/src/api/deps.ts+++ b/src/api/deps.ts@@ -35,7 +35,7 @@ import type { BrokerFetch } from "./credential-broker.ts";import type { GitHttpFetch } from "./git-http-broker.ts";import type { KeychainApprovals } from "../credentials/keychain-approval.ts";import type { AdminService } from "../admin/admin-service.ts";-import type { InviteMailer } from "../admin/invite-email.ts";+import type { Mailer } from "../../plugins/chassis/src/resend.ts";import type { SessionStore } from "../sessions/session-store.ts";import type { SecurityScreenProbe } from "../security/security-screener.ts";import type { AuditLog } from "../audit/audit-log.ts";@@ -147,7 +147,7 @@ export interface ServerDeps {harnessId?: string;harnessCarriedModelAuth?: ModelProvider;admin?: AdminService;- inviteMailer?: InviteMailer;+ inviteMailer?: Mailer;emailAuthPrincipals?: readonly string[];emailAuthDomain?: string;slackAllowFrom?: readonly string[];diff --git a/src/loops/sources/gmail.ts b/src/loops/sources/gmail.tsindex 8348c7214..7f4192236 100644--- a/src/loops/sources/gmail.ts+++ b/src/loops/sources/gmail.ts@@ -1,3 +1,4 @@+import MailComposer from "nodemailer/lib/mail-composer";import type { LoopItem, LoopSourcePayload } from "../../types.ts";import { isAccountType } from "../../connectors/oauth.ts";import { errMessage } from "../../util/errors.ts";@@ -60,23 +61,6 @@ function titleOf(item: LoopItem): string {return clip(item.sourcePayload?.title, 300) ?? "";}-function b64(bytes: Uint8Array): string {- return Buffer.from(bytes).toString("base64");-}--function isAscii(s: string): boolean {- return /^[\x20-\x7e]*$/.test(s);-}--function headerValue(s: string): string {- if (isAscii(s)) return s;- return `=?UTF-8?B?${b64(new TextEncoder().encode(s))}?=`;-}--function wrap76(s: string): string {- return s.replace(/(.{76})/g, "$1\r\n").replace(/\r\n$/, "");-}-export function replySubject(item: LoopItem, draft: ReplyDraft): string {const explicit = draft.subject?.trim();if (explicit) return explicit;@@ -85,28 +69,24 @@ export function replySubject(item: LoopItem, draft: ReplyDraft): string {return /^re:/i.test(original) ? original : `Re: ${original}`;}-export function buildGmailReplyMime(item: LoopItem, draft: ReplyDraft): string | null {+export async function buildGmailReplyMime(item: LoopItem, draft: ReplyDraft): Promise<Buffer | null> {const meta = metaOf(item);if (!meta) return null;const parsed = parseReplyDraft(draft);if (!parsed) return null;- draft = parsed;- const to = draft.to ?? meta.to ?? [];+ const to = parsed.to ?? meta.to ?? [];if (to.length === 0) return null;- const cc = draft.cc ?? meta?.cc ?? [];- const rfcId = meta?.rfcMessageId;- const lines = [- `To: ${to.join(", ")}`,- ...(cc.length ? [`Cc: ${cc.join(", ")}`] : []),- `Subject: ${headerValue(replySubject(item, draft))}`,- ...(rfcId ? [`In-Reply-To: ${rfcId}`, `References: ${rfcId}`] : []),- "MIME-Version: 1.0",- 'Content-Type: text/plain; charset="UTF-8"',- "Content-Transfer-Encoding: base64",- "",- wrap76(b64(new TextEncoder().encode(draft.body))),- ];- return lines.join("\r\n");+ const rfcId = meta.rfcMessageId;+ return new MailComposer({+ to,+ cc: parsed.cc ?? meta.cc ?? [],+ subject: replySubject(item, parsed),+ ...(rfcId ? { inReplyTo: rfcId, references: rfcId } : {}),+ text: parsed.body,+ textEncoding: "base64",+ })+ .compile()+ .build();}async function sendGmail(deps: SourceActionDeps, item: LoopItem, draft: ReplyDraft): Promise<SourceActionResult> {@@ -118,7 +98,7 @@ async function sendGmail(deps: SourceActionDeps, item: LoopItem, draft: ReplyDra? await deps.tokens.connectorAccessToken(GMAIL_HOST, deps.owner, accountType): await tokenFor(deps.tokens, GMAIL_HOST, deps.owner);if (!token) return { ok: false, reason: "not_connected", message: "Google is not connected for this account" };- const mime = buildGmailReplyMime(item, draft);+ const mime = await buildGmailReplyMime(item, draft);if (!mime) return { ok: false, reason: "bad_item", message: "no recipient — add a To: address to the draft" };const threadId = metaOf(item)?.threadId;const res = await fetchImpl(`https://${GMAIL_HOST}/gmail/v1/users/me/messages/send`, {@@ -126,7 +106,7 @@ async function sendGmail(deps: SourceActionDeps, item: LoopItem, draft: ReplyDrasignal: AbortSignal.timeout(30000),headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },body: JSON.stringify({- raw: Buffer.from(mime, "utf8").toString("base64url"),+ raw: mime.toString("base64url"),...(threadId ? { threadId } : {}),}),});diff --git a/src/wiring.ts b/src/wiring.tsindex a3b6b30b2..632cd7ec0 100644--- a/src/wiring.ts+++ b/src/wiring.ts@@ -86,7 +86,7 @@ import {import type { SlackAccountLink, ComposioReturn } from "./api/routes/composio.ts";import { installPrincipalLinks } from "./directory/person.ts";import type { ExternalMember } from "./identity/external-members.ts";-import { createResendMailer } from "./admin/invite-email.ts";+import { resendMailer } from "../plugins/chassis/src/resend.ts";import {createMemoryConfigStore,type ScopedConfigStore,@@ -2130,7 +2130,7 @@ export function buildApp(...(config.publicWebUrl ? { publicWebUrl: config.publicWebUrl } : {}),...(config.deployAppsDomain ? { deployAppsDomain: config.deployAppsDomain } : {}),...(config.resendApiKey && config.emailFrom- ? { inviteMailer: createResendMailer(config.resendApiKey, config.emailFrom) }+ ? { inviteMailer: resendMailer(config.resendApiKey, config.emailFrom) }: {}),...(config.publicUrl ? { webhookPublicUrl: config.publicUrl } : {}),memoryPolicy: { recall: config.memoryRecall, capture: config.memoryCapture },@@ -3155,7 +3155,7 @@ export function serverDeps(...(config.emailAuthDomain ? { emailAuthDomain: config.emailAuthDomain } : {}),...(config.slack ? { slackAllowFrom: config.slack.allowFrom ?? [] } : {}),...(config.resendApiKey && config.emailFrom- ? { inviteMailer: createResendMailer(config.resendApiKey, config.emailFrom) }+ ? { inviteMailer: resendMailer(config.resendApiKey, config.emailFrom) }: {}),rateLimiter: built.rateLimiter,acl: built.acl,diff --git a/test/admin-external-users.test.ts b/test/admin-external-users.test.tsindex 4540ba2e1..886b68b00 100644--- a/test/admin-external-users.test.ts+++ b/test/admin-external-users.test.ts@@ -11,7 +11,8 @@ import { join } from "node:path";import type { AddressInfo } from "node:net";import { createInsecureTestServer, createServer } from "../src/api/server.ts";import { buildApp } from "../src/wiring.ts";-import { INVITE_EMAIL_NOT_CONFIGURED, renderInviteEmail, type InviteMailer } from "../src/admin/invite-email.ts";+import { INVITE_EMAIL_NOT_CONFIGURED, renderInviteEmail } from "../src/admin/invite-email.ts";+import type { Mailer } from "../plugins/chassis/src/resend.ts";import { adminStatusFromGrants } from "../src/admin/admin-service.ts";import { coreEmailAdmission, coreEmailAllowed } from "../plugins/chassis/src/external-members.ts";import { mintCapabilityToken, CAPABILITY_TTL_MS, CONTROL_PLANE_AUD } from "../src/auth/capability-token.ts";@@ -27,7 +28,7 @@ const DAY_MS = 24 * 60 * 60 * 1000;type Sent = { to: string; subject: string; text: string; html: string };-function stubMailer(fail?: string): { sent: Sent[]; mailer: InviteMailer } {+function stubMailer(fail?: string): { sent: Sent[]; mailer: Mailer } {const sent: Sent[] = [];return {sent,@@ -42,7 +43,7 @@ function stubMailer(fail?: string): { sent: Sent[]; mailer: InviteMailer } {}function start(- opts: { mailer?: InviteMailer; signed?: boolean; emailAuthDomain?: string; emailAuthPrincipals?: string[] } = {},+ opts: { mailer?: Mailer; signed?: boolean; emailAuthDomain?: string; emailAuthPrincipals?: string[] } = {},) {const built = buildApp(testConfig({diff --git a/test/loop-source-send.test.ts b/test/loop-source-send.test.tsindex 68a2f2ad2..7c98db6de 100644--- a/test/loop-source-send.test.ts+++ b/test/loop-source-send.test.ts@@ -60,26 +60,27 @@ function slackSpy(fail?: string): { calls: SlackCall[]; factory: (token: string)};}-test("gmail reply MIME threads correctly and survives a UTF-8 body", () => {- const mime = buildGmailReplyMime(gmailItem, { body: "Confirmed — see attached. ✅" })!;- assert.match(mime, /^To: ada@example\.com\r\n/);- assert.match(mime, /Subject: Re: Quarterly numbers\r\n/);- assert.match(mime, /In-Reply-To: <msg-1@mail>\r\n/);- assert.match(mime, /References: <msg-1@mail>\r\n/);+test("gmail reply MIME threads correctly and survives a UTF-8 body", async () => {+ const mime = (await buildGmailReplyMime(gmailItem, { body: "Confirmed — see attached. ✅" }))!.toString();+ assert.match(mime, /^To: ada@example\.com\r$/m);+ assert.match(mime, /^Subject: Re: Quarterly numbers\r$/m);+ assert.match(mime, /^In-Reply-To: <msg-1@mail>\r$/m);+ assert.match(mime, /^References: <msg-1@mail>\r$/m);const body = mime.split("\r\n\r\n")[1]!;assert.equal(Buffer.from(body.replaceAll("\r\n", ""), "base64").toString("utf8"), "Confirmed — see attached. ✅");});-test("subjects keep an existing Re: and non-ASCII subjects get RFC 2047 encoding", () => {+test("subjects keep an existing Re: and non-ASCII subjects get RFC 2047 encoding", async () => {assert.equal(replySubject(item("gmail", { gmail: { threadId: "t", subject: "RE: hello" } }), { body: "x" }),"RE: hello",);assert.equal(replySubject(gmailItem, { body: "x", subject: "Override" }), "Override");- const mime = buildGmailReplyMime(item("gmail", { gmail: { threadId: "t", subject: "café plans", to: ["[email protected]"] } }), {- body: "x",- })!;- assert.match(mime, /Subject: =\?UTF-8\?B\?/);+ const mime = (await buildGmailReplyMime(+ item("gmail", { gmail: { threadId: "t", subject: "café plans", to: ["[email protected]"] } }),+ { body: "x" },+ ))!.toString();+ assert.match(mime, /^Subject: =\?UTF-8\?[BQ]\?[\x21-\x7e]+\?=\r$/m);});test("a gmail item with no recipient anywhere refuses to send", async () => {@@ -133,8 +134,7 @@ test("the held proposal is what goes out when the action carries no draft", asyn{},);assert.equal(result.ok, true);- const encoded = sent.split("\r\n\r\n")[1]!;- assert.equal(Buffer.from(encoded, "base64").toString("utf8"), "the held draft");+ assert.equal(sent.split("\r\n\r\n")[1], "the held draft\r\n");});test("a missing connector reads as not_connected, not an exception", async () => {@@ -425,9 +425,9 @@ test("Gmail sends only through the explicitly bound account, including legacy setest("Gmail drafts preserve recipient lists and reject invalid recipients without falling back", async () => {const addresses = Array.from({ length: 15 }, (_, i) => `person${i}@example.com`);- const mime = buildGmailReplyMime(gmailItem, { body: "Hi", to: addresses, cc: [] })!;- assert.ok(mime.startsWith(`To: ${addresses.join(", ")}\r\n`));- assert.equal(buildGmailReplyMime(gmailItem, { body: "Hi", to: [] }), null);+ const mime = (await buildGmailReplyMime(gmailItem, { body: "Hi", to: addresses, cc: [] }))!.toString();+ assert.ok(mime.replaceAll("\r\n ", " ").startsWith(`To: ${addresses.join(", ")}\r\n`));+ assert.equal(await buildGmailReplyMime(gmailItem, { body: "Hi", to: [] }), null);const held = { ...gmailItem, proposal: { data: { body: "Previously saved" }, by: "human" as const, at: 1 } };for (const to of [["x".repeat(8001)], Array(101).fill("[email protected]"), ["[email protected]\nBcc: [email protected]"]]) {assert.equal(gmailAdapter.parseProposal({ body: "Hi", to }), null);diff --git a/test/sent-chat.test.ts b/test/sent-chat.test.tsindex 248306a3f..ded2912eb 100644--- a/test/sent-chat.test.ts+++ b/test/sent-chat.test.ts@@ -183,8 +183,8 @@ test("sent chat preserves long quoted recipient headers and rejects oversized inawait ensureSentChat(ctx);assert.equal(status, 200);const stored = (await items.get(id))!;- const mime = buildGmailReplyMime(stored, { body: "Hello" })!;- assert.ok(mime.startsWith(`To: ${to}\r\nCc: ${cc}\r\n`));+ const mime = (await buildGmailReplyMime(stored, { body: "Hello" }))!.toString();+ assert.ok(mime.replaceAll("\r\n ", " ").startsWith(`To: ${to}\r\nCc: ${cc}\r\n`));for (const invalid of [{ to: "x".repeat(8001) },{ cc: "x".repeat(8001) },