Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(email): check turn lifetime before SMTP dispatch

Afloat628307b1d3dd
diff --git a/server/email/client.ts b/server/email/client.ts
index 16a64dfd78..d62f1c5330 100644
--- a/server/email/client.ts
+++ b/server/email/client.ts
@@ -412,7 +412,8 @@ export function inlineAttachments(images: InlineImage[] = []) {
export interface SendInput { to: string[]; cc?: string[]; bcc?: string[]; subject: string; text: string; html?: string; inline_images?: InlineImage[]; inReplyTo?: string; references?: string }
/** 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 }> {
+export async function sendMessage(account: EmailAccount, guard: EmailGuard, input: SendInput, assertActive?: () => void): Promise<{ messageId: string; accepted: string[]; rejected: string[]; filed: boolean }> {
+ assertActive?.();
checkSendBudget({ ...input, inReplyTo: undefined, references: undefined });
const attachments = inlineAttachments(input.inline_images);
const server = account.smtp;
@@ -430,6 +431,7 @@ export async function sendMessage(account: EmailAccount, guard: EmailGuard, inpu
let transport: Awaited<ReturnType<typeof smtpTransport>> | undefined;
try {
transport = await smtpTransport(account, server, guard);
+ assertActive?.();
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);
diff --git a/server/email/host.ts b/server/email/host.ts
index eced5d3d89..00086f084d 100644
--- a/server/email/host.ts
+++ b/server/email/host.ts
@@ -96,7 +96,7 @@ export function createEmailHost(deps: EmailHostDeps) {
return accounts[0]!;
}
- async function call(name: EmailToolName, args: Record<string, any>, mailbox: EmailAccount, capability: { botId: string; threadId: string }): Promise<EmailToolResult> {
+ async function call(name: EmailToolName, args: Record<string, any>, mailbox: EmailAccount, capability: { botId: string; threadId: string }, assertActive: () => void): Promise<EmailToolResult> {
const { guard } = service;
const box = typeof args.mailbox === "string" && args.mailbox ? args.mailbox : "INBOX";
const limit = Math.min(args.limit ?? 20, LIST_MAX);
@@ -115,7 +115,7 @@ export function createEmailHost(deps: EmailHostDeps) {
const references = [...ancestors, ...(original.messageId ? [original.messageId] : [])];
threading = { ...(original.messageId ? { inReplyTo: original.messageId } : {}), ...(references.length ? { references: references.join(" ") } : {}) };
}
- return emailText({ account: from, ...await run.sendMessage(mailbox, guard, { to: args.to, subject: args.subject, text: args.text, ...pick(args, ["cc", "bcc", "html", "inline_images"]), ...threading }) });
+ return emailText({ account: from, ...await run.sendMessage(mailbox, guard, { to: args.to, subject: args.subject, text: args.text, ...pick(args, ["cc", "bcc", "html", "inline_images"]), ...threading }, assertActive) });
}
}
}
@@ -167,7 +167,7 @@ export function createEmailHost(deps: EmailHostDeps) {
if (isEmailRead(name)) deps.markOutside(capability.threadId);
let result: EmailToolResult;
try {
- result = await call(name, args, mailbox, capability);
+ result = await call(name, args, mailbox, capability, assertActive);
} catch (error) {
if (error instanceof SendingError) {
if (!LASTING_SENDING_FAULTS.has(error.fault)) return emailError(EMAIL_NOT_SENT_TEXT(error.message));
diff --git a/server/email/send-turn-lifetime.test.ts b/server/email/send-turn-lifetime.test.ts
new file mode 100644
index 0000000000..853038c15d
--- /dev/null
+++ b/server/email/send-turn-lifetime.test.ts
@@ -0,0 +1,83 @@
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+
+import { startFakeSmtp, testCertificate, trustTestCertificate, type FakeSmtp } from "../testing/fake-smtp.ts";
+import { createEmailHost } from "./host.ts";
+import { createEmailService } from "./service.ts";
+import type { EmailToolResult } from "./tools.ts";
+
+const stored = vi.hoisted(() => ({ copies: 0 }));
+vi.mock("imapflow", () => ({ ImapFlow: class {
+ on() {} async connect() {} async logout() {}
+ async list() { return [{ path: "Sent", specialUse: "\\Sent" }]; }
+ async append() { stored.copies++; }
+} }));
+
+const ADDRESS = "[email protected]", HOST = "smtp.example.test", PASSWORD = "fixture-password";
+const certificate = testCertificate([HOST]);
+const servers: FakeSmtp[] = [], 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 });
+});
+
+describe.skipIf(!certificate)("mail dispatch after a turn ends", () => {
+ it.each([
+ { wait: "reply", stop: true }, { wait: "smtp address", stop: true },
+ { wait: "reply", stop: false }, { wait: "smtp address", stop: false },
+ ])("waits on $wait with stop=$stop before contacting SMTP", async ({ wait, stop }) => {
+ stored.copies = 0;
+ const smtp = await startFakeSmtp({ certificate: certificate!, security: "tls", mechanisms: ["PLAIN"], users: { [ADDRESS]: PASSWORD } });
+ servers.push(smtp);
+ const dataDir = mkdtempSync(join(tmpdir(), "omb-email-turn-")); dirs.push(dataDir);
+ let reached!: () => void, release!: () => void;
+ const waiting = new Promise<void>((resolve) => { reached = resolve; });
+ const ready = new Promise<void>((resolve) => { release = resolve; });
+ const pause = async () => { reached(); await ready; };
+ let active = true;
+ const service = createEmailService({ dataDir, publicOnly: false, guard: async ({ host }) => {
+ if (wait === "smtp address" && host === HOST) await pause();
+ return { host: "127.0.0.1", servername: host };
+ } });
+ service.store.put({ address: ADDRESS, username: ADDRESS, password: PASSWORD, connectedAt: 1,
+ imap: { host: "imap.example.test", port: 993, secure: true }, smtp: { host: HOST, port: smtp.port, secure: true } });
+ const rows: unknown[] = [];
+ const host = createEmailHost({ service, dataDir, bot: () => ({ id: "bot", name: "Bot" }), inRoom: () => false,
+ appendMessage: (_thread, message) => rows.push(message), markOutside() {}, run: { readMessage: async () => {
+ await pause();
+ return { uid: 1, from: "[email protected]", to: [ADDRESS], subject: "Question", date: null, unread: true,
+ cc: [], replyTo: [], messageId: "<[email protected]>", text: "Original", truncated: false, attachments: [] };
+ } } });
+ const pending = (host.handle({ method: "tools/call", params: { name: "EMAIL_SEND_MESSAGE", arguments: {
+ to: ["[email protected]"], subject: "Reply", text: "The requested reply.", ...(wait === "reply" ? { reply_to_uid: 1 } : {}),
+ } } }, { botId: "bot", threadId: "thread" }, () => {
+ if (!active) throw Object.assign(new Error("The turn ended."), { status: 401 });
+ }) as Promise<EmailToolResult>).catch((error: unknown) => error);
+ try {
+ await waiting;
+ if (stop) active = false;
+ release();
+ const answer = await pending;
+ if (stop) {
+ expect(smtp.received).toEqual([]);
+ expect(smtp.signIns).toEqual([]);
+ expect(stored.copies).toBe(0);
+ expect(rows).toEqual([]);
+ } else {
+ expect(answer).not.toBeInstanceOf(Error);
+ expect((answer as EmailToolResult).isError).toBeUndefined();
+ expect(smtp.received).toHaveLength(1);
+ expect(smtp.received[0]).toMatchObject({ from: ADDRESS, to: ["[email protected]"] });
+ expect(smtp.received[0]!.data).toContain("The requested reply.");
+ if (wait === "reply") expect(smtp.received[0]!.data).toContain("In-Reply-To: <[email protected]>");
+ expect(stored.copies).toBe(1);
+ expect(rows).toHaveLength(1);
+ }
+ } finally { release(); await pending; }
+ });
+});