Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(email): strip RFC822 headers from body response and populate To field

Gener6bb5d9db203e
diff --git a/src/email-worker/src/index.ts b/src/email-worker/src/index.ts
index 71f078802..2944aff74 100644
--- a/src/email-worker/src/index.ts
+++ b/src/email-worker/src/index.ts
@@ -1,5 +1,5 @@
import { nanoid } from "nanoid"
-import { createDb, queries, parseEmailHandle } from "@alook/shared"
+import { createDb, queries, parseEmailHandle, DEV_WEB_URL } from "@alook/shared"
interface EmailEnv {
DB: D1Database
@@ -7,6 +7,27 @@ interface EmailEnv {
WEB_SERVICE: Fetcher
}
+async function notifyWeb(env: EmailEnv, payload: Record<string, unknown>) {
+ const body = JSON.stringify(payload)
+ const headers = { "Content-Type": "application/json" }
+
+ // Service bindings may connect in local dev but not route to Next.js — check response status
+ try {
+ const res = await env.WEB_SERVICE.fetch("http://internal/api/email/notify", {
+ method: "POST",
+ headers,
+ body,
+ })
+ if (!res.ok) throw new Error(`WEB_SERVICE responded ${res.status}`)
+ } catch {
+ await fetch(`${DEV_WEB_URL}/api/email/notify`, {
+ method: "POST",
+ headers,
+ body,
+ })
+ }
+}
+
export default {
async fetch(request: Request, env: EmailEnv): Promise<Response> {
const url = new URL(request.url)
@@ -79,16 +100,13 @@ export default {
const subject = message.headers.get("subject") ?? ""
if (whitelisted) {
- await env.WEB_SERVICE.fetch("http://internal/api/email/notify", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- agentId: agent.id,
- r2Key,
- from: message.from,
- subject,
- isWhitelisted: true,
- }),
+ await notifyWeb(env, {
+ agentId: agent.id,
+ r2Key,
+ from: message.from,
+ to: message.to,
+ subject,
+ isWhitelisted: true,
})
} else {
const forwardToEmail = agent.forwardToEmail ?? ""
@@ -101,17 +119,14 @@ export default {
const forwarded = !!forwardAddress
- await env.WEB_SERVICE.fetch("http://internal/api/email/notify", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- agentId: agent.id,
- r2Key,
- from: message.from,
- subject,
- isWhitelisted: false,
- forwarded,
- }),
+ await notifyWeb(env, {
+ agentId: agent.id,
+ r2Key,
+ from: message.from,
+ to: message.to,
+ subject,
+ isWhitelisted: false,
+ forwarded,
})
if (forwardAddress) {
diff --git a/src/shared/src/constants.ts b/src/shared/src/constants.ts
index 0e6064ac9..2d5d149c4 100644
--- a/src/shared/src/constants.ts
+++ b/src/shared/src/constants.ts
@@ -38,3 +38,8 @@ export const HEARTBEAT_INTERVAL_MS = 3_000;
export const OFFLINE_THRESHOLD_MS = 9_000;
export const EVENT_POLL_INTERVAL_MS = 2_000;
export const AGENT_HANDLE_MIN_LENGTH = 4;
+
+// Local dev URLs (used for service-binding fallbacks)
+export const DEV_WEB_URL = "http://localhost:3000";
+export const DEV_WS_DO_URL = "http://localhost:8789";
+export const DEV_EMAIL_WORKER_URL = "http://localhost:8788";
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index e8dc1051f..3e200c08e 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -52,6 +52,9 @@ export {
OFFLINE_THRESHOLD_MS,
EVENT_POLL_INTERVAL_MS,
AGENT_HANDLE_MIN_LENGTH,
+ DEV_WEB_URL,
+ DEV_WS_DO_URL,
+ DEV_EMAIL_WORKER_URL,
} from "./constants";
export type {
diff --git a/src/web/src/app/api/email/[id]/body/route.test.ts b/src/web/src/app/api/email/[id]/body/route.test.ts
new file mode 100644
index 000000000..4ee94cde4
--- /dev/null
+++ b/src/web/src/app/api/email/[id]/body/route.test.ts
@@ -0,0 +1,101 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+const mockR2Get = vi.fn();
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({
+ env: { DB: {}, EMAIL_BUCKET: { get: (...args: unknown[]) => mockR2Get(...args) } },
+ })),
+}));
+
+const mockGetEmailById = vi.fn();
+const mockGetAgentInWorkspace = vi.fn();
+
+vi.mock("@alook/shared", () => ({
+ createDb: vi.fn(() => ({})),
+ queries: {
+ email: { getEmailById: (...args: unknown[]) => mockGetEmailById(...args) },
+ agent: { getAgentInWorkspace: (...args: unknown[]) => mockGetAgentInWorkspace(...args) },
+ },
+}));
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
+ return handler(req, { userId: "u1", email: "[email protected]", params });
+ }),
+}));
+
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "ws1" })),
+}));
+
+vi.mock("@/lib/middleware/helpers", () => {
+ const { NextResponse } = require("next/server");
+ return {
+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),
+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),
+ };
+});
+
+import { GET } from "./route";
+
+function makeR2Object(text: string) {
+ return { text: () => Promise.resolve(text) };
+}
+
+describe("GET /api/email/[id]/body", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("strips RFC822 headers (CRLF) and returns only body text", async () => {
+ mockGetEmailById.mockResolvedValue({ id: "e1", agentId: "a1", r2Key: "emails/abc/raw" });
+ mockGetAgentInWorkspace.mockResolvedValue({ id: "a1" });
+ mockR2Get.mockResolvedValue(
+ makeR2Object("From: [email protected]\r\nTo: [email protected]\r\nSubject: Test\r\n\r\nHello world")
+ );
+
+ const req = new NextRequest("http://localhost/api/email/e1/body?workspace_id=ws1");
+ const res = await GET(req, { params: Promise.resolve({ id: "e1" }) } as any);
+
+ expect(res.status).toBe(200);
+ expect(await res.text()).toBe("Hello world");
+ });
+
+ it("strips RFC822 headers (LF) and returns only body text", async () => {
+ mockGetEmailById.mockResolvedValue({ id: "e1", agentId: "a1", r2Key: "emails/abc/raw" });
+ mockGetAgentInWorkspace.mockResolvedValue({ id: "a1" });
+ mockR2Get.mockResolvedValue(
+ makeR2Object("From: [email protected]\nTo: [email protected]\nSubject: Test\n\nHello world")
+ );
+
+ const req = new NextRequest("http://localhost/api/email/e1/body?workspace_id=ws1");
+ const res = await GET(req, { params: Promise.resolve({ id: "e1" }) } as any);
+
+ expect(res.status).toBe(200);
+ expect(await res.text()).toBe("Hello world");
+ });
+
+ it("returns full content if no header/body separator found", async () => {
+ mockGetEmailById.mockResolvedValue({ id: "e1", agentId: "a1", r2Key: "emails/abc/raw" });
+ mockGetAgentInWorkspace.mockResolvedValue({ id: "a1" });
+ mockR2Get.mockResolvedValue(makeR2Object("Just plain text with no headers"));
+
+ const req = new NextRequest("http://localhost/api/email/e1/body?workspace_id=ws1");
+ const res = await GET(req, { params: Promise.resolve({ id: "e1" }) } as any);
+
+ expect(res.status).toBe(200);
+ expect(await res.text()).toBe("Just plain text with no headers");
+ });
+
+ it("returns 404 when R2 object not found", async () => {
+ mockGetEmailById.mockResolvedValue({ id: "e1", agentId: "a1", r2Key: "emails/abc/raw" });
+ mockGetAgentInWorkspace.mockResolvedValue({ id: "a1" });
+ mockR2Get.mockResolvedValue(null);
+
+ const req = new NextRequest("http://localhost/api/email/e1/body?workspace_id=ws1");
+ const res = await GET(req, { params: Promise.resolve({ id: "e1" }) } as any);
+
+ expect(res.status).toBe(404);
+ });
+});
diff --git a/src/web/src/app/api/email/[id]/body/route.ts b/src/web/src/app/api/email/[id]/body/route.ts
index e47ea3ecf..8dd03b327 100644
--- a/src/web/src/app/api/email/[id]/body/route.ts
+++ b/src/web/src/app/api/email/[id]/body/route.ts
@@ -28,7 +28,15 @@ export const GET = withAuth(async (req, ctx) => {
});
}
- return new Response(object.body, {
+ const raw = await object.text();
+ // RFC822: headers and body are separated by a blank line
+ const crlfIdx = raw.indexOf("\r\n\r\n");
+ const lfIdx = raw.indexOf("\n\n");
+ const sepIdx = crlfIdx !== -1 ? crlfIdx : lfIdx;
+ const sepLen = crlfIdx !== -1 ? 4 : 2;
+ const bodyText = sepIdx !== -1 ? raw.slice(sepIdx + sepLen) : raw;
+
+ return new Response(bodyText, {
headers: { "Content-Type": "text/plain; charset=utf-8" },
});
});
diff --git a/src/web/src/app/api/email/notify/route.ts b/src/web/src/app/api/email/notify/route.ts
index b474862fb..b0894e195 100644
--- a/src/web/src/app/api/email/notify/route.ts
+++ b/src/web/src/app/api/email/notify/route.ts
@@ -8,13 +8,13 @@ export async function POST(req: NextRequest) {
const { env } = getCloudflareContext()
const db = createDb((env as Env).DB)
- let body: { agentId: string; r2Key: string; from: string; subject: string; isWhitelisted: boolean; forwarded?: boolean }
+ let body: { agentId: string; r2Key: string; from: string; to?: string; subject: string; isWhitelisted: boolean; forwarded?: boolean }
try { body = await req.json() } catch { return writeError("invalid body", 400) }
await queries.email.createEmail(db, {
agentId: body.agentId,
fromEmail: body.from,
- toEmail: "",
+ toEmail: body.to ?? "",
subject: body.subject,
r2Key: body.r2Key,
isWhitelisted: body.isWhitelisted,
diff --git a/src/web/src/lib/broadcast.ts b/src/web/src/lib/broadcast.ts
index b64554d35..5a20d5b45 100644
--- a/src/web/src/lib/broadcast.ts
+++ b/src/web/src/lib/broadcast.ts
@@ -1,7 +1,6 @@
import { getCloudflareContext } from "@opennextjs/cloudflare"
import type { WsMessage } from "@alook/shared"
-
-const WS_DO_DEV_URL = "http://localhost:8789"
+import { DEV_WS_DO_URL } from "@alook/shared"
export async function broadcastToUser(userId: string, message: WsMessage) {
const body = JSON.stringify(message)
@@ -17,7 +16,7 @@ export async function broadcastToUser(userId: string, message: WsMessage) {
body,
})
} catch {
- await fetch(`${WS_DO_DEV_URL}${url}`, {
+ await fetch(`${DEV_WS_DO_URL}${url}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body,
@@ -37,7 +36,7 @@ export async function broadcastToAgent(agentId: string, message: WsMessage) {
body,
})
} catch {
- await fetch(`${WS_DO_DEV_URL}${url}`, {
+ await fetch(`${DEV_WS_DO_URL}${url}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body,