Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Email: sending works with any provider, and says why when it doesn't (#4696)
Milind Sonid602f986086d
diff --git a/server/drivers/agents-call.ts b/server/drivers/agents-call.tsindex e67e0e90c8..1f728c75ec 100644--- a/server/drivers/agents-call.ts+++ b/server/drivers/agents-call.ts@@ -904,7 +904,7 @@ async function requestEmailCard(args: Json, context: ToolCallContext): Promise<Tbody: JSON.stringify({ fromBotId: context.botId, fromThreadId: context.threadId, credentialId: EMAIL_CREDENTIAL, address: args.address, reason: args.reason }),});if (!r.ok) return { text: String(r.body.error ?? `request_credential failed (HTTP ${r.status}).`), isError: true };- if (r.body.alreadyConfigured === true) return { text: `${String(r.body.label)} is already connected. Use the email tools.` };+ if (r.body.alreadyConfigured === true) return { text: typeof r.body.text === "string" ? r.body.text : `${String(r.body.label)} is already connected. Use the email tools.` };return { text: "A secure card for the mailbox is ready in OpenMausBot, on the computer and on a freshly QR-paired phone. End this turn now and say in one line that you are waiting for it; OpenMausBot resumes you when the person connects it or declines." };}diff --git a/server/email/client.ts b/server/email/client.tsindex cf86799e84..4d4d971800 100644--- a/server/email/client.ts+++ b/server/email/client.ts@@ -10,8 +10,9 @@ import { isIP } from "node:net";import type { EmailAccount, EmailServer } from "./store.ts";export class EmailError extends Error {- /** `password`: the server refused the sign-in. `network`: no answer, or no valid TLS. `server`: it answered no. */- readonly code: "password" | "network" | "server" | "refused" | "not-found" | "too-big";+ /** `password`: the server refused the sign-in. `network`: no answer, or no valid TLS. `server`: it answered no.+ * `sending`: the outgoing server, which says why in a SendingError. */+ readonly code: "password" | "network" | "server" | "refused" | "not-found" | "too-big" | "sending";constructor(code: EmailError["code"], message: string) {super(message);this.name = "EmailError";@@ -112,21 +113,110 @@ export async function testMailbox(account: Pick<EmailAccount, "username" | "pass});}-/** Whether this server sends with this password; nothing is sent. */-export async function testSending(account: Pick<EmailAccount, "username" | "password">, server: EmailServer, guard: EmailGuard): Promise<void> {- const transport = await smtpTransport(account, server, guard);- try { await transport.verify(); } catch (error) { throw failure(error); } finally { transport.close(); }+/** Why an outgoing server can't send: `missing` no such name; `no-answer` nothing answered on that port; `wrong-security`+ * it speaks TLS the other way on that port (from the first byte, or upgraded with STARTTLS); `certificate` its+ * certificate isn't valid for the name; `no-tls` no secure connection on offer; `no-sign-in` no sign-in on offer;+ * `password` it refused the sign-in; `refused` not a place this host may reach; `rejected` it refused a message's+ * sender or recipients; `server` any other no. */+export type SendingFault = "missing" | "no-answer" | "wrong-security" | "certificate" | "no-tls" | "no-sign-in" | "password" | "refused" | "rejected" | "server";++/** Faults that stay until the person changes something; the others may pass on their own. */+export const LASTING_SENDING_FAULTS: ReadonlySet<SendingFault> = new Set(["missing", "wrong-security", "certificate", "no-tls", "no-sign-in", "password", "refused"]);++const where = (server: EmailServer) => `${server.host}:${server.port}`;++/** One plain sentence that names the server. */+export function sendingSentence(fault: SendingFault, server: EmailServer, responseCode?: number): string {+ switch (fault) {+ case "missing": return `There is no mail server called ${server.host}.`;+ case "no-answer": return `${server.host} didn't answer on port ${server.port}.`;+ case "wrong-security": return server.secure+ ? `${where(server)} starts without TLS and upgrades with STARTTLS; choose STARTTLS for it, not SSL/TLS.`+ : `${where(server)} expects SSL/TLS from the first byte; choose SSL/TLS for it, not STARTTLS.`;+ case "certificate": return `The certificate of ${server.host} isn't valid for that name, so the password wasn't sent there.`;+ case "no-tls": return `${where(server)} doesn't offer a secure connection, so the password wasn't sent there.`;+ case "no-sign-in": return `${where(server)} doesn't offer a sign-in for sending.`;+ case "password": return `The outgoing server ${where(server)} refused the password.`;+ case "refused": return "My Cloud can only reach mail servers on the public internet.";+ case "rejected": return `The outgoing server ${where(server)} refused this message's sender or recipients${responseCode ? ` (${responseCode})` : ""}.`;+ case "server": return `The outgoing server ${where(server)} said no${responseCode ? ` (${responseCode})` : ""}.`;+ }}-async function smtpTransport(account: Pick<EmailAccount, "username" | "password">, server: EmailServer, guard: EmailGuard) {- const { createTransport } = await import("nodemailer");- const at = await guard(server);- return createTransport({- host: at.host, port: server.port, secure: server.secure, requireTLS: !server.secure,- auth: { user: account.username, pass: account.password },+/** An outgoing server's no, with the server it came from. Its message is ours, never the server's words. */+export class SendingError extends EmailError {+ readonly fault: SendingFault;+ readonly server: EmailServer;+ constructor(fault: SendingFault, server: EmailServer, responseCode?: number) {+ super("sending", sendingSentence(fault, server, responseCode));+ this.name = "SendingError";+ this.fault = fault;+ this.server = server;+ }+}++/** What a Nodemailer failure means, from its codes: the server's own text is never kept. */+export function sendingError(error: unknown, server: EmailServer): SendingError {+ if (error instanceof SendingError) return error;+ if (error instanceof EmailError) return new SendingError(error.code === "refused" ? "refused" : "missing", server);+ const known = (error ?? {}) as { code?: string; originalCode?: string; responseCode?: number; message?: string };+ const code = `${known.code ?? ""} ${known.originalCode ?? ""}`;+ const message = known.message ?? "";+ const answered = typeof known.responseCode === "number" ? known.responseCode : undefined;+ if (/ENOTFOUND|EAI_AGAIN|EDNS|ENODATA/u.test(code)) return new SendingError("missing", server);+ if (/CERT|ALTNAME|SELF_SIGNED|UNABLE_TO_VERIFY|UNABLE_TO_GET_ISSUER|DEPTH_ZERO/u.test(code) || /certificate|altnames/iu.test(message)) return new SendingError("certificate", server);+ // Nodemailer's words for the two mix-ups: STARTTLS on a port that starts in TLS waits for a greeting that never comes,+ // and TLS on a port that starts in the clear reads its plain greeting as a broken TLS record.+ if (!server.secure && /greeting never received/iu.test(message)) return new SendingError("wrong-security", server);+ if (server.secure && (/WRONG_VERSION_NUMBER|PACKET_LENGTH_TOO_LONG|RECORD_LAYER/u.test(code) || /wrong version number|packet length too long|record layer failure/iu.test(message))) return new SendingError("wrong-security", server);+ if (known.code === "EAUTH") {+ if (answered && answered >= 500 && answered <= 504) return new SendingError("no-sign-in", server);+ return answered && answered >= 530 ? new SendingError("password", server) : new SendingError("server", server, answered);+ }+ if (known.code === "ETLS") return new SendingError("no-tls", server);+ if (known.code === "EENVELOPE" || known.code === "EMESSAGE") return new SendingError("rejected", server, answered);+ if (answered) return new SendingError("server", server, answered);+ return new SendingError("no-answer", server);+}++function smtpOptions(server: EmailServer, at: { host: string; servername?: string }) {+ return {+ host: at.host, port: server.port, secure: server.secure,+ // Never in the clear: on a port that upgrades, no STARTTLS means nothing more is sent.+ requireTLS: !server.secure,tls: { ...TLS, ...(at.servername ? { servername: at.servername } : {}) },connectionTimeout: CONNECT_MS, greetingTimeout: CONNECT_MS, socketTimeout: COMMAND_MS,- });+ };+}++/** Whether this outgoing server answers over TLS with a valid certificate and offers a sign-in, and, given a login, takes+ * it. Nothing is sent, and without a login no password either. */+export async function testSending(login: { username: string; password: string } | null, server: EmailServer, guard: EmailGuard): Promise<void> {+ const { default: SMTPConnection } = await import("nodemailer/lib/smtp-connection");+ let at: { host: string; servername?: string };+ try { at = await guard(server); } catch (error) { throw sendingError(error, server); }+ const connection = new SMTPConnection(smtpOptions(server, at));+ // A failure after the answer below reports here too; the awaited step carries it.+ connection.on("error", () => {});+ try {+ await new Promise<void>((resolve, reject) => { connection.once("error", reject); connection.connect(() => { connection.removeListener("error", reject); resolve(); }); });+ if (!connection.secure) throw new SendingError("no-tls", server);+ if (!connection.allowsAuth) throw new SendingError("no-sign-in", server);+ if (login) await new Promise<void>((resolve, reject) => connection.login({ user: login.username, pass: login.password }, (error) => (error ? reject(error) : resolve())));+ } catch (error) {+ throw sendingError(error, server);+ } finally { connection.close(); }+}++/** The sign-in an account sends with: the outgoing server's own, else the incoming one's. */+export const sendingLogin = (account: Pick<EmailAccount, "username" | "password" | "smtpUsername" | "smtpPassword">) =>+ ({ username: account.smtpUsername ?? account.username, password: account.smtpPassword ?? account.password });++async function smtpTransport(account: Pick<EmailAccount, "username" | "password" | "smtpUsername" | "smtpPassword">, server: EmailServer, guard: EmailGuard) {+ const { createTransport } = await import("nodemailer");+ const at = await guard(server);+ const login = sendingLogin(account);+ return createTransport({ ...smtpOptions(server, at), auth: { user: login.username, pass: login.password } });}export async function listMailboxes(account: EmailAccount, guard: EmailGuard): Promise<Array<{ path: string; role?: string }>> {@@ -241,7 +331,8 @@ export interface SendInput { to: string[]; cc?: string[]; bcc?: string[]; subjec/** Sends as the mailbox's own address and files a copy in its Sent folder when it has one. */export async function sendMessage(account: EmailAccount, guard: EmailGuard, input: SendInput): Promise<{ messageId: string; accepted: string[]; rejected: string[]; filed: boolean }> {- if (!account.smtp) throw new EmailError("refused", `No server that sends was found for ${account.address}. Reconnect it under Connected apps and enter its outgoing server.`);+ const server = account.smtp;+ if (!server) throw new EmailError("refused", `No outgoing server is set for ${account.address}.`);const { default: MailComposer } = await import("nodemailer/lib/mail-composer");const composed = new MailComposer({from: account.address, to: input.to, ...(input.cc?.length ? { cc: input.cc } : {}), ...(input.bcc?.length ? { bcc: input.bcc } : {}),@@ -249,9 +340,12 @@ export async function sendMessage(account: EmailAccount, guard: EmailGuard, inpu}).compile();const envelope = composed.getEnvelope();const raw = await composed.build();- const transport = await smtpTransport(account, account.smtp, guard);let sent: { accepted?: unknown[]; rejected?: unknown[]; messageId?: string };- try { sent = await transport.sendMail({ envelope, raw }); } catch (error) { throw failure(error); } finally { transport.close(); }+ let transport: Awaited<ReturnType<typeof smtpTransport>> | undefined;+ try {+ transport = await smtpTransport(account, server, guard);+ sent = await transport.sendMail({ envelope, raw });+ } catch (error) { throw sendingError(error, server); } finally { transport?.close(); }const text = (list: unknown[] | undefined) => (list ?? []).map((entry) => (typeof entry === "string" ? entry : (entry as Address).address ?? "")).filter(Boolean);let filed = false;try {diff --git a/server/email/discover.test.ts b/server/email/discover.test.tsindex 21a83112f9..ff241b6e82 100644--- a/server/email/discover.test.ts+++ b/server/email/discover.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { baseDomain, discoverMailServers, parseAutoconfig, type DiscoverDeps } from "./discover.ts";+import { baseDomain, discoverMailServers, parseAutoconfig, smtpBeside, type DiscoverDeps } from "./discover.ts";const AUTOCONFIG = `<?xml version="1.0"?><clientConfig version="1.1"><emailProvider id="x"><incomingServer type="pop3"><hostname>pop.example.com</hostname><port>995</port><socketType>SSL</socketType></incomingServer>@@ -16,6 +16,8 @@ function deps(over: Partial<DiscoverDeps> & { pages?: Record<string, string> } =fetchText: over.fetchText ?? (async (url) => { asked.push(url); return over.pages?.[url] ?? null; }),mx: over.mx ?? (async () => []),srv: over.srv ?? (async () => []),+ cname: over.cname ?? (async () => []),+ reverse: over.reverse ?? (async () => []),};}@@ -48,6 +50,44 @@ describe("where a mailbox's servers are", () => {expect(found.smtp[0]).toEqual({ host: "smtp.world4you.com", port: 587, secure: false });});+ it("a domain hosted at a provider under its own names: the provider's servers, found from the names behind them", async () => {+ // How a World4You domain looks: its MX is mail.<the domain> on World4You's address, imap.<the domain> is a CNAME to+ // imap.world4you.com, and World4You's certificates are for *.world4you.com only.+ const found = await discoverMailServers("[email protected]", deps({+ mx: async () => ["mail.small-shop.at."],+ cname: async (name) => (name === "imap.small-shop.at" ? ["imap.world4you.com"] : []),+ reverse: async (host) => (host === "mail.small-shop.at" ? ["mail25.world4you.com"] : []),+ }));+ expect(found.imap[0]).toEqual({ host: "imap.world4you.com", port: 993, secure: true });+ expect(found.smtp[0]).toEqual({ host: "smtp.world4you.com", port: 587, secure: false });+ });++ it("the same domain known only by its MX's reverse name", async () => {+ const found = await discoverMailServers("[email protected]", deps({ mx: async () => ["mail.small-shop.at."], reverse: async () => ["mail25.world4you.com."] }));+ expect(found.smtp[0]).toEqual({ host: "smtp.world4you.com", port: 587, secure: false });+ });++ it("knows Easyname, whose outgoing server takes TLS on 465", async () => {+ const found = await discoverMailServers("[email protected]", deps({ mx: async () => ["mx01.easyname.com."] }));+ expect(found.imap[0]).toEqual({ host: "imap.easyname.com", port: 993, secure: true });+ expect(found.smtp.slice(0, 2)).toEqual([{ host: "smtp.easyname.com", port: 465, secure: true }, { host: "smtp.easyname.com", port: 587, secure: false }]);+ });++ it("the outgoing server beside an incoming one: smtp.x and mail.x for imap.x or pop.x, on both ports", () => {+ expect(smtpBeside("imap.wh20.easyname.systems").map((server) => `${server.host}:${server.port}`)).toEqual([+ "smtp.wh20.easyname.systems:587", "smtp.wh20.easyname.systems:465", "mail.wh20.easyname.systems:587", "mail.wh20.easyname.systems:465",+ "imap.wh20.easyname.systems:587", "imap.wh20.easyname.systems:465",+ ]);+ expect(smtpBeside("pop.world4you.com")[0]).toEqual({ host: "smtp.world4you.com", port: 587, secure: false });+ expect(smtpBeside("mail.example.com").map((server) => server.host)).toEqual(["smtp.example.com", "smtp.example.com", "mail.example.com", "mail.example.com"]);+ expect(smtpBeside("imap.com").map((server) => server.host), "never a bare top-level name").not.toContain("smtp.com");+ });++ it("Gmail and Outlook come with what they need instead of a password", async () => {+ expect((await discoverMailServers("[email protected]", deps())).provider).toEqual({ rule: "app-password", hint: { provider: "Google", app: "gmail", appPasswordUrl: "https://myaccount.google.com/apppasswords" } });+ expect((await discoverMailServers("[email protected]", deps({ mx: async () => ["company-example.mail.protection.outlook.com."] }))).provider).toMatchObject({ rule: "no-password", hint: { app: "outlook" } });+ });+it("asks Thunderbird's list about the provider behind an MX record it doesn't know", async () => {const asking = deps({ mx: async () => ["mx.hoster.example."], pages: { "https://autoconfig.thunderbird.net/v1.1/hoster.example": AUTOCONFIG } });const found = await discoverMailServers("[email protected]", asking);diff --git a/server/email/discover.ts b/server/email/discover.tsindex d6e6e9dbdd..93747636b0 100644--- a/server/email/discover.ts+++ b/server/email/discover.ts@@ -1,9 +1,12 @@// Where a mailbox's mail servers are, from its address alone, the way a mail program finds them: the domain's own// autoconfig file, a few well-known hosts, Thunderbird's public list (by domain, then by the provider behind the domain's-// MX record), RFC 6186 SRV records, and last the usual names. Only a list of places to try: nothing here sees a password,-// and the client (client.ts) sends it only over TLS to a host whose certificate is valid for that name.-import { resolveMx, resolveSrv } from "node:dns/promises";+// MX record), RFC 6186 SRV records, and last the usual names. A domain hosted under its own names (mail.<domain> on the+// provider's address, imap.<domain> an alias of the provider's server) is known by the names behind them: the aliases'+// targets and the MX address's reverse name. Only a list of places to try: nothing here sees a password, and the client+// (client.ts) sends it only over TLS to a host whose certificate is valid for that name.+import { resolve4, resolveCname, resolveMx, resolveSrv, reverse } from "node:dns/promises";+import type { EmailSignInHint } from "../../shared/email.ts";import type { EmailServer } from "./store.ts";export interface MailCandidates {@@ -11,13 +14,22 @@ export interface MailCandidates {smtp: EmailServer[];/** A found list says which name signs in; none says, so both are tried. */username?: "address" | "localpart";+ /** A provider whose sign-in needs more than the mailbox password. */+ provider?: PasswordRule;}+/** `app-password`: an app password from the account's security settings; `no-password`: no password sign-in at all. */+export type PasswordRule = { rule: "app-password" | "no-password"; hint: EmailSignInHint };+export interface DiscoverDeps {/** The text at an https address, or null. */fetchText(url: string): Promise<string | null>;mx(domain: string): Promise<string[]>;srv(name: string): Promise<Array<{ name: string; port: number }>>;+ /** What a name is an alias (CNAME) of, if it is one. */+ cname(name: string): Promise<string[]>;+ /** The reverse (PTR) names of a host's addresses. */+ reverse(host: string): Promise<string[]>;}const IMAPS = 993, IMAP_STARTTLS = 143, SMTPS = 465, SUBMISSION = 587;@@ -33,24 +45,43 @@ export function baseDomain(host: string): string {return parts.slice(two ? -3 : -2).join(".");}-/** The places a well-known provider's mail is, by the address's domain or by the host of its MX record. */-const KNOWN: ReadonlyArray<{ domain?: RegExp; mx?: RegExp; imap: string; smtp: string }> = [- { domain: /^(?:gmail|googlemail)\.com$/u, mx: /\.google(?:mail)?\.com$/u, imap: "imap.gmail.com", smtp: "smtp.gmail.com" },- { domain: /^(?:outlook|hotmail|live|msn)\.[a-z.]+$/u, mx: /\.protection\.outlook\.com$/u, imap: "outlook.office365.com", smtp: "smtp.office365.com" },- { domain: /^(?:icloud|me|mac)\.com$/u, imap: "imap.mail.me.com", smtp: "smtp.mail.me.com" },- { domain: /^yahoo\.[a-z.]+$/u, mx: /\.yahoodns\.net$/u, imap: "imap.mail.yahoo.com", smtp: "smtp.mail.yahoo.com" },- { domain: /^gmx\.[a-z.]+$/u, mx: /\.gmx\.net$/u, imap: "imap.gmx.net", smtp: "mail.gmx.net" },- { domain: /^web\.de$/u, mx: /\.web\.de$/u, imap: "imap.web.de", smtp: "smtp.web.de" },+/** The places a well-known provider's mail is, by the address's domain or by a host of the provider behind it (its MX+ * record, an alias's target, the MX address's reverse name). `smtps`: its own help pages give TLS on 465 first. */+const KNOWN: ReadonlyArray<{ domain?: RegExp; host?: RegExp; imap: string; smtp: string; smtps?: true; provider?: PasswordRule }> = [+ { domain: /^(?:gmail|googlemail)\.com$/u, host: /\.google(?:mail)?\.com$/u, imap: "imap.gmail.com", smtp: "smtp.gmail.com",+ provider: { rule: "app-password", hint: { provider: "Google", app: "gmail", appPasswordUrl: "https://myaccount.google.com/apppasswords" } } },+ // Exchange Online has no password sign-in for reading, and turns it off for sending (by default from December 2026).+ { domain: /^(?:outlook|hotmail|live|msn)\.[a-z.]+$/u, host: /\.protection\.outlook\.com$/u, imap: "outlook.office365.com", smtp: "smtp.office365.com",+ provider: { rule: "no-password", hint: { provider: "Microsoft", app: "outlook" } } },+ { domain: /^(?:icloud|me|mac)\.com$/u, imap: "imap.mail.me.com", smtp: "smtp.mail.me.com",+ provider: { rule: "app-password", hint: { provider: "Apple", appPasswordUrl: "https://account.apple.com/account/manage" } } },+ { domain: /^yahoo\.[a-z.]+$/u, host: /\.yahoodns\.net$/u, imap: "imap.mail.yahoo.com", smtp: "smtp.mail.yahoo.com",+ provider: { rule: "app-password", hint: { provider: "Yahoo", appPasswordUrl: "https://login.yahoo.com/account/security" } } },+ { domain: /^gmx\.[a-z.]+$/u, host: /\.gmx\.net$/u, imap: "imap.gmx.net", smtp: "mail.gmx.net" },+ { domain: /^web\.de$/u, host: /\.web\.de$/u, imap: "imap.web.de", smtp: "smtp.web.de" },{ domain: /^t-online\.de$/u, imap: "secureimap.t-online.de", smtp: "securesmtp.t-online.de" },- { mx: /(?:^|\.)world4you\.com$/u, imap: "imap.world4you.com", smtp: "smtp.world4you.com" },- { mx: /(?:^|\.)(?:kundenserver\.de|ionos\.[a-z.]+)$/u, imap: "imap.ionos.de", smtp: "smtp.ionos.de" },- { mx: /(?:^|\.)strato\.de$/u, imap: "imap.strato.de", smtp: "smtp.strato.de" },- { mx: /(?:^|\.)zoho\.[a-z.]+$/u, imap: "imap.zoho.com", smtp: "smtp.zoho.com" },- { mx: /(?:^|\.)(?:fastmail\.com|messagingengine\.com)$/u, imap: "imap.fastmail.com", smtp: "smtp.fastmail.com" },+ { host: /(?:^|\.)world4you\.com$/u, imap: "imap.world4you.com", smtp: "smtp.world4you.com" },+ { host: /(?:^|\.)easyname\.(?:com|eu)$/u, imap: "imap.easyname.com", smtp: "smtp.easyname.com", smtps: true },+ { host: /(?:^|\.)(?:kundenserver\.de|ionos\.[a-z.]+)$/u, imap: "imap.ionos.de", smtp: "smtp.ionos.de" },+ { host: /(?:^|\.)strato\.de$/u, imap: "imap.strato.de", smtp: "smtp.strato.de" },+ { host: /(?:^|\.)zoho\.[a-z.]+$/u, imap: "imap.zoho.com", smtp: "smtp.zoho.com" },+ { host: /(?:^|\.)(?:fastmail\.com|messagingengine\.com)$/u, imap: "imap.fastmail.com", smtp: "smtp.fastmail.com" },];const imapOn = (host: string): EmailServer[] => [{ host, port: IMAPS, secure: true }, { host, port: IMAP_STARTTLS, secure: false }];-const smtpOn = (host: string): EmailServer[] => [{ host, port: SUBMISSION, secure: false }, { host, port: SMTPS, secure: true }];+const smtpOn = (host: string, tlsFirst = false): EmailServer[] => {+ const both: EmailServer[] = [{ host, port: SUBMISSION, secure: false }, { host, port: SMTPS, secure: true }];+ return tlsFirst ? both.reverse() : both;+};++/** Where the outgoing server usually is, beside an incoming one that took the password: imap.x (or pop.x, mail.x) has+ * smtp.x and mail.x, and some hosts send from the incoming name itself. */+export function smtpBeside(incoming: string): EmailServer[] {+ const host = incoming.toLowerCase();+ const rest = /^(?:imap|imaps|pop|pop3|mail|secureimap)\d*\.(.+)$/u.exec(host)?.[1];+ const names = [...(rest && rest.includes(".") ? [`smtp.${rest}`, `mail.${rest}`] : []), host];+ return [...new Set(names)].filter(validHost).flatMap((name) => smtpOn(name));+}/** The servers in a Mozilla autoconfig file (config-v1.1.xml), TLS only, with `%EMAILDOMAIN%` filled in. */export function parseAutoconfig(xml: string, domain: string): MailCandidates {@@ -84,8 +115,14 @@ export const liveDiscoverDeps = (allowed: (url: URL) => Promise<boolean>): Disco},mx: async (domain) => (await resolveMx(domain).catch(() => [])).sort((a, b) => a.priority - b.priority).map((record) => record.exchange.toLowerCase()),srv: async (name) => (await resolveSrv(name).catch(() => [])).sort((a, b) => a.priority - b.priority).map((record) => ({ name: record.name.toLowerCase(), port: record.port })),+ cname: async (name) => resolveCname(name).catch(() => []),+ reverse: async (host) => (await Promise.all((await resolve4(host).catch(() => [])).slice(0, 2).map((ip) => reverse(ip).catch(() => [])))).flat(),});+const bare = (host: string) => host.toLowerCase().replace(/\.$/u, "");+/** A host without its first name: "mx.wh20.host.example" is "wh20.host.example". */+const parent = (host: string) => { const rest = host.slice(host.indexOf(".") + 1); return rest.includes(".") ? rest : host; };+/** Every place to try for this address, likeliest first, each once. */export async function discoverMailServers(address: string, deps: DiscoverDeps): Promise<MailCandidates> {const domain = address.slice(address.lastIndexOf("@") + 1).trim().toLowerCase();@@ -102,23 +139,32 @@ export async function discoverMailServers(address: string, deps: DiscoverDeps):return xml ? parseAutoconfig(xml, domain) : { imap: [], smtp: [] };};const list = (name: string) => autoconfig(`https://autoconfig.thunderbird.net/v1.1/${encodeURIComponent(name)}`);- const [own, wellKnown, listed, mx, imaps, submission] = await Promise.all([+ const alias = async (label: string) => (await deps.cname(`${label}.${domain}`).catch(() => [])).map(bare).filter(validHost);+ const mxHosts = deps.mx(domain).then((hosts) => hosts.map(bare).filter(validHost));+ const [own, wellKnown, listed, mx, imaps, submission, imapAlias, smtpAlias, mailAlias, mxNames] = await Promise.all([autoconfig(`https://autoconfig.${domain}/mail/config-v1.1.xml`),autoconfig(`https://${domain}/.well-known/autoconfig/mail/config-v1.1.xml`),list(domain),- deps.mx(domain),+ mxHosts,deps.srv(`_imaps._tcp.${domain}`),deps.srv(`_submission._tcp.${domain}`),+ alias("imap"), alias("smtp"), alias("mail"),+ mxHosts.then(async (hosts) => (await Promise.all(hosts.slice(0, 2).map((host) => deps.reverse(host).catch(() => [])))).flat().map(bare).filter(validHost)),]);add(own); add(wellKnown);- const known = KNOWN.filter((entry) => entry.domain?.test(domain) || mx.some((host) => entry.mx?.test(host.replace(/\.$/u, ""))));- for (const entry of known) add({ imap: imapOn(entry.imap), smtp: smtpOn(entry.smtp) });+ const aliases = [...imapAlias, ...smtpAlias, ...mailAlias];+ const behind = [...mx, ...aliases, ...mxNames];+ const known = KNOWN.filter((entry) => entry.domain?.test(domain) || behind.some((host) => entry.host?.test(host)));+ for (const entry of known) add({ imap: imapOn(entry.imap), smtp: smtpOn(entry.smtp, entry.smtps) });+ out.provider = known.find((entry) => entry.provider)?.provider;add(listed);- const providers = [...new Set(mx.map(baseDomain))].filter((base) => base !== domain && validHost(base)).slice(0, 2);+ // The domain's own aliases name the provider's servers, whose certificates are for those names.+ add({ imap: [...imapAlias, ...mailAlias].flatMap(imapOn), smtp: [...smtpAlias, ...mailAlias].flatMap((host) => smtpOn(host)) });+ const providers = [...new Set([...mx, ...aliases].flatMap((host) => [parent(host), baseDomain(host)]))].filter((base) => base !== domain && validHost(base)).slice(0, 4);if (!known.length) for (const found of await Promise.all(providers.map(list))) add(found);add({ imap: imaps.filter((record) => validHost(record.name)).map((record) => ({ host: record.name, port: record.port, secure: true })),smtp: submission.filter((record) => validHost(record.name)).map((record) => ({ host: record.name, port: record.port, secure: false })) });- const guesses = [`imap.${domain}`, `mail.${domain}`, ...mx.slice(0, 1).filter(validHost), ...providers.flatMap((base) => [`imap.${base}`, `mail.${base}`])];- add({ imap: guesses.flatMap(imapOn), smtp: [`smtp.${domain}`, `mail.${domain}`, ...providers.flatMap((base) => [`smtp.${base}`, `mail.${base}`]), ...mx.slice(0, 1).filter(validHost)].flatMap(smtpOn) });+ const guesses = [`imap.${domain}`, `mail.${domain}`, ...mx.slice(0, 1), ...providers.flatMap((base) => [`imap.${base}`, `mail.${base}`])];+ add({ imap: guesses.flatMap(imapOn), smtp: [`smtp.${domain}`, `mail.${domain}`, ...providers.flatMap((base) => [`smtp.${base}`, `mail.${base}`]), ...mx.slice(0, 1)].flatMap((host) => smtpOn(host)) });return out;}diff --git a/server/email/host.test.ts b/server/email/host.test.tsindex c4a0cafadc..2479bf85ec 100644--- a/server/email/host.test.ts+++ b/server/email/host.test.ts@@ -6,7 +6,7 @@ import { afterEach, describe, expect, it } from "vitest";import "../server-line-packs.ts";import { setConversationLanguage } from "../server-lines.ts";import { boxUploadsDir } from "../bot-box/plan.ts";-import { EmailError, openGuard } from "./client.ts";+import { EmailError, openGuard, SendingError } from "./client.ts";import { outsideRouteRefused } from "../host/outside-fence.ts";import { createEmailHost, EMAIL_INTERNAL_MCP_PATH, emailAccess, emailAllowedFor, type EmailBot, type EmailHostDeps } from "./host.ts";import { createEmailService } from "./service.ts";@@ -20,7 +20,7 @@ afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: truasync function fixture(run: EmailHostDeps["run"] = {}, bot: EmailBot | null = { id: "b1", name: "Ada", color: "blue" }, connected = true) {const dataDir = mkdtempSync(join(tmpdir(), "omb-mail-host-")); dirs.push(dataDir);- const service = createEmailService({ dataDir, publicOnly: false, guard: openGuard, discover: { fetchText: async () => null, mx: async () => [], srv: async () => [] }, test: { mailbox: (async () => ({ messages: 1 })) as never, sending: (async () => {}) as never } });+ const service = createEmailService({ dataDir, publicOnly: false, guard: openGuard, discover: { fetchText: async () => null, mx: async () => [], srv: async () => [], cname: async () => [], reverse: async () => [] }, test: { mailbox: (async () => ({ messages: 1 })) as never, sending: (async () => {}) as never } });if (connected) await service.connect({ address: "[email protected]", password: PASSWORD });const marked: string[] = [];const rows: Array<Record<string, unknown>> = [];@@ -81,6 +81,27 @@ describe("a turn's Email tools", () => {expect(JSON.stringify(rows)).not.toContain("Body");});+ it("a send the outgoing server refuses for good stops sends until the person fixes it; one that may pass doesn't", async () => {+ const server = { host: "smtp.shop.example", port: 587, secure: false };+ let fault: "password" | "no-answer" = "no-answer";+ let calls = 0;+ const { call, service, host } = await fixture({ sendMessage: (async () => { calls++; throw new SendingError(fault, server); }) as never });+ const send = () => call("EMAIL_SEND_MESSAGE", { to: ["[email protected]"], subject: "Hi", text: "Body" });+ const passing = await send();+ expect(passing).toMatchObject({ isError: true });+ expect(passing.content[0]!.text).toContain("smtp.shop.example didn't answer on port 587.");+ expect(service.sendingProblem("[email protected]")).toBeUndefined();+ fault = "password";+ const lasting = await send();+ expect(lasting.content[0]!.text).toContain("The outgoing server smtp.shop.example:587 refused the password.");+ expect(lasting.content[0]!.text).toContain("Connected apps");+ expect(lasting.content[0]!.text).not.toMatch(/try again/iu);+ expect(service.sendingProblem("[email protected]")).toContain("refused the password");+ expect((await send()).isError).toBe(true);+ expect(calls, "the third send never reached the server").toBe(2);+ expect(host.prompt({ id: "b1", name: "Ada" })).toContain("Sending from [email protected] doesn't work until the person fixes its outgoing server");+ });+it("a header can't be smuggled into a send", async () => {let sent = 0;const { call } = await fixture({ sendMessage: (async () => { sent++; return { messageId: "<1@x>", accepted: [], rejected: [], filed: false }; }) as never });diff --git a/server/email/host.ts b/server/email/host.tsindex d08f6a1dda..a96a34fea1 100644--- a/server/email/host.ts+++ b/server/email/host.ts@@ -13,9 +13,9 @@ import { conversationLanguage, serverLine } from "../server-lines.ts";import { boxUploadsDir } from "../bot-box/plan.ts";import { harnessMcpTokenEnv } from "../harness-mcp-token.ts";import { AGENTS_NODE_FLAG, SPAWNED_PROXIES } from "../proxy-paths.ts";-import { EmailError, LIST_MAX, listMailboxes, listMessages, readMessage, searchMessages, sendMessage } from "./client.ts";-import { EMAIL_INSTRUCTIONS, EMAIL_NOT_CONNECTED_TEXT, EMAIL_PROMPT, EMAIL_TO_CONNECT_PROMPT } from "./instructions.ts";-import type { EmailService } from "./service.ts";+import { EmailError, LASTING_SENDING_FAULTS, LIST_MAX, listMailboxes, listMessages, readMessage, searchMessages, sendMessage, SendingError } from "./client.ts";+import { EMAIL_CANT_SEND_PROMPT, EMAIL_CANT_SEND_TEXT, EMAIL_INSTRUCTIONS, EMAIL_NOT_CONNECTED_TEXT, EMAIL_NOT_SENT_TEXT, EMAIL_PROMPT, EMAIL_TO_CONNECT_PROMPT } from "./instructions.ts";+import { sendingProblem, type EmailService } from "./service.ts";import type { EmailAccount } from "./store.ts";import { EMAIL_TOOLS, emailError, emailText, emailToolCallProblem, isEmailRead, isEmailToolName, type EmailTool, type EmailToolResult } from "./tools.ts";@@ -126,7 +126,8 @@ export function createEmailHost(deps: EmailHostDeps) {const scopes = bot.connectorScopes ? { apps: { [EMAIL_SLUG]: bot.connectorScopes.apps[EMAIL_SLUG]! } } : undefined;const grant = bot.connectorTools?.[EMAIL_SLUG];const granted = grant && grant.tools !== "*" ? ` Of the email tools, this bot was granted only: ${grant.tools.join(", ")}.` : "";- return EMAIL_PROMPT(service.store.list().map((one) => one.address)) + granted + describeConnectorScopes(scopes);+ const cantSend = service.store.list().flatMap((one) => { const problem = sendingProblem(one); return problem ? [EMAIL_CANT_SEND_PROMPT(one.address, problem)] : []; }).join("");+ return EMAIL_PROMPT(service.store.list().map((one) => one.address)) + cantSend + granted + describeConnectorScopes(scopes);},toolListing: () => (service.status().state === "unavailable" ? null : { email: EMAIL_TOOLS.map(({ name, description }) => ({ name, description })) }),@@ -152,12 +153,19 @@ export function createEmailHost(deps: EmailHostDeps) {if (!allowed.ok) return emailError(allowed.text);const mailbox = account(args.account);if ("content" in mailbox) return mailbox;+ const cantSend = name === "EMAIL_SEND_MESSAGE" ? sendingProblem(mailbox) : undefined;+ if (cantSend) return emailError(EMAIL_CANT_SEND_TEXT(mailbox.address, cantSend));// Before anything comes back: a failure halfway must not leave mail in a conversation not marked as outside work.if (isEmailRead(name)) deps.markOutside(capability.threadId);let result: EmailToolResult;try {result = await call(name, args, mailbox, capability);} catch (error) {+ if (error instanceof SendingError) {+ if (!LASTING_SENDING_FAULTS.has(error.fault)) return emailError(EMAIL_NOT_SENT_TEXT(error.message));+ service.store.markSendingProblem(mailbox, error.message);+ return emailError(EMAIL_CANT_SEND_TEXT(mailbox.address, error.message));+ }const failed = error instanceof EmailError ? error : new EmailError("server", "The mail server did not finish this call.");if (failed.code === "password") service.store.markProblem(mailbox.address, mailbox.password, "The mail server stopped accepting this password. Connect it again.");return emailError(failed.code === "password"@@ -165,7 +173,7 @@ export function createEmailHost(deps: EmailHostDeps) {: failed.message);}assertActive();- if (mailbox.problem && !result.isError) service.store.markProblem(mailbox.address, mailbox.password, mailbox.smtp ? undefined : mailbox.problem);+ if (mailbox.problem && !result.isError) service.store.markProblem(mailbox.address, mailbox.password, undefined);if (name === "EMAIL_SEND_MESSAGE" && !result.isError) {deps.appendMessage(capability.threadId, {role: "bot", kind: "activity", tool: { name: `mcp__${EMAIL_MCP_SERVER}__${name}`, ok: true, summary: serverLine(conversationLanguage(capability.threadId), "server.email.sent", { address: mailbox.address, count: (args.to as string[]).length }) },diff --git a/server/email/instructions.ts b/server/email/instructions.tsindex a9ba6615d1..d50326dc4f 100644--- a/server/email/instructions.ts+++ b/server/email/instructions.ts@@ -18,3 +18,17 @@ export const EMAIL_TO_CONNECT_PROMPT =/** The failed-call text when no mailbox is connected. */export const EMAIL_NOT_CONNECTED_TEXT ="OpenMausBot note: no mailbox is connected, so this call did not run. Call request_credential with credential_id email, then end this turn.";++/** The failed-call text for a mailbox that can't send until the person fixes its outgoing server: what is wrong, who+ * fixes it and where, and no way round it, so a bot neither retries nor builds one. */+export const EMAIL_CANT_SEND_TEXT = (address: string, problem: string) =>+ `OpenMausBot note: nothing was sent. Sending from ${address} doesn't work: ${problem} Only the person can fix this, under Outgoing server for ${address} in Connected apps › Email; reading mail still works. ` ++ "Don't retry, don't send another way (no script, other mail tool or mail client of your own) and don't ask for the password: tell the person this in one line and carry on without sending.";++/** The system prompt line for a mailbox that can't send yet. */+export const EMAIL_CANT_SEND_PROMPT = (address: string, problem: string) =>+ ` Sending from ${address} doesn't work until the person fixes its outgoing server in Connected apps › Email (${problem}); don't try to send from it, and say so if a task needs it.`;++/** The failed-call text when a send didn't go but may later: nothing to retry now. */+export const EMAIL_NOT_SENT_TEXT = (problem: string) =>+ `OpenMausBot note: nothing was sent. ${problem} Tell the person in one line; don't retry in this turn or send another way.`;diff --git a/server/email/real-server.test.ts b/server/email/real-server.test.tsindex 9f163c382d..0c0278faa8 100644--- a/server/email/real-server.test.ts+++ b/server/email/real-server.test.ts@@ -22,7 +22,7 @@ const AUTOCONFIG = `<clientConfig><emailProvider id="x"><incomingServer type="imap"><hostname>${HOST}</hostname><port>${IMAPS}</port><socketType>SSL</socketType><username>%EMAILADDRESS%</username></incomingServer><outgoingServer type="smtp"><hostname>${HOST}</hostname><port>${SUBMISSION}</port><socketType>STARTTLS</socketType><username>%EMAILADDRESS%</username></outgoingServer></emailProvider></clientConfig>`;-const discover = { fetchText: async (url: string) => (url.includes("autoconfig.omb-test.example") ? AUTOCONFIG : null), mx: async () => [], srv: async () => [] };+const discover = { fetchText: async (url: string) => (url.includes("autoconfig.omb-test.example") ? AUTOCONFIG : null), mx: async () => [], srv: async () => [], cname: async () => [], reverse: async () => [] };const PDF = Buffer.concat([Buffer.from("%PDF-1.4\n%\xE2\xE3\xCF\xD3\n", "latin1"), randomBytes(2048), Buffer.from("\n%%EOF\n")]);const sha = (bytes: Buffer) => createHash("sha256").update(bytes).digest("hex");diff --git a/server/email/sending.test.ts b/server/email/sending.test.tsnew file mode 100644index 0000000000..9525091487--- /dev/null+++ b/server/email/sending.test.ts@@ -0,0 +1,152 @@+// Sending against a local mail submission server (server/testing/fake-smtp.ts) the way mail hosts run theirs: STARTTLS on+// a submission port with AUTH only once TLS is up, TLS from the first byte, AUTH LOGIN or PLAIN alone. Made-up names on+// loopback with a certificate for them; made-up passwords.+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";++import { startFakeSmtp, testCertificate, trustTestCertificate, type FakeSmtp, type FakeSmtpOptions } from "../testing/fake-smtp.ts";+import { testSending, type EmailGuard } from "./client.ts";+import { createEmailHost } from "./host.ts";+import { createEmailService } from "./service.ts";+import type { EmailToolResult } from "./tools.ts";++const ADDRESS = "[email protected]";+const PASSWORD = "fake-mailbox-password-1";+const OTHER = "fake-outgoing-password-2";+const HOST = "smtp.small-shop.example";+const certificate = testCertificate([HOST, "imap.small-shop.example"]);+/** Every made-up name is the fake on loopback; its certificate is for that name. */+const guard: EmailGuard = async ({ host }) => ({ host: "127.0.0.1", servername: host });+const plain = (user: string, password: string) => Buffer.from(`\0${user}\0${password}`).toString("base64");++const servers: FakeSmtp[] = [];+const dirs: string[] = [];+let untrust = () => {};+beforeAll(() => { if (certificate) untrust = trustTestCertificate(certificate.cert); });+afterAll(() => untrust());+afterEach(() => {+ for (const server of servers.splice(0)) server.close();+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 });+});++async function fake(options: Partial<FakeSmtpOptions> = {}): Promise<FakeSmtp> {+ const server = await startFakeSmtp({ certificate: certificate!, security: "starttls", mechanisms: ["PLAIN", "LOGIN"], users: { [ADDRESS]: PASSWORD }, ...options });+ servers.push(server);+ return server;+}++describe.skipIf(!certificate)("an outgoing server, over the wire", () => {+ it("587's way: plain until STARTTLS, a sign-in only after it, and the password never in the clear", async () => {+ const smtp = await fake();+ await testSending({ username: ADDRESS, password: PASSWORD }, { host: HOST, port: smtp.port, secure: false }, guard);+ expect(smtp.signIns).toEqual([{ mechanism: "PLAIN", user: ADDRESS, ok: true }]);+ expect(smtp.plain.some((line) => /^STARTTLS/iu.test(line))).toBe(true);+ expect(smtp.plain.join("\n")).not.toContain(plain(ADDRESS, PASSWORD));+ expect(smtp.plain.some((line) => /^AUTH/iu.test(line))).toBe(false);+ }, 20_000);++ it("465's way: TLS from the first byte", async () => {+ const smtp = await fake({ security: "tls" });+ await testSending({ username: ADDRESS, password: PASSWORD }, { host: HOST, port: smtp.port, secure: true }, guard);+ expect(smtp.signIns).toEqual([{ mechanism: "PLAIN", user: ADDRESS, ok: true }]);+ expect(smtp.plain).toEqual([]);+ }, 20_000);++ it("signs in with AUTH LOGIN where that is all a server offers, and with AUTH PLAIN where that is", async () => {+ const login = await fake({ mechanisms: ["LOGIN"] });+ await testSending({ username: ADDRESS, password: PASSWORD }, { host: HOST, port: login.port, secure: false }, guard);+ expect(login.signIns).toEqual([{ mechanism: "LOGIN", user: ADDRESS, ok: true }]);+ const onlyPlain = await fake({ security: "tls", mechanisms: ["PLAIN"] });+ await testSending({ username: ADDRESS, password: PASSWORD }, { host: HOST, port: onlyPlain.port, secure: true }, guard);+ expect(onlyPlain.signIns).toEqual([{ mechanism: "PLAIN", user: ADDRESS, ok: true }]);+ }, 20_000);++ it("a refused password is said in one plain sentence naming the server", async () => {+ const smtp = await fake();+ await expect(testSending({ username: ADDRESS, password: "fake-wrong-password" }, { host: HOST, port: smtp.port, secure: false }, guard))+ .rejects.toMatchObject({ fault: "password", message: `The outgoing server ${HOST}:${smtp.port} refused the password.` });+ }, 20_000);++ it("no password goes to a server that doesn't take one, and none at all without a login", async () => {+ const smtp = await fake();+ await testSending(null, { host: HOST, port: smtp.port, secure: false }, guard);+ expect(smtp.signIns).toEqual([]);+ }, 20_000);++ it("TLS from the first byte on a port that starts in the clear: said as the mix-up it is", async () => {+ const smtp = await fake();+ await expect(testSending({ username: ADDRESS, password: PASSWORD }, { host: HOST, port: smtp.port, secure: true }, guard))+ .rejects.toMatchObject({ fault: "wrong-security", message: expect.stringContaining("choose STARTTLS for it, not SSL/TLS") });+ expect(smtp.signIns).toEqual([]);+ }, 20_000);++ it("STARTTLS on a port that starts in TLS: the greeting never comes, and that is said as the mix-up too", async () => {+ const smtp = await fake({ security: "tls" });+ await expect(testSending({ username: ADDRESS, password: PASSWORD }, { host: HOST, port: smtp.port, secure: false }, guard))+ .rejects.toMatchObject({ fault: "wrong-security", message: expect.stringContaining("expects SSL/TLS from the first byte") });+ expect(smtp.signIns).toEqual([]);+ }, 30_000);+});++describe.skipIf(!certificate)("connecting, checking and sending through the fake", () => {+ function setup(smtp: FakeSmtp, socketType: "STARTTLS" | "SSL") {+ const dataDir = mkdtempSync(join(tmpdir(), "omb-mail-sending-")); dirs.push(dataDir);+ const autoconfig = `<clientConfig><emailProvider id="x">+ <incomingServer type="imap"><hostname>imap.small-shop.example</hostname><port>993</port><socketType>SSL</socketType><username>%EMAILADDRESS%</username></incomingServer>+ <outgoingServer type="smtp"><hostname>${HOST}</hostname><port>${smtp.port}</port><socketType>${socketType}</socketType><username>%EMAILADDRESS%</username></outgoingServer>+ </emailProvider></clientConfig>`;+ const service = createEmailService({+ dataDir, publicOnly: false, guard,+ discover: { fetchText: async (url) => (url.startsWith("https://autoconfig.small-shop.example/") ? autoconfig : null), mx: async () => [], srv: async () => [], cname: async () => [], reverse: async () => [] },+ // Reading is a stand-in; sending is the real client.+ test: { mailbox: (async () => ({ messages: 1 })) as never, sending: testSending },+ });+ const host = createEmailHost({ service, dataDir, bot: () => ({ id: "b1", name: "Ada", color: "blue" }), inRoom: () => false, appendMessage: () => {}, markOutside: () => {} });+ const call = (name: string, args: Record<string, unknown>) => host.handle({ method: "tools/call", params: { name, arguments: args } }, { botId: "b1", threadId: "t1" }, () => {}) as Promise<EmailToolResult>;+ return { service, call };+ }++ it("connect keeps the outgoing server that took the password, and the email tool sends from the address", async () => {+ const smtp = await fake();+ const { service, call } = setup(smtp, "STARTTLS");+ expect(await service.connect({ address: ADDRESS, password: PASSWORD })).toMatchObject({ ok: true, sending: { ok: true }, account: { smtpHost: HOST, smtpPort: smtp.port, smtpSecurity: "starttls" } });+ const sent = await call("EMAIL_SEND_MESSAGE", { to: ["[email protected]"], subject: "Hello", text: "Body" });+ expect(sent.isError, sent.content[0]?.text).toBeUndefined();+ expect(smtp.received).toHaveLength(1);+ expect(smtp.received[0]).toMatchObject({ from: ADDRESS, to: ["[email protected]"] });+ expect(smtp.received[0]!.data).toContain(`From: ${ADDRESS}`);+ }, 30_000);++ it("reading that works with sending that doesn't is saved saying why; the outgoing server typed later is checked alone, and a test goes to the address", async () => {+ const smtp = await fake({ security: "tls", users: { [ADDRESS]: OTHER } });+ const { service, call } = setup(smtp, "SSL");+ const answer = await service.connect({ address: ADDRESS, password: PASSWORD });+ const refused = `The outgoing server ${HOST}:${smtp.port} refused the password.`;+ expect(answer).toMatchObject({ ok: true, sending: { ok: false, problem: refused }, account: { sendingProblem: refused, smtpTried: { smtpHost: HOST, smtpPort: smtp.port, smtpSecurity: "tls" } } });+ expect(answer.ok && answer.account.smtpHost).toBeFalsy();+ const refusedSend = await call("EMAIL_SEND_MESSAGE", { to: ["[email protected]"], subject: "Hello", text: "Body" });+ expect(refusedSend).toMatchObject({ isError: true });+ expect(refusedSend.content[0]?.text).toContain(refused);+ expect(refusedSend.content[0]?.text).toContain("Don't retry");++ const signIns = smtp.signIns.length;+ expect(await service.checkOutgoing(ADDRESS, { smtpHost: HOST, smtpPort: smtp.port, smtpSecurity: "tls", smtpPassword: OTHER })).toMatchObject({ ok: true, account: { smtpHost: HOST, smtpPort: smtp.port } });+ expect(smtp.signIns.slice(signIns)).toEqual([{ mechanism: "PLAIN", user: ADDRESS, ok: true }]);+ expect(service.store.get(ADDRESS)).toMatchObject({ password: PASSWORD, smtpPassword: OTHER });+ expect(service.status().accounts[0]!.sendingProblem).toBeUndefined();++ expect(await service.sendTest(ADDRESS)).toEqual({ ok: true });+ expect(smtp.received.at(-1)).toMatchObject({ from: ADDRESS, to: [ADDRESS] });+ expect(service.scrub(`a ${OTHER} b`)).not.toContain(OTHER);+ }, 30_000);++ it("a mix-up typed by hand is said as one and nothing is saved over it", async () => {+ const smtp = await fake();+ const { service } = setup(smtp, "STARTTLS");+ await service.connect({ address: ADDRESS, password: PASSWORD });+ expect(await service.checkOutgoing(ADDRESS, { smtpHost: HOST, smtpPort: smtp.port, smtpSecurity: "tls" })).toMatchObject({ ok: false, error: expect.stringContaining("choose STARTTLS") });+ expect(service.store.get(ADDRESS)?.smtp).toEqual({ host: HOST, port: smtp.port, secure: false });+ }, 30_000);+});diff --git a/server/email/service.test.ts b/server/email/service.test.tsindex 17ccb222d2..e99f322301 100644--- a/server/email/service.test.ts+++ b/server/email/service.test.ts@@ -3,7 +3,7 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, describe, expect, it } from "vitest";-import { EmailError, openGuard } from "./client.ts";+import { EmailError, openGuard, sendingError } from "./client.ts";import type { DiscoverDeps } from "./discover.ts";import { createEmailService } from "./service.ts";import { MAX_EMAIL_ACCOUNTS } from "./store.ts";@@ -12,20 +12,33 @@ const PASSWORD = "fake-mailbox-password-1";const dirs: string[] = [];afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });-const NOWHERE: DiscoverDeps = { fetchText: async () => null, mx: async () => [], srv: async () => [] };+const NOWHERE: DiscoverDeps = { fetchText: async () => null, mx: async () => [], srv: async () => [], cname: async () => [], reverse: async () => [] };-function service(mailbox: (imap: { host: string; port: number }, username: string, password: string) => { messages: number; newest?: { from: string; subject: string } } | EmailError, sending: (host: string) => EmailError | void = () => {}, more: { refusal?: string; dataDir?: string } = {}) {+type Login = { username: string; password: string } | null;+type Server = { host: string; port: number; secure: boolean };++/** `sending` answers both the check without a password (login null) and the sign-in; `sent` records only sign-ins. */+function service(mailbox: (imap: { host: string; port: number }, username: string, password: string) => { messages: number; newest?: { from: string; subject: string } } | EmailError, sending: (host: string, login: Login, server: Server) => Error | void = () => {}, more: { refusal?: string; dataDir?: string; discover?: Partial<DiscoverDeps>; send?: (account: unknown, input: unknown) => void } = {}) {const dataDir = more.dataDir ?? mkdtempSync(join(tmpdir(), "omb-mail-service-")); if (!more.dataDir) dirs.push(dataDir);const tried: string[] = [];const sent: string[] = [];- const email = createEmailService({ dataDir, publicOnly: false, ...(more.refusal ? { refusal: more.refusal } : {}), discover: NOWHERE, guard: openGuard, test: {+ const logins: string[] = [];+ const email = createEmailService({ dataDir, publicOnly: false, ...(more.refusal ? { refusal: more.refusal } : {}), discover: { ...NOWHERE, ...more.discover }, guard: openGuard, test: {mailbox: (async (account: { username: string; password: string; imap: { host: string; port: number } }) => { tried.push(`${account.imap.host}:${account.imap.port}:${account.username}`); const answer = mailbox(account.imap, account.username, account.password); if (answer instanceof EmailError) throw answer; return answer; }) as never,- sending: (async (_account: unknown, server: { host: string; port: number }) => { sent.push(`${server.host}:${server.port}`); const answer = sending(server.host); if (answer) throw answer; }) as never,+ sending: (async (login: Login, server: Server) => {+ if (login) { sent.push(`${server.host}:${server.port}`); logins.push(`${server.host}:${login.username}:${login.password}`); }+ const answer = sending(server.host, login, server);+ if (answer) throw answer;+ }) as never,+ send: (async (account: unknown, _guard: unknown, input: unknown) => { more.send?.(account, input); return { messageId: "<1@x>", accepted: [], rejected: [], filed: false }; }) as never,} });- return { email, tried, sent, dataDir };+ return { email, tried, sent, logins, dataDir };}const NO_ANSWER = () => new EmailError("network", "no");const WRONG = () => new EmailError("password", "no");+/** What Nodemailer says when nothing answers, and when a server refuses the password. */+const SILENT = () => Object.assign(new Error("Connection timeout"), { code: "ETIMEDOUT" });+const REFUSED = () => Object.assign(new Error("Invalid login"), { code: "EAUTH", responseCode: 535 });describe("connecting a mailbox", () => {it("keeps nothing until a real header has been read back, and then says what it read", async () => {@@ -71,22 +84,130 @@ describe("connecting a mailbox", () => {expect(sent).toEqual(["out.hoster.example:2525"]);});+ it("typing only the incoming server still finds the outgoing one beside it", async () => {+ const { email, sent } = service((imap) => (imap.host === "imap.world4you.com" ? { messages: 2 } : NO_ANSWER()), (host) => (host === "smtp.world4you.com" ? undefined : NO_ANSWER()));+ expect(await email.connect({ address: "[email protected]", password: PASSWORD, imapHost: "imap.world4you.com" })).toMatchObject({ ok: true, sending: { ok: true }, account: { smtpHost: "smtp.world4you.com" } });+ expect(sent[0]).toBe("smtp.world4you.com:587");+ });+it("a typed port says how it speaks TLS: the well-known ports as they are, any other tried in TLS first, then upgraded", async () => {const seen: Array<Record<string, unknown>> = [];const dataDir = mkdtempSync(join(tmpdir(), "omb-mail-service-")); dirs.push(dataDir);const email = createEmailService({ dataDir, publicOnly: false, discover: NOWHERE, guard: openGuard, test: {mailbox: (async (account: { imap: Record<string, unknown> }) => { seen.push(account.imap); return { messages: 1 }; }) as never,- sending: (async (_account: unknown, server: Record<string, unknown>) => { seen.push(server); }) as never,+ sending: (async (login: unknown, server: Record<string, unknown>) => { if (login) seen.push(server); }) as never,} });for (const [imapPort, smtpPort] of [[993, 465], [143, 587], [10143, 2525]]) await email.connect({ address: "[email protected]", password: PASSWORD, imapHost: "a.example", imapPort, smtpHost: "b.example", smtpPort });expect(seen.map((server) => [server.port, server.secure])).toEqual([[993, true], [465, true], [143, false], [587, false], [10143, true], [2525, true]]);});- it("reading can work while sending doesn't, and it says so", async () => {- const { email } = service(() => ({ messages: 2 }), () => NO_ANSWER());- expect(await email.connect({ address: "[email protected]", password: PASSWORD })).toMatchObject({ ok: true, sending: { ok: false, problem: "No outgoing mail server answered." } });- expect(email.status().accounts[0]).toMatchObject({ problem: expect.stringContaining("Reading works") });+ it("reading can work while sending doesn't, and it says so in one sentence naming where it looked", async () => {+ const { email, sent } = service(() => ({ messages: 2 }), () => SILENT());+ const problem = "No outgoing mail server answered: smtp.shop.example, mail.shop.example, imap.shop.example on 465 or 587.";+ expect(await email.connect({ address: "[email protected]", password: PASSWORD })).toMatchObject({ ok: true, sending: { ok: false, problem } });+ expect(email.status().accounts[0]).toMatchObject({ sendingProblem: problem, smtpTried: { smtpHost: "smtp.shop.example" } });+ expect(email.status().accounts[0]!.problem).toBeUndefined();expect(email.store.get("[email protected]")?.smtp).toBeUndefined();+ expect(sent, "the password went nowhere that didn't answer").toEqual([]);+ expect(email.sendingProblem("[email protected]")).toBe(problem);+ });++ it("a refused outgoing password: tried under the other user names on that server only, then said plainly", async () => {+ const { email, logins } = service(() => ({ messages: 2 }), (_host, login) => (login ? REFUSED() : undefined));+ const problem = "The outgoing server smtp.shop.example:587 refused the password.";+ expect(await email.connect({ address: "[email protected]", password: PASSWORD })).toMatchObject({ ok: true, sending: { ok: false, problem }, account: { sendingProblem: problem } });+ expect(logins).toEqual([`smtp.shop.example:[email protected]:${PASSWORD}`, `smtp.shop.example:me:${PASSWORD}`]);+ });++ it("sends with the short name where only that works", async () => {+ const { email } = service(() => ({ messages: 2 }), (host, login) => (host !== "smtp.shop.example" ? SILENT() : login && login.username !== "me" ? REFUSED() : undefined));+ expect(await email.connect({ address: "[email protected]", password: PASSWORD })).toMatchObject({ ok: true, sending: { ok: true } });+ expect(email.store.get("[email protected]")).toMatchObject({ username: "[email protected]", smtpUsername: "me" });+ });++ it("the servers found for the address come before the ones beside the incoming server", async () => {+ const autoconfig = `<clientConfig><emailProvider id="x"><incomingServer type="imap"><hostname>imap.hoster.example</hostname><port>993</port><socketType>SSL</socketType></incomingServer>+ <outgoingServer type="smtp"><hostname>out.hoster.example</hostname><port>465</port><socketType>SSL</socketType></outgoingServer></emailProvider></clientConfig>`;+ const { email, sent } = service(() => ({ messages: 1 }), () => {}, { discover: { fetchText: async (url) => (url.includes("autoconfig.shop.example") ? autoconfig : null) } });+ await email.connect({ address: "[email protected]", password: PASSWORD });+ expect(sent).toEqual(["out.hoster.example:465"]);+ });++ it("a found server answered the other way round on its port is reached that way", async () => {+ const { email } = service(() => ({ messages: 1 }), (host, _login, server) => (host === "smtp.shop.example" && server.port === 587 && server.secure ? undefined : SILENT()));+ expect(await email.connect({ address: "[email protected]", password: PASSWORD })).toMatchObject({ ok: true, account: { smtpHost: "smtp.shop.example", smtpPort: 587, smtpSecurity: "tls" } });+ });++ it("Gmail and Outlook say what they need in one line, and Outlook never gets the password", async () => {+ const google = service(WRONG);+ expect(await google.email.connect({ address: "[email protected]", password: PASSWORD })).toEqual({ ok: false, error: expect.stringContaining("app password"), signIn: { provider: "Google", app: "gmail", appPasswordUrl: "https://myaccount.google.com/apppasswords" } });+ const microsoft = service(WRONG);+ expect(await microsoft.email.connect({ address: "[email protected]", password: PASSWORD })).toEqual({ ok: false, error: expect.stringContaining("sign in with Microsoft"), signIn: { provider: "Microsoft", app: "outlook" } });+ expect(microsoft.tried).toEqual([]);+ });++ it("an app password that reads but doesn't send at Google says what to do instead", async () => {+ const { email } = service(() => ({ messages: 1 }), (_host, login) => (login ? REFUSED() : undefined));+ expect(await email.connect({ address: "[email protected]", password: PASSWORD })).toMatchObject({ ok: true, sending: { ok: false, problem: expect.stringContaining("connect Gmail in Connected apps"), signIn: { app: "gmail" } } });+ });++ it("sending is checked again on its own: reading isn't signed in again, a server that works is kept, and one typed that fails changes nothing", async () => {+ let up = false;+ const { email, tried, sent } = service(() => ({ messages: 1 }), (host) => (up && host === "smtp.shop.example" ? undefined : SILENT()));+ await email.connect({ address: "[email protected]", password: PASSWORD });+ tried.length = 0;+ expect(await email.checkOutgoing("[email protected]", {})).toMatchObject({ ok: false, account: { sendingProblem: expect.stringContaining("No outgoing mail server answered") } });+ up = true;+ expect(await email.checkOutgoing("[email protected]", {})).toMatchObject({ ok: true, account: { smtpHost: "smtp.shop.example" } });+ expect(tried, "reading was not signed in again").toEqual([]);+ expect(email.status().accounts[0]!.sendingProblem).toBeUndefined();+ sent.length = 0;+ expect(await email.checkOutgoing("[email protected]", { smtpHost: "other.shop.example", smtpPort: 2525, smtpSecurity: "starttls" })).toMatchObject({ ok: false, error: "other.shop.example didn't answer on 2525." });+ expect(email.store.get("[email protected]")?.smtp).toMatchObject({ host: "smtp.shop.example" });+ expect(email.status().accounts[0]!.sendingProblem).toBeUndefined();+ expect(await email.checkOutgoing("[email protected]", { smtpHost: "bad host;x" })).toMatchObject({ ok: false });+ expect(await email.checkOutgoing("[email protected]", {})).toMatchObject({ ok: false });+ });++ it("the outgoing server typed by hand, with its own sign-in, is the only place its password goes", async () => {+ const { email, logins } = service(() => ({ messages: 1 }), (host, login) => (host !== "out.hoster.example" ? SILENT() : login && login.password !== "fake-outgoing-2" ? REFUSED() : undefined));+ await email.connect({ address: "[email protected]", password: PASSWORD });+ logins.length = 0;+ expect(await email.checkOutgoing("[email protected]", { smtpHost: "out.hoster.example", smtpPort: 465, smtpSecurity: "tls", smtpUsername: "sender-7", smtpPassword: "fake-outgoing-2" })).toMatchObject({ ok: true, account: { smtpHost: "out.hoster.example", smtpUsername: "sender-7" } });+ expect(logins).toEqual(["out.hoster.example:sender-7:fake-outgoing-2"]);+ expect(email.store.get("[email protected]")).toMatchObject({ password: PASSWORD, smtpUsername: "sender-7", smtpPassword: "fake-outgoing-2" });+ expect(JSON.stringify(email.status())).not.toContain("fake-outgoing-2");+ expect(email.scrub("x fake-outgoing-2 y")).not.toContain("fake-outgoing-2");+ });++ it("a test goes from the mailbox to itself, and only once it sends", async () => {+ const sentTo: unknown[] = [];+ const { email } = service(() => ({ messages: 1 }), (host) => (host === "smtp.shop.example" ? undefined : SILENT()), { send: (_account, input) => sentTo.push(input) });+ await email.connect({ address: "[email protected]", password: PASSWORD });+ expect(await email.sendTest("[email protected]")).toEqual({ ok: true });+ expect(sentTo).toMatchObject([{ to: ["[email protected]"] }]);+ const { email: unsent } = service(() => ({ messages: 1 }), () => SILENT());+ await unsent.connect({ address: "[email protected]", password: PASSWORD });+ expect(await unsent.sendTest("[email protected]")).toMatchObject({ ok: false, error: expect.stringContaining("No outgoing mail server answered") });+ });++ it("the plain words of a send's failure name the server and never the server's own text", () => {+ const server = { host: "smtp.shop.example", port: 587, secure: false };+ expect(sendingError(Object.assign(new Error("535 secret detail from the server"), { code: "EAUTH", responseCode: 535 }), server).message).toBe("The outgoing server smtp.shop.example:587 refused the password.");+ expect(sendingError(Object.assign(new Error("Greeting never received"), { code: "ETIMEDOUT" }), { ...server, port: 465 }).message).toBe("smtp.shop.example:465 expects SSL/TLS from the first byte; choose SSL/TLS for it, not STARTTLS.");+ expect(sendingError(Object.assign(new Error("ssl3_get_record:wrong version number"), { code: "ESOCKET" }), { ...server, secure: true }).message).toBe("smtp.shop.example:587 starts without TLS and upgrades with STARTTLS; choose STARTTLS for it, not SSL/TLS.");+ expect(sendingError(Object.assign(new Error("getaddrinfo ENOTFOUND"), { code: "EDNS" }), server).message).toBe("There is no mail server called smtp.shop.example.");+ });++ it("a mailbox saved read-only, which said so as its problem, is not held back by it", async () => {+ const { email, dataDir } = service(() => ({ messages: 1 }), () => SILENT());+ await email.connect({ address: "[email protected]", password: PASSWORD });+ const saved = email.store.get("[email protected]")!;+ const { sendingProblem: _problem, ...rest } = saved;+ email.store.put({ ...rest, problem: "Reading works. Sending doesn't yet: No outgoing mail server was found." });+ const again = service(() => ({ messages: 1 }), undefined, { dataDir }).email;+ expect(again.store.get("[email protected]")?.problem).toBeUndefined();+ expect(again.sendingProblem("[email protected]")).toBe("No outgoing server is set for sending.");});it("refuses what isn't an address or a host, and more mailboxes than it keeps", async () => {diff --git a/server/email/service.ts b/server/email/service.tsindex 640d86fe77..8517ddcffb 100644--- a/server/email/service.ts+++ b/server/email/service.ts@@ -1,19 +1,21 @@// The person's mailboxes: connecting one (find its servers, prove it reads a real header, keep the password sealed),// what the app shows of them, and a guard over where they connect. Shared by the Apps card, the card in a chat and a// move from the person's computer.-import { EMAIL_SLUG, type EmailAccountView, type EmailConnectAnswer, type EmailConnectRequest, type EmailStatus } from "../../shared/email.ts";+import { EMAIL_SLUG, type EmailAccountView, type EmailConnectAnswer, type EmailConnectRequest, type EmailOutgoingAnswer, type EmailOutgoingFields, type EmailSignInHint, type EmailStatus, type EmailTestAnswer } from "../../shared/email.ts";import { boxRefusal } from "../bot-box/egress-gate.ts";import { resolveTarget } from "../browser/egress/gate.ts";import { secretForms } from "../login-store.ts";import { HELD_SECRET_MASK } from "../redact.ts";-import { EmailError, openGuard, pinned, testMailbox, testSending, type EmailGuard } from "./client.ts";-import { discoverMailServers, liveDiscoverDeps, type DiscoverDeps, type MailCandidates } from "./discover.ts";+import { EmailError, LASTING_SENDING_FAULTS, openGuard, pinned, sendingError, sendMessage, SendingError, testMailbox, testSending, type EmailGuard, type SendingFault } from "./client.ts";+import { discoverMailServers, liveDiscoverDeps, smtpBeside, type DiscoverDeps, type MailCandidates } from "./discover.ts";import { EmailStore, MAX_EMAIL_ACCOUNTS, parseEmailAccount, type EmailAccount, type EmailServer } from "./store.ts";const ADDRESS = /^[^\s@<>()",;:]{1,200}@[a-z0-9-]+(?:\.[a-z0-9-]+)+$/iu;const HOST = /^[a-z0-9.-]{1,253}$/iu;/** How long connecting may look for a server that answers. */const FIND_MS = 60_000;+/** How long the password may go round the outgoing servers that answered. */+const SIGN_IN_MS = 60_000;export interface EmailServiceDeps {dataDir: string;@@ -24,7 +26,7 @@ export interface EmailServiceDeps {/** Test seams. */discover?: DiscoverDeps;guard?: EmailGuard;- test?: { mailbox: typeof testMailbox; sending: typeof testSending };+ test?: { mailbox: typeof testMailbox; sending: typeof testSending; send?: typeof sendMessage };now?(): number;}@@ -36,28 +38,71 @@ const publicGuard: EmailGuard = async ({ host, port }) => {return pinned(host, addresses[0]!.address);};-const view = (account: EmailAccount): EmailAccountView => ({- address: account.address, imapHost: account.imap.host, ...(account.smtp ? { smtpHost: account.smtp.host } : {}),- connectedAt: new Date(account.connectedAt).toISOString(), ...(account.problem ? { problem: account.problem } : {}),-});--function typed(request: EmailConnectRequest): MailCandidates | null {- const imap = request.imapHost?.trim();- if (!imap) return null;- // The first port of each pair starts in TLS, the second upgrades to it; any other port is tried both ways, TLS first- // (an upgrade on a TLS port only times out). Either way the password goes only once TLS is up.- const on = (host: string, port: number | undefined, [tls, upgraded]: [number, number]): EmailServer[] =>- port === tls ? [{ host, port, secure: true }] : port === upgraded ? [{ host, port, secure: false }]- : port ? [{ host, port, secure: true }, { host, port, secure: false }] : [{ host, port: tls, secure: true }, { host, port: upgraded, secure: false }];- return { imap: on(imap, request.imapPort, [993, 143]), smtp: request.smtpHost?.trim() ? on(request.smtpHost.trim(), request.smtpPort, [465, 587]) : [] };+/** Why this mailbox can't send, in one sentence; none while it can. */+export const sendingProblem = (account: EmailAccount): string | undefined => account.sendingProblem ?? (account.smtp ? undefined : "No outgoing server is set for sending.");++const security = (server: EmailServer) => (server.secure ? "tls" as const : "starttls" as const);++const view = (account: EmailAccount): EmailAccountView => {+ const sending = sendingProblem(account);+ return {+ address: account.address, imapHost: account.imap.host,+ ...(account.smtp ? { smtpHost: account.smtp.host, smtpPort: account.smtp.port, smtpSecurity: security(account.smtp) } : {}),+ ...(!account.smtp && account.smtpTried ? { smtpTried: { smtpHost: account.smtpTried.host, smtpPort: account.smtpTried.port, smtpSecurity: security(account.smtpTried) } } : {}),+ ...(account.smtpUsername ? { smtpUsername: account.smtpUsername } : {}),+ connectedAt: new Date(account.connectedAt).toISOString(), ...(account.problem ? { problem: account.problem } : {}), ...(sending ? { sendingProblem: sending } : {}),+ };+};++/** The places a typed port means: the first port of each pair starts in TLS, the second upgrades to it; any other port+ * is tried both ways, TLS first (an upgrade on a TLS port only times out). Either way the password goes only once TLS is up. */+function onPort(host: string, port: number | undefined, [tls, upgraded]: [number, number]): EmailServer[] {+ return port === tls ? [{ host, port, secure: true }] : port === upgraded ? [{ host, port, secure: false }]+ : port ? [{ host, port, secure: true }, { host, port, secure: false }] : [{ host, port: tls, secure: true }, { host, port: upgraded, secure: false }];+}++function typedOutgoing(fields: EmailOutgoingFields): EmailServer[] | null {+ const host = fields.smtpHost?.trim().toLowerCase();+ if (!host) return null;+ if (fields.smtpSecurity) return [{ host, port: fields.smtpPort ?? (fields.smtpSecurity === "tls" ? 465 : 587), secure: fields.smtpSecurity === "tls" }];+ return onPort(host, fields.smtpPort, [465, 587]);+}++/** A server's answer that says the most: one that spoke beats one that didn't, and silence beats a name that isn't there. */+const TELLING: readonly SendingFault[] = ["password", "refused", "no-sign-in", "no-tls", "wrong-security", "server", "rejected", "certificate", "no-answer", "missing"];+const telling = (misses: readonly SendingError[]) => [...misses].sort((a, b) => TELLING.indexOf(a.fault) - TELLING.indexOf(b.fault))[0];++/** Why no outgoing server would do, in one sentence, and the server it is about: what one that answered said, else which+ * were silent and where. */+function sendingSummary(misses: readonly SendingError[]): { problem: string; tried?: EmailServer } {+ const told = telling(misses.filter((miss) => miss.fault !== "no-answer" && miss.fault !== "missing"));+ if (told) return { problem: told.message, tried: told.server };+ const silent = misses.filter((miss) => miss.fault === "no-answer");+ if (!silent.length) return { problem: "No outgoing mail server was found for this address." };+ const hosts = [...new Set(silent.map((miss) => miss.server.host))];+ const ports = [...new Set(silent.map((miss) => miss.server.port))].sort((a, b) => a - b);+ const on = ports.length > 1 ? `${ports.slice(0, -1).join(", ")} or ${ports.at(-1)}` : String(ports[0]);+ const problem = hosts.length === 1 ? `${hosts[0]} didn't answer on ${on}.` : `No outgoing mail server answered: ${hosts.slice(0, 3).join(", ")}${hosts.length > 3 ? " and more" : ""} on ${on}.`;+ return { problem, tried: silent[0]!.server };}+/** What a provider needs instead of the mailbox password for sending, after the sentence that says it was refused. */+function sendingHint(hint: EmailSignInHint | undefined): string {+ if (hint?.app === "outlook") return " Microsoft is turning off password sign-in for sending (off by default from December 2026): connect Outlook in Connected apps instead.";+ if (hint?.app === "gmail") return " Google needs an app password for this, made with 2-step verification on, or connect Gmail in Connected apps instead.";+ if (hint) return ` ${hint.provider} needs an app password for this, made in the account's security settings.`;+ return "";+}++type Login = { username: string; password: string };+type Sending = { smtp: EmailServer; login: Login } | { problem: string; tried?: EmailServer };+export function createEmailService(deps: EmailServiceDeps) {const store = new EmailStore(deps.dataDir);/** Masks every saved password, in every form it might be written, in whatever a bot or a transcript can read. */const scrub = (text: string) => store.secretValues().flatMap(secretForms).reduce((safe, form) => (safe.includes(form) ? safe.split(form).join(HELD_SECRET_MASK) : safe), text);const guard = deps.guard ?? (deps.publicOnly ? publicGuard : openGuard);- const live = deps.test ?? { mailbox: testMailbox, sending: testSending };+ const live = { mailbox: testMailbox, sending: testSending, send: sendMessage, ...deps.test };const allowed = async (url: URL) => {if (!deps.publicOnly) return true;await publicGuard({ host: url.hostname, port: 443 });@@ -91,6 +136,62 @@ export function createEmailService(deps: EmailServiceDeps) {return last ?? new EmailError("network", "No mail server was found for this address.");}+ /** An outgoing server that answers over TLS with a sign-in on offer, or why not. No password goes. Found places are+ * reached in either way of starting TLS (a server may start TLS on 587, or upgrade on 465); a way the person chose is+ * reached only that way, so a mix-up is said as one. */+ async function reach(server: EmailServer, exact: boolean): Promise<EmailServer | SendingError> {+ const ways = exact ? [server] : [server, { ...server, secure: !server.secure }];+ try {+ return await Promise.any(ways.map(async (way) => { await live.sending(null, way, guard); return way; }));+ } catch (error) {+ const misses = ways.map((way, index) => sendingError((error as AggregateError).errors[index], way));+ return misses.find((miss) => miss.fault !== "no-answer") ?? misses[0]!;+ }+ }++ /** The first outgoing server that takes one of these sign-ins (the same password under another user name), or why none+ * would. Every place is reached at once without the password; then it goes, in order, only to those that answered,+ * and a refusal ends it there: it goes to no other host. */+ async function findSending(logins: readonly Login[], candidates: readonly EmailServer[], options: { exact?: boolean; hint?: EmailSignInHint } = {}): Promise<Sending> {+ const places = candidates.filter((server, index) => candidates.findIndex((other) => other.host === server.host && other.port === server.port) === index);+ const reached = places.map((server) => reach(server, options.exact === true));+ const misses: SendingError[] = [];+ const deadline = now() + SIGN_IN_MS;+ for (const answer of reached) {+ const server = await answer;+ if (server instanceof SendingError) { misses.push(server); continue; }+ if (now() > deadline) break;+ let refused: SendingError | undefined;+ for (const login of logins) {+ try {+ await live.sending(login, server, guard);+ return { smtp: server, login };+ } catch (error) {+ const failed = sendingError(error, server);+ if (failed.fault !== "password") { misses.push(failed); refused = undefined; break; }+ refused = failed;+ }+ }+ if (refused) return { problem: refused.message + sendingHint(options.hint), tried: server };+ }+ return sendingSummary(misses);+ }++ /** The user names to send with: one typed, else the one reading took, then the address or its local part. */+ const sendingNames = (address: string, reading: string, typed: string | undefined): string[] => {+ if (typed) return [typed];+ const local = address.slice(0, address.lastIndexOf("@"));+ return [...new Set([reading, address, local])];+ };++ /** The outgoing sign-in to keep: only what differs from the incoming one. */+ const ownLogin = (login: Login, account: Pick<EmailAccount, "username" | "password">) => ({+ ...(login.username !== account.username ? { smtpUsername: login.username } : {}),+ ...(login.password !== account.password ? { smtpPassword: login.password } : {}),+ });++ const outgoingHostProblem = (fields: EmailOutgoingFields) => (fields.smtpHost?.trim() && !HOST.test(fields.smtpHost.trim()) ? "A mail server is a name like mail.example.com." : null);+return {store,guard,@@ -98,9 +199,13 @@ export function createEmailService(deps: EmailServiceDeps) {scrub,mounted: () => !deps.refusal && store.list().length > 0,slug: EMAIL_SLUG,+ /** Why this mailbox can't send, or nothing while it can. */+ sendingProblem: (address: string): string | undefined => { const account = store.get(address); return account ? sendingProblem(account) : undefined; },- /** Connects a mailbox, or says why not. Nothing is saved until a real header has been read back. */- async connect(request: EmailConnectRequest): Promise<EmailConnectAnswer> {+ /** Connects a mailbox, or says why not. Nothing is saved until a real header has been read back; sending is checked+ * too, and a mailbox that only reads says why it can't send. `reading` hears the incoming server once it took the+ * password, while sending is still being checked. */+ async connect(request: EmailConnectRequest, reading?: (imapHost: string) => void): Promise<EmailConnectAnswer> {if (deps.refusal) return { ok: false, error: deps.refusal };const address = request.address.trim();const password = request.password;@@ -110,38 +215,83 @@ export function createEmailService(deps: EmailServiceDeps) {const existing = store.get(address);if (!existing && store.list().length >= MAX_EMAIL_ACCOUNTS) return { ok: false, error: `You can connect at most ${MAX_EMAIL_ACCOUNTS} mailboxes.` };const deadline = now() + FIND_MS;- const found = typed(request) ?? await discoverMailServers(address, discover);- if (existing && !request.imapHost?.trim()) {- found.imap = [existing.imap, ...found.imap.filter((server) => server.host !== existing.imap.host || server.port !== existing.imap.port)];- if (existing.smtp) found.smtp = [existing.smtp, ...found.smtp.filter((server) => server.host !== existing.smtp!.host || server.port !== existing.smtp!.port)];- }+ const imapHost = request.imapHost?.trim().toLowerCase();+ const outgoing = typedOutgoing(request);+ const found: MailCandidates = imapHost && outgoing ? { imap: [], smtp: [] } : await discoverMailServers(address, discover);+ // A provider with no password sign-in at all never gets one.+ if (!imapHost && found.provider?.rule === "no-password") return { ok: false, error: passwordHelp(found.provider), signIn: found.provider.hint };+ if (imapHost) found.imap = onPort(imapHost, request.imapPort, [993, 143]);+ else if (existing) found.imap = [existing.imap, ...found.imap.filter((server) => server.host !== existing.imap.host || server.port !== existing.imap.port)];let signedIn: Awaited<ReturnType<typeof signIn>>;try { signedIn = await signIn(address, password, request.username?.trim() || undefined, found, deadline); } catch (error) {const failed = error instanceof EmailError ? error : new EmailError("server", "The mail server said no.");- return { ok: false, error: failed.code === "password" ? passwordHelp(address) : failed.message };+ if (failed.code !== "password") return { ok: false, error: failed.message };+ return { ok: false, error: passwordHelp(found.provider), ...(found.provider ? { signIn: found.provider.hint } : {}) };}if (signedIn instanceof EmailError) {if (signedIn.code === "refused") return { ok: false, needsServer: true, error: signedIn.message };- return { ok: false, needsServer: true, error: request.imapHost?.trim() ? "That mail server did not answer over a secure connection. Check its name and port." : "We couldn't find your mail server. Type its name, which your mail provider's help pages list." };+ return { ok: false, needsServer: true, error: imapHost ? "That mail server did not answer over a secure connection. Check its name and port." : "We couldn't find your mail server. Type its name, which your mail provider's help pages list." };}- let smtp: EmailServer | undefined;- let problem: string | undefined;- for (const server of found.smtp) {- if (now() > deadline) break;- try {- await live.sending({ username: signedIn.username, password }, server, guard);- smtp = server;- problem = undefined;- break;- } catch (error) {- problem = error instanceof EmailError && error.code === "password" ? "The outgoing server did not accept this password." : "No outgoing mail server answered.";- if (error instanceof EmailError && error.code === "password") break;- }- }- if (!found.smtp.length) problem = "No outgoing mail server was found.";- const account: EmailAccount = { address, username: signedIn.username, password, imap: signedIn.imap, ...(smtp ? { smtp } : {}), connectedAt: now(), ...(smtp ? {} : { problem: `Reading works. Sending doesn't yet: ${problem ?? "No outgoing mail server was found."}` }) };+ reading?.(signedIn.imap.host);+ const smtpPassword = request.smtpPassword || password;+ const logins = sendingNames(address, signedIn.username, request.smtpUsername?.trim()).map((username) => ({ username, password: smtpPassword }));+ const places = outgoing ?? [...(existing?.smtp ? [existing.smtp] : []), ...found.smtp, ...smtpBeside(signedIn.imap.host)];+ const sending = await findSending(logins, places, { exact: Boolean(request.smtpSecurity), hint: found.provider?.hint });+ const account: EmailAccount = {+ address, username: signedIn.username, password, imap: signedIn.imap, connectedAt: now(),+ ...("smtp" in sending+ ? { smtp: sending.smtp, ...ownLogin(sending.login, { username: signedIn.username, password }) }+ : { ...ownLogin({ username: request.smtpUsername?.trim() || signedIn.username, password: smtpPassword }, { username: signedIn.username, password }), sendingProblem: sending.problem, ...(sending.tried ? { smtpTried: sending.tried } : {}) }),+ };store.put(account);- return { ok: true, account: view(account), inbox: signedIn.inbox, sending: smtp ? { ok: true } : { ok: false, problem: problem ?? "No outgoing mail server was found." } };+ const hint = "smtp" in sending ? undefined : found.provider?.hint;+ return { ok: true, account: view(account), inbox: signedIn.inbox, sending: "smtp" in sending ? { ok: true } : { ok: false, problem: sending.problem, ...(hint ? { signIn: hint } : {}) } };+ },++ /** Checks sending again for a connected mailbox, at the outgoing server typed here or the ones found for it, without+ * signing in to read again. A working server is kept; a failed check leaves one that worked as it was. */+ async checkOutgoing(address: string, fields: EmailOutgoingFields): Promise<EmailOutgoingAnswer> {+ if (deps.refusal) return { ok: false, error: deps.refusal };+ const account = store.get(address);+ if (!account) return { ok: false, error: `No mailbox ${address} is connected.` };+ const bad = outgoingHostProblem(fields);+ if (bad) return { ok: false, error: bad };+ const password = fields.smtpPassword || account.smtpPassword || account.password;+ const logins = sendingNames(account.address, account.smtpUsername ?? account.username, fields.smtpUsername?.trim()).map((username) => ({ username, password }));+ const typed = typedOutgoing(fields);+ const found = typed ? null : await discoverMailServers(account.address, discover);+ const places = typed ?? [...(account.smtp ? [account.smtp] : []), ...(account.smtpTried ? [account.smtpTried] : []), ...found!.smtp, ...smtpBeside(account.imap.host)];+ const sending = await findSending(logins, places, { exact: Boolean(fields.smtpSecurity), hint: found?.provider?.hint });+ const current = store.get(address);+ if (!current || current.password !== account.password) return { ok: false, error: "This mailbox changed while sending was checked. Check again." };+ const { smtpUsername: _username, smtpPassword: _password, sendingProblem: _problem, smtpTried: _tried, ...rest } = current;+ if ("smtp" in sending) {+ const next: EmailAccount = { ...rest, smtp: sending.smtp, ...ownLogin(sending.login, current) };+ store.put(next);+ return { ok: true, account: view(next) };+ }+ // A server that sends stays until one typed here works instead.+ if (current.smtp && !current.sendingProblem) return { ok: false, error: sending.problem };+ const { smtp: _smtp, ...unsent } = rest;+ const next: EmailAccount = { ...unsent, ...ownLogin({ username: logins[0]!.username, password }, current), sendingProblem: sending.problem, ...(sending.tried ? { smtpTried: sending.tried } : {}) };+ store.put(next);+ return { ok: false, error: sending.problem, account: view(next) };+ },++ /** Sends a short message from a mailbox to itself: sending proven end to end. */+ async sendTest(address: string): Promise<EmailTestAnswer> {+ if (deps.refusal) return { ok: false, error: deps.refusal };+ const account = store.get(address);+ if (!account) return { ok: false, error: `No mailbox ${address} is connected.` };+ const problem = sendingProblem(account);+ if (problem) return { ok: false, error: problem };+ try {+ await live.send(account, guard, { to: [account.address], subject: "OpenMausBot test", text: `This message is a test from OpenMausBot: sending from ${account.address} works.` });+ return { ok: true };+ } catch (error) {+ if (error instanceof SendingError && LASTING_SENDING_FAULTS.has(error.fault)) store.markSendingProblem(account, error.message);+ return { ok: false, error: error instanceof EmailError ? error.message : "The test message could not be sent." };+ }},disconnect(address: string): EmailStatus {@@ -166,11 +316,10 @@ export function createEmailService(deps: EmailServiceDeps) {export type EmailService = ReturnType<typeof createEmailService>;-/** Why a password failed, with what the big providers need instead. */-function passwordHelp(address: string): string {- const domain = address.slice(address.lastIndexOf("@") + 1).toLowerCase();- if (/^(?:gmail|googlemail)\.com$/u.test(domain)) return "Google needs an app password here, not your normal password. For Gmail, the Gmail app in Connected apps is easier.";- if (/^(?:outlook|hotmail|live|msn)\.[a-z.]+$/u.test(domain)) return "Microsoft no longer lets mail programs in with a password.";- if (/^(?:icloud|me|mac)\.com$/u.test(domain)) return "Apple needs an app-specific password here, not your Apple account password.";+/** Why a password failed, with what the big providers need instead, in one line. */+function passwordHelp(provider: MailCandidates["provider"]): string {+ if (provider?.hint.app === "outlook") return "Microsoft doesn't let mail programs in with a password: sign in with Microsoft instead.";+ if (provider?.hint.app === "gmail") return "Google needs an app password here (with 2-step verification on), or sign in with Google instead.";+ if (provider) return `${provider.hint.provider} needs an app password here, made in your account's security settings, not your normal password.`;return "The mail server did not accept this address and password. Check them and try again.";}diff --git a/server/email/store.ts b/server/email/store.tsindex 4211cff569..a1de8bb422 100644--- a/server/email/store.ts+++ b/server/email/store.ts@@ -20,8 +20,15 @@ const accountSchema = z.object({password: z.string().min(1).max(4_096),imap: serverSchema,smtp: serverSchema.optional(),+ /** The outgoing server's own sign-in, when it isn't the incoming one's. */+ smtpUsername: z.string().min(1).max(320).optional(),+ smtpPassword: z.string().min(1).max(4_096).optional(),connectedAt: z.number(),problem: z.string().max(400).optional(),+ /** Why sending doesn't work, from the last check or send; sends wait for the person while it is set. */+ sendingProblem: z.string().max(400).optional(),+ /** While sending doesn't work: the outgoing server that reason is about. */+ smtpTried: serverSchema.optional(),});const fileSchema = z.object({ version: z.literal(1), accounts: z.array(accountSchema).max(MAX_EMAIL_ACCOUNTS) });@@ -35,7 +42,14 @@ const EMPTY: StoreFile = { version: 1, accounts: [] };/** A mailbox as this store keeps it, from anywhere else (one moved from the person's own computer); null if not. */export function parseEmailAccount(value: unknown): EmailAccount | null {const parsed = accountSchema.safeParse(value);- return parsed.success ? parsed.data : null;+ return parsed.success ? withoutReadOnlyProblem(parsed.data) : null;+}++/** "Reading works. …" as the problem of a mailbox with no outgoing server is a sending problem, which isn't kept there. */+function withoutReadOnlyProblem(account: EmailAccount): EmailAccount {+ if (account.smtp || !account.problem?.startsWith("Reading works.")) return account;+ const { problem: _problem, ...rest } = account;+ return rest;}const same = (a: string, b: string) => a.toLowerCase() === b.toLowerCase();@@ -70,7 +84,8 @@ export class EmailStore {const key = this.key(false);try {if (!key) throw new Error("missing key");- data = fileSchema.parse(JSON.parse(decryptBrowserState(readFileSync(this.file), key)));+ const parsed = fileSchema.parse(JSON.parse(decryptBrowserState(readFileSync(this.file), key)));+ data = { ...parsed, accounts: parsed.accounts.map(withoutReadOnlyProblem) };} catch {// Never log an unreadable file's contents.if (!this.unreadableWarned) console.warn("Email: the saved mailboxes could not be opened; connect them again");@@ -118,8 +133,15 @@ export class EmailStore {this.put({ ...rest, ...(problem ? { problem } : {}) });}+ /** Says sending stopped working, only while the outgoing server and its password are still the ones that failed. */+ markSendingProblem(failed: Pick<EmailAccount, "address" | "password" | "smtp" | "smtpPassword">, problem: string): void {+ const current = this.get(failed.address);+ if (!current || current.password !== failed.password || current.smtpPassword !== failed.smtpPassword || current.smtp?.host !== failed.smtp?.host || current.smtp?.port !== failed.smtp?.port || current.sendingProblem === problem) return;+ this.put({ ...current, sendingProblem: problem });+ }+/** The passwords, for secret redaction. */secretValues(): string[] {- return this.list().map((account) => account.password);+ return this.list().flatMap((account) => (account.smtpPassword ? [account.password, account.smtpPassword] : [account.password]));}}diff --git a/server/host/secret-cards.test.ts b/server/host/secret-cards.test.tsindex 3588b0ae20..e18e14d7d6 100644--- a/server/host/secret-cards.test.ts+++ b/server/host/secret-cards.test.ts@@ -94,7 +94,7 @@ describe("the card a bot asks for a key or secret with", () => {describe("the mailbox card", () => {const PASSWORD = "fake-mailbox-password";const ACCOUNT = { address: "[email protected]", imapHost: "imap.shop.example", smtpHost: "smtp.shop.example", connectedAt: "2026-11-04T00:00:00.000Z" };- function mail(options: { refusal?: string; connected?: boolean; profile?: string; connect?: (request: Record<string, unknown>) => unknown } = {}) {+ function mail(options: { refusal?: string; connected?: boolean; sendingProblem?: string; profile?: string; connect?: (request: Record<string, unknown>, reading?: (host: string) => void) => unknown } = {}) {const dataDir = mkdtempSync(join(tmpdir(), "omb-secret-cards-"));dirs.push(dataDir);const lines: Message[] = [];@@ -115,8 +115,8 @@ describe("the mailbox card", () => {connectorThread: () => ({ bot, group: undefined }), answerCardNode: (_thread, _id, text) => { resumed.push(text); return true; }, followCard: () => {}, dataDir, providerKeysRefused: false,layerFolder: () => dataDir, turnVm: () => undefined,email: {- connect: async (request) => { connects.push(request as never); return (options.connect?.(request as never) ?? { ok: true, account: ACCOUNT, inbox: { messages: 3 }, sending: { ok: true } }) as never; },- refusal: () => options.refusal, connected: () => options.connected === true, profileAddress: () => options.profile,+ connect: async (request, reading) => { connects.push(request as never); return (options.connect?.(request as never, reading) ?? { ok: true, account: ACCOUNT, inbox: { messages: 3 }, sending: { ok: true } }) as never; },+ refusal: () => options.refusal, connected: () => options.connected === true, sendingProblem: () => options.sendingProblem, profileAddress: () => options.profile,},});return { cards, lines, bot, connects, resumed };@@ -143,7 +143,7 @@ describe("the mailbox card", () => {it("doesn't ask again for a mailbox that works, and a newer card replaces an older one", () => {const working = mail({ connected: true });- expect(ask(working, { address: "[email protected]" })).toEqual({ status: 200, body: { alreadyConfigured: true, label: "[email protected]" } });+ expect(ask(working, { address: "[email protected]" })).toEqual({ status: 200, body: { alreadyConfigured: true, label: "[email protected]", text: "[email protected] is already connected. Use the email tools." } });expect(working.lines).toEqual([]);const fixture = mail();ask(fixture);@@ -197,6 +197,47 @@ describe("the mailbox card", () => {expect(fixture.connects).toEqual([]);});+ it("a mailbox that reads but can't send isn't asked for again: the bot hears why, who fixes it, and not to retry", () => {+ const reading = mail({ connected: true, sendingProblem: "The outgoing server smtp.shop.example:587 refused the password." });+ const text = String(ask(reading, { address: "[email protected]" }).body.text);+ expect(text).toContain("refused the password");+ expect(text).toContain("Connected apps");+ expect(text).toContain("Don't retry");+ expect(text).not.toMatch(/try again/iu);+ expect(reading.lines).toEqual([]);+ });++ it("while connecting the card shows the incoming server that took the password, and a failure takes it away", async () => {+ const shown: Array<string | undefined> = [];+ let fail = true;+ const fixture = mail({ connect: (_request, reading) => {+ reading?.("imap.shop.example");+ shown.push(card(fixture).secret!.emailReading);+ return fail ? { ok: false, error: "nope" } : undefined;+ } });+ ask(fixture, { address: "[email protected]" });+ const { id } = card(fixture);+ await fixture.cards.saveEmailSecret("ledger", "t1", id, { value: PASSWORD });+ expect(shown).toEqual(["imap.shop.example"]);+ expect(card(fixture).secret!.emailReading).toBeUndefined();+ fail = false;+ await fixture.cards.saveEmailSecret("ledger", "t1", id, { value: PASSWORD });+ expect(card(fixture).secret).toMatchObject({ provided: true, emailReading: "imap.shop.example" });+ });++ it("Gmail and Outlook's way to sign in reaches the card, and only reading connected tells the bot sending waits for the person", async () => {+ const signIn = { provider: "Microsoft", app: "outlook" };+ const refused = mail({ connect: () => ({ ok: false, error: "Microsoft doesn't let mail programs in with a password.", signIn }) });+ ask(refused, { address: "[email protected]" });+ expect(await refused.cards.saveEmailSecret("ledger", "t1", card(refused).id, { value: PASSWORD })).toEqual({ status: 400, body: { error: "Microsoft doesn't let mail programs in with a password.", signIn } });+ const problem = "smtp.shop.example didn't answer on 465 or 587.";+ const readOnly = mail({ sendingProblem: problem, connect: () => ({ ok: true, account: { ...ACCOUNT, smtpHost: undefined, sendingProblem: problem }, inbox: { messages: 3 }, sending: { ok: false, problem } }) });+ ask(readOnly, { address: "[email protected]" });+ expect(await readOnly.cards.saveEmailSecret("ledger", "t1", card(readOnly).id, { value: PASSWORD })).toMatchObject({ status: 200, body: { provided: true, sendingProblem: problem } });+ expect(readOnly.resumed[0]).toContain(problem);+ expect(readOnly.resumed[0]).not.toContain("EMAIL_SEND_MESSAGE");+ });+it("the bot hears that it may go on, or that the person declined, never a value", () => {const fixture = mail();ask(fixture, { address: "[email protected]" });diff --git a/server/host/secret-cards.ts b/server/host/secret-cards.tsindex 18a76daf77..a882b7bad5 100644--- a/server/host/secret-cards.ts+++ b/server/host/secret-cards.ts@@ -21,6 +21,7 @@ import {type SecretDelivery,} from "../../shared/credential-request.ts";import { EMAIL_CREDENTIAL, type EmailConnectAnswer, type EmailConnectRequest, type EmailServerFields } from "../../shared/email.ts";+import { EMAIL_CANT_SEND_TEXT } from "../email/instructions.ts";import type { SecretRequestCardData } from "../../shared/wire.ts";import type { AppConfig } from "../config.ts";import { perBotLocalVmTarget, poolLocalVmTarget, SHARED_LOCAL_VM_TARGET, VM_WORKSPACE_GUEST } from "../container-computer.ts";@@ -72,11 +73,13 @@ export interface SecretCardsDeps {threadLanguage?(threadId: string): string | undefined;/** The Email connector the mailbox card saves to: connecting proves it reads a real header before anything is kept. */email?: {- connect(request: EmailConnectRequest): Promise<EmailConnectAnswer>;+ connect(request: EmailConnectRequest, reading?: (imapHost: string) => void): Promise<EmailConnectAnswer>;/** Why a mailbox can't be connected here, if so. */refusal(): string | undefined;/** Already connected and working. */connected(address: string): boolean;+ /** Why a connected mailbox can't send, if it can't. */+ sendingProblem(address: string): string | undefined;/** The person's own address, the likeliest mailbox when the bot names none. */profileAddress(): string | undefined;};@@ -113,18 +116,22 @@ function vmFileHome(botId: string, vm: string): SecretFileHome | null {}/** What the bot hears when the mailbox card settles; it never hears the password. */-function emailUpdateText(secret: SecretRequestCardData, outcome: "provided" | "dismissed"): string {- return outcome === "provided"- ? `OpenMausBot secret update: the person connected the mailbox ${secret.address ?? "they typed"}. The email tools (EMAIL_LIST_MESSAGES, EMAIL_READ_MESSAGE, EMAIL_SEND_MESSAGE and others) are ready. Continue the task that paused for it.`- : "OpenMausBot secret update: the person chose not to connect a mailbox. Say briefly what you cannot do without it, and do not ask for the password in chat.";+function emailUpdateText(secret: SecretRequestCardData, outcome: "provided" | "dismissed", sendingProblem: string | undefined): string {+ if (outcome === "dismissed") return "OpenMausBot secret update: the person chose not to connect a mailbox. Say briefly what you cannot do without it, and do not ask for the password in chat.";+ const address = secret.address ?? "they typed";+ return sendingProblem+ ? `OpenMausBot secret update: the person connected the mailbox ${address} for reading: EMAIL_LIST_MESSAGES, EMAIL_READ_MESSAGE and the other reading tools are ready. Sending from it doesn't work yet: ${sendingProblem} Only the person can fix that, under Outgoing server in Connected apps › Email. Continue the task as far as reading allows; don't try to send another way.`+ : `OpenMausBot secret update: the person connected the mailbox ${address}. The email tools (EMAIL_LIST_MESSAGES, EMAIL_READ_MESSAGE, EMAIL_SEND_MESSAGE and others) are ready. Continue the task that paused for it.`;}-const SERVER_FIELDS = ["imapHost", "imapPort", "smtpHost", "smtpPort", "username"] as const;+const SERVER_FIELDS = ["imapHost", "imapPort", "smtpHost", "smtpPort", "smtpSecurity", "username", "smtpUsername", "smtpPassword"] as const;function emailServerFields(fields: Record<string, unknown>): EmailServerFields {const out: Record<string, unknown> = {};for (const name of SERVER_FIELDS) {const value = fields[name];- if ((name.endsWith("Port") && Number.isInteger(value)) || (!name.endsWith("Port") && typeof value === "string" && value.trim())) out[name] = value;+ if (name === "smtpSecurity") { if (value === "tls" || value === "starttls") out[name] = value; }+ else if (name === "smtpPassword") { if (typeof value === "string" && value && Buffer.byteLength(value) <= SECRET_VALUE_MAX_BYTES) out[name] = value; }+ else if ((name.endsWith("Port") && Number.isInteger(value)) || (!name.endsWith("Port") && typeof value === "string" && value.trim())) out[name] = value;}return out as EmailServerFields;}@@ -155,7 +162,7 @@ export function createSecretCards(deps: SecretCardsDeps) {function updateText(messageId: string, secret: SecretRequestCardData, outcome: "provided" | "dismissed"): string {if (!custom(secret)) return credentialUpdateText(secret.label, outcome);- if (secret.delivery === "email") return emailUpdateText(secret, outcome);+ if (secret.delivery === "email") return emailUpdateText(secret, outcome, secret.address ? deps.email?.sendingProblem(secret.address) : undefined);return outcome === "provided"? `OpenMausBot secret update: ${savedSecretText(secret.label, vault.savedFor(messageId))} Continue the task that paused for it.`: `OpenMausBot secret update: the person declined to provide ${secret.label}. Continue without it if you can, or say briefly what you cannot do. Do not ask for it in chat.`;@@ -242,11 +249,18 @@ export function createSecretCards(deps: SecretCardsDeps) {const address = typeof fields.address === "string" && fields.address.trim() ? fields.address.trim() : secret.address ?? "";if (!address || !password.trim() || Buffer.byteLength(password) > SECRET_VALUE_MAX_BYTES) return { status: 400, body: userError("serverError.secret.emailAndPassword") };if (!deps.email) return { status: 409, body: userError("serverError.secret.emailUnavailable") };- const answer = await deps.email.connect({ address, password, ...emailServerFields(fields) });- if (!answer.ok) return { status: 400, body: { error: answer.error, ...(answer.needsServer ? { needsServer: true } : {}) } };+ const reading = (emailReading: string) => {+ const card = secretMessage(botId, threadId, messageId);+ if (card?.secret && card.secret.savedAt === undefined) store.patchMessage(threadId, message.id, { secret: { ...card.secret, emailReading } });+ };+ const answer = await deps.email.connect({ address, password, ...emailServerFields(fields) }, reading);const current = secretMessage(botId, threadId, messageId);+ if (!answer.ok) {+ if (current?.secret?.emailReading) { const { emailReading: _reading, ...rest } = current.secret; store.patchMessage(threadId, message.id, { secret: rest }); }+ return { status: 400, body: { error: answer.error, ...(answer.needsServer ? { needsServer: true } : {}), ...(answer.signIn ? { signIn: answer.signIn } : {}) } };+ }if (!current?.secret) return { status: 409, body: userError("serverError.secret.unavailableLower") };- store.patchMessage(threadId, message.id, { secret: { ...current.secret, address: answer.account.address, savedAt: Date.now() } });+ store.patchMessage(threadId, message.id, { secret: { ...current.secret, address: answer.account.address, emailReading: answer.account.imapHost, savedAt: Date.now() } });if (!resumeSecretCard(botId, threadId, message.id, "provided")) return { status: 409, body: userError("serverError.secret.unavailableLower") };return { status: 200, body: { ...currentSecretState(botId, threadId, message.id), ...(answer.sending.ok ? {} : { sendingProblem: answer.sending.problem }) } };}@@ -456,7 +470,10 @@ export function createSecretCards(deps: SecretCardsDeps) {const refusal = deps.email ? deps.email.refusal() : "Email can't be connected here.";if (refusal || !deps.email) return { status: 403, body: { error: refusal } };const named = typeof body.address === "string" && /^[^\s@]+@[^\s@]+$/u.test(body.address.trim()) ? body.address.trim() : undefined;- if (named && deps.email.connected(named)) return { status: 200, body: { alreadyConfigured: true, label: named } };+ if (named && deps.email.connected(named)) {+ const sending = deps.email.sendingProblem(named);+ return { status: 200, body: { alreadyConfigured: true, label: named, text: sending ? `${named} is connected for reading. ${EMAIL_CANT_SEND_TEXT(named, sending)}` : `${named} is already connected. Use the email tools.` } };+ }const address = named ?? deps.email.profileAddress();const reason = typeof body.reason === "string" ? body.reason.trim().slice(0, CUSTOM_SECRET_REASON_MAX) : "";const language = deps.threadLanguage?.(threadId);diff --git a/server/index.ts b/server/index.tsindex 8022cf5240..bbc7a8700f 100644--- a/server/index.ts+++ b/server/index.ts@@ -11563,7 +11563,7 @@ function claimPhoneSecretBotDeletion(botId: string): (() => void) | null {};}-const secretCards = createSecretCards({ store, cfg, botLogins, phoneSecrets, phoneSecretSubmissions, connectorThread, answerCardNode, followCard: (threadId, from, to) => coordinator.followCard(threadId, from, to), threadLanguage, email: { connect: (request) => emailService.connect(request), refusal: () => emailService.status().reason, connected: (address) => { const one = emailService.store.get(address); return Boolean(one && !one.problem); }, profileAddress: () => cfg.profile?.email?.trim() || undefined }, dataDir: DATA_DIR, providerKeysRefused: Boolean(hostedModels), layerFolder: (botId, threadId) => workspaceDir(teamHost.layer(botId, threadId)), turnVm: (threadId) => localVmThreadTargets.get(threadId)?.key });+const secretCards = createSecretCards({ store, cfg, botLogins, phoneSecrets, phoneSecretSubmissions, connectorThread, answerCardNode, followCard: (threadId, from, to) => coordinator.followCard(threadId, from, to), threadLanguage, email: { connect: (request, reading) => emailService.connect(request, reading), refusal: () => emailService.status().reason, connected: (address) => { const one = emailService.store.get(address); return Boolean(one && !one.problem); }, sendingProblem: (address) => emailService.sendingProblem(address), profileAddress: () => cfg.profile?.email?.trim() || undefined }, dataDir: DATA_DIR, providerKeysRefused: Boolean(hostedModels), layerFolder: (botId, threadId) => workspaceDir(teamHost.layer(botId, threadId)), turnVm: (threadId) => localVmThreadTargets.get(threadId)?.key });ROUTES.push(createSecretCardRoutes({ cards: secretCards, phoneSecretSubmissions, threadVisible: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), answerContext: (auth, botId, threadId) => ({ personalCloud: Boolean(CLOUD_PERSONAL), shared: sharedMembership(), owner: (CLOUD_TEAM ? teamOwners.routing.askedPerson(botId, threadId) : null) ?? threadStarters.get(threadId) ?? null, person: auth.kind === "session" ? personKey(auth.session) : null }) }));// By design OpenMausBot never receives a website password: the person signs in where the bot works, and the bot uses that session.diff --git a/server/routes/email.test.ts b/server/routes/email.test.tsindex 1f16e7090e..d840f1e757 100644--- a/server/routes/email.test.ts+++ b/server/routes/email.test.ts@@ -3,11 +3,11 @@ import type { EmailService } from "../email/service.ts";import { createEmailRoutes } from "./email.ts";describe("mailbox route refusals", () => {- async function call(admin: boolean, input: unknown) {+ async function call(admin: boolean, input: unknown, path = "/api/email/accounts", service: Partial<EmailService> = {}, type = "application/json") {const answers: unknown[] = [];- await createEmailRoutes({ service: {} as EmailService })({- req: { headers: { "content-type": "application/json" } }, res: { setHeader() {} },- path: "/api/email/accounts", method: "POST", auth: { scopes: admin ? ["admin"] : [] },+ await createEmailRoutes({ service: service as EmailService })({+ req: { headers: { "content-type": type } }, res: { setHeader() {} },+ path, method: "POST", auth: { scopes: admin ? ["admin"] : [] },json: (_res: unknown, status: number, body: unknown) => answers.push([status, body]), readBody: async () => input,} as never);return answers;@@ -18,4 +18,15 @@ describe("mailbox route refusals", () => {it("keeps English and identifies invalid connection fields", async () => {expect(await call(true, {})).toEqual([[400, { error: "Enter your email address and password.", errorKey: "serverError.mailbox.addressAndPassword" }]]);});+ it("checks sending again with only the outgoing fields, and a test send only as JSON", async () => {+ const checked: unknown[] = [];+ const service = { checkOutgoing: async (address: string, fields: unknown) => { checked.push([address, fields]); return { ok: true }; }, sendTest: async () => ({ ok: true }) } as unknown as Partial<EmailService>;+ const at = `/api/email/accounts/${encodeURIComponent("[email protected]")}`;+ expect(await call(true, { smtpHost: "smtp.shop.example", smtpPort: 465, smtpSecurity: "tls" }, `${at}/outgoing`, service)).toEqual([[200, { ok: true }]]);+ expect(checked).toEqual([["[email protected]", { smtpHost: "smtp.shop.example", smtpPort: 465, smtpSecurity: "tls" }]]);+ expect(await call(true, { smtpHost: "smtp.shop.example", password: "x" }, `${at}/outgoing`, service)).toEqual([[400, { error: expect.stringContaining("outgoing server"), errorKey: "serverError.mailbox.outgoingFields" }]]);+ expect(await call(true, {}, `${at}/test`, service, "text/plain")).toEqual([[415, { error: "content-type must be application/json" }]]);+ expect(await call(true, {}, `${at}/test`, service)).toEqual([[200, { ok: true }]]);+ expect(await call(false, {}, `${at}/test`, service)).toMatchObject([[403, {}]]);+ });});diff --git a/server/routes/email.ts b/server/routes/email.tsindex 4ff9d8789d..6be9206582 100644--- a/server/routes/email.ts+++ b/server/routes/email.ts@@ -6,17 +6,23 @@ import type { EmailService } from "../email/service.ts";import { userError } from "../user-errors.ts";import { PASS, type RouteHandler } from "./table.ts";-const body = z.object({+const outgoing = z.object({+ smtpHost: z.string().trim().max(253).optional(),+ smtpPort: z.number().int().min(1).max(65_535).optional(),+ smtpSecurity: z.enum(["tls", "starttls"]).optional(),+ smtpUsername: z.string().trim().max(320).optional(),+ smtpPassword: z.string().max(4_096).optional(),+}).strict();++const body = outgoing.extend({address: z.string().trim().min(3).max(320),password: z.string().min(1).max(4_096),imapHost: z.string().trim().max(253).optional(),imapPort: z.number().int().min(1).max(65_535).optional(),- smtpHost: z.string().trim().max(253).optional(),- smtpPort: z.number().int().min(1).max(65_535).optional(),username: z.string().trim().max(320).optional(),}).strict();-const ACCOUNT = /^\/api\/email\/accounts\/([^/]{3,960})$/u;+const ACCOUNT = /^\/api\/email\/accounts\/([^/]{3,960})(?:\/(outgoing|test))?$/u;export function createEmailRoutes(deps: { service: EmailService }): RouteHandler {const { service } = deps;@@ -34,7 +40,16 @@ export function createEmailRoutes(deps: { service: EmailService }): RouteHandlerreturn json(res, 200, answer);}const one = ACCOUNT.exec(path);- if (one && method === "DELETE") return json(res, 200, service.disconnect(decodeURIComponent(one[1]!)));- return json(res, 404, { error: "not found" });+ let address: string | null = null;+ try { address = one ? decodeURIComponent(one[1]!) : null; } catch {}+ if (!one || !address) return json(res, 404, { error: "not found" });+ if (!one[2]) return method === "DELETE" ? json(res, 200, service.disconnect(address)) : json(res, 405, { error: "method not allowed" });+ if (method !== "POST") return json(res, 405, { error: "method not allowed" });+ // JSON only, so a form posted from another page can't send a message or change where mail goes.+ if (!String(req.headers["content-type"] ?? "").toLowerCase().startsWith("application/json")) return json(res, 415, { error: "content-type must be application/json" });+ if (one[2] === "test") return json(res, 200, await service.sendTest(address));+ const fields = outgoing.safeParse(await readBody(req, 20_480));+ if (!fields.success) return json(res, 400, userError("serverError.mailbox.outgoingFields"));+ return json(res, 200, await service.checkOutgoing(address, fields.data));};}diff --git a/server/testing/fake-smtp.ts b/server/testing/fake-smtp.tsnew file mode 100644index 0000000000..e1650805d6--- /dev/null+++ b/server/testing/fake-smtp.ts@@ -0,0 +1,167 @@+// A loopback mail submission server, shaped like the ones mail hosts run: STARTTLS on a submission port or TLS from+// the first byte, AUTH PLAIN and/or LOGIN, offered before or only after STARTTLS. Its certificate is one made for the+// test (openssl, two days), valid for the names the test asks for, which the test's process trusts as a mail program+// trusts a public one.+import { spawnSync } from "node:child_process";+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { createServer, type Server, type Socket } from "node:net";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { createSecureContext, getCACertificates, setDefaultCACertificates, TLSSocket, type SecureContext } from "node:tls";++export interface TestCertificate { key: string; cert: string }++/** A self-signed certificate for `names`, or undefined where no openssl runs. */+export function testCertificate(names: string[]): TestCertificate | undefined {+ const dir = mkdtempSync(join(tmpdir(), "omb-fake-smtp-cert-"));+ try {+ // A config of its own, so no system openssl.cnf is needed (Windows).+ writeFileSync(join(dir, "openssl.cnf"), [+ "[req]", "distinguished_name = dn", "x509_extensions = v3", "prompt = no",+ "[dn]", "CN = OpenMausBot fake mail",+ "[v3]", "basicConstraints = critical,CA:TRUE", "keyUsage = critical,digitalSignature,keyCertSign",+ "extendedKeyUsage = serverAuth", `subjectAltName = ${names.map((name) => `DNS:${name}`).join(",")}`, "",+ ].join("\n"));+ const made = spawnSync("openssl", ["req", "-x509", "-config", join(dir, "openssl.cnf"), "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:prime256v1",+ "-nodes", "-keyout", join(dir, "key.pem"), "-out", join(dir, "cert.pem"), "-days", "2"], { stdio: "pipe", timeout: 30_000 });+ if (made.error || made.status !== 0) return undefined;+ return { key: readFileSync(join(dir, "key.pem"), "utf8"), cert: readFileSync(join(dir, "cert.pem"), "utf8") };+ } finally { rmSync(dir, { recursive: true, force: true }); }+}++/** Trusts `cert` in this process until the returned function puts the trusted list back. */+export function trustTestCertificate(cert: string): () => void {+ const before = getCACertificates("default");+ setDefaultCACertificates([...before, cert]);+ return () => setDefaultCACertificates(before);+}++export interface FakeSmtpOptions {+ certificate: TestCertificate;+ /** "tls": TLS from the first byte (port 465's way); "starttls": plain until STARTTLS (port 587's way). */+ security: "tls" | "starttls";+ mechanisms: Array<"PLAIN" | "LOGIN">;+ /** Offer AUTH before STARTTLS too; most hosts offer it only after. */+ authBeforeTls?: boolean;+ /** Leave STARTTLS out of the plain EHLO answer. */+ noStarttls?: boolean;+ /** user name to password */+ users: Record<string, string>;+}++export interface FakeSmtp {+ port: number;+ /** What came over the wire before TLS, as text. */+ plain: string[];+ signIns: Array<{ mechanism: string; user: string; ok: boolean }>;+ received: Array<{ from: string; to: string[]; data: string }>;+ close(): void;+}++export async function startFakeSmtp(options: FakeSmtpOptions): Promise<FakeSmtp> {+ const context: SecureContext = createSecureContext({ key: options.certificate.key, cert: options.certificate.cert, minVersion: "TLSv1.2" });+ const fake: Omit<FakeSmtp, "port" | "close"> = { plain: [], signIns: [], received: [] };+ const sockets = new Set<Socket>();++ const session = (raw: Socket) => {+ sockets.add(raw);+ raw.on("close", () => sockets.delete(raw));+ raw.on("error", () => {});+ let socket: Socket = raw;+ let secure = false;+ let user: string | null = null;+ let buffer = "";+ let pending: ((line: string) => void) | null = null;+ let mail: { from: string; to: string[]; data: string } | null = null;+ let inData = false;+ const say = (text: string) => { if (!socket.destroyed) socket.write(`${text}\r\n`); };+ const decode = (value: string) => Buffer.from(value, "base64").toString("utf8");+ const signIn = (mechanism: string, name: string, password: string) => {+ const ok = Object.hasOwn(options.users, name) && options.users[name] === password;+ fake.signIns.push({ mechanism, user: name, ok });+ if (ok) { user = name; say("235 2.7.0 Authentication successful"); } else say("535 5.7.8 Authentication credentials invalid");+ };+ const ehlo = () => {+ const lines = ["fake.mail.test", "PIPELINING", "8BITMIME", "SIZE 10485760"];+ if (!secure && !options.noStarttls && options.security === "starttls") lines.push("STARTTLS");+ if (secure || options.authBeforeTls) lines.push(`AUTH ${options.mechanisms.join(" ")}`);+ lines.forEach((line, index) => say(`250${index === lines.length - 1 ? " " : "-"}${line}`));+ };+ const line = (text: string) => {+ if (!secure) fake.plain.push(text);+ if (inData) {+ if (text === ".") { inData = false; fake.received.push(mail!); mail = null; say("250 2.0.0 Ok: queued"); } else mail!.data += `${text.startsWith("..") ? text.slice(1) : text}\n`;+ return;+ }+ if (pending) { const next = pending; pending = null; next(text); return; }+ const [verb = "", ...rest] = text.split(" ");+ const argument = rest.join(" ");+ switch (verb.toUpperCase()) {+ case "EHLO": ehlo(); return;+ case "HELO": say("250 fake.mail.test"); return;+ case "STARTTLS": {+ if (secure || options.noStarttls || options.security !== "starttls") { say("502 5.5.1 Not here"); return; }+ say("220 2.0.0 Ready to start TLS");+ raw.removeAllListeners("data");+ const upgraded = new TLSSocket(raw, { isServer: true, secureContext: context });+ upgraded.on("error", () => {});+ upgraded.on("secure", () => { secure = true; });+ socket = upgraded;+ buffer = "";+ listen(upgraded);+ return;+ }+ case "AUTH": {+ const [mechanism = "", initial] = argument.split(" ");+ const offered = (secure || options.authBeforeTls) && (options.mechanisms as string[]).includes(mechanism.toUpperCase());+ if (!offered) { say("504 5.5.4 Unrecognized authentication type"); return; }+ if (mechanism.toUpperCase() === "PLAIN") {+ const plain = (value: string) => { const [, name = "", password = ""] = decode(value).split("\0"); signIn("PLAIN", name, password); };+ if (initial) plain(initial); else { say("334 "); pending = plain; }+ } else {+ say(`334 ${Buffer.from("Username:").toString("base64")}`);+ pending = (name) => { say(`334 ${Buffer.from("Password:").toString("base64")}`); pending = (password) => signIn("LOGIN", decode(name), decode(password)); };+ }+ return;+ }+ case "MAIL":+ if (!user) { say("530 5.7.0 Authentication required"); return; }+ mail = { from: /<([^>]*)>/u.exec(argument)?.[1] ?? "", to: [], data: "" };+ say("250 2.1.0 Ok");+ return;+ case "RCPT":+ if (!mail) { say("503 5.5.1 MAIL first"); return; }+ mail.to.push(/<([^>]*)>/u.exec(argument)?.[1] ?? "");+ say("250 2.1.5 Ok");+ return;+ case "DATA":+ if (!mail?.to.length) { say("503 5.5.1 RCPT first"); return; }+ inData = true;+ say("354 End data with <CR><LF>.<CR><LF>");+ return;+ case "RSET": mail = null; say("250 2.0.0 Ok"); return;+ case "NOOP": say("250 2.0.0 Ok"); return;+ case "QUIT": say("221 2.0.0 Bye"); socket.end(); return;+ default: say("502 5.5.2 Error: command not recognized");+ }+ };+ const listen = (stream: Socket) => {+ stream.on("data", (chunk: Buffer) => {+ buffer += chunk.toString("utf8");+ for (let at = buffer.indexOf("\r\n"); at >= 0; at = buffer.indexOf("\r\n")) { const text = buffer.slice(0, at); buffer = buffer.slice(at + 2); line(text); }+ });+ };+ if (options.security === "tls") {+ const wrapped = new TLSSocket(raw, { isServer: true, secureContext: context });+ wrapped.on("error", () => {});+ socket = wrapped;+ secure = true;+ listen(wrapped);+ } else listen(raw);+ say("220 fake.mail.test ESMTP ready");+ };++ const server: Server = createServer(session);+ const port = await new Promise<number>((resolve) => server.listen(0, "127.0.0.1", () => resolve((server.address() as { port: number }).port)));+ return { port, ...fake, close: () => { for (const socket of sockets) socket.destroy(); server.close(); } };+}diff --git a/server/user-errors.ts b/server/user-errors.tsindex 795b8a5492..d3f3e7a6ce 100644--- a/server/user-errors.ts+++ b/server/user-errors.ts@@ -197,6 +197,7 @@ export const USER_ERROR = {"serverError.secret.emailUnavailable": "Email can't be connected here.","serverError.mailbox.adminOnly": "Only the owner or an admin can manage the mailboxes.","serverError.mailbox.addressAndPassword": "Enter your email address and password.",+ "serverError.mailbox.outgoingFields": "Check the outgoing server: a name like mail.example.com, a port from 1 to 65535, and SSL/TLS or STARTTLS.","serverError.voice.fishKeyRequired": "Add a Fish Audio key in Settings → API keys to talk to your bots here.","serverError.voice.fishTranscribeConnection": "Couldn't reach Fish Audio to hear you — check your connection.",} as const;diff --git a/shared/email.ts b/shared/email.tsindex 111fd61b56..fd8ccef0c9 100644--- a/shared/email.ts+++ b/shared/email.ts@@ -12,12 +12,23 @@ export const EMAIL_READ_TOOL_NAMES = ["EMAIL_LIST_MAILBOXES", "EMAIL_LIST_MESSAGexport const EMAIL_TOOL_NAMES = [...EMAIL_READ_TOOL_NAMES, "EMAIL_SEND_MESSAGE"] as const;export type EmailToolName = (typeof EMAIL_TOOL_NAMES)[number];-/** Where a mailbox's mail server is, when the person types it. */-export interface EmailServerFields {- imapHost?: string;- imapPort?: number;+/** How a mail server speaks TLS: from the first byte, or upgraded with STARTTLS. Never in the clear. */+export type EmailSecurity = "tls" | "starttls";++/** Where a mailbox's outgoing server is, when the person types it, and its own sign-in when that isn't the incoming+ * server's. A password left out is the mailbox's own. */+export interface EmailOutgoingFields {smtpHost?: string;smtpPort?: number;+ smtpSecurity?: EmailSecurity;+ smtpUsername?: string;+ smtpPassword?: string;+}++/** Where a mailbox's mail servers are, when the person types them. */+export interface EmailServerFields extends EmailOutgoingFields {+ imapHost?: string;+ imapPort?: number;username?: string;}@@ -31,11 +42,34 @@ export interface EmailAccountView {imapHost: string;/** The server that sends, once one took the password. */smtpHost?: string;+ smtpPort?: number;+ smtpSecurity?: EmailSecurity;+ /** The outgoing server's own user name, when it has one. */+ smtpUsername?: string;+ /** While sending doesn't work: the outgoing server the reason is about, to start the form with. */+ smtpTried?: Pick<EmailOutgoingFields, "smtpHost" | "smtpPort" | "smtpSecurity">;connectedAt: string;/** Why it needs the person, in one plain sentence. */problem?: string;+ /** Why sending doesn't work, in one plain sentence naming the server; none while it works. */+ sendingProblem?: string;+}++/** What POST /api/email/accounts/:address/outgoing answers: it checked sending again, at the server typed there (an+ * EmailOutgoingFields body) or the ones found for the address, without signing in to read again. */+export type EmailOutgoingAnswer = { ok: true; account: EmailAccountView } | { ok: false; error: string; account?: EmailAccountView };++/** A provider whose own sign-in fits better than a mailbox password: its app in Connected apps (`app`, its slug there),+ * or an app password made at `appPasswordUrl`. */+export interface EmailSignInHint {+ provider: string;+ app?: "gmail" | "outlook";+ appPasswordUrl?: string;}+/** POST /api/email/accounts/:address/test: a message from the mailbox to itself. */+export type EmailTestAnswer = { ok: true } | { ok: false; error: string };+/** GET /api/email. */export interface EmailStatus {state: "unavailable" | "signed-out" | "connected";@@ -47,5 +81,5 @@ export interface EmailStatus {/** What POST /api/email/accounts answers: read a real header, or why not. `needsServer`: nothing was found, so the person* types where their mail server is. */export type EmailConnectAnswer =- | { ok: true; account: EmailAccountView; inbox: { messages: number; newest?: { from: string; subject: string } }; sending: { ok: boolean; problem?: string } }- | { ok: false; error: string; needsServer?: true };+ | { ok: true; account: EmailAccountView; inbox: { messages: number; newest?: { from: string; subject: string } }; sending: { ok: boolean; problem?: string; signIn?: EmailSignInHint } }+ | { ok: false; error: string; needsServer?: true; signIn?: EmailSignInHint };diff --git a/shared/wire.ts b/shared/wire.tsindex bc87670174..89cd8e4dd5 100644--- a/shared/wire.ts+++ b/shared/wire.ts@@ -738,6 +738,8 @@ export interface SecretRequestCardData {helpUrl: string;/** A custom secret's use: "ref", OpenMausBot's own tools only; "file", the bot's commands; "email", the Email connector, never a bot. */ delivery?: SecretDelivery | "email";/** An email card: the mailbox it is for, when known; off a phone the person can change it on the card. */ address?: string;+ /** An email card: the incoming server that took the password, once it did, while sending is still being checked. */+ emailReading?: string;/** A custom secret: the bot's own words on why; `description` adds what the bot may do with it, and helpUrl is empty. */reason?: string;/** A file secret's Local VM target key, when the asking turn ran in one. */diff --git a/src/components/EmailCard.tsx b/src/components/EmailCard.tsxindex b63771d2f4..36ca8118cb 100644--- a/src/components/EmailCard.tsx+++ b/src/components/EmailCard.tsx@@ -1,37 +1,91 @@-import { useCallback, useEffect, useState } from "react";-import { Check, Loader2, Mail, MoreHorizontal } from "lucide-react";+import { useCallback, useEffect, useState, type CSSProperties, type ReactNode } from "react";+import { Check, Loader2, Mail, MoreHorizontal, Plus } from "lucide-react";import { api } from "@/state/store";import { t } from "@/lib/i18n";-import type { EmailConnectAnswer, EmailServerFields, EmailStatus } from "../../shared/email";+import type { EmailConnectAnswer, EmailConnectRequest, EmailServerFields, EmailSignInHint, EmailStatus } from "../../shared/email";+import { EMAIL_FIELD, EMAIL_LINK, EMAIL_PILL, EmailCheckLines, EmailMailbox, EmailSignInNote, OutgoingServerInputs } from "./EmailMailbox";import { SidebarPopoverMenu } from "./SidebarPopoverMenu";-const pill = "inline-flex h-7 min-w-[64px] shrink-0 items-center justify-center gap-2 rounded-full bg-control/80 px-3 text-[13px] font-medium leading-5 text-ink transition-colors hover:bg-raised-hover disabled:opacity-40";-const field = "h-8 w-full min-w-0 rounded-lg bg-inset px-2.5 text-[13px] text-ink placeholder:text-ink-secondary focus:outline-none focus:ring-1 focus:ring-accent/50";-export function EmailIcon() {return (<span className="grid size-10 shrink-0 place-items-center rounded-[10px] bg-[#2f6f6d] text-white" aria-hidden="true"><Mail size={20} /></span>);}-/** Where a mail server is, for when it can't be found from the address. */-export function EmailServerInputs({ value, onChange, className = field }: { value: EmailServerFields; onChange: (next: EmailServerFields) => void; className?: string }) {- const text = (name: "imapHost" | "smtpHost" | "username", label: string) => (+/** Where a mail server is, for when it can't be found from the address; the outgoing one only behind its own button. */+export function EmailServerInputs({ value, onChange, className = EMAIL_FIELD }: { value: EmailServerFields; onChange: (next: EmailServerFields) => void; className?: string }) {+ const [outgoing, setOutgoing] = useState(Boolean(value.smtpHost));+ const text = (name: "imapHost" | "username", label: string) => (<input type="text" autoComplete="off" spellCheck={false} dir="ltr" aria-label={label} placeholder={label} value={value[name] ?? ""} onChange={(event) => onChange({ ...value, [name]: event.target.value })} className={className} />);- const port = (name: "imapPort" | "smtpPort", label: string) => (- <input type="number" min={1} max={65535} autoComplete="off" dir="ltr" aria-label={label} placeholder={label} value={value[name] ?? ""} onChange={(event) => { const { [name]: _gone, ...rest } = value; onChange(event.target.value ? { ...rest, [name]: Number(event.target.value) } : rest); }} className={className} />- );return (- <div data-email-server-fields className="grid grid-cols-[minmax(0,1fr)_6rem] gap-2">- {text("imapHost", t("email.incomingServer"))}{port("imapPort", t("email.port"))}- {text("smtpHost", t("email.outgoingServer"))}{port("smtpPort", t("email.port"))}- <div className="col-span-2">{text("username", t("email.username"))}</div>+ <div data-email-server-fields className="flex flex-col gap-2">+ <div className="grid grid-cols-[minmax(0,1fr)_6rem] gap-2">+ {text("imapHost", t("email.incomingServer"))}+ <input type="number" min={1} max={65535} autoComplete="off" dir="ltr" aria-label={t("email.port")} placeholder={t("email.port")} value={value.imapPort ?? ""} onChange={(event) => { const { imapPort: _gone, ...rest } = value; onChange(event.target.value ? { ...rest, imapPort: Number(event.target.value) } : rest); }} className={className} />+ <div className="col-span-2">{text("username", t("email.username"))}</div>+ </div>+ {outgoing ? <OutgoingServerInputs value={value} onChange={onChange} className={className} /> : <button type="button" onClick={() => setOutgoing(true)} className={EMAIL_LINK}>{t("email.outgoing")}</button>}</div>);}+/** Why a connect didn't take: in one sentence, with the servers to type when none was found, or a provider's own way in. */+export type EmailConnectRefusal = { error: string; needsServer?: boolean; signIn?: EmailSignInHint };++/** Email and password, and Connect: the servers are found from the address. While it checks, "Reading" and "Sending"+ * tick as they pass; `reading` is the incoming server once it took the password. */+export function EmailConnectForm({ initialAddress = "", submit, reading, fieldClassName = EMAIL_FIELD, submitClassName = EMAIL_PILL, submitStyle, footer }: {+ initialAddress?: string;+ /** Connects, or says why not. */+ submit: (request: EmailConnectRequest) => Promise<EmailConnectRefusal | null>;+ reading?: string;+ fieldClassName?: string;+ submitClassName?: string;+ submitStyle?: CSSProperties;+ footer?: ReactNode;+}) {+ const [address, setAddress] = useState(initialAddress);+ const [password, setPassword] = useState("");+ const [server, setServer] = useState<EmailServerFields>({});+ const [needsServer, setNeedsServer] = useState(false);+ const [busy, setBusy] = useState(false);+ const [refusal, setRefusal] = useState<EmailConnectRefusal | null>(null);++ const connect = async () => {+ if (busy || !address.trim() || !password) return;+ setBusy(true);+ setRefusal(null);+ try {+ // A password goes as typed: a mailbox's can begin or end with a space.+ const refused = await submit({ address: address.trim(), password, ...server });+ if (refused) {+ setRefusal(refused);+ if (refused.needsServer) setNeedsServer(true);+ } else setPassword("");+ } finally { setBusy(false); }+ };++ const anyScreenConnecting = busy || Boolean(reading);+ return (+ <form data-email-form className="flex flex-col gap-2" onSubmit={(event) => { event.preventDefault(); void connect(); }}>+ <input type="email" autoComplete="off" spellCheck={false} dir="ltr" disabled={busy} aria-label={t("email.address")} placeholder={t("email.address")} value={address} onChange={(event) => setAddress(event.target.value)} className={fieldClassName} />+ <input type="password" autoComplete="new-password" spellCheck={false} dir="ltr" disabled={busy} aria-label={t("email.password")} placeholder={t("email.password")} value={password} onChange={(event) => setPassword(event.target.value)} className={fieldClassName} />+ {needsServer && <EmailServerInputs value={server} onChange={setServer} className={fieldClassName} />}+ {anyScreenConnecting && <EmailCheckLines reading={reading ? { state: "done", host: reading } : { state: "waiting" }} sending={{ state: "waiting" }} />}+ {refusal && (refusal.signIn ? <EmailSignInNote hint={refusal.signIn} /> : <p role="alert" className="text-[12px] text-danger">{refusal.error}</p>)}+ <div className="flex flex-wrap items-center gap-2">+ <button type="submit" disabled={busy || !address.trim() || !password} className={submitClassName} style={submitStyle}>+ {busy ? <Loader2 size={14} className="animate-spin" /> : t("connectors.action.connect")}+ </button>+ {!needsServer && !busy && <button type="button" onClick={() => setNeedsServer(true)} className={EMAIL_LINK}>{t("email.typeServer")}</button>}+ </div>+ {footer}+ </form>+ );+}+/** The Email card in Apps: any mailbox on any mail host, connected with an address and a password. */export function EmailCard({ refreshKey = 0, onConnection }: {refreshKey?: number;@@ -41,11 +95,6 @@ export function EmailCard({ refreshKey = 0, onConnection }: {const [status, setStatus] = useState<EmailStatus | null>(null);const [loadFailed, setLoadFailed] = useState(false);const [open, setOpen] = useState(false);- const [busy, setBusy] = useState(false);- const [address, setAddress] = useState("");- const [password, setPassword] = useState("");- const [server, setServer] = useState<EmailServerFields>({});- const [needsServer, setNeedsServer] = useState(false);const [error, setError] = useState<string | null>(null);const [done, setDone] = useState<string | null>(null);@@ -59,28 +108,18 @@ export function EmailCard({ refreshKey = 0, onConnection }: {useEffect(() => { void load(); }, [load, refreshKey]);useEffect(() => { onConnection?.(status ? status.state === "connected" : null); }, [status, onConnection]);- const connect = async () => {- if (busy) return;- setBusy(true);- setError(null);+ const connect = async (request: EmailConnectRequest): Promise<EmailConnectRefusal | null> => {setDone(null);try {- const answer = await api("/api/email/accounts", { method: "POST", body: JSON.stringify({ address: address.trim(), password, ...server }) }) as EmailConnectAnswer;- if (!answer.ok) {- setError(answer.error);- if (answer.needsServer) setNeedsServer(true);- return;- }- setPassword("");+ const answer = await api("/api/email/accounts", { method: "POST", body: JSON.stringify(request) }) as EmailConnectAnswer;+ if (!answer.ok) return { error: answer.error, ...(answer.needsServer ? { needsServer: true } : {}), ...(answer.signIn ? { signIn: answer.signIn } : {}) };setOpen(false);- setNeedsServer(false);- setServer({});- setAddress("");setDone(answer.sending.ok ? t("email.connected", { count: answer.inbox.messages }) : t("email.connectedNoSending", { count: answer.inbox.messages }));await load();+ return null;} catch (cause) {- setError(cause instanceof Error ? cause.message : String(cause));- } finally { setBusy(false); }+ return { error: cause instanceof Error ? cause.message : String(cause) };+ }};const disconnect = async (mailbox: string) => {@@ -93,7 +132,6 @@ export function EmailCard({ refreshKey = 0, onConnection }: {const accounts = status?.accounts ?? [];const connected = accounts.length > 0;const description = connected ? accounts.map((account) => account.address).join(", ") : t("email.description");- const problem = accounts.find((account) => account.problem)?.problem;return (<div data-app-tile="email" data-email-state={status?.state ?? "loading"} className="flex min-w-0 flex-col rounded-xl px-2 py-2 transition-colors hover:bg-raised/40">@@ -108,11 +146,11 @@ export function EmailCard({ refreshKey = 0, onConnection }: {</div>{status === null ? (loadFailed- ? <button type="button" onClick={() => void load()} className={pill}>{t("connectors.action.retry")}</button>- : <button type="button" disabled className={pill} aria-label={t("common.checking")}><Loader2 size={14} className="animate-spin" /></button>+ ? <button type="button" onClick={() => void load()} className={EMAIL_PILL}>{t("connectors.action.retry")}</button>+ : <button type="button" disabled className={EMAIL_PILL} aria-label={t("common.checking")}><Loader2 size={14} className="animate-spin" /></button>) : (<div className="flex shrink-0 items-center gap-1.5">- {(!connected || open) && <button type="button" disabled={busy} onClick={() => { setOpen(!open); setError(null); }} className={pill} aria-expanded={open}>{open ? t("common.cancel") : t("connectors.action.connect")}</button>}+ {(!connected || open) && <button type="button" onClick={() => { setOpen(!open); setError(null); }} className={EMAIL_PILL} aria-expanded={open}>{open ? t("common.cancel") : t("connectors.action.connect")}</button>}{connected && (<SidebarPopoverMenuplacement="below"@@ -128,24 +166,15 @@ export function EmailCard({ refreshKey = 0, onConnection }: {</div>)}</div>- <div className="ps-[52px]">+ <div className="flex flex-col gap-3 ps-[52px]">{done && <p role="status" className="mt-1.5 text-[12px] text-ink-secondary">{done}</p>}- {problem && !open && <p role="alert" className="mt-1.5 text-[12px] text-warning">{problem}</p>}- {error && <p role="alert" className="mt-1.5 text-[12px] text-danger">{error}</p>}- {open && (- <form data-email-form className="mt-2 flex flex-col gap-2" onSubmit={(event) => { event.preventDefault(); void connect(); }}>- <input type="email" autoComplete="off" spellCheck={false} dir="ltr" aria-label={t("email.address")} placeholder={t("email.address")} value={address} onChange={(event) => setAddress(event.target.value)} className={field} />- <input type="password" autoComplete="new-password" spellCheck={false} dir="ltr" aria-label={t("email.password")} placeholder={t("email.password")} value={password} onChange={(event) => setPassword(event.target.value)} className={field} />- {needsServer && <EmailServerInputs value={server} onChange={setServer} />}- <p className="text-[12px] leading-relaxed text-ink-secondary">{t("email.help")}</p>- <div className="flex items-center gap-2">- <button type="submit" disabled={busy || !address.trim() || !password} className={pill}>- {busy ? <Loader2 size={14} className="animate-spin" /> : t("connectors.action.connect")}- </button>- {busy && <span role="status" className="text-[12px] text-ink-secondary">{t("email.checking")}</span>}- {!needsServer && !busy && <button type="button" onClick={() => setNeedsServer(true)} className="text-[12px] text-ink-secondary underline underline-offset-2 hover:text-ink">{t("email.typeServer")}</button>}- </div>- </form>+ {accounts.map((account) => <EmailMailbox key={`${account.address}:${account.connectedAt}`} compact account={account} onChanged={load} />)}+ {error && <p role="alert" className="text-[12px] text-danger">{error}</p>}+ {open && <EmailConnectForm submit={connect} footer={<p className="text-[12px] leading-relaxed text-ink-secondary">{t("email.help")}</p>} />}+ {connected && !open && (+ <button type="button" onClick={() => { setOpen(true); setError(null); }} className="inline-flex items-center gap-1 self-start text-[12px] text-ink-secondary hover:text-ink">+ <Plus size={12} aria-hidden="true" />{t("email.addAnotherAddress")}+ </button>)}</div></div>diff --git a/src/components/EmailMailbox.test.ts b/src/components/EmailMailbox.test.tsnew file mode 100644index 0000000000..9ca989b8e8--- /dev/null+++ b/src/components/EmailMailbox.test.ts@@ -0,0 +1,95 @@+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++vi.mock("@/state/store", async (original) => ({ ...await original<typeof import("@/state/store")>(), api: vi.fn() }));++import { setLocale } from "@/lib/i18n";+import type { EmailAccountView } from "../../shared/email";+import { EmailConnectForm } from "./EmailCard";+import { EmailCheckLines, EmailMailbox, EmailSignInNote, outgoingOf } from "./EmailMailbox";+import { EmailRequestSettled } from "./EmailRequestCard";++const WORKS: EmailAccountView = { address: "[email protected]", imapHost: "imap.world4you.com", smtpHost: "smtp.world4you.com", smtpPort: 587, smtpSecurity: "starttls", connectedAt: "2026-11-06T00:00:00.000Z" };+const PROBLEM = "The outgoing server smtp.world4you.com:465 refused the password.";+const FAILS: EmailAccountView = { address: "[email protected]", imapHost: "imap.world4you.com", sendingProblem: PROBLEM, smtpTried: { smtpHost: "smtp.world4you.com", smtpPort: 465, smtpSecurity: "tls" }, connectedAt: "2026-11-06T00:00:00.000Z" };+const html = (element: Parameters<typeof renderToStaticMarkup>[0]) => renderToStaticMarkup(element);+const mailbox = (account: EmailAccountView, compact = false) => html(createElement(EmailMailbox, { account, onChanged: () => {}, compact }));++beforeEach(() => vi.stubGlobal("window", {}));+afterEach(() => { setLocale("en"); vi.unstubAllGlobals(); });++describe("the email card", () => {+ it("simple: an address, a password and Connect, with no server fields", () => {+ const form = html(createElement(EmailConnectForm, { initialAddress: "[email protected]", submit: async () => null }));+ expect(form).toContain('type="email"');+ expect(form).toContain('value="[email protected]"');+ expect(form).toContain('type="password"');+ expect(form).toContain(">Connect<");+ expect(form).not.toContain("data-email-outgoing-fields");+ expect(form).not.toContain("Incoming mail server");+ expect(form).not.toContain("data-email-checks");+ });++ it("ticking: Reading passes with the server it reached while Sending is still checked", () => {+ const form = html(createElement(EmailConnectForm, { submit: async () => null, reading: "imap.world4you.com" }));+ expect(form).toMatch(/data-email-check="done".*Reading.*imap\.world4you\.com/su);+ expect(form).toMatch(/data-email-check="waiting".*Sending/su);+ const lines = html(createElement(EmailCheckLines, { reading: { state: "done", host: "imap.x.example" }, sending: { state: "done", host: "smtp.x.example" } }));+ expect(lines.match(/data-email-check="done"/gu)).toHaveLength(2);+ expect(lines).toContain("smtp.x.example");+ });++ it("sending failed: the reason in one sentence and the Outgoing server open, filled with what was tried, and Try again", () => {+ const card = mailbox(FAILS);+ expect(card).toContain('data-email-check="failed"');+ expect(card).toContain(PROBLEM.replaceAll("'", "'"));+ expect(card).toContain("data-email-outgoing");+ expect(card).toContain('value="smtp.world4you.com"');+ expect(card).toContain('value="465"');+ expect(card).toMatch(/<option value="tls" selected="">SSL\/TLS<\/option>/u);+ expect(card).toContain('aria-label="Password for sending, if different"');+ expect(card).toContain(">Try again<");+ expect(card).not.toContain("Send a test to myself");+ expect(card).not.toContain("Connected.");+ expect(outgoingOf(FAILS)).toEqual({ smtpHost: "smtp.world4you.com", smtpPort: 465, smtpSecurity: "tls" });+ });++ it("connected: Connected., both lines ticked with their servers, and a test to myself", () => {+ const card = mailbox(WORKS);+ expect(card).toContain("Connected.");+ expect(card.match(/data-email-check="done"/gu)).toHaveLength(2);+ expect(card).toContain("smtp.world4you.com");+ expect(card).toContain(">Send a test to myself<");+ expect(card).not.toContain("data-email-outgoing-fields");+ });++ it("in Apps the same mailbox has its address, Test and Edit", () => {+ const row = mailbox(WORKS, true);+ expect(row).toContain("[email protected]");+ expect(row).toContain(">Test<");+ expect(row).toContain(">Edit<");+ expect(row).not.toContain("Connected.");+ expect(mailbox(FAILS, true)).toContain(">Try again<");+ });++ it("Gmail and Outlook: one line and their own sign-in, or an app password", () => {+ const google = html(createElement(EmailSignInNote, { hint: { provider: "Google", app: "gmail", appPasswordUrl: "https://myaccount.google.com/apppasswords" } }));+ expect(google).toContain("Sign in with Google");+ expect(google).toContain('href="https://myaccount.google.com/apppasswords"');+ const microsoft = html(createElement(EmailSignInNote, { hint: { provider: "Microsoft", app: "outlook" } }));+ expect(microsoft).toContain("Sign in with Microsoft");+ expect(microsoft).not.toContain("href=");+ expect(html(createElement(EmailSignInNote, { hint: { provider: "Apple", appPasswordUrl: "https://account.apple.com/account/manage" } }))).toContain("Apple needs an app password");+ });++ it("in a chat, a connected card is that mailbox; without one it is the settled line", () => {+ expect(html(createElement(EmailRequestSettled, { address: WORKS.address, label: "Connect your mailbox", settled: "settled-line", initial: WORKS }))).toContain("Send a test to myself");+ expect(html(createElement(EmailRequestSettled, { address: WORKS.address, label: "Connect your mailbox", settled: "settled-line" }))).toBe("settled-line");+ });++ it("speaks the person's language", () => {+ setLocale("de");+ expect(mailbox(FAILS)).toContain("Postausgangsserver");+ });+});diff --git a/src/components/EmailMailbox.tsx b/src/components/EmailMailbox.tsxnew file mode 100644index 0000000000..720954ff7f--- /dev/null+++ b/src/components/EmailMailbox.tsx@@ -0,0 +1,192 @@+import { useRef, useState } from "react";+import { Check, Loader2, X } from "lucide-react";++import { api } from "@/state/store";+import { cn } from "@/lib/cn";+import { t } from "@/lib/i18n";+import { reserveConnectionPage } from "@/lib/connector-oauth";+import { mcpSignInLink } from "@/lib/mcp-sign-in";+import { Select } from "./Select";+import type { EmailAccountView, EmailOutgoingAnswer, EmailOutgoingFields, EmailSignInHint, EmailTestAnswer } from "../../shared/email";++export const EMAIL_PILL = "inline-flex h-7 min-w-[64px] shrink-0 items-center justify-center gap-2 rounded-full bg-control/80 px-3 text-[13px] font-medium leading-5 text-ink transition-colors hover:bg-raised-hover disabled:opacity-40";+export const EMAIL_FIELD = "h-8 w-full min-w-0 rounded-lg bg-inset px-2.5 text-[13px] text-ink placeholder:text-ink-secondary focus:outline-none focus:ring-1 focus:ring-accent/50";+export const EMAIL_LINK = "self-start text-[12px] text-ink-secondary underline underline-offset-2 hover:text-ink";++/** A step of connecting: still going, passed (with the server it reached), or failed (with why, in one sentence). */+export type EmailCheck = { state: "waiting" } | { state: "done"; host?: string } | { state: "failed"; problem: string };++function CheckLine({ label, check }: { label: string; check: EmailCheck }) {+ return (+ <li data-email-check={check.state} className="flex min-w-0 items-start gap-1.5 text-[12px] leading-[18px]">+ <span aria-hidden="true" className="flex h-[18px] w-3.5 shrink-0 items-center justify-center">+ {check.state === "waiting" ? <Loader2 size={12} className="animate-spin text-ink-tertiary" />+ : check.state === "done" ? <Check size={13} strokeWidth={2.5} className="text-success" />+ : <X size={13} strokeWidth={2.5} className="text-warning" />}+ </span>+ <span className="shrink-0 text-ink">{label}</span>+ {check.state === "done" && check.host && <span dir="ltr" className="min-w-0 truncate text-ink-secondary">{check.host}</span>}+ {check.state === "failed" && <span role="alert" className="min-w-0 text-warning">{check.problem}</span>}+ </li>+ );+}++/** "✓ Reading imap.x" and "✓ Sending smtp.x", or what is still being checked, or why sending doesn't work. */+export function EmailCheckLines({ reading, sending }: { reading: EmailCheck; sending: EmailCheck }) {+ return (+ <ul data-email-checks className="flex flex-col gap-0.5">+ <CheckLine label={t("email.reading")} check={reading} />+ <CheckLine label={t("email.sending")} check={sending} />+ </ul>+ );+}++/** The outgoing server and its own sign-in, for when it can't be found or takes another one. */+export function OutgoingServerInputs<T extends EmailOutgoingFields>({ value, onChange, className = EMAIL_FIELD, disabled = false }: { value: T; onChange: (next: T) => void; className?: string; disabled?: boolean }) {+ const set = (name: keyof EmailOutgoingFields, next: string | number | undefined) => {+ const { [name]: _gone, ...rest } = value;+ onChange((next === undefined || next === "" ? rest : { ...rest, [name]: next }) as T);+ };+ return (+ <div data-email-outgoing-fields className="grid grid-cols-[minmax(0,1fr)_6rem] gap-2">+ <input type="text" autoComplete="off" spellCheck={false} dir="ltr" disabled={disabled} aria-label={t("email.outgoingServer")} placeholder={t("email.outgoingServer")} value={value.smtpHost ?? ""} onChange={(event) => set("smtpHost", event.target.value)} className={className} />+ <input type="number" min={1} max={65535} autoComplete="off" dir="ltr" disabled={disabled} aria-label={t("email.port")} placeholder={t("email.port")} value={value.smtpPort ?? ""} onChange={(event) => set("smtpPort", event.target.value ? Number(event.target.value) : undefined)} className={className} />+ <div className="col-span-2 flex">+ <Select size="sm" className="w-full" aria-label={t("email.security")} disabled={disabled} value={value.smtpSecurity ?? ""} onChange={(event) => set("smtpSecurity", event.target.value)}>+ <option value="">{t("email.securityAuto")}</option>+ <option value="tls">{t("email.securityTls")}</option>+ <option value="starttls">{t("email.securityStarttls")}</option>+ </Select>+ </div>+ <input type="text" autoComplete="off" spellCheck={false} dir="ltr" disabled={disabled} aria-label={t("email.smtpUsername")} placeholder={t("email.smtpUsername")} value={value.smtpUsername ?? ""} onChange={(event) => set("smtpUsername", event.target.value)} className={cn(className, "col-span-2")} />+ <input type="password" autoComplete="new-password" spellCheck={false} dir="ltr" disabled={disabled} aria-label={t("email.smtpPassword")} placeholder={t("email.smtpPassword")} value={value.smtpPassword ?? ""} onChange={(event) => set("smtpPassword", event.target.value)} className={cn(className, "col-span-2")} />+ </div>+ );+}++/** What the outgoing form starts with: the server a mailbox sends through, or the one the reason is about; never a password. */+export const outgoingOf = (account: EmailAccountView): EmailOutgoingFields => {+ const server = account.smtpHost ? { smtpHost: account.smtpHost, smtpPort: account.smtpPort, smtpSecurity: account.smtpSecurity } : account.smtpTried ?? {};+ return Object.fromEntries(Object.entries({ ...server, smtpUsername: account.smtpUsername }).filter(([, value]) => value !== undefined)) as EmailOutgoingFields;+};++const message = (cause: unknown) => (cause instanceof Error ? cause.message : String(cause));++/** Gmail, Outlook and the providers that want an app password: one line, and their own way in. */+export function EmailSignInNote({ hint }: { hint: EmailSignInHint }) {+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const opening = useRef<ReturnType<typeof reserveConnectionPage> | null>(null);+ const signIn = async (slug: "gmail" | "outlook") => {+ if (opening.current) return;+ const launch = reserveConnectionPage();+ opening.current = launch;+ setBusy(true);+ setError(null);+ try {+ const result = await api(`/api/connectors/${slug}/authorize`, { method: "POST" }) as { url?: unknown };+ const url = mcpSignInLink(typeof result.url === "string" ? result.url : null);+ if (!url) throw new Error(t("connectors.invalidAuthorizationUrl"));+ if (!await launch.open(url)) setError(t("connectors.popupBlockedContinue"));+ } catch (cause) { setError(message(cause)); }+ finally {+ launch.cancel();+ opening.current = null;+ setBusy(false);+ }+ };+ const note = hint.app === "gmail" ? t("email.needsGoogle") : hint.app === "outlook" ? t("email.needsMicrosoft") : t("email.needsAppPassword", { provider: hint.provider });+ return (+ <div data-email-sign-in={hint.app ?? "app-password"} className="flex flex-col gap-1.5">+ <p role="alert" className="text-[12px] leading-[18px] text-ink">{note}</p>+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1.5">+ {hint.app && (+ <button type="button" disabled={busy} onClick={() => void signIn(hint.app!)} className={EMAIL_PILL}>+ {busy ? <Loader2 size={14} className="animate-spin" /> : t(hint.app === "gmail" ? "email.signInGoogle" : "email.signInMicrosoft")}+ </button>+ )}+ {hint.appPasswordUrl && <a href={hint.appPasswordUrl} target="_blank" rel="noopener noreferrer" className={EMAIL_LINK}>{t("email.makeAppPassword")}</a>}+ </div>+ {error && <p role="alert" className="text-[12px] text-danger">{error}</p>}+ </div>+ );+}++/** One connected mailbox, the same in Apps and in a chat: whether it reads and sends, a test to itself, and its outgoing+ * server, open by itself while sending doesn't work. `compact`: Apps' short button names, with the address on top. */+export function EmailMailbox({ account, onChanged, compact = false, fieldClassName = EMAIL_FIELD }: {+ account: EmailAccountView;+ onChanged: (account: EmailAccountView | null) => void | Promise<void>;+ compact?: boolean;+ fieldClassName?: string;+}) {+ const failing = Boolean(account.sendingProblem);+ const [editing, setEditing] = useState(failing);+ const [fields, setFields] = useState<EmailOutgoingFields>(() => outgoingOf(account));+ const [busy, setBusy] = useState<"check" | "test" | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [done, setDone] = useState<string | null>(null);+ const at = `/api/email/accounts/${encodeURIComponent(account.address)}`;++ const check = async () => {+ if (busy) return;+ setBusy("check");+ setError(null);+ setDone(null);+ try {+ const answer = await api(`${at}/outgoing`, { method: "POST", body: JSON.stringify(fields) }) as EmailOutgoingAnswer;+ if (answer.ok) {+ setEditing(false);+ setFields(outgoingOf(answer.account));+ await onChanged(answer.account);+ } else {+ setError(answer.error);+ if (answer.account) await onChanged(answer.account);+ }+ } catch (cause) { setError(message(cause)); } finally { setBusy(null); }+ };++ const test = async () => {+ if (busy) return;+ setBusy("test");+ setError(null);+ setDone(null);+ try {+ const answer = await api(`${at}/test`, { method: "POST" }) as EmailTestAnswer;+ if (answer.ok) setDone(t("email.testSent", { address: account.address })); else { setError(answer.error); await onChanged(null); }+ } catch (cause) { setError(message(cause)); } finally { setBusy(null); }+ };++ const sending: EmailCheck = account.sendingProblem ? { state: "failed", problem: account.sendingProblem } : { state: "done", host: account.smtpHost };+ return (+ <div data-email-mailbox={account.address} className="flex min-w-0 flex-col gap-1.5">+ {compact && <p dir="ltr" className="truncate text-start text-[13px] font-medium leading-5 text-ink">{account.address}</p>}+ {!compact && !failing && <p role="status" className="text-[13px] font-medium leading-5 text-ink">{t("email.connectedDone")}</p>}+ <EmailCheckLines reading={account.problem ? { state: "failed", problem: account.problem } : { state: "done", host: account.imapHost }} sending={sending} />+ {!editing && (+ <div className="flex flex-wrap items-center gap-2">+ {!failing && (+ <button type="button" disabled={busy !== null} onClick={() => void test()} className={EMAIL_PILL}>+ {busy === "test" ? <Loader2 size={14} className="animate-spin" /> : t(compact ? "email.test" : "email.sendTestToMyself")}+ </button>+ )}+ <button type="button" disabled={busy !== null} onClick={() => { setEditing(true); setError(null); setDone(null); }} className={failing ? EMAIL_PILL : EMAIL_LINK}>+ {t(failing ? "email.outgoing" : "email.edit")}+ </button>+ </div>+ )}+ {editing && (+ <form data-email-outgoing className="flex flex-col gap-2" onSubmit={(event) => { event.preventDefault(); void check(); }}>+ <p className="text-[12px] font-medium text-ink">{t("email.outgoing")}</p>+ <OutgoingServerInputs value={fields} onChange={setFields} className={fieldClassName} disabled={busy !== null} />+ <div className="flex items-center gap-2">+ <button type="submit" disabled={busy !== null} className={EMAIL_PILL}>{busy === "check" ? <Loader2 size={14} className="animate-spin" /> : t("common.tryAgain")}</button>+ {!failing && <button type="button" disabled={busy !== null} onClick={() => { setEditing(false); setFields(outgoingOf(account)); setError(null); }} className={EMAIL_LINK}>{t("common.cancel")}</button>}+ </div>+ </form>+ )}+ {done && <p role="status" className="text-[12px] text-ink-secondary">{done}</p>}+ {error && error !== account.sendingProblem && <p role="alert" className="text-[12px] text-danger">{error}</p>}+ </div>+ );+}diff --git a/src/components/EmailRequestCard.tsx b/src/components/EmailRequestCard.tsxnew file mode 100644index 0000000000..036c9da28b--- /dev/null+++ b/src/components/EmailRequestCard.tsx@@ -0,0 +1,28 @@+import { useCallback, useEffect, useState, type ReactNode } from "react";+import { Mail } from "lucide-react";++import { api } from "@/state/store";+import { cn } from "@/lib/cn";+import type { EmailAccountView, EmailStatus } from "../../shared/email";+import { ASK_FIELD, AskCard } from "./AskCard";+import { EmailMailbox } from "./EmailMailbox";++/** A chat's mailbox card once connected: the same mailbox as in Apps, with a test to itself, and its outgoing server open+ * while sending doesn't work. Where the mailbox can't be shown (gone, or this person doesn't manage mailboxes), the+ * settled line instead. */+export function EmailRequestSettled({ address, label, settled, initial }: { address: string; label: string; settled: ReactNode; initial?: EmailAccountView }) {+ const [account, setAccount] = useState<EmailAccountView | null>(initial ?? null);+ const load = useCallback(async () => {+ try {+ const status = await api("/api/email") as EmailStatus;+ setAccount(status.accounts.find((one) => one.address.toLowerCase() === address.toLowerCase()) ?? null);+ } catch { setAccount(null); }+ }, [address]);+ useEffect(() => { if (!initial) void load(); }, [initial, load]);+ if (!account) return <>{settled}</>;+ return (+ <AskCard ariaLabel={label} icon={<Mail size={15} />} title={<span dir="ltr">{account.address}</span>}>+ <EmailMailbox account={account} onChanged={(next) => (next ? setAccount(next) : load())} fieldClassName={cn(ASK_FIELD, "w-full")} />+ </AskCard>+ );+}diff --git a/src/components/SecretRequestCard.test.ts b/src/components/SecretRequestCard.test.tsindex ac1107eeec..96a379b24f 100644--- a/src/components/SecretRequestCard.test.ts+++ b/src/components/SecretRequestCard.test.ts@@ -234,6 +234,13 @@ describe("SecretRequestCard mailbox", () => {expect(view({})).not.toContain('type="email"');});+ it("connects with Connect, and while it checks shows the incoming server that took the password", () => {+ expect(view({ ...email, address: "[email protected]" })).toContain(">Connect<");+ const html = view({ ...email, address: "[email protected]", emailReading: "imap.shop.example" });+ expect(html).toMatch(/data-email-check="done".*imap\.shop\.example/su);+ expect(html).toContain('data-email-check="waiting"');+ });+it("says the bot goes on once connected, without the address field", () => {const html = view({ ...email, provided: true, resumed: true, address: "[email protected]" });expect(html).toContain('data-ask-card="settled"');diff --git a/src/components/SecretRequestCard.tsx b/src/components/SecretRequestCard.tsxindex e1103d0d2d..f0f6147c68 100644--- a/src/components/SecretRequestCard.tsx+++ b/src/components/SecretRequestCard.tsx@@ -8,8 +8,9 @@ import { activeLocale, t } from "@/lib/i18n";import { keySaved, keySaveFailure, savedKeyResult } from "@/lib/product-events";import { api, useStore, type Bot, type ConfigStatus, type Message } from "@/state/store";import { ASK_FIELD, askPrimary, ASK_QUIET_BUTTON, AskCard, AskSettledLine, returnFocusToComposer } from "./AskCard";-import { EmailServerInputs } from "./EmailCard";-import type { EmailServerFields } from "../../shared/email";+import { EmailConnectForm, type EmailConnectRefusal } from "./EmailCard";+import { EmailRequestSettled } from "./EmailRequestCard";+import type { EmailConnectRequest } from "../../shared/email";import { productName } from "@/lib/brand";// Security: the value goes straight to the host's settings, never into the chat.@@ -43,9 +44,6 @@ export function SecretRequestCard({const [savedLocally, setSavedLocally] = useState(false);const [localError, setLocalError] = useState<string | null>(null);const email = secret.delivery === "email";- const [address, setAddress] = useState(secret.address ?? "");- const [server, setServer] = useState<EmailServerFields>({});- const [needsServer, setNeedsServer] = useState(false);const endpoint = `/api/bots/${encodeURIComponent(botId)}/secret-cards/${encodeURIComponent(message.id)}`;const error = localError ?? secret.error;const custom = secret.target === CUSTOM_SECRET_TARGET;@@ -112,18 +110,27 @@ export function SecretRequestCard({setSaving(true);setLocalError(null);try {- // A password goes as typed: a mailbox's can begin or end with a space.- await api(`${endpoint}/save`, { method: "POST", body: JSON.stringify(email ? { threadId, value, address: address.trim(), ...server } : { threadId, value: value.trim() }) });+ await api(`${endpoint}/save`, { method: "POST", body: JSON.stringify({ threadId, value: value.trim() }) });setValue("");returnFocusToComposer();} catch (error) {- if ((error as { body?: { needsServer?: unknown } }).body?.needsServer === true) setNeedsServer(true);setLocalError(error instanceof Error ? error.message : String(error));} finally {setSaving(false);}};+ const saveEmail = async ({ password, ...fields }: EmailConnectRequest): Promise<EmailConnectRefusal | null> => {+ try {+ await api(`${endpoint}/save`, { method: "POST", body: JSON.stringify({ threadId, value: password, ...fields }) });+ returnFocusToComposer();+ return null;+ } catch (error) {+ const body = (error as { body?: Partial<EmailConnectRefusal> }).body;+ return { error: error instanceof Error ? error.message : String(error), ...(body?.needsServer === true ? { needsServer: true } : {}), ...(body?.signIn ? { signIn: body.signIn } : {}) };+ }+ };+const save = async (event?: FormEvent) => {event?.preventDefault();if (custom) return saveCustom();@@ -192,7 +199,7 @@ export function SecretRequestCard({{t("common.tryAgain")}</button>) : undefined;- return (+ const line = (<AskSettledLineariaLabel={label}icon={secret.resumed || stopped@@ -209,6 +216,8 @@ export function SecretRequestCard({<span className={declined ? "text-danger" : undefined}> · {footerLabel}</span></AskSettledLine>);+ if (email && provided && secret.address && !retry) return <EmailRequestSettled address={secret.address} label={label} settled={line} />;+ return line;}return (@@ -225,14 +234,18 @@ export function SecretRequestCard({<div className="text-[13px] leading-relaxed text-ink-secondary">{t("chat.secret.remoteClient")}</div>+ ) : email ? (+ <EmailConnectForm+ initialAddress={secret.address ?? ""}+ reading={secret.emailReading}+ submit={saveEmail}+ fieldClassName={cn(ASK_FIELD, "w-full")}+ submitClassName={askPrimary(color).className}+ submitStyle={askPrimary(color).style}+ footer={<span className="flex items-center gap-1 text-[12px] text-ink-tertiary"><LockKeyhole size={11} /> {t("secretCard.email")}</span>}+ />) : (<form onSubmit={(event) => void save(event)}>- {email && (- <div className="mb-2 flex flex-col gap-2">- <input type="email" autoComplete="off" spellCheck={false} dir="ltr" value={address} onChange={(event) => setAddress(event.target.value)} placeholder={t("email.address")} disabled={saving} aria-label={t("email.address")} className={cn(ASK_FIELD, "w-full")} />- {needsServer && <EmailServerInputs value={server} onChange={setServer} className={cn(ASK_FIELD, "w-full")} />}- </div>- )}<div className="flex flex-wrap gap-2"><inputtype="password"@@ -246,7 +259,7 @@ export function SecretRequestCard({aria-label={label}className={cn(ASK_FIELD, "min-w-[10rem] flex-1")}/>- <button type="submit" disabled={saving || (!value.trim() && !savedLocally) || (email && !address.trim())} {...askPrimary(color)}>+ <button type="submit" disabled={saving || (!value.trim() && !savedLocally)} {...askPrimary(color)}>{saving ? <Loader2 size={14} className="animate-spin" /> : <LockKeyhole size={14} />}{t(savedLocally ? "chat.secret.continue" : "chat.secret.save")}</button>@@ -254,7 +267,7 @@ export function SecretRequestCard({<div className="mt-2 flex flex-wrap items-center gap-x-3 gap-y-1 text-[12px] text-ink-tertiary"><span className="flex items-center gap-1"><LockKeyhole size={11} />{" "}- {!custom ? t("chat.secret.storedHint", { app: productName() }) : email ? t("secretCard.email") : secret.delivery === "file" ? t("secretCard.file") : t("secretCard.ref")}+ {!custom ? t("chat.secret.storedHint", { app: productName() }) : secret.delivery === "file" ? t("secretCard.file") : t("secretCard.ref")}</span>{secret.helpUrl && (<adiff --git a/src/locales/de.json b/src/locales/de.jsonindex c50167f4b7..ce0feeb1d9 100644--- a/src/locales/de.json+++ b/src/locales/de.json@@ -3216,5 +3216,27 @@"remote.devices.removed": "{name} entfernt.","remote.e2e.anywhere": "Von überall erreichbar · Ende-zu-Ende-verschlüsselt","remote.e2e.connecting": "Verbindung zu MausBot Relay…",- "remote.e2e.local": "In diesem WLAN und über Tailscale · Ende-zu-Ende-verschlüsselt"+ "remote.e2e.local": "In diesem WLAN und über Tailscale · Ende-zu-Ende-verschlüsselt",+ "email.reading": "Lesen",+ "email.sending": "Senden",+ "email.connectedDone": "Verbunden.",+ "email.sendTestToMyself": "Test an mich senden",+ "email.test": "Testen",+ "email.edit": "Bearbeiten",+ "email.outgoing": "Postausgangsserver",+ "email.security": "Sicherheit",+ "email.securityAuto": "Sicherheit: automatisch",+ "email.securityTls": "SSL/TLS",+ "email.securityStarttls": "STARTTLS",+ "email.smtpUsername": "Benutzername zum Senden, falls anders",+ "email.smtpPassword": "Passwort zum Senden, falls anders",+ "email.testSent": "Eine Testnachricht ist unterwegs an {address}.",+ "email.addAnotherAddress": "Weitere Adresse hinzufügen",+ "email.signInGoogle": "Mit Google anmelden",+ "email.signInMicrosoft": "Mit Microsoft anmelden",+ "email.makeAppPassword": "App-Passwort erstellen",+ "email.needsGoogle": "Gmail braucht hier ein App-Passwort (mit aktivierter Bestätigung in zwei Schritten), oder melde dich mit Google an.",+ "email.needsMicrosoft": "Outlook nimmt hier kein Mail-Passwort an: Melde dich mit Microsoft an.",+ "email.needsAppPassword": "{provider} braucht hier ein App-Passwort, nicht dein normales Passwort.",+ "serverError.mailbox.outgoingFields": "Prüfe den Postausgangsserver: ein Name wie mail.example.com, ein Port von 1 bis 65535 und SSL/TLS oder STARTTLS."}diff --git a/src/locales/en.json b/src/locales/en.jsonindex bbc98e518c..0a82e9976a 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -40,7 +40,6 @@"email.address": "Email address","email.password": "Mailbox password","email.help": "OpenMausBot finds your mail server and checks it can read your mail. Your bots never see the password.",- "email.checking": "Finding your mail server…","email.typeServer": "Enter the mail server yourself","email.incomingServer": "Incoming mail server (IMAP)","email.outgoingServer": "Outgoing mail server (SMTP)",@@ -50,6 +49,27 @@"email.connectedNoSending": "Connected for reading: {count} messages. Sending doesn't work yet.","email.addAnother": "Add another mailbox","email.disconnect": "Disconnect {address}",+ "email.reading": "Reading",+ "email.sending": "Sending",+ "email.connectedDone": "Connected.",+ "email.sendTestToMyself": "Send a test to myself",+ "email.test": "Test",+ "email.edit": "Edit",+ "email.outgoing": "Outgoing server",+ "email.security": "Security",+ "email.securityAuto": "Security: automatic",+ "email.securityTls": "SSL/TLS",+ "email.securityStarttls": "STARTTLS",+ "email.smtpUsername": "User name for sending, if different",+ "email.smtpPassword": "Password for sending, if different",+ "email.testSent": "A test is on its way to {address}.",+ "email.addAnotherAddress": "Add another address",+ "email.signInGoogle": "Sign in with Google",+ "email.signInMicrosoft": "Sign in with Microsoft",+ "email.makeAppPassword": "Make an app password",+ "email.needsGoogle": "Gmail needs an app password here (with 2-step verification on), or sign in with Google.",+ "email.needsMicrosoft": "Outlook doesn't take a mail password here: sign in with Microsoft.",+ "email.needsAppPassword": "{provider} needs an app password here, not your normal password.","highlevel.title": "HighLevel","highlevel.description": "Also Growably and other HighLevel-based CRMs.","highlevel.connect": "Connect HighLevel",@@ -9630,5 +9650,6 @@"remote.devices.removed": "Removed {name}.","remote.e2e.anywhere": "Reachable from anywhere · end-to-end encrypted","remote.e2e.connecting": "Connecting to MausBot Relay…",- "remote.e2e.local": "On this Wi-Fi and Tailscale · end-to-end encrypted"+ "remote.e2e.local": "On this Wi-Fi and Tailscale · end-to-end encrypted",+ "serverError.mailbox.outgoingFields": "Check the outgoing server: a name like mail.example.com, a port from 1 to 65535, and SSL/TLS or STARTTLS."}diff --git a/src/locales/es.json b/src/locales/es.jsonindex 550fee5ad8..fa92a31ba1 100644--- a/src/locales/es.json+++ b/src/locales/es.json@@ -5882,5 +5882,27 @@"remote.devices.removed": "Se quitó {name}.","remote.e2e.anywhere": "Accesible desde cualquier lugar · cifrado de extremo a extremo","remote.e2e.connecting": "Conectando con MausBot Relay…",- "remote.e2e.local": "En este Wi-Fi y Tailscale · cifrado de extremo a extremo"+ "remote.e2e.local": "En este Wi-Fi y Tailscale · cifrado de extremo a extremo",+ "email.reading": "Lectura",+ "email.sending": "Envío",+ "email.connectedDone": "Conectado.",+ "email.sendTestToMyself": "Enviarme una prueba",+ "email.test": "Probar",+ "email.edit": "Editar",+ "email.outgoing": "Servidor de salida",+ "email.security": "Seguridad",+ "email.securityAuto": "Seguridad: automática",+ "email.securityTls": "SSL/TLS",+ "email.securityStarttls": "STARTTLS",+ "email.smtpUsername": "Usuario para enviar, si es distinto",+ "email.smtpPassword": "Contraseña para enviar, si es distinta",+ "email.testSent": "Una prueba va de camino a {address}.",+ "email.addAnotherAddress": "Añadir otra dirección",+ "email.signInGoogle": "Iniciar sesión con Google",+ "email.signInMicrosoft": "Iniciar sesión con Microsoft",+ "email.makeAppPassword": "Crear una contraseña de aplicación",+ "email.needsGoogle": "Gmail necesita aquí una contraseña de aplicación (con la verificación en dos pasos activada), o inicia sesión con Google.",+ "email.needsMicrosoft": "Outlook no acepta aquí una contraseña de correo: inicia sesión con Microsoft.",+ "email.needsAppPassword": "{provider} necesita aquí una contraseña de aplicación, no tu contraseña normal.",+ "serverError.mailbox.outgoingFields": "Revisa el servidor de salida: un nombre como mail.example.com, un puerto de 1 a 65535 y SSL/TLS o STARTTLS."}diff --git a/src/locales/fr.json b/src/locales/fr.jsonindex 5cc67230ac..5bc414006a 100644--- a/src/locales/fr.json+++ b/src/locales/fr.json@@ -3082,5 +3082,27 @@"remote.devices.removed": "{name} retiré.","remote.e2e.anywhere": "Accessible de partout · chiffré de bout en bout","remote.e2e.connecting": "Connexion à MausBot Relay…",- "remote.e2e.local": "Sur ce Wi-Fi et Tailscale · chiffré de bout en bout"+ "remote.e2e.local": "Sur ce Wi-Fi et Tailscale · chiffré de bout en bout",+ "email.reading": "Lecture",+ "email.sending": "Envoi",+ "email.connectedDone": "Connecté.",+ "email.sendTestToMyself": "M’envoyer un test",+ "email.test": "Tester",+ "email.edit": "Modifier",+ "email.outgoing": "Serveur sortant",+ "email.security": "Sécurité",+ "email.securityAuto": "Sécurité : automatique",+ "email.securityTls": "SSL/TLS",+ "email.securityStarttls": "STARTTLS",+ "email.smtpUsername": "Nom d’utilisateur pour l’envoi, s’il est différent",+ "email.smtpPassword": "Mot de passe pour l’envoi, s’il est différent",+ "email.testSent": "Un message de test part vers {address}.",+ "email.addAnotherAddress": "Ajouter une autre adresse",+ "email.signInGoogle": "Se connecter avec Google",+ "email.signInMicrosoft": "Se connecter avec Microsoft",+ "email.makeAppPassword": "Créer un mot de passe d’application",+ "email.needsGoogle": "Gmail demande ici un mot de passe d’application (avec la validation en deux étapes activée), ou connectez-vous avec Google.",+ "email.needsMicrosoft": "Outlook n’accepte pas de mot de passe de messagerie ici : connectez-vous avec Microsoft.",+ "email.needsAppPassword": "{provider} demande ici un mot de passe d’application, pas votre mot de passe habituel.",+ "serverError.mailbox.outgoingFields": "Vérifiez le serveur sortant : un nom comme mail.example.com, un port de 1 à 65535, et SSL/TLS ou STARTTLS."}diff --git a/src/locales/hi.json b/src/locales/hi.jsonindex 57672e561e..a8793ce0df 100644--- a/src/locales/hi.json+++ b/src/locales/hi.json@@ -2934,5 +2934,27 @@"remote.devices.removed": "{name} हटाया गया।","remote.e2e.anywhere": "कहीं से भी पहुँच योग्य · एंड-टू-एंड एन्क्रिप्टेड","remote.e2e.connecting": "MausBot Relay से कनेक्ट हो रहा है…",- "remote.e2e.local": "इस वाई-फ़ाई और Tailscale पर · एंड-टू-एंड एन्क्रिप्टेड"+ "remote.e2e.local": "इस वाई-फ़ाई और Tailscale पर · एंड-टू-एंड एन्क्रिप्टेड",+ "email.reading": "पढ़ना",+ "email.sending": "भेजना",+ "email.connectedDone": "कनेक्ट हो गया।",+ "email.sendTestToMyself": "खुद को एक टेस्ट भेजें",+ "email.test": "टेस्ट",+ "email.edit": "बदलें",+ "email.outgoing": "आउटगोइंग सर्वर",+ "email.security": "सुरक्षा",+ "email.securityAuto": "सुरक्षा: अपने-आप",+ "email.securityTls": "SSL/TLS",+ "email.securityStarttls": "STARTTLS",+ "email.smtpUsername": "भेजने के लिए यूज़रनेम, अगर अलग हो",+ "email.smtpPassword": "भेजने के लिए पासवर्ड, अगर अलग हो",+ "email.testSent": "एक टेस्ट {address} पर भेजा जा रहा है।",+ "email.addAnotherAddress": "एक और पता जोड़ें",+ "email.signInGoogle": "Google से साइन इन करें",+ "email.signInMicrosoft": "Microsoft से साइन इन करें",+ "email.makeAppPassword": "ऐप पासवर्ड बनाएँ",+ "email.needsGoogle": "Gmail को यहाँ ऐप पासवर्ड चाहिए (2-स्टेप वेरिफ़िकेशन चालू होने पर), या Google से साइन इन करें।",+ "email.needsMicrosoft": "Outlook यहाँ मेल पासवर्ड नहीं लेता: Microsoft से साइन इन करें।",+ "email.needsAppPassword": "{provider} को यहाँ ऐप पासवर्ड चाहिए, आपका सामान्य पासवर्ड नहीं।",+ "serverError.mailbox.outgoingFields": "आउटगोइंग सर्वर जाँचें: mail.example.com जैसा नाम, 1 से 65535 तक का पोर्ट, और SSL/TLS या STARTTLS।"}diff --git a/src/locales/it.json b/src/locales/it.jsonindex 2dd865de96..417feced31 100644--- a/src/locales/it.json+++ b/src/locales/it.json@@ -6504,5 +6504,27 @@"remote.devices.removed": "{name} rimosso.","remote.e2e.anywhere": "Raggiungibile da ovunque · crittografia end-to-end","remote.e2e.connecting": "Connessione a MausBot Relay…",- "remote.e2e.local": "Su questa rete Wi-Fi e Tailscale · crittografia end-to-end"+ "remote.e2e.local": "Su questa rete Wi-Fi e Tailscale · crittografia end-to-end",+ "email.reading": "Lettura",+ "email.sending": "Invio",+ "email.connectedDone": "Connesso.",+ "email.sendTestToMyself": "Inviami una prova",+ "email.test": "Prova",+ "email.edit": "Modifica",+ "email.outgoing": "Server in uscita",+ "email.security": "Sicurezza",+ "email.securityAuto": "Sicurezza: automatica",+ "email.securityTls": "SSL/TLS",+ "email.securityStarttls": "STARTTLS",+ "email.smtpUsername": "Nome utente per l’invio, se diverso",+ "email.smtpPassword": "Password per l’invio, se diversa",+ "email.testSent": "Un messaggio di prova sta arrivando a {address}.",+ "email.addAnotherAddress": "Aggiungi un altro indirizzo",+ "email.signInGoogle": "Accedi con Google",+ "email.signInMicrosoft": "Accedi con Microsoft",+ "email.makeAppPassword": "Crea una password per le app",+ "email.needsGoogle": "Gmail richiede qui una password per le app (con la verifica in due passaggi attiva), oppure accedi con Google.",+ "email.needsMicrosoft": "Outlook non accetta qui una password di posta: accedi con Microsoft.",+ "email.needsAppPassword": "{provider} richiede qui una password per le app, non la tua password normale.",+ "serverError.mailbox.outgoingFields": "Controlla il server in uscita: un nome come mail.example.com, una porta da 1 a 65535 e SSL/TLS o STARTTLS."}diff --git a/src/locales/ja.json b/src/locales/ja.jsonindex 45f0b1f76b..f9979d34cb 100644--- a/src/locales/ja.json+++ b/src/locales/ja.json@@ -7563,5 +7563,27 @@"remote.devices.removed": "{name} を削除しました。","remote.e2e.anywhere": "どこからでも接続可能 · エンドツーエンド暗号化","remote.e2e.connecting": "MausBot Relay に接続中…",- "remote.e2e.local": "このWi-FiとTailscale · エンドツーエンド暗号化"+ "remote.e2e.local": "このWi-FiとTailscale · エンドツーエンド暗号化",+ "email.reading": "受信",+ "email.sending": "送信",+ "email.connectedDone": "接続しました。",+ "email.sendTestToMyself": "自分にテストを送る",+ "email.test": "テスト",+ "email.edit": "編集",+ "email.outgoing": "送信サーバー",+ "email.security": "セキュリティ",+ "email.securityAuto": "セキュリティ: 自動",+ "email.securityTls": "SSL/TLS",+ "email.securityStarttls": "STARTTLS",+ "email.smtpUsername": "送信用のユーザー名(異なる場合)",+ "email.smtpPassword": "送信用のパスワード(異なる場合)",+ "email.testSent": "{address} にテストを送信しています。",+ "email.addAnotherAddress": "別のアドレスを追加",+ "email.signInGoogle": "Google でサインイン",+ "email.signInMicrosoft": "Microsoft でサインイン",+ "email.makeAppPassword": "アプリ パスワードを作成",+ "email.needsGoogle": "Gmail ではここでアプリ パスワード(2 段階認証プロセスを有効にしたもの)が必要です。または Google でサインインしてください。",+ "email.needsMicrosoft": "Outlook はここでメールのパスワードを受け付けません。Microsoft でサインインしてください。",+ "email.needsAppPassword": "{provider} ではここでアプリ パスワードが必要です。通常のパスワードは使えません。",+ "serverError.mailbox.outgoingFields": "送信サーバーを確認してください: mail.example.com のような名前、1〜65535 のポート、SSL/TLS または STARTTLS。"}diff --git a/src/locales/ko.json b/src/locales/ko.jsonindex be8f10e672..9d56c7d142 100644--- a/src/locales/ko.json+++ b/src/locales/ko.json@@ -7229,5 +7229,27 @@"remote.devices.removed": "{name}을(를) 제거했습니다.","remote.e2e.anywhere": "어디서나 연결 가능 · 종단 간 암호화","remote.e2e.connecting": "MausBot Relay에 연결 중…",- "remote.e2e.local": "이 Wi-Fi 및 Tailscale · 종단 간 암호화"+ "remote.e2e.local": "이 Wi-Fi 및 Tailscale · 종단 간 암호화",+ "email.reading": "읽기",+ "email.sending": "보내기",+ "email.connectedDone": "연결되었습니다.",+ "email.sendTestToMyself": "나에게 테스트 보내기",+ "email.test": "테스트",+ "email.edit": "편집",+ "email.outgoing": "보내는 서버",+ "email.security": "보안",+ "email.securityAuto": "보안: 자동",+ "email.securityTls": "SSL/TLS",+ "email.securityStarttls": "STARTTLS",+ "email.smtpUsername": "보내기용 사용자 이름(다른 경우)",+ "email.smtpPassword": "보내기용 비밀번호(다른 경우)",+ "email.testSent": "{address}(으)로 테스트를 보내는 중입니다.",+ "email.addAnotherAddress": "다른 주소 추가",+ "email.signInGoogle": "Google로 로그인",+ "email.signInMicrosoft": "Microsoft로 로그인",+ "email.makeAppPassword": "앱 비밀번호 만들기",+ "email.needsGoogle": "Gmail은 여기서 앱 비밀번호(2단계 인증 사용 시)가 필요합니다. 또는 Google로 로그인하세요.",+ "email.needsMicrosoft": "Outlook은 여기서 메일 비밀번호를 받지 않습니다. Microsoft로 로그인하세요.",+ "email.needsAppPassword": "{provider}은(는) 여기서 일반 비밀번호가 아닌 앱 비밀번호가 필요합니다.",+ "serverError.mailbox.outgoingFields": "보내는 서버를 확인하세요: mail.example.com 같은 이름, 1~65535 사이의 포트, SSL/TLS 또는 STARTTLS."}diff --git a/src/locales/pl.json b/src/locales/pl.jsonindex 55f741a622..691c3f42e5 100644--- a/src/locales/pl.json+++ b/src/locales/pl.json@@ -6644,5 +6644,27 @@"remote.devices.removed": "Usunięto {name}.","remote.e2e.anywhere": "Dostępny z dowolnego miejsca · szyfrowanie end-to-end","remote.e2e.connecting": "Łączenie z MausBot Relay…",- "remote.e2e.local": "W tej sieci Wi-Fi i przez Tailscale · szyfrowanie end-to-end"+ "remote.e2e.local": "W tej sieci Wi-Fi i przez Tailscale · szyfrowanie end-to-end",+ "email.reading": "Odbieranie",+ "email.sending": "Wysyłanie",+ "email.connectedDone": "Połączono.",+ "email.sendTestToMyself": "Wyślij test do siebie",+ "email.test": "Test",+ "email.edit": "Edytuj",+ "email.outgoing": "Serwer wychodzący",+ "email.security": "Zabezpieczenia",+ "email.securityAuto": "Zabezpieczenia: automatycznie",+ "email.securityTls": "SSL/TLS",+ "email.securityStarttls": "STARTTLS",+ "email.smtpUsername": "Nazwa użytkownika do wysyłania, jeśli inna",+ "email.smtpPassword": "Hasło do wysyłania, jeśli inne",+ "email.testSent": "Wiadomość testowa jest w drodze do {address}.",+ "email.addAnotherAddress": "Dodaj kolejny adres",+ "email.signInGoogle": "Zaloguj się przez Google",+ "email.signInMicrosoft": "Zaloguj się przez Microsoft",+ "email.makeAppPassword": "Utwórz hasło do aplikacji",+ "email.needsGoogle": "Gmail wymaga tu hasła do aplikacji (przy włączonej weryfikacji dwuetapowej) albo zaloguj się przez Google.",+ "email.needsMicrosoft": "Outlook nie przyjmuje tu hasła do poczty: zaloguj się przez Microsoft.",+ "email.needsAppPassword": "{provider} wymaga tu hasła do aplikacji, a nie zwykłego hasła.",+ "serverError.mailbox.outgoingFields": "Sprawdź serwer wychodzący: nazwa w rodzaju mail.example.com, port od 1 do 65535 oraz SSL/TLS lub STARTTLS."}diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex e027d26b21..1bde528338 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -23,7 +23,6 @@"email.address": "Endereço de e-mail","email.password": "Senha da conta de e-mail","email.help": "O OpenMausBot encontra seu servidor de e-mail e verifica se consegue ler suas mensagens. Seus bots nunca veem a senha.",- "email.checking": "Buscando seu servidor de e-mail…","email.typeServer": "Informar o servidor de e-mail manualmente","email.incomingServer": "Servidor de entrada (IMAP)","email.outgoingServer": "Servidor de saída (SMTP)",@@ -33,6 +32,27 @@"email.connectedNoSending": "Conectado para leitura. Mensagens: {count}. O envio ainda não funciona.","email.addAnother": "Adicionar outra conta de e-mail","email.disconnect": "Desconectar {address}",+ "email.reading": "Leitura",+ "email.sending": "Envio",+ "email.connectedDone": "Conectado.",+ "email.sendTestToMyself": "Enviar um teste para mim",+ "email.test": "Testar",+ "email.edit": "Editar",+ "email.outgoing": "Servidor de saída",+ "email.security": "Segurança",+ "email.securityAuto": "Segurança: automática",+ "email.securityTls": "SSL/TLS",+ "email.securityStarttls": "STARTTLS",+ "email.smtpUsername": "Usuário para envio, se for diferente",+ "email.smtpPassword": "Senha para envio, se for diferente",+ "email.testSent": "Um teste está a caminho de {address}.",+ "email.addAnotherAddress": "Adicionar outro endereço",+ "email.signInGoogle": "Entrar com o Google",+ "email.signInMicrosoft": "Entrar com a Microsoft",+ "email.makeAppPassword": "Criar uma senha de app",+ "email.needsGoogle": "O Gmail precisa aqui de uma senha de app (com a verificação em duas etapas ativada), ou entre com o Google.",+ "email.needsMicrosoft": "O Outlook não aceita aqui uma senha de e-mail: entre com a Microsoft.",+ "email.needsAppPassword": "{provider} precisa aqui de uma senha de app, não da sua senha normal.","highlevel.title": "HighLevel","highlevel.description": "Também para o Growably e outros CRMs baseados no HighLevel.","highlevel.connect": "Conectar o HighLevel",@@ -9630,5 +9650,6 @@"remote.devices.removed": "{name} removido.","remote.e2e.anywhere": "Acessível de qualquer lugar · criptografia de ponta a ponta","remote.e2e.connecting": "Conectando ao MausBot Relay…",- "remote.e2e.local": "Neste Wi-Fi e Tailscale · criptografia de ponta a ponta"+ "remote.e2e.local": "Neste Wi-Fi e Tailscale · criptografia de ponta a ponta",+ "serverError.mailbox.outgoingFields": "Confira o servidor de saída: um nome como mail.example.com, uma porta de 1 a 65535 e SSL/TLS ou STARTTLS."}diff --git a/src/locales/ru.json b/src/locales/ru.jsonindex 9268524108..7dbf8a800c 100644--- a/src/locales/ru.json+++ b/src/locales/ru.json@@ -6706,5 +6706,27 @@"remote.devices.removed": "{name} удалён.","remote.e2e.anywhere": "Доступен откуда угодно · сквозное шифрование","remote.e2e.connecting": "Подключение к MausBot Relay…",- "remote.e2e.local": "В этой сети Wi-Fi и через Tailscale · сквозное шифрование"+ "remote.e2e.local": "В этой сети Wi-Fi и через Tailscale · сквозное шифрование",+ "email.reading": "Чтение",+ "email.sending": "Отправка",+ "email.connectedDone": "Подключено.",+ "email.sendTestToMyself": "Отправить себе тест",+ "email.test": "Проверить",+ "email.edit": "Изменить",+ "email.outgoing": "Сервер исходящей почты",+ "email.security": "Безопасность",+ "email.securityAuto": "Безопасность: автоматически",+ "email.securityTls": "SSL/TLS",+ "email.securityStarttls": "STARTTLS",+ "email.smtpUsername": "Имя пользователя для отправки, если другое",+ "email.smtpPassword": "Пароль для отправки, если другой",+ "email.testSent": "Тестовое письмо отправляется на {address}.",+ "email.addAnotherAddress": "Добавить ещё один адрес",+ "email.signInGoogle": "Войти через Google",+ "email.signInMicrosoft": "Войти через Microsoft",+ "email.makeAppPassword": "Создать пароль приложения",+ "email.needsGoogle": "Gmail требует здесь пароль приложения (при включённой двухэтапной аутентификации) — или войдите через Google.",+ "email.needsMicrosoft": "Outlook не принимает здесь пароль от почты: войдите через Microsoft.",+ "email.needsAppPassword": "{provider} требует здесь пароль приложения, а не обычный пароль.",+ "serverError.mailbox.outgoingFields": "Проверьте сервер исходящей почты: имя вроде mail.example.com, порт от 1 до 65535 и SSL/TLS или STARTTLS."}diff --git a/src/locales/tr.json b/src/locales/tr.jsonindex 58de71df5d..a3ea664493 100644--- a/src/locales/tr.json+++ b/src/locales/tr.json@@ -5365,5 +5365,27 @@"remote.devices.removed": "{name} kaldırıldı.","remote.e2e.anywhere": "Her yerden erişilebilir · uçtan uca şifreli","remote.e2e.connecting": "MausBot Relay'e bağlanılıyor…",- "remote.e2e.local": "Bu Wi-Fi ve Tailscale'de · uçtan uca şifreli"+ "remote.e2e.local": "Bu Wi-Fi ve Tailscale'de · uçtan uca şifreli",+ "email.reading": "Okuma",+ "email.sending": "Gönderme",+ "email.connectedDone": "Bağlandı.",+ "email.sendTestToMyself": "Kendime test gönder",+ "email.test": "Test et",+ "email.edit": "Düzenle",+ "email.outgoing": "Giden sunucu",+ "email.security": "Güvenlik",+ "email.securityAuto": "Güvenlik: otomatik",+ "email.securityTls": "SSL/TLS",+ "email.securityStarttls": "STARTTLS",+ "email.smtpUsername": "Gönderme için kullanıcı adı (farklıysa)",+ "email.smtpPassword": "Gönderme için şifre (farklıysa)",+ "email.testSent": "{address} adresine bir test gönderiliyor.",+ "email.addAnotherAddress": "Başka bir adres ekle",+ "email.signInGoogle": "Google ile oturum aç",+ "email.signInMicrosoft": "Microsoft ile oturum aç",+ "email.makeAppPassword": "Uygulama şifresi oluştur",+ "email.needsGoogle": "Gmail burada bir uygulama şifresi ister (2 Adımlı Doğrulama açıkken) ya da Google ile oturum açın.",+ "email.needsMicrosoft": "Outlook burada e-posta şifresi kabul etmiyor: Microsoft ile oturum açın.",+ "email.needsAppPassword": "{provider} burada normal şifrenizi değil, bir uygulama şifresi ister.",+ "serverError.mailbox.outgoingFields": "Giden sunucuyu kontrol edin: mail.example.com gibi bir ad, 1 ile 65535 arasında bir bağlantı noktası ve SSL/TLS veya STARTTLS."}diff --git a/src/locales/uk.json b/src/locales/uk.jsonindex ea5156ecff..03fff1a441 100644--- a/src/locales/uk.json+++ b/src/locales/uk.json@@ -3375,5 +3375,27 @@"remote.devices.removed": "{name} видалено.","remote.e2e.anywhere": "Доступний звідусіль · наскрізне шифрування","remote.e2e.connecting": "Під’єднання до MausBot Relay…",- "remote.e2e.local": "У цій мережі Wi-Fi і через Tailscale · наскрізне шифрування"+ "remote.e2e.local": "У цій мережі Wi-Fi і через Tailscale · наскрізне шифрування",+ "email.reading": "Читання",+ "email.sending": "Надсилання",+ "email.connectedDone": "Підключено.",+ "email.sendTestToMyself": "Надіслати собі тест",+ "email.test": "Перевірити",+ "email.edit": "Змінити",+ "email.outgoing": "Сервер вихідної пошти",+ "email.security": "Безпека",+ "email.securityAuto": "Безпека: автоматично",+ "email.securityTls": "SSL/TLS",+ "email.securityStarttls": "STARTTLS",+ "email.smtpUsername": "Ім’я користувача для надсилання, якщо інше",+ "email.smtpPassword": "Пароль для надсилання, якщо інший",+ "email.testSent": "Тестовий лист надсилається на {address}.",+ "email.addAnotherAddress": "Додати ще одну адресу",+ "email.signInGoogle": "Увійти через Google",+ "email.signInMicrosoft": "Увійти через Microsoft",+ "email.makeAppPassword": "Створити пароль застосунку",+ "email.needsGoogle": "Gmail потребує тут пароль застосунку (з увімкненою двоетапною перевіркою) — або увійдіть через Google.",+ "email.needsMicrosoft": "Outlook не приймає тут пароль від пошти: увійдіть через Microsoft.",+ "email.needsAppPassword": "{provider} потребує тут пароль застосунку, а не звичайний пароль.",+ "serverError.mailbox.outgoingFields": "Перевірте сервер вихідної пошти: назва на кшталт mail.example.com, порт від 1 до 65535 і SSL/TLS або STARTTLS."}diff --git a/src/locales/vi.json b/src/locales/vi.jsonindex dda1c6dee3..4e5c090946 100644--- a/src/locales/vi.json+++ b/src/locales/vi.json@@ -5365,5 +5365,27 @@"remote.devices.removed": "Đã gỡ {name}.","remote.e2e.anywhere": "Truy cập được từ mọi nơi · mã hóa đầu cuối","remote.e2e.connecting": "Đang kết nối MausBot Relay…",- "remote.e2e.local": "Trên Wi-Fi này và Tailscale · mã hóa đầu cuối"+ "remote.e2e.local": "Trên Wi-Fi này và Tailscale · mã hóa đầu cuối",+ "email.reading": "Đọc",+ "email.sending": "Gửi",+ "email.connectedDone": "Đã kết nối.",+ "email.sendTestToMyself": "Gửi thử cho chính tôi",+ "email.test": "Kiểm tra",+ "email.edit": "Sửa",+ "email.outgoing": "Máy chủ thư đi",+ "email.security": "Bảo mật",+ "email.securityAuto": "Bảo mật: tự động",+ "email.securityTls": "SSL/TLS",+ "email.securityStarttls": "STARTTLS",+ "email.smtpUsername": "Tên người dùng để gửi, nếu khác",+ "email.smtpPassword": "Mật khẩu để gửi, nếu khác",+ "email.testSent": "Một thư thử đang được gửi tới {address}.",+ "email.addAnotherAddress": "Thêm địa chỉ khác",+ "email.signInGoogle": "Đăng nhập bằng Google",+ "email.signInMicrosoft": "Đăng nhập bằng Microsoft",+ "email.makeAppPassword": "Tạo mật khẩu ứng dụng",+ "email.needsGoogle": "Gmail cần mật khẩu ứng dụng ở đây (khi đã bật xác minh 2 bước), hoặc đăng nhập bằng Google.",+ "email.needsMicrosoft": "Outlook không nhận mật khẩu thư ở đây: hãy đăng nhập bằng Microsoft.",+ "email.needsAppPassword": "{provider} cần mật khẩu ứng dụng ở đây, không phải mật khẩu thường của bạn.",+ "serverError.mailbox.outgoingFields": "Hãy kiểm tra máy chủ thư đi: một tên như mail.example.com, cổng từ 1 đến 65535, và SSL/TLS hoặc STARTTLS."}diff --git a/src/locales/zh-tw.json b/src/locales/zh-tw.jsonindex 4c2386355a..bd76d0bb2c 100644--- a/src/locales/zh-tw.json+++ b/src/locales/zh-tw.json@@ -4757,5 +4757,27 @@"remote.devices.removed": "已移除 {name}。","remote.e2e.anywhere": "隨時隨地可存取 · 端對端加密","remote.e2e.connecting": "正在連線 MausBot Relay…",- "remote.e2e.local": "在此 Wi-Fi 和 Tailscale 上 · 端對端加密"+ "remote.e2e.local": "在此 Wi-Fi 和 Tailscale 上 · 端對端加密",+ "email.reading": "收信",+ "email.sending": "寄信",+ "email.connectedDone": "已連線。",+ "email.sendTestToMyself": "寄一封測試信給自己",+ "email.test": "測試",+ "email.edit": "編輯",+ "email.outgoing": "外寄伺服器",+ "email.security": "安全性",+ "email.securityAuto": "安全性:自動",+ "email.securityTls": "SSL/TLS",+ "email.securityStarttls": "STARTTLS",+ "email.smtpUsername": "寄信用的使用者名稱(如果不同)",+ "email.smtpPassword": "寄信用的密碼(如果不同)",+ "email.testSent": "測試信正寄往 {address}。",+ "email.addAnotherAddress": "新增其他地址",+ "email.signInGoogle": "使用 Google 登入",+ "email.signInMicrosoft": "使用 Microsoft 登入",+ "email.makeAppPassword": "建立應用程式密碼",+ "email.needsGoogle": "Gmail 在這裡需要應用程式密碼(需開啟兩步驟驗證),或使用 Google 登入。",+ "email.needsMicrosoft": "Outlook 在這裡不接受郵件密碼:請使用 Microsoft 登入。",+ "email.needsAppPassword": "{provider} 在這裡需要應用程式密碼,而不是你平常的密碼。",+ "serverError.mailbox.outgoingFields": "請檢查外寄伺服器:名稱如 mail.example.com、1 到 65535 之間的連接埠,以及 SSL/TLS 或 STARTTLS。"}diff --git a/src/locales/zh.json b/src/locales/zh.jsonindex 0966d83aa1..f5172a9403 100644--- a/src/locales/zh.json+++ b/src/locales/zh.json@@ -7449,5 +7449,27 @@"remote.devices.removed": "已移除 {name}。","remote.e2e.anywhere": "随时随地可访问 · 端到端加密","remote.e2e.connecting": "正在连接 MausBot Relay…",- "remote.e2e.local": "在此 Wi-Fi 和 Tailscale 上 · 端到端加密"+ "remote.e2e.local": "在此 Wi-Fi 和 Tailscale 上 · 端到端加密",+ "email.reading": "收信",+ "email.sending": "发信",+ "email.connectedDone": "已连接。",+ "email.sendTestToMyself": "给自己发一封测试邮件",+ "email.test": "测试",+ "email.edit": "编辑",+ "email.outgoing": "发件服务器",+ "email.security": "安全性",+ "email.securityAuto": "安全性:自动",+ "email.securityTls": "SSL/TLS",+ "email.securityStarttls": "STARTTLS",+ "email.smtpUsername": "发信用户名(如不同)",+ "email.smtpPassword": "发信密码(如不同)",+ "email.testSent": "测试邮件正在发往 {address}。",+ "email.addAnotherAddress": "添加其他地址",+ "email.signInGoogle": "使用 Google 登录",+ "email.signInMicrosoft": "使用 Microsoft 登录",+ "email.makeAppPassword": "创建应用专用密码",+ "email.needsGoogle": "Gmail 在这里需要应用专用密码(需开启两步验证),或使用 Google 登录。",+ "email.needsMicrosoft": "Outlook 在这里不接受邮箱密码:请使用 Microsoft 登录。",+ "email.needsAppPassword": "{provider} 在这里需要应用专用密码,而不是你的常用密码。",+ "serverError.mailbox.outgoingFields": "请检查发件服务器:名称如 mail.example.com,端口在 1 到 65535 之间,以及 SSL/TLS 或 STARTTLS。"}