Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix(email-worker): replace cf-imap with custom IMAP client to fix Gmail login (#24)
Generd590b213306e
diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 1c739e456..68d5a5281 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -51,9 +51,6 @@ importers:'@alook/shared':specifier: workspace:*version: link:../shared- cf-imap:- specifier: ^0.0.12- version: 0.0.12([email protected])nanoid:specifier: ^5.1.9version: 5.1.9@@ -2948,11 +2945,6 @@ packages:resolution: {integrity: sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==}- resolution: {integrity: sha512-ZE4XWXZPV+aXZTcJKWNAgg340WEmP29SKZ+mnweZQ2q8KTcDGXT3oz5LLTXwGA2huRpI55+lBqIk4nB+nIfz4Q==}- peerDependencies:- typescript: ^5.0.0-resolution: {integrity: sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==}engines: {node: '>=18'}@@ -9111,10 +9103,6 @@ snapshots:- dependencies:- typescript: 6.0.3-@@ -9788,8 +9776,8 @@ snapshots:'@next/eslint-plugin-next': 16.2.4eslint: 9.39.4([email protected])eslint-import-resolver-node: 0.3.10- eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))- eslint-plugin-import: 2.32.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))+ eslint-import-resolver-typescript: 3.10.1([email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])))([email protected]([email protected]))+ eslint-plugin-import: 2.32.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected]))eslint-plugin-jsx-a11y: 6.10.2([email protected]([email protected]))eslint-plugin-react: 7.37.5([email protected]([email protected]))eslint-plugin-react-hooks: 7.1.1([email protected]([email protected]))@@ -9811,7 +9799,7 @@ snapshots:transitivePeerDependencies:- supports-color+ [email protected]([email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])))([email protected]([email protected])):dependencies:'@nolyfill/is-core-module': 1.0.39debug: 4.4.3@@ -9822,22 +9810,22 @@ snapshots:tinyglobby: 0.2.16unrs-resolver: 1.11.1optionalDependencies:- eslint-plugin-import: 2.32.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))+ eslint-plugin-import: 2.32.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected]))transitivePeerDependencies:- supports-color- [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected]([email protected])):+ [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected])):dependencies:debug: 3.2.7optionalDependencies:eslint: 9.39.4([email protected])eslint-import-resolver-node: 0.3.10- eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))+ eslint-import-resolver-typescript: 3.10.1([email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])))([email protected]([email protected]))transitivePeerDependencies:- supports-color- [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected])):+ [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected])):dependencies:'@rtsao/scc': 1.1.0array-includes: 3.1.9@@ -9848,7 +9836,7 @@ snapshots:doctrine: 2.1.0eslint: 9.39.4([email protected])eslint-import-resolver-node: 0.3.10- eslint-module-utils: 2.12.1(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected]([email protected]))+ eslint-module-utils: 2.12.1(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected]))hasown: 2.0.3is-core-module: 2.16.1is-glob: 4.0.3diff --git a/src/email-worker/package.json b/src/email-worker/package.jsonindex 25ce41601..540e3c1d1 100644--- a/src/email-worker/package.json+++ b/src/email-worker/package.json@@ -10,7 +10,6 @@},"dependencies": {"@alook/shared": "workspace:*",- "cf-imap": "^0.0.12","nanoid": "^5.1.9","postal-mime": "^2.7.4","worker-mailer": "^1.2.1"diff --git a/src/email-worker/src/imap-poller-do.test.ts b/src/email-worker/src/imap-poller-do.test.tsindex f5dc1551b..7cb86953c 100644--- a/src/email-worker/src/imap-poller-do.test.ts+++ b/src/email-worker/src/imap-poller-do.test.ts@@ -11,24 +11,29 @@ vi.mock("cloudflare:workers", () => ({},}))-const { mockConnect, mockSelectFolder, mockLogout } = vi.hoisted(() => ({- mockConnect: vi.fn().mockResolvedValue(undefined),- mockSelectFolder: vi.fn().mockResolvedValue({ exists: 5 }),- mockLogout: vi.fn().mockResolvedValue(true),-}))--const { mockWriterWrite, mockReaderRead } = vi.hoisted(() => ({- mockWriterWrite: vi.fn().mockResolvedValue(undefined),- mockReaderRead: vi.fn<() => Promise<{ value: Uint8Array; done: boolean }>>(),-}))+const { mockConnect, mockSelect, mockLogout, mockCommand, MockImapAuthError } = vi.hoisted(() => {+ class _MockImapAuthError extends Error {+ constructor(msg: string) { super(msg); this.name = "ImapAuthError" }+ }+ return {+ mockConnect: vi.fn().mockResolvedValue(undefined),+ mockSelect: vi.fn().mockResolvedValue({ exists: 5 }),+ mockLogout: vi.fn().mockResolvedValue(undefined),+ mockCommand: vi.fn<(tag: string, cmd: string) => Promise<string>>(),+ MockImapAuthError: _MockImapAuthError,+ }+})-vi.mock("cf-imap", () => ({- CFImap: class {+vi.mock("./lib/imap-client", () => ({+ ImapClient: class {connect = mockConnect- selectFolder = mockSelectFolder+ select = mockSelectlogout = mockLogout- writer = { write: mockWriterWrite }- reader = { read: mockReaderRead }+ command = mockCommand+ },+ ImapAuthError: MockImapAuthError,+ ImapError: class extends Error {+ constructor(msg: string) { super(msg); this.name = "ImapError" }},}))@@ -144,19 +149,6 @@ function createDO() {return { durable, ctx, storage, env, putR2, webFetch, getAlarm }}-const encoder = new TextEncoder()--/** Queue raw IMAP response strings for the mock reader. */-function queueReaderResponses(...responses: string[]) {- let idx = 0- mockReaderRead.mockImplementation(async () => {- if (idx < responses.length) {- return { value: encoder.encode(responses[idx++]), done: false }- }- return { value: new Uint8Array(), done: true }- })-}-function buildFetchResponse(uid: number, rawEmail: string): string {return `* 1 FETCH (UID ${uid} BODY[] {${rawEmail.length}}\r\n${rawEmail}\r\n)\r\nF${uid} OK UID FETCH completed\r\n`}@@ -189,11 +181,10 @@ describe("alarm — normal UID-based flow", () => {.mockResolvedValueOnce({ from: { name: "", address: "[email protected]" }, subject: "Hi", messageId: "<msg1>", inReplyTo: "", references: "" }).mockResolvedValueOnce({ from: { name: "", address: "[email protected]" }, subject: "Hey", messageId: "<msg2>", inReplyTo: "", references: "" })- queueReaderResponses(- "* SEARCH 101 102\r\nS1 OK UID SEARCH completed\r\n",- buildFetchResponse(101, RAW_EMAIL_1),- buildFetchResponse(102, RAW_EMAIL_2),- )+ mockCommand+ .mockResolvedValueOnce("* SEARCH 101 102\r\nS1 OK UID SEARCH completed\r\n")+ .mockResolvedValueOnce(buildFetchResponse(101, RAW_EMAIL_1))+ .mockResolvedValueOnce(buildFetchResponse(102, RAW_EMAIL_2))mockGetEmailAccount.mockResolvedValue({ ...ACCOUNT, lastSyncedUid: "100" })await ctx.storage.put("accountId", "aea_test1")@@ -223,25 +214,23 @@ describe("alarm — normal UID-based flow", () => {it("uses SINCE filter for first sync (lastSyncedUid=0)", async () => {const { durable, ctx } = createDO()- queueReaderResponses("* SEARCH\r\nS1 OK UID SEARCH completed\r\n")+ mockCommand.mockResolvedValueOnce("* SEARCH\r\nS1 OK UID SEARCH completed\r\n")mockGetEmailAccount.mockResolvedValue({ ...ACCOUNT, lastSyncedUid: "0" })await ctx.storage.put("accountId", "aea_test1")await durable.alarm()- const writeCall = mockWriterWrite.mock.calls[0][0]- const cmd = new TextDecoder().decode(writeCall)- expect(cmd).toMatch(/S1 UID SEARCH SINCE \d{1,2}-\w{3}-\d{4}/)+ const [tag, cmd] = mockCommand.mock.calls[0]!+ expect(tag).toBe("S1")+ expect(cmd).toMatch(/UID SEARCH SINCE \d{1,2}-\w{3}-\d{4}/)})it("filters out UIDs <= lastSyncedUid from SEARCH results", async () => {const { durable, ctx, putR2 } = createDO()- // UID SEARCH UID 101:* might return UID 100 on some servers- queueReaderResponses(- "* SEARCH 100 101 102\r\nS1 OK UID SEARCH completed\r\n",- buildFetchResponse(101, RAW_EMAIL_1),- buildFetchResponse(102, RAW_EMAIL_2),- )+ mockCommand+ .mockResolvedValueOnce("* SEARCH 100 101 102\r\nS1 OK UID SEARCH completed\r\n")+ .mockResolvedValueOnce(buildFetchResponse(101, RAW_EMAIL_1))+ .mockResolvedValueOnce(buildFetchResponse(102, RAW_EMAIL_2))mockGetEmailAccount.mockResolvedValue({ ...ACCOUNT, lastSyncedUid: "100" })await ctx.storage.put("accountId", "aea_test1")@@ -257,10 +246,9 @@ describe("alarm — normal UID-based flow", () => {describe("alarm — whitelist filtering", () => {it("passes isWhitelisted=true for whitelisted sender", async () => {const { durable, ctx, webFetch } = createDO()- queueReaderResponses(- "* SEARCH 50\r\nS1 OK UID SEARCH completed\r\n",- buildFetchResponse(50, RAW_EMAIL_1),- )+ mockCommand+ .mockResolvedValueOnce("* SEARCH 50\r\nS1 OK UID SEARCH completed\r\n")+ .mockResolvedValueOnce(buildFetchResponse(50, RAW_EMAIL_1))mockGetEmailAccount.mockResolvedValue({ ...ACCOUNT, lastSyncedUid: "0" })mockIsWhitelisted.mockResolvedValue(true)@@ -273,10 +261,9 @@ describe("alarm — whitelist filtering", () => {it("passes isWhitelisted=false for non-whitelisted sender", async () => {const { durable, ctx, webFetch } = createDO()- queueReaderResponses(- "* SEARCH 50\r\nS1 OK UID SEARCH completed\r\n",- buildFetchResponse(50, RAW_EMAIL_1),- )+ mockCommand+ .mockResolvedValueOnce("* SEARCH 50\r\nS1 OK UID SEARCH completed\r\n")+ .mockResolvedValueOnce(buildFetchResponse(50, RAW_EMAIL_1))mockGetEmailAccount.mockResolvedValue({ ...ACCOUNT, lastSyncedUid: "0" })mockIsWhitelisted.mockResolvedValue(false)@@ -309,17 +296,16 @@ describe("alarm — connection failure & backoff", () => {// ─── Auth failure ───describe("alarm — auth failure", () => {- it("stops polling on authentication error", async () => {+ it("stops polling on authentication error from connect", async () => {const { durable, ctx } = createDO()- mockConnect.mockResolvedValueOnce(undefined)- mockSelectFolder.mockRejectedValueOnce(new Error("Authentication failed"))+ mockConnect.mockRejectedValueOnce(new MockImapAuthError("IMAP A1 failed: A1 NO [AUTHENTICATIONFAILED]"))await ctx.storage.put("accountId", "aea_test1")await durable.alarm()expect(mockUpdateEmailAccount).toHaveBeenCalledWith(expect.anything(), "aea_test1", "ws_test1",- expect.objectContaining({ status: "error", errorMessage: expect.stringContaining("Authentication") })+ expect.objectContaining({ status: "error", errorMessage: expect.stringContaining("AUTHENTICATIONFAILED") }))expect(ctx.storage.deleteAlarm).toHaveBeenCalled()})@@ -330,7 +316,7 @@ describe("alarm — auth failure", () => {describe("alarm — no new emails", () => {it("reschedules without fetching when UID SEARCH returns empty", async () => {const { durable, ctx, putR2, webFetch } = createDO()- queueReaderResponses("* SEARCH\r\nS1 OK UID SEARCH completed\r\n")+ mockCommand.mockResolvedValueOnce("* SEARCH\r\nS1 OK UID SEARCH completed\r\n")mockGetEmailAccount.mockResolvedValue({ ...ACCOUNT, lastSyncedUid: "50" })await ctx.storage.put("accountId", "aea_test1")@@ -346,31 +332,12 @@ describe("alarm — no new emails", () => {})})-// ─── Multi-chunk and error responses ───--describe("alarm — IMAP response edge cases", () => {- it("handles FETCH response split across multiple TCP reads", async () => {- const { durable, ctx, putR2 } = createDO()- const rawEmail = RAW_EMAIL_1- const fullFetch = buildFetchResponse(101, rawEmail)- const mid = Math.floor(fullFetch.length / 2)-- queueReaderResponses(- "* SEARCH 101\r\nS1 OK UID SEARCH completed\r\n",- fullFetch.substring(0, mid),- fullFetch.substring(mid),- )- mockGetEmailAccount.mockResolvedValue({ ...ACCOUNT, lastSyncedUid: "100" })-- await ctx.storage.put("accountId", "aea_test1")- await durable.alarm()-- expect(putR2).toHaveBeenCalledTimes(1)- })+// ─── IMAP command error responses ───+describe("alarm — IMAP command error responses", () => {it("throws and triggers backoff when IMAP SEARCH returns NO", async () => {const { durable, ctx } = createDO()- queueReaderResponses("S1 NO [NONEXISTENT] Mailbox not found\r\n")+ mockCommand.mockRejectedValueOnce(new Error("IMAP S1 failed: S1 NO [NONEXISTENT] Mailbox not found"))mockGetEmailAccount.mockResolvedValue({ ...ACCOUNT, lastSyncedUid: "50" })await ctx.storage.put("accountId", "aea_test1")@@ -385,9 +352,7 @@ describe("alarm — IMAP response edge cases", () => {it("throws and triggers backoff when IMAP stream ends prematurely", async () => {const { durable, ctx } = createDO()- // Stream ends without a tagged response- mockReaderRead.mockResolvedValueOnce({ value: encoder.encode("* SEARCH 101\r\n"), done: false })- mockReaderRead.mockResolvedValueOnce({ value: new Uint8Array(), done: true })+ mockCommand.mockRejectedValueOnce(new Error("IMAP stream ended without tagged response for S1"))mockGetEmailAccount.mockResolvedValue({ ...ACCOUNT, lastSyncedUid: "100" })await ctx.storage.put("accountId", "aea_test1")@@ -425,7 +390,7 @@ describe("fetch() routing", () => {it("POST /sync triggers immediate poll", async () => {const { durable, ctx } = createDO()- queueReaderResponses("* SEARCH\r\nS1 OK UID SEARCH completed\r\n")+ mockCommand.mockResolvedValueOnce("* SEARCH\r\nS1 OK UID SEARCH completed\r\n")await ctx.storage.put("accountId", "aea_test1")const res = await durable.fetch(new Request("http://internal/sync", { method: "POST" }))expect(res.status).toBe(200)diff --git a/src/email-worker/src/imap-poller-do.ts b/src/email-worker/src/imap-poller-do.tsindex 81540801e..12a9df716 100644--- a/src/email-worker/src/imap-poller-do.ts+++ b/src/email-worker/src/imap-poller-do.ts@@ -1,9 +1,9 @@import { DurableObject } from "cloudflare:workers"-import { CFImap } from "cf-imap"import PostalMime from "postal-mime"import { nanoid } from "nanoid"import { createDb, queries, createLogger } from "@alook/shared"import { decrypt } from "@alook/shared/crypto"+import { ImapClient, ImapAuthError } from "./lib/imap-client"import type { EmailEnv } from "./types"const log = createLogger({ service: "imap-poller" })@@ -71,7 +71,7 @@ export class ImapPollerDO extends DurableObject<EmailEnv> {}const pollLog = log.child({ accountId, agentId: account.agentId })- let imap: CFImap | null = null+ let client: ImapClient | null = nulltry {const secret = this.env.ENCRYPTION_KEY@@ -80,23 +80,16 @@ export class ImapPollerDO extends DurableObject<EmailEnv> {const imapUsername = decrypt(account.imapUsername, secret)const imapPassword = decrypt(account.imapPassword, secret)- imap = new CFImap({+ client = new ImapClient({host: account.imapHost,port: account.imapPort,tls: account.imapTls as unknown as boolean,auth: { username: imapUsername, password: imapPassword },})- await imap.connect()- await imap.selectFolder("INBOX")+ await client.connect()+ await client.select("INBOX")- const encoder = new TextEncoder()- const writer = (imap as any).writer as WritableStreamDefaultWriter- const reader = (imap as any).reader as ReadableStreamDefaultReader-- // UID-based search instead of SEARCH UNSEEN — catches emails- // regardless of \Seen flag (fixes Feishu and similar IMAP servers- // that auto-mark emails as read).const lastUid = parseInt(account.lastSyncedUid, 10) || 0let searchCmd: stringif (lastUid > 0) {@@ -108,7 +101,7 @@ export class ImapPollerDO extends DurableObject<EmailEnv> {searchCmd = `UID SEARCH SINCE ${since.getDate()}-${months[since.getMonth()]}-${since.getFullYear()}`}- const searchResp = await this.imapReadUntilTag(writer, reader, encoder, "S1", searchCmd)+ const searchResp = await client.command("S1", searchCmd)const searchLine = searchResp.split("\r\n").find(l => l.startsWith("* SEARCH"))const uids: number[] = searchLine? searchLine.replace("* SEARCH", "").trim().split(/\s+/).map(Number).filter(n => !isNaN(n) && n > lastUid)@@ -123,7 +116,7 @@ export class ImapPollerDO extends DurableObject<EmailEnv> {errorMessage: "",})await this.scheduleNext(account.pollIntervalSeconds * 1000)- await imap.logout()+ await client.logout()return}@@ -133,7 +126,7 @@ export class ImapPollerDO extends DurableObject<EmailEnv> {let maxUid = lastUidfor (const uid of batch) {const tag = `F${uid}`- const fetchResp = await this.imapReadUntilTag(writer, reader, encoder, tag, `UID FETCH ${uid} (BODY.PEEK[])`)+ const fetchResp = await client.command(tag, `UID FETCH ${uid} (BODY.PEEK[])`)const rawEmail = this.extractEmailFromFetch(fetchResp)if (!rawEmail) {@@ -182,19 +175,17 @@ export class ImapPollerDO extends DurableObject<EmailEnv> {await this.ctx.storage.put("backoffMs", 0)await this.scheduleNext(account.pollIntervalSeconds * 1000)- await imap.logout()+ await client.logout()} catch (err: unknown) {const msg = err instanceof Error ? err.message : String(err)pollLog.error("poll failed", { error: msg })- const isAuthError = /auth|login|credentials/i.test(msg)-await queries.emailAccount.updateEmailAccount(db, accountId, account.workspaceId, {status: "error",errorMessage: msg.slice(0, 500),})- if (isAuthError) {+ if (err instanceof ImapAuthError) {pollLog.warn("auth error — stopping polling, user must fix credentials")await this.ctx.storage.deleteAlarm()return@@ -208,40 +199,8 @@ export class ImapPollerDO extends DurableObject<EmailEnv> {await this.ctx.storage.put("backoffMs", nextBackoff)await this.scheduleNext(nextBackoff)- try { await imap?.logout() } catch { /* ignore */ }- }- }-- private async imapReadUntilTag(- writer: WritableStreamDefaultWriter,- reader: ReadableStreamDefaultReader,- encoder: TextEncoder,- tag: string,- cmd: string,- ): Promise<string> {- await writer.write(encoder.encode(`${tag} ${cmd}\r\n`))- const decoder = new TextDecoder()- let buf = ""- const READ_TIMEOUT_MS = 15_000- while (true) {- const { value, done } = await Promise.race([- reader.read(),- new Promise<never>((_, reject) =>- setTimeout(() => reject(new Error(`IMAP read timeout for ${tag}`)), READ_TIMEOUT_MS)- ),- ])- if (done) break- buf += decoder.decode(value, { stream: true })- for (const line of buf.split("\r\n")) {- if (line.startsWith(`${tag} OK`) || line.startsWith(`${tag} NO`) || line.startsWith(`${tag} BAD`)) {- if (line.startsWith(`${tag} NO`) || line.startsWith(`${tag} BAD`)) {- throw new Error(`IMAP ${tag} failed: ${line}`)- }- return buf- }- }+ try { await client?.logout() } catch { /* ignore */ }}- throw new Error(`IMAP stream ended without tagged response for ${tag}`)}private extractEmailFromFetch(response: string): string | null {diff --git a/src/email-worker/src/index.test.ts b/src/email-worker/src/index.test.tsindex 0beb396df..144282eb1 100644--- a/src/email-worker/src/index.test.ts+++ b/src/email-worker/src/index.test.ts@@ -6,9 +6,11 @@ vi.mock("cloudflare:workers", () => ({DurableObject: class {},}))-// Mock cf-imap — not used by index.ts directly but imported transitively-vi.mock("cf-imap", () => ({- CFImap: class {},+// Mock imap-client — imported transitively via imap-poller-do+vi.mock("./lib/imap-client", () => ({+ ImapClient: class {},+ ImapAuthError: class extends Error {},+ ImapError: class extends Error {},}))// Mock worker-mailerdiff --git a/src/email-worker/src/index.ts b/src/email-worker/src/index.tsindex 87e4a9503..0dbb34547 100644--- a/src/email-worker/src/index.ts+++ b/src/email-worker/src/index.ts@@ -319,8 +319,8 @@ export default {const result: { imap: string; smtp: string } = { imap: "untested", smtp: "untested" }try {- const { CFImap } = await import("cf-imap")- const imapClient = new CFImap({+ const { ImapClient } = await import("./lib/imap-client")+ const imapClient = new ImapClient({host: account.imapHost,port: account.imapPort,tls: account.imapTls as unknown as boolean,diff --git a/src/email-worker/src/lib/imap-client.ts b/src/email-worker/src/lib/imap-client.tsnew file mode 100644index 000000000..6e2d1cd82--- /dev/null+++ b/src/email-worker/src/lib/imap-client.ts@@ -0,0 +1,152 @@+import { connect } from "cloudflare:sockets"++export interface ImapClientOptions {+ host: string+ port: number+ tls: boolean+ auth: { username: string; password: string }+ readTimeoutMs?: number+}++export class ImapError extends Error {+ constructor(message: string) {+ super(message)+ this.name = "ImapError"+ }+}++export class ImapAuthError extends ImapError {+ constructor(message: string) {+ super(message)+ this.name = "ImapAuthError"+ }+}++const DEFAULT_READ_TIMEOUT_MS = 15_000++export class ImapClient {+ private socket: Socket | null = null+ private writer: WritableStreamDefaultWriter<Uint8Array> | null = null+ private reader: ReadableStreamDefaultReader<Uint8Array> | null = null+ private encoder = new TextEncoder()+ private tagCounter = 0+ private readTimeoutMs: number++ constructor(private options: ImapClientOptions) {+ this.readTimeoutMs = options.readTimeoutMs ?? DEFAULT_READ_TIMEOUT_MS+ }++ async connect(): Promise<void> {+ const opts: Record<string, unknown> = { allowHalfOpen: true }+ if (this.options.tls) opts.secureTransport = "starttls"++ this.socket = connect(+ { hostname: this.options.host, port: this.options.port },+ opts as any,+ )++ if (this.options.tls) {+ this.socket = this.socket.startTls()+ }++ this.writer = this.socket.writable.getWriter()+ this.reader = this.socket.readable.getReader()++ await this.readGreeting()++ const tag = this.nextTag()+ const user = this.quote(this.options.auth.username)+ const pass = this.quote(this.options.auth.password)++ try {+ await this.sendCommand(tag, `LOGIN ${user} ${pass}`)+ } catch (err) {+ if (err instanceof ImapError) throw new ImapAuthError(err.message)+ throw err+ }+ }++ async select(folder: string): Promise<{ exists: number }> {+ const tag = this.nextTag()+ const resp = await this.sendCommand(tag, `SELECT ${this.quote(folder)}`)+ const existsMatch = resp.match(/\* (\d+) EXISTS/)+ return { exists: existsMatch ? parseInt(existsMatch[1]!, 10) : 0 }+ }++ async command(tag: string, cmd: string): Promise<string> {+ return this.sendCommand(tag, cmd)+ }++ async logout(): Promise<void> {+ try {+ const tag = this.nextTag()+ await this.writer?.write(this.encoder.encode(`${tag} LOGOUT\r\n`))+ } catch { /* best-effort */ }+ await this.close()+ }++ async close(): Promise<void> {+ try { this.reader?.releaseLock() } catch { /* ignore */ }+ try { this.writer?.releaseLock() } catch { /* ignore */ }+ try { await this.socket?.close() } catch { /* ignore */ }+ this.socket = null+ this.writer = null+ this.reader = null+ }++ private nextTag(): string {+ return `A${++this.tagCounter}`+ }++ private async sendCommand(tag: string, cmd: string): Promise<string> {+ if (!this.writer || !this.reader) throw new ImapError("Not connected")+ await this.writer.write(this.encoder.encode(`${tag} ${cmd}\r\n`))+ return this.readUntilTag(tag)+ }++ private async readGreeting(): Promise<void> {+ const decoder = new TextDecoder()+ let buf = ""+ while (true) {+ const chunk = await this.timedRead()+ if (chunk.done) throw new ImapError("Connection closed before greeting")+ buf += decoder.decode(chunk.value, { stream: true })+ if (buf.split("\r\n").some(l => l.startsWith("* OK"))) return+ if (buf.split("\r\n").some(l => l.startsWith("* BYE"))) {+ throw new ImapError(`Server rejected connection: ${buf.trim()}`)+ }+ }+ }++ private async readUntilTag(tag: string): Promise<string> {+ if (!this.reader) throw new ImapError("Not connected")+ const decoder = new TextDecoder()+ let buf = ""+ while (true) {+ const chunk = await this.timedRead()+ if (chunk.done) break+ buf += decoder.decode(chunk.value, { stream: true })+ for (const line of buf.split("\r\n")) {+ if (line.startsWith(`${tag} OK`)) return buf+ if (line.startsWith(`${tag} NO`) || line.startsWith(`${tag} BAD`)) {+ throw new ImapError(`IMAP ${tag} failed: ${line}`)+ }+ }+ }+ throw new ImapError(`IMAP stream ended without tagged response for ${tag}`)+ }++ private async timedRead(): Promise<ReadableStreamReadResult<Uint8Array>> {+ if (!this.reader) throw new ImapError("Not connected")+ return Promise.race([+ this.reader.read(),+ new Promise<never>((_, reject) =>+ setTimeout(() => reject(new ImapError("IMAP read timeout")), this.readTimeoutMs)+ ),+ ])+ }++ private quote(s: string): string {+ return `"${s.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`+ }+}