Skip to content

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

9.5 KB
Raw Blame
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { simpleParser } from "mailparser";

import { draftsFolder, MAX_FILE_ATTACHMENT_BYTES, openGuard, saveDraft, sendMessage } from "./client.ts";
import { createEmailHost, type EmailFileReader } from "./host.ts";
import { createEmailService } from "./service.ts";
import type { EmailAccount } from "./store.ts";
import type { EmailToolResult } from "./tools.ts";

const fake = vi.hoisted(() => ({
  boxes: [] as Array<{ path: string; specialUse?: string }>, appended: [] as Array<{ path: string; raw: Buffer; flags: string[] }>,
  deleted: [] as string[], deleteFails: false, flags: new Map<string, string[]>(), smtpCalls: 0, raw: Buffer.alloc(0) as Buffer,
}));
vi.mock("nodemailer", () => ({ createTransport: () => { fake.smtpCalls++; return { sendMail: async ({ raw, envelope }: any) => { fake.raw = raw; return { accepted: envelope.to }; }, close() {} }; } }));
vi.mock("imapflow", () => ({ ImapFlow: class {
  on() {} async connect() {} async logout() {}
  async list() { return fake.boxes; }
  async getMailboxLock() { return { release() {} }; }
  async fetchOne(uid: string) { const flags = fake.flags.get(uid); return flags ? { uid: Number(uid), flags: new Set(flags) } : false; }
  async append(path: string, raw: Buffer, flags: string[]) { fake.appended.push({ path, raw: Buffer.from(raw), flags }); return { uid: 40 + fake.appended.length }; }
  async messageDelete(uid: string) { if (fake.deleteFails) throw new Error("NO"); fake.deleted.push(uid); return true; }
} }));

const account = { address: "[email protected]", username: "fake", password: "fake", smtp: { host: "fake.invalid", port: 465, secure: true }, imap: { host: "fake.invalid", port: 993, secure: true } } as EmailAccount;
const pdf = { filename: "report.pdf", contentType: "application/pdf", content: Buffer.from("%PDF-1.4 synthetic") };
beforeEach(() => {
  fake.boxes = [{ path: "INBOX" }, { path: "Entwürfe", specialUse: "\\Drafts" }, { path: "Drafts" }];
  fake.appended = []; fake.deleted = []; fake.deleteFails = false; fake.flags = new Map(); fake.smtpCalls = 0; fake.raw = Buffer.alloc(0);
});

describe("drafts folder", () => {
  it("is the one the server marks as Drafts, else one named Drafts, else the one asked for", () => {
    expect(draftsFolder(fake.boxes)).toBe("Entwürfe");
    expect(draftsFolder([{ path: "INBOX" }, { path: "INBOX.Drafts" }])).toBe("INBOX.Drafts");
    expect(draftsFolder([{ path: "INBOX" }, { path: "Old Drafts" }])).toBeUndefined();
    expect(draftsFolder(fake.boxes, "Mine")).toBe("Mine");
  });
});

describe("saving a draft", () => {
  it("appends it flagged \\Draft with its files and Bcc, and sends nothing", async () => {
    const saved = await saveDraft(account, openGuard, { to: ["[email protected]"], bcc: ["[email protected]"], subject: "Plan", text: "Body", files: [pdf] });
    expect(saved).toEqual({ mailbox: "Entwürfe", uid: 41 });
    expect(fake.smtpCalls).toBe(0);
    expect(fake.appended[0]!.flags).toEqual(["\\Draft", "\\Seen"]);
    const parsed = await simpleParser(fake.appended[0]!.raw);
    expect(parsed.subject).toBe("Plan");
    expect(parsed.bcc).toMatchObject({ value: [{ address: "[email protected]" }] });
    expect(parsed.attachments.map((one) => [one.filename, one.content.toString()])).toEqual([["report.pdf", "%PDF-1.4 synthetic"]]);
  });

  it("can have no recipient yet", async () => {
    await saveDraft(account, openGuard, { subject: "Later", text: "Body" });
    expect((await simpleParser(fake.appended[0]!.raw)).to).toBeUndefined();
  });

  it("says so when the mailbox has no Drafts folder", async () => {
    fake.boxes = [{ path: "INBOX" }];
    await expect(saveDraft(account, openGuard, { subject: "s", text: "b" })).rejects.toMatchObject({ code: "not-found" });
    expect(fake.appended).toEqual([]);
  });

  it("replaces a draft: the new one is saved first, then the old one removed", async () => {
    fake.flags.set("7", ["\\Draft", "\\Seen"]);
    expect(await saveDraft(account, openGuard, { subject: "v2", text: "b", replaceUid: 7 })).toEqual({ mailbox: "Entwürfe", uid: 41, replaced: 7 });
    expect(fake.deleted).toEqual(["7"]);
  });

  it("keeps the new draft and says so when the old one can't be removed", async () => {
    fake.flags.set("7", ["\\Draft"]);
    fake.deleteFails = true;
    expect(await saveDraft(account, openGuard, { subject: "v2", text: "b", replaceUid: 7 })).toEqual({ mailbox: "Entwürfe", uid: 41, oldDraftKept: 7 });
  });

  it("never removes a message that is not a draft, or one that is gone", async () => {
    fake.flags.set("8", ["\\Seen"]);
    await expect(saveDraft(account, openGuard, { subject: "v2", text: "b", replaceUid: 8 })).rejects.toMatchObject({ code: "refused" });
    await expect(saveDraft(account, openGuard, { subject: "v2", text: "b", replaceUid: 9 })).rejects.toMatchObject({ code: "not-found" });
    expect(fake.appended).toEqual([]);
    expect(fake.deleted).toEqual([]);
  });
});

describe("file attachments", () => {
  it("go out with a sent message", async () => {
    fake.boxes = [{ path: "Sent", specialUse: "\\Sent" }];
    await sendMessage(account, openGuard, { to: ["[email protected]"], subject: "s", text: "b", files: [pdf] });
    const parsed = await simpleParser(fake.raw);
    expect(parsed.attachments.map((one) => one.filename)).toEqual(["report.pdf"]);
  });

  it("are refused before anything is sent when there are too many or too much", async () => {
    const big = { ...pdf, content: Buffer.alloc(MAX_FILE_ATTACHMENT_BYTES / 2 + 1) };
    for (const files of [Array.from({ length: 11 }, () => pdf), [big, big]]) {
      await expect(sendMessage(account, openGuard, { to: ["[email protected]"], subject: "s", text: "b", files })).rejects.toMatchObject({ code: "too-big" });
      await expect(saveDraft(account, openGuard, { subject: "s", text: "b", files })).rejects.toMatchObject({ code: "too-big" });
    }
    expect(fake.smtpCalls).toBe(0);
    expect(fake.appended).toEqual([]);
  });
});

describe("the host", () => {
  const dirs: string[] = [];
  afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 }); });
  async function host(openFile?: EmailFileReader) {
    const dataDir = mkdtempSync(join(tmpdir(), "omb-mail-drafts-")); dirs.push(dataDir);
    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 } });
    await service.connect({ address: "[email protected]", password: "fake-mailbox-password-1" });
    const rows: unknown[] = [];
    const sent: Array<Record<string, unknown>> = [];
    const drafts: Array<Record<string, unknown>> = [];
    const mail = createEmailHost({ service, dataDir, bot: () => ({ id: "b1", name: "Ada" }), inRoom: () => false, appendMessage: (_t, row) => rows.push(row), markOutside: () => {},
      run: { sendMessage: (async (_a: unknown, _g: unknown, input: Record<string, unknown>) => { sent.push(input); return { messageId: "<1@x>", accepted: ["[email protected]"], rejected: [], filed: true }; }) as never,
        saveDraft: (async (_a: unknown, _g: unknown, input: Record<string, unknown>) => { drafts.push(input); return { mailbox: "Drafts", uid: 3 }; }) as never } });
    const call = (name: string, args: Record<string, unknown>) => mail.handle({ method: "tools/call", params: { name, arguments: args } }, { botId: "b1", threadId: "t1" }, () => {}, undefined, openFile) as Promise<EmailToolResult>;
    return { call, sent, drafts, rows };
  }
  const reader: EmailFileReader = async (path) => {
    if (path !== "out/report.pdf") throw Object.assign(new Error("outside the bot's folders"), { status: 403 });
    return { name: "report.pdf", mime: "application/pdf", content: pdf.content };
  };

  it("reads attachments only through the bot's own file reader", async () => {
    const { call, sent, drafts } = await host(reader);
    expect((await call("EMAIL_SEND_MESSAGE", { to: ["[email protected]"], subject: "s", text: "b", attachments: ["out/report.pdf"] })).isError).toBeUndefined();
    expect(sent[0]!.files).toEqual([pdf]);
    const answer = await call("EMAIL_SAVE_DRAFT", { subject: "s", text: "b", attachments: ["out/report.pdf"], replace_uid: 2 });
    expect(JSON.parse(answer.content[0]!.text)).toEqual({ account: "[email protected]", mailbox: "Drafts", uid: 3 });
    expect(drafts[0]).toEqual({ subject: "s", text: "b", files: [pdf], replaceUid: 2 });
  });

  it("sends and saves nothing when a file can't be read, or there is no reader", async () => {
    const { call, sent, drafts } = await host(reader);
    const refused = await call("EMAIL_SEND_MESSAGE", { to: ["[email protected]"], subject: "s", text: "b", attachments: ["/etc/passwd"] });
    expect(refused.isError).toBe(true);
    expect(refused.content[0]!.text).toContain("/etc/passwd could not be attached");
    const none = await host();
    expect((await none.call("EMAIL_SAVE_DRAFT", { subject: "s", text: "b", attachments: ["out/report.pdf"] })).isError).toBe(true);
    expect([...sent, ...drafts, ...none.sent, ...none.drafts]).toEqual([]);
  });

  it("a draft adds no sent row", async () => {
    const { call, rows } = await host(reader);
    expect((await call("EMAIL_SAVE_DRAFT", { subject: "s", text: "b" })).isError).toBeUndefined();
    expect(rows).toEqual([]);
  });
});