Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

qm check: verify Fly sandbox token, SMTP credentials, and Node engine before deploy (#27)

Regan Bell783715c714e7
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 27543f8ca..37c20c81a 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -17,6 +17,7 @@ import { runSetup } from "./commands/setup.ts";
import { buildAwsMicrovmImage, deleteAwsMicrovmImage, deleteAwsTaskDefinitions } from "./commands/infra.ts";
import { runSandboxBuild } from "./commands/sandbox.ts";
import { runChecks, runCheckCommand } from "./commands/check.ts";
+import { assertNodeEngine } from "./preflight.ts";
import { devCiDown, devCiUp } from "./backends/dev-ci.ts";
import { hostingProvider, hostingProviderUpFlags, type DeployContext } from "./backends/registry.ts";
import { runConformance } from "./commands/conformance.ts";
@@ -110,7 +111,8 @@ ${bold("DEPLOY (operator)")} ${dim("— runs in the deployment directory")}
--build-from[=<qm-repo>] build from local Dockerfiles instead of pulling
--dry-run resolve the config + report the plan, change nothing
plan an alias for up --dry-run
- check validate config + sandbox/ (skills & tools); no build, no network
+ check validate config + sandbox/ (skills & tools); no build; verifies
+ provider credentials whose values are present locally
--json machine-readable results keyed by contract clause
--live verify running identity, rendered config, and health
doctor verify deployment prerequisites read-only
@@ -300,6 +302,7 @@ async function dispatch(argv: string[]): Promise<void> {
rejectUnknownFlags(flags, ["json", "live", "config", "env-file", "sandbox-dir", "target"]);
rejectExtraPositionals(positionals, 0);
const ctx = deployContext(flags);
+ assertNodeEngine(ctx.configDir);
const result = runChecks(ctx.config, ctx.configDir, ctx.sandboxDir, { report: false });
if (boolFlag(flags, "live")) {
const checkLive = deploymentBackend(ctx).checkLive;
@@ -360,11 +363,11 @@ async function dispatch(argv: string[]): Promise<void> {
const checkLive = deploymentBackend(ctx).checkLive;
if (!checkLive)
throw new CliError(`check --live is not implemented for target ${ctx.target}`, { clause: "cli.invocation" });
- runCheckCommand(ctx.config, ctx.configDir, ctx.sandboxDir);
+ await runCheckCommand(ctx.config, ctx.configDir, ctx.sandboxDir, ctx.envFile);
await checkLive();
return;
}
- runCheckCommand(ctx.config, ctx.configDir, ctx.sandboxDir);
+ await runCheckCommand(ctx.config, ctx.configDir, ctx.sandboxDir, ctx.envFile);
return;
}
diff --git a/cli/src/commands/check.ts b/cli/src/commands/check.ts
index fa258e337..c1b23cff6 100644
--- a/cli/src/commands/check.ts
+++ b/cli/src/commands/check.ts
@@ -1,5 +1,7 @@
import { existsSync, statSync } from "node:fs";
-import { relative, resolve } from "node:path";
+import { join, relative, resolve } from "node:path";
+import { assertNodeEngine, emailTransportPreflight, flySandboxTokenPreflight } from "../preflight.ts";
+import { readEnvFile } from "../util.ts";
import { CliError, errMessage, header, note, ok, step, warn } from "../log.ts";
import { validateSandboxLayer, type SandboxValidation } from "../sandbox-layer.ts";
import { discoverPlugins, type ResolvedPlugin } from "../plugins.ts";
@@ -165,9 +167,18 @@ export function runChecks(
return { layer, plugins, secrets };
}
-export function runCheckCommand(config: QmConfig, configDir: string, sandboxDir: string): void {
+export async function runCheckCommand(
+ config: QmConfig,
+ configDir: string,
+ sandboxDir: string,
+ envFile?: string,
+): Promise<void> {
header(`qm check — ${config.orgId}`);
+ assertNodeEngine(configDir);
runChecks(config, configDir, sandboxDir, { report: true });
+ const secrets = readEnvFile(envFile ?? join(configDir, ".env"));
+ await flySandboxTokenPreflight(config, secrets);
+ await emailTransportPreflight(config, secrets);
note("");
ok("check passed — config, sandbox layer, and plugins are valid.");
}
diff --git a/cli/src/commands/init.ts b/cli/src/commands/init.ts
index 3b704a435..f1cbddfd1 100644
--- a/cli/src/commands/init.ts
+++ b/cli/src/commands/init.ts
@@ -12,6 +12,7 @@ import {
type QmConfig,
} from "../config.ts";
import { die, note, ok, warn } from "../log.ts";
+import { assertNodeEngine } from "../preflight.ts";
import { cliPackageName, cliVersion } from "../manifest.ts";
import { computedSecrets, renderEnvExample } from "../secrets.ts";
import { renderSlackManifests, usesSlackOidc } from "../slack-manifests.ts";
@@ -65,8 +66,9 @@ Copy its shape, then replace or delete it.
Run every command from this directory.
1. \`npm exec qm -- check\` validates the config and the sandbox layer and prints the
- secret names the config currently requires. It builds nothing and touches no
- network, so run it after every edit.
+ secret names the config currently requires. It builds nothing, and when
+ credential values are already present in \`.env\` it also verifies them
+ against their providers, so run it after every edit.
2. \`npm exec qm -- plan\` reports what deployment would do
without changing anything.
3. After the target prerequisites are complete, \`npm exec qm -- up\` brings the
@@ -255,6 +257,7 @@ function scaffoldDeploymentSkill(dir: string): void {
}
export function runInit(opts: { org?: string; target?: Target; modelProvider?: ModelProvider; dir?: string }): void {
+ assertNodeEngine();
const orgId = opts.org ?? "default-org";
if (!validOrgId(orgId)) die(`--org must be a lowercase DNS label (a-z, 0-9, and hyphens between)`);
const dir = opts.dir ?? process.cwd();
diff --git a/cli/src/preflight.ts b/cli/src/preflight.ts
new file mode 100644
index 000000000..63b3268a9
--- /dev/null
+++ b/cli/src/preflight.ts
@@ -0,0 +1,306 @@
+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 type { QmConfig } from "./config.ts";
+import { CliError, errMessage, step, warn } from "./log.ts";
+import { deploymentSecretValue } from "./util.ts";
+
+const PROBE_TIMEOUT_MS = 10_000;
+
+function versionParts(version: string): number[] {
+ return version
+ .replace(/^v/, "")
+ .split(".")
+ .map((part) => Number.parseInt(part, 10) || 0);
+}
+
+function versionAtLeast(actual: string, minimum: string): boolean {
+ const a = versionParts(actual);
+ const b = versionParts(minimum);
+ for (let i = 0; i < Math.max(a.length, b.length); i++) {
+ const delta = (a[i] ?? 0) - (b[i] ?? 0);
+ if (delta !== 0) return delta > 0;
+ }
+ return true;
+}
+
+function enginesNodeSpec(packagePath: string): string | undefined {
+ if (!existsSync(packagePath)) return undefined;
+ try {
+ const parsed = JSON.parse(readFileSync(packagePath, "utf8")) as { engines?: { node?: string } };
+ return parsed.engines?.node;
+ } catch {
+ return undefined;
+ }
+}
+
+function cliPackagePath(): string {
+ const direct = fileURLToPath(new URL("../package.json", import.meta.url));
+ return existsSync(direct) ? direct : fileURLToPath(new URL("../../package.json", import.meta.url));
+}
+
+export function nodeEngineProblem(spec: string, source: string, nodeVersion = process.version): string | undefined {
+ const minimums = [...spec.matchAll(/>=\s*v?(\d+(?:\.\d+){0,2})/g)].map((match) => match[1]!);
+ for (const minimum of minimums) {
+ if (!versionAtLeast(nodeVersion, minimum)) {
+ return (
+ `Node ${nodeVersion} does not satisfy "node": ${JSON.stringify(spec)} required by ${source} — ` +
+ `install Node >=${minimum} (e.g. \`nvm install ${minimum.split(".")[0]}\`) and rerun`
+ );
+ }
+ }
+ return undefined;
+}
+
+export function assertNodeEngine(deploymentDir?: string): void {
+ const sources = [
+ { path: cliPackagePath(), source: "the qm CLI package" },
+ ...(deploymentDir ? [{ path: join(deploymentDir, "package.json"), source: "this deployment directory" }] : []),
+ ];
+ for (const { path, source } of sources) {
+ const spec = enginesNodeSpec(path);
+ if (!spec) continue;
+ const problem = nodeEngineProblem(spec, `${source} (${path})`);
+ if (problem) throw new CliError(problem, { clause: "cli.node-engine" });
+ }
+}
+
+export async function flySandboxTokenPreflight(
+ config: QmConfig,
+ secrets: ReadonlyMap<string, string>,
+ fetchImpl: typeof fetch = fetch,
+): Promise<void> {
+ const app = config.sandbox?.app?.trim();
+ if (!app) return;
+ const token = deploymentSecretValue("FLY_SANDBOX_API_TOKEN", secrets.get("FLY_SANDBOX_API_TOKEN"))?.trim();
+ if (!token) return;
+ let response: Response;
+ try {
+ response = await fetchImpl(`https://api.machines.dev/v1/apps/${encodeURIComponent(app)}`, {
+ headers: { authorization: token.startsWith("FlyV1") ? token : `Bearer ${token}` },
+ signal: AbortSignal.timeout(PROBE_TIMEOUT_MS),
+ });
+ } catch (e) {
+ warn(`could not verify FLY_SANDBOX_API_TOKEN against Fly app ${app}: ${errMessage(e)} — continuing`);
+ return;
+ }
+ if (response.status === 401 || response.status === 403 || response.status === 404) {
+ throw new CliError(
+ `FLY_SANDBOX_API_TOKEN cannot access the Fly app ${app} (HTTP ${response.status}) — the app may not exist ` +
+ `or the token is scoped elsewhere. Create the app and mint an app-scoped deploy token:\n` +
+ ` fly apps create ${app}${config.flyOrg ? ` --org ${config.flyOrg}` : ""}\n` +
+ ` fly tokens create deploy -a ${app} -x 8760h`,
+ { clause: "sandbox.fly-token" },
+ );
+ }
+ if (!response.ok) {
+ warn(`the Fly API returned HTTP ${response.status} while verifying FLY_SANDBOX_API_TOKEN — continuing`);
+ return;
+ }
+ step(`Fly sandbox app ${app}: FLY_SANDBOX_API_TOKEN ok`);
+}
+
+type SmtpTlsMode = "starttls" | "implicit" | "none";
+
+export interface SmtpVerifyOptions {
+ host: string;
+ port: number;
+ username: string;
+ password: string;
+ tls: SmtpTlsMode;
+ timeoutMs?: number;
+}
+
+export class SmtpRejectedError extends Error {}
+
+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 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();
+ }
+}
+
+export async function emailTransportPreflight(config: QmConfig, secrets: ReadonlyMap<string, string>): Promise<void> {
+ if (!config.services.includes("auth")) return;
+ const transport = config.env.auth?.AUTH_EMAIL_TRANSPORT?.trim() === "smtp" ? "smtp" : "resend";
+ const value = (name: string): string | undefined => deploymentSecretValue(name, secrets.get(name))?.trim();
+ if (transport === "resend") {
+ const stray = ["SMTP_HOST", "SMTP_USERNAME", "SMTP_PASSWORD"].filter((name) => value(name));
+ if (stray.length) {
+ warn(
+ `${stray.join(", ")} ${stray.length === 1 ? "is" : "are"} set but env.auth.AUTH_EMAIL_TRANSPORT is "resend" — ` +
+ `the value${stray.length === 1 ? " is" : "s are"} unused; remove ${stray.length === 1 ? "it" : "them"} or set the transport to "smtp"`,
+ );
+ }
+ return;
+ }
+ if (value("RESEND_API_KEY")) {
+ warn(
+ 'RESEND_API_KEY is set but env.auth.AUTH_EMAIL_TRANSPORT is "smtp" — the value is unused; ' +
+ 'remove it or set the transport to "resend"',
+ );
+ }
+ const host = value("SMTP_HOST");
+ const username = value("SMTP_USERNAME");
+ const password = value("SMTP_PASSWORD");
+ if (!host || !username || !password) return;
+ const port = Number(config.env.auth?.SMTP_PORT ?? 587);
+ const tls = smtpTlsMode(config.env.auth?.SMTP_TLS, port);
+ try {
+ await smtpVerify({ host, port, username, password, tls });
+ } catch (e) {
+ if (e instanceof SmtpRejectedError) {
+ throw new CliError(
+ `${errMessage(e)} — ${host}:${port} refused the SMTP_USERNAME/SMTP_PASSWORD credentials; ` +
+ `sign-in links cannot be sent until they are fixed`,
+ { clause: "auth.smtp-credentials" },
+ );
+ }
+ warn(`could not verify the SMTP credentials against ${host}:${port}: ${errMessage(e)} — continuing`);
+ return;
+ }
+ step(`SMTP relay ${host}:${port}: credentials accepted`);
+}
diff --git a/cli/test/preflight.test.ts b/cli/test/preflight.test.ts
new file mode 100644
index 000000000..cc1a73cee
--- /dev/null
+++ b/cli/test/preflight.test.ts
@@ -0,0 +1,201 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { createServer, type Server, type Socket } from "node:net";
+import type { QmConfig } from "../src/config.ts";
+import { CliError } from "../src/log.ts";
+import {
+ emailTransportPreflight,
+ flySandboxTokenPreflight,
+ nodeEngineProblem,
+ smtpVerify,
+ SmtpRejectedError,
+} from "../src/preflight.ts";
+
+const CONFIG: QmConfig = {
+ contract: 1,
+ orgId: "acme",
+ publicUrl: "http://localhost:8080",
+ target: "docker",
+ services: ["core", "auth"],
+ plugins: [],
+ skills: [],
+ env: {},
+ imageOverrides: {},
+ sandbox: { app: "acme-sandboxes" },
+};
+
+async function quietAsync(fn: () => Promise<void>): Promise<string[]> {
+ const lines: string[] = [];
+ const log = console.log,
+ warnFn = console.warn;
+ console.log = (...args: unknown[]): void => void lines.push(args.join(" "));
+ console.warn = (...args: unknown[]): void => void lines.push(args.join(" "));
+ try {
+ await fn();
+ return lines;
+ } finally {
+ console.log = log;
+ console.warn = warnFn;
+ }
+}
+
+test("nodeEngineProblem accepts a satisfying version and rejects an older one", () => {
+ assert.equal(nodeEngineProblem(">=24.15.0", "package.json", "v24.15.0"), undefined);
+ assert.equal(nodeEngineProblem(">=24.0.0", "package.json", "v24.13.0"), undefined);
+ const problem = nodeEngineProblem(">=24.15.0", "the repo package.json", "v24.13.0");
+ assert.ok(problem?.includes("v24.13.0"));
+ assert.ok(problem?.includes(">=24.15.0"));
+ assert.ok(problem?.includes("the repo package.json"));
+});
+
+test("fly sandbox preflight fails with the exact fix when the token cannot reach the app", async () => {
+ const secrets = new Map([["FLY_SANDBOX_API_TOKEN", "fm2_dead"]]);
+ const fetchImpl = (async () => new Response("not found", { status: 404 })) as typeof fetch;
+ await assert.rejects(
+ () => flySandboxTokenPreflight({ ...CONFIG, flyOrg: "personal" }, secrets, fetchImpl),
+ (e: unknown) => {
+ assert.ok(e instanceof CliError);
+ assert.ok(e.message.includes("fly apps create acme-sandboxes --org personal"));
+ assert.ok(e.message.includes("fly tokens create deploy -a acme-sandboxes"));
+ return true;
+ },
+ );
+});
+
+test("fly sandbox preflight passes a live token and skips when no token is present", async () => {
+ const fetchImpl = (async () => new Response("{}", { status: 200 })) as typeof fetch;
+ const lines = await quietAsync(() =>
+ flySandboxTokenPreflight(CONFIG, new Map([["FLY_SANDBOX_API_TOKEN", "fm2_ok"]]), fetchImpl),
+ );
+ assert.ok(lines.some((line) => line.includes("FLY_SANDBOX_API_TOKEN ok")));
+ const skipped = await quietAsync(() =>
+ flySandboxTokenPreflight(CONFIG, new Map(), (async () => {
+ throw new Error("must not be called");
+ }) as typeof fetch),
+ );
+ assert.deepEqual(skipped, []);
+});
+
+test("fly sandbox preflight warns instead of failing when the Fly API is unreachable", async () => {
+ const fetchImpl = (async () => {
+ throw new Error("network is down");
+ }) as typeof fetch;
+ const lines = await quietAsync(() =>
+ flySandboxTokenPreflight(CONFIG, new Map([["FLY_SANDBOX_API_TOKEN", "fm2_x"]]), fetchImpl),
+ );
+ assert.ok(lines.some((line) => line.includes("could not verify FLY_SANDBOX_API_TOKEN")));
+});
+
+interface FakeSmtp {
+ server: Server;
+ port: number;
+ close: () => Promise<void>;
+}
+
+function fakeSmtp(password: string): Promise<FakeSmtp> {
+ const server = createServer((socket: Socket) => {
+ socket.write("220 fake ESMTP\r\n");
+ let buffer = "";
+ socket.on("data", (chunk: Buffer) => {
+ buffer += chunk.toString("utf8");
+ let index: number;
+ while ((index = buffer.indexOf("\r\n")) !== -1) {
+ const line = buffer.slice(0, index);
+ buffer = buffer.slice(index + 2);
+ if (line.startsWith("EHLO")) socket.write("250-fake\r\n250 AUTH PLAIN LOGIN\r\n");
+ else if (line.startsWith("AUTH PLAIN")) {
+ const decoded = Buffer.from(line.slice("AUTH PLAIN ".length), "base64").toString("utf8");
+ socket.write(decoded === `\0user\0${password}` ? "235 ok\r\n" : "535 auth failed\r\n");
+ } else if (line === "QUIT") {
+ socket.write("221 bye\r\n");
+ socket.end();
+ } else socket.write("502 what\r\n");
+ }
+ });
+ });
+ return new Promise((resolve) => {
+ server.listen(0, "127.0.0.1", () => {
+ const address = server.address();
+ resolve({
+ server,
+ port: typeof address === "object" && address ? address.port : 0,
+ close: () => new Promise((done) => server.close(() => done())),
+ });
+ });
+ });
+}
+
+test("smtpVerify authenticates without sending mail and rejects bad credentials", async () => {
+ const smtp = await fakeSmtp("right");
+ try {
+ await smtpVerify({ host: "127.0.0.1", port: smtp.port, username: "user", password: "right", tls: "none" });
+ await assert.rejects(
+ () => smtpVerify({ host: "127.0.0.1", port: smtp.port, username: "user", password: "wrong", tls: "none" }),
+ SmtpRejectedError,
+ );
+ } finally {
+ await smtp.close();
+ }
+});
+
+test("email preflight fails check on rejected SMTP credentials and warns on stray transport vars", async () => {
+ const smtp = await fakeSmtp("right");
+ const config = {
+ ...CONFIG,
+ env: { auth: { AUTH_EMAIL_TRANSPORT: "smtp", SMTP_PORT: String(smtp.port), SMTP_TLS: "none" } },
+ };
+ try {
+ const okLines = await quietAsync(() =>
+ emailTransportPreflight(
+ config,
+ new Map([
+ ["SMTP_HOST", "127.0.0.1"],
+ ["SMTP_USERNAME", "user"],
+ ["SMTP_PASSWORD", "right"],
+ ["RESEND_API_KEY", "re_unused"],
+ ]),
+ ),
+ );
+ assert.ok(okLines.some((line) => line.includes("credentials accepted")));
+ assert.ok(okLines.some((line) => line.includes("RESEND_API_KEY is set but")));
+ await assert.rejects(
+ () =>
+ emailTransportPreflight(
+ config,
+ new Map([
+ ["SMTP_HOST", "127.0.0.1"],
+ ["SMTP_USERNAME", "user"],
+ ["SMTP_PASSWORD", "wrong"],
+ ]),
+ ),
+ (e: unknown) => {
+ assert.ok(e instanceof CliError);
+ assert.ok(e.message.includes("sign-in links cannot be sent"));
+ return true;
+ },
+ );
+ } finally {
+ await smtp.close();
+ }
+});
+
+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(() =>
+ emailTransportPreflight(
+ config,
+ new Map([
+ ["SMTP_HOST", "smtp.example.com"],
+ ["SMTP_PASSWORD", "hunter2"],
+ ]),
+ ),
+ );
+ assert.ok(lines.some((line) => line.includes('set but env.auth.AUTH_EMAIL_TRANSPORT is "resend"')));
+});
+
+test("email preflight does nothing without the auth service", async () => {
+ const lines = await quietAsync(() =>
+ emailTransportPreflight({ ...CONFIG, services: ["core"] }, new Map([["RESEND_API_KEY", "re_x"]])),
+ );
+ assert.deepEqual(lines, []);
+});