Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

feat(email): verify the SMTP connection and send an admin test email

Tin4ef0b38431df
diff --git a/packages/email/src/index.tsx b/packages/email/src/index.tsx
index 4cb16e7e4..f70a0437d 100644
--- a/packages/email/src/index.tsx
+++ b/packages/email/src/index.tsx
@@ -7,10 +7,16 @@ export {
sendNotificationEmail,
sendOtpEmail,
sendPasswordResetEmail,
+ sendTestEmail,
sendTrialReminderEmail,
sendWorkspaceInvitationEmail,
} from "./send-email";
export { isSmtpConfigured } from "./smtp-config";
+export { getSmtpErrorDetails } from "./smtp-error-details";
+export {
+ type SmtpVerification,
+ verifySmtpConnection,
+} from "./verify-smtp-connection";
export type { BoardColumnIcon } from "./components/board-column";
export type {
TaskCardDueStatus,
diff --git a/packages/email/src/send-email.tsx b/packages/email/src/send-email.tsx
index 7fe1949a7..a1d3750d9 100644
--- a/packages/email/src/send-email.tsx
+++ b/packages/email/src/send-email.tsx
@@ -18,6 +18,7 @@ import NotificationEmail, {
} from "./templates/notification";
import type { OtpEmailProps } from "./templates/otp";
import OtpEmail from "./templates/otp";
+import TestEmail, { type TestEmailProps } from "./templates/test-email";
import PasswordResetEmail, {
type PasswordResetEmailProps,
} from "./templates/password-reset";
@@ -227,3 +228,28 @@ export const sendEmailVerificationEmail = (
subject,
EmailVerificationEmail({ email: to, instance: instanceHost(), ...data }),
);
+
+/**
+ * Send the administrator's SMTP test. It throws the SMTP error itself so the
+ * caller can tell the administrator what went wrong.
+ */
+export const sendTestEmail = async (
+ to: string,
+ subject: string,
+ data: Omit<TestEmailProps, "email" | "instance">,
+): Promise<EmailResult> => {
+ if (!isSmtpConfigured()) {
+ return { success: false, reason: "SMTP_NOT_CONFIGURED" };
+ }
+
+ const emailTemplate = await render(
+ TestEmail({ email: to, instance: instanceHost(), ...data }),
+ );
+ await transporter.sendMail({
+ from: process.env.SMTP_FROM,
+ to,
+ subject,
+ html: emailTemplate,
+ });
+ return { success: true };
+};
diff --git a/packages/email/src/smtp-transport.test.ts b/packages/email/src/smtp-transport.test.ts
index 2f04347e5..82e167ba8 100644
--- a/packages/email/src/smtp-transport.test.ts
+++ b/packages/email/src/smtp-transport.test.ts
@@ -1,66 +1,7 @@
-import { once } from "node:events";
-import { createServer, type Socket } from "node:net";
import * as nodemailer from "nodemailer";
import { describe, expect, it } from "vite-plus/test";
import { getSmtpTransportOptions } from "./smtp-config";
-
-// A loopback-only SMTP sink: never forwards mail or connects to a real provider.
-async function createPlaintextRelay() {
- const commands: string[] = [];
- const sockets = new Set<Socket>();
- const server = createServer((socket) => {
- sockets.add(socket);
- socket.on("close", () => sockets.delete(socket));
- socket.write("220 localhost test relay\r\n");
- let pending = "";
- let inData = false;
- socket.on("data", (chunk) => {
- pending += chunk.toString();
- let end = pending.indexOf("\r\n");
- while (end >= 0) {
- const line = pending.slice(0, end);
- pending = pending.slice(end + 2);
- if (inData) {
- if (line === ".") {
- inData = false;
- socket.write("250 accepted\r\n");
- }
- } else {
- commands.push(line);
- if (line.startsWith("EHLO")) {
- socket.write("250-localhost\r\n250 AUTH PLAIN\r\n");
- } else if (line === "STARTTLS") {
- socket.write("502 TLS unavailable\r\n");
- } else if (line.startsWith("AUTH")) {
- socket.write("235 authenticated\r\n");
- } else if (line === "DATA") {
- inData = true;
- socket.write("354 start mail\r\n");
- } else if (line === "QUIT") {
- socket.end("221 bye\r\n");
- } else {
- socket.write("250 OK\r\n");
- }
- }
- end = pending.indexOf("\r\n");
- }
- });
- });
- server.listen(0, "127.0.0.1");
- await once(server, "listening");
- const address = server.address();
- if (!address || typeof address === "string") throw new Error("No relay port");
- return {
- commands,
- port: address.port,
- async close() {
- for (const socket of sockets) socket.destroy();
- await new Promise<void>((resolve, reject) =>
- server.close((error) => (error ? reject(error) : resolve())),
- );
- },
- };
-}
+import { createPlaintextRelay } from "./test-support/smtp-relay";
describe("SMTP transport encryption", () => {
it.each([false, true])(
diff --git a/packages/email/src/templates/test-email.test.ts b/packages/email/src/templates/test-email.test.ts
new file mode 100644
index 000000000..b6750b535
--- /dev/null
+++ b/packages/email/src/templates/test-email.test.ts
@@ -0,0 +1,20 @@
+import { render } from "@react-email/render";
+import { createElement } from "react";
+import { describe, expect, it } from "vite-plus/test";
+import TestEmail from "./test-email";
+
+describe("TestEmail", () => {
+ it("names the recipient and instance without any links into Kaneo", async () => {
+ const html = await render(
+ createElement(TestEmail, {
+ email: "[email protected]",
+ instance: "kaneo.example.com",
+ }),
+ );
+
+ expect(html).toContain("Your email settings work");
+ expect(html).toContain("[email protected]");
+ expect(html).toContain("kaneo.example.com");
+ expect(html).not.toMatch(/href="https?:\/\/kaneo\.example\.com/);
+ });
+});
diff --git a/packages/email/src/templates/test-email.tsx b/packages/email/src/templates/test-email.tsx
new file mode 100644
index 000000000..2566c5366
--- /dev/null
+++ b/packages/email/src/templates/test-email.tsx
@@ -0,0 +1,50 @@
+import React from "react";
+import { EmailFooter } from "../components/email-footer";
+import { EmailIntro } from "../components/email-intro";
+import { EmailNote } from "../components/email-note";
+import { EmailShell } from "../components/email-shell";
+import { footerLinks } from "../components/footer-links";
+import {
+ type RequestContext,
+ RequestDetails,
+} from "../components/request-details";
+
+void React;
+
+// Only instance administrators receive this diagnostic, so it stays English.
+export type TestEmailProps = Pick<
+ RequestContext,
+ "email" | "instance" | "requestedAt"
+>;
+
+const copy = {
+ preview: "Outgoing email from your Kaneo instance is working.",
+ title: "Your email settings work",
+ subtitle:
+ "An administrator sent this test from the System page. If you can read it, your Kaneo instance can deliver email.",
+ noteTitle: "Nothing else to do",
+ note: "You can delete this email. It contains no links and changes nothing in Kaneo.",
+ footer: "Kaneo test email",
+};
+
+const TestEmail = ({ email, instance, requestedAt }: TestEmailProps) => (
+ <EmailShell title={copy.title} preview={copy.preview} lang="en">
+ <EmailIntro title={copy.title} subtitle={copy.subtitle} />
+ <RequestDetails
+ locale="en"
+ email={email}
+ instance={instance}
+ requestedAt={requestedAt}
+ />
+ <EmailNote title={copy.noteTitle}>{copy.note}</EmailNote>
+ <EmailFooter title={copy.footer} links={footerLinks("en")} />
+ </EmailShell>
+);
+
+TestEmail.PreviewProps = {
+ email: "[email protected]",
+ instance: "kaneo.example.com",
+ requestedAt: "2026-10-26T09:30:00.000Z",
+} as TestEmailProps;
+
+export default TestEmail;
diff --git a/packages/email/src/test-support/smtp-relay.ts b/packages/email/src/test-support/smtp-relay.ts
new file mode 100644
index 000000000..0de4c8c04
--- /dev/null
+++ b/packages/email/src/test-support/smtp-relay.ts
@@ -0,0 +1,60 @@
+import { once } from "node:events";
+import { createServer, type Socket } from "node:net";
+
+// A loopback-only SMTP sink: never forwards mail or connects to a real provider.
+export async function createPlaintextRelay() {
+ const commands: string[] = [];
+ const sockets = new Set<Socket>();
+ const server = createServer((socket) => {
+ sockets.add(socket);
+ socket.on("close", () => sockets.delete(socket));
+ socket.write("220 localhost test relay\r\n");
+ let pending = "";
+ let inData = false;
+ socket.on("data", (chunk) => {
+ pending += chunk.toString();
+ let end = pending.indexOf("\r\n");
+ while (end >= 0) {
+ const line = pending.slice(0, end);
+ pending = pending.slice(end + 2);
+ if (inData) {
+ if (line === ".") {
+ inData = false;
+ socket.write("250 accepted\r\n");
+ }
+ } else {
+ commands.push(line);
+ if (line.startsWith("EHLO")) {
+ socket.write("250-localhost\r\n250 AUTH PLAIN\r\n");
+ } else if (line === "STARTTLS") {
+ socket.write("502 TLS unavailable\r\n");
+ } else if (line.startsWith("AUTH")) {
+ socket.write("235 authenticated\r\n");
+ } else if (line === "DATA") {
+ inData = true;
+ socket.write("354 start mail\r\n");
+ } else if (line === "QUIT") {
+ socket.end("221 bye\r\n");
+ } else {
+ socket.write("250 OK\r\n");
+ }
+ }
+ end = pending.indexOf("\r\n");
+ }
+ });
+ });
+ server.listen(0, "127.0.0.1");
+ await once(server, "listening");
+ const address = server.address();
+ if (!address || typeof address === "string") throw new Error("No relay port");
+ return {
+ commands,
+ port: address.port,
+ async close() {
+ for (const socket of sockets) socket.destroy();
+ await new Promise<void>((resolve, reject) =>
+ server.close((error) => (error ? reject(error) : resolve())),
+ );
+ },
+ };
+}
diff --git a/packages/email/src/verify-smtp-connection.test.ts b/packages/email/src/verify-smtp-connection.test.ts
new file mode 100644
index 000000000..f10bd0c0a
--- /dev/null
+++ b/packages/email/src/verify-smtp-connection.test.ts
@@ -0,0 +1,69 @@
+import { once } from "node:events";
+import { createServer, type Socket } from "node:net";
+import { describe, expect, it } from "vite-plus/test";
+import { createPlaintextRelay } from "./test-support/smtp-relay";
+import { verifySmtpConnection } from "./verify-smtp-connection";
+
+const plaintextEnv = (port: number) => ({
+ SMTP_HOST: "127.0.0.1",
+ SMTP_PORT: String(port),
+ SMTP_FROM: "[email protected]",
+ SMTP_SECURE: "false",
+ SMTP_REQUIRE_TLS: "false",
+});
+
+describe("verifySmtpConnection", () => {
+ it("reports a missing host or sender as not configured", async () => {
+ await expect(
+ verifySmtpConnection(1000, { SMTP_HOST: "smtp.example.test" }),
+ ).resolves.toEqual({ status: "not_configured" });
+ });
+
+ it("connects to the relay without sending mail", async () => {
+ const relay = await createPlaintextRelay();
+ try {
+ await expect(
+ verifySmtpConnection(1000, plaintextEnv(relay.port)),
+ ).resolves.toEqual({ status: "ok" });
+ expect(
+ relay.commands.some((line) => /^(MAIL|RCPT|DATA)/.test(line)),
+ ).toBe(false);
+ } finally {
+ await relay.close();
+ }
+ });
+
+ it("gives up on a server that never answers within the timeout", async () => {
+ const sockets = new Set<Socket>();
+ const silent = createServer((socket) => sockets.add(socket));
+ silent.listen(0, "127.0.0.1");
+ await once(silent, "listening");
+ const address = silent.address();
+ if (!address || typeof address === "string") throw new Error("No port");
+ const started = Date.now();
+ try {
+ const result = await verifySmtpConnection(
+ 200,
+ plaintextEnv(address.port),
+ );
+ expect(result).toMatchObject({ status: "failed" });
+ expect(Date.now() - started).toBeLessThan(2000);
+ } finally {
+ for (const socket of sockets) socket.destroy();
+ silent.close();
+ }
+ });
+
+ it("only reports the error category, never the server's message", async () => {
+ const result = await verifySmtpConnection(500, {
+ ...plaintextEnv(1),
+ SMTP_PASSWORD: "super-secret-password",
+ SMTP_USER: "someone",
+ });
+ expect(result).toMatchObject({ status: "failed" });
+ expect(JSON.stringify(result)).not.toContain("super-secret-password");
+ expect(Object.keys(result).sort()).toEqual(
+ expect.arrayContaining(["code", "status"]),
+ );
+ });
+});
diff --git a/packages/email/src/verify-smtp-connection.ts b/packages/email/src/verify-smtp-connection.ts
new file mode 100644
index 000000000..5dea44066
--- /dev/null
+++ b/packages/email/src/verify-smtp-connection.ts
@@ -0,0 +1,39 @@
+import * as nodemailer from "nodemailer";
+import { getSmtpTransportOptions, isSmtpConfigured } from "./smtp-config";
+import { getSmtpErrorDetails } from "./smtp-error-details";
+
+export type SmtpVerification =
+ | { status: "not_configured" }
+ | { status: "ok" }
+ | { status: "failed"; code: string; responseCode?: number };
+
+/**
+ * Open a connection to the SMTP server, authenticate if credentials are set,
+ * and close it again without sending anything. Every phase is bounded by
+ * `timeoutMs` so a dead relay can't hold the caller. Failures only report the
+ * nodemailer error category and SMTP status, never the server's message.
+ */
+export async function verifySmtpConnection(
+ timeoutMs: number,
+ env: Record<string, string | undefined> = process.env,
+): Promise<SmtpVerification> {
+ if (!isSmtpConfigured(env)) {
+ return { status: "not_configured" };
+ }
+
+ let transport: nodemailer.Transporter | undefined;
+ try {
+ transport = nodemailer.createTransport({
+ ...getSmtpTransportOptions(env),
+ connectionTimeout: timeoutMs,
+ greetingTimeout: timeoutMs,
+ socketTimeout: timeoutMs,
+ });
+ await transport.verify();
+ return { status: "ok" };
+ } catch (error) {
+ return { status: "failed", ...getSmtpErrorDetails(error) };
+ } finally {
+ transport?.close();
+ }
+}
diff --git a/packages/email/tsconfig.json b/packages/email/tsconfig.json
index 29444f944..3d405fc56 100644
--- a/packages/email/tsconfig.json
+++ b/packages/email/tsconfig.json
@@ -30,5 +30,10 @@
"noImplicitAny": true
},
"include": ["src"],
- "exclude": ["node_modules", "src/**/*.test.ts", "src/**/*.test.tsx"]
+ "exclude": [
+ "node_modules",
+ "src/**/*.test.ts",
+ "src/**/*.test.tsx",
+ "src/test-support"
+ ]
}