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
feat(email,auth): block sends to sensitive domains; enforce deletedAt in token auth (#369)
Gener4214992f655e
diff --git a/src/shared/src/constants.ts b/src/shared/src/constants.tsindex 2ade915ad..83e6862c0 100644--- a/src/shared/src/constants.ts+++ b/src/shared/src/constants.ts@@ -135,6 +135,34 @@ export const COMMUNITY_BOT_IMAGE_URL_MAX = 2048;// non-routable local domain.export const COMMUNITY_BOT_EMAIL_DOMAIN = "bots.alook.local";export const COMMUNITY_BOT_EMAIL_PREFIX = "bot-";++// Outbound recipient domains that agents must never email — government,+// law-enforcement, and intelligence services. Matched by exact domain OR+// suffix (so `.gov.br` catches `foo.gov.br`), case-insensitive. Adjusting the+// list ships via code release. See `isSensitiveRecipient` in utils/email.+export const SENSITIVE_RECIPIENT_DOMAINS: string[] = [+ ".gov",+ ".gov.br",+ ".gov.uk",+ ".gov.au",+ ".gov.in",+ ".gov.cn",+ ".gouv.fr",+ ".go.jp",+ ".mp.br",+ ".jus.br",+ ".gob.es",+ ".gob.mx",+ ".gc.ca",+ ".govt.nz",+ "pj.pt",+ "nca.gov.uk",+ "fbi.gov",+ "cia.gov",+ "nsa.gov",+ "interpol.int",+ "europol.europa.eu",+];/*** Single source of truth for constructing a bot's synthetic email.* Always lowercased before insert — Better-Auth lowercases inputs and thediff --git a/src/shared/src/db/queries/community/machine.ts b/src/shared/src/db/queries/community/machine.tsindex 4911e35b8..b14759f1a 100644--- a/src/shared/src/db/queries/community/machine.ts+++ b/src/shared/src/db/queries/community/machine.ts@@ -635,10 +635,12 @@ export async function findCredentialByHash(doName: communityMachineCredential.doName,}).from(communityMachineCredential)+ .innerJoin(user, eq(user.id, communityMachineCredential.userId)).where(and(eq(communityMachineCredential.credentialHash, hash),- isNull(communityMachineCredential.revokedAt)+ isNull(communityMachineCredential.revokedAt),+ isNull(user.deletedAt))).limit(1);@@ -873,10 +875,12 @@ export async function findActiveAgentRunnerKeyByBearer(doName: communityAgentRunnerKey.doName,}).from(communityAgentRunnerKey)+ .innerJoin(user, eq(user.id, communityAgentRunnerKey.userId)).where(and(eq(communityAgentRunnerKey.runnerKeyHash, hash),- isNull(communityAgentRunnerKey.revokedAt)+ isNull(communityAgentRunnerKey.revokedAt),+ isNull(user.deletedAt))).limit(1);diff --git a/src/shared/src/db/queries/machine-token.ts b/src/shared/src/db/queries/machine-token.tsindex a2e295e15..ce9967190 100644--- a/src/shared/src/db/queries/machine-token.ts+++ b/src/shared/src/db/queries/machine-token.ts@@ -40,7 +40,7 @@ export async function getMachineTokenByToken(db: Database, token: string) {}).from(machineToken).innerJoin(user, eq(user.id, machineToken.userId))- .where(eq(machineToken.token, token));+ .where(and(eq(machineToken.token, token), isNull(user.deletedAt)));return rows[0] ?? null;}diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex 8e1ccdf18..9198105a2 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -104,6 +104,7 @@ export {COMMUNITY_BOT_IMAGE_URL_MAX,COMMUNITY_BOT_EMAIL_DOMAIN,COMMUNITY_BOT_EMAIL_PREFIX,+ SENSITIVE_RECIPIENT_DOMAINS,communityBotSyntheticEmail,SELF_BOT_FRIENDSHIP_PREFIX,isSelfBotFriendship,@@ -508,7 +509,7 @@ export {} from "./db/queries/calendar-event";// Utils-export { parseEmailHandle, toAlookAddress, isValidHandle } from "./utils/email";+export { parseEmailHandle, toAlookAddress, isValidHandle, extractDomain, isSensitiveRecipient } from "./utils/email";export { parsePromptMentions } from "./utils/prompt-parser";export type { PromptAgent, PromptMention, ParseResult } from "./utils/prompt-parser";export { MENTION_TOKEN_RE, stripMentionTokens } from "./utils/mention-token";diff --git a/src/shared/src/utils/email.test.ts b/src/shared/src/utils/email.test.tsnew file mode 100644index 000000000..e18c591cb--- /dev/null+++ b/src/shared/src/utils/email.test.ts@@ -0,0 +1,55 @@+import { describe, it, expect } from "vitest"+import { extractDomain, isSensitiveRecipient } from "./email"++describe("extractDomain", () => {+ it("returns the domain of a normal address", () => {+ expect(extractDomain("[email protected]")).toBe("b.com")+ })++ it("returns the domain from a display-name form", () => {+ expect(extractDomain("Foo <[email protected]>")).toBe("b.com")+ })++ it("lowercases the domain", () => {+ expect(extractDomain("[email protected]")).toBe("b.com")+ })++ it("returns null for no-@ input", () => {+ expect(extractDomain("not-an-email")).toBeNull()+ })++ it("returns null for empty input", () => {+ expect(extractDomain("")).toBeNull()+ })+})++describe("isSensitiveRecipient", () => {+ it("matches an exact domain", () => {+ expect(isSensitiveRecipient("[email protected]")).toBe(true)+ })++ it("matches by suffix (.gov.br)", () => {+ expect(isSensitiveRecipient("[email protected]")).toBe(true)+ })++ it("is case-insensitive", () => {+ expect(isSensitiveRecipient("[email protected]")).toBe(true)+ })++ it("passes a normal external domain", () => {+ expect(isSensitiveRecipient("[email protected]")).toBe(false)+ })++ it("does not match the internal @alook.ai domain", () => {+ expect(isSensitiveRecipient("[email protected]")).toBe(false)+ })++ it("returns false for a malformed address without throwing", () => {+ expect(isSensitiveRecipient("garbage")).toBe(false)+ expect(isSensitiveRecipient("")).toBe(false)+ })++ it("does not let a display-name wrapper bypass the filter", () => {+ expect(isSensitiveRecipient("Government <[email protected]>")).toBe(true)+ })+})diff --git a/src/shared/src/utils/email.ts b/src/shared/src/utils/email.tsindex 59ab1b4a7..47762c305 100644--- a/src/shared/src/utils/email.ts+++ b/src/shared/src/utils/email.ts@@ -1,3 +1,5 @@+import { SENSITIVE_RECIPIENT_DOMAINS } from "../constants"+const DOMAIN = `@${process.env.ALOOK_DOMAIN || "alook.ai"}`const HANDLE_RE = /^[a-zA-Z0-9-]{3,}$/@@ -22,3 +24,22 @@ const RESERVED_HANDLES = new Set([export function parseEmailHandle(a: string) { return a.endsWith(DOMAIN) ? a.slice(0, -DOMAIN.length) : "" }export function toAlookAddress(h: string) { return `${h}${DOMAIN}` }export function isValidHandle(h: string) { return HANDLE_RE.test(h) && !RESERVED_HANDLES.has(h.toLowerCase()) }++export function extractDomain(email: string): string | null {+ if (!email) return null+ const angleMatch = email.match(/<([^<>]*)>[^<>]*$/)+ const addr = (angleMatch ? angleMatch[1] : email).trim()+ const at = addr.lastIndexOf("@")+ if (at < 0) return null+ const domain = addr.slice(at + 1).trim().toLowerCase()+ return domain || null+}++export function isSensitiveRecipient(email: string): boolean {+ const domain = extractDomain(email)+ if (!domain) return false+ return SENSITIVE_RECIPIENT_DOMAINS.some((entry) => {+ const target = entry.toLowerCase()+ return domain === target || domain.endsWith(target)+ })+}diff --git a/src/shared/test/queries/community-machine.test.ts b/src/shared/test/queries/community-machine.test.tsindex c462397ea..6df729adf 100644--- a/src/shared/test/queries/community-machine.test.ts+++ b/src/shared/test/queries/community-machine.test.ts@@ -880,20 +880,50 @@ describe("activateMachineCredential — success paths", () => {// findCredentialByHash / findActiveCredentialByBearer// ---------------------------------------------------------------------------+function whereRefsColumn(node: unknown, columnName: string, seen = new Set<unknown>()): boolean {+ if (node === null || typeof node !== "object") return false;+ if (seen.has(node)) return false;+ seen.add(node);+ if ((node as { name?: unknown }).name === columnName) return true;+ for (const [key, value] of Object.entries(node as Record<string, unknown>)) {+ if (key === "table") continue;+ if (Array.isArray(value)) {+ if (value.some((v) => whereRefsColumn(v, columnName, seen))) return true;+ } else if (whereRefsColumn(value, columnName, seen)) {+ return true;+ }+ }+ return false;+}+describe("findCredentialByHash", () => {it("returns null when no active row matches", async () => {const chain: any = {};chain.select = vi.fn(() => chain);chain.from = vi.fn(() => chain);+ chain.innerJoin = vi.fn(() => chain);chain.where = vi.fn(() => chain);chain.limit = vi.fn(() => Promise.resolve([]));expect(await q.findCredentialByHash(chain, "deadbeef")).toBeNull();});+ it("joins `user` and filters `user.deletedAt` so a soft-deleted owner's daemon credential stops authenticating", async () => {+ const chain: any = {};+ chain.select = vi.fn(() => chain);+ chain.from = vi.fn(() => chain);+ chain.innerJoin = vi.fn(() => chain);+ chain.where = vi.fn(() => chain);+ chain.limit = vi.fn(() => Promise.resolve([]));+ await q.findCredentialByHash(chain, "h");+ expect(chain.innerJoin).toHaveBeenCalled();+ expect(whereRefsColumn(chain.where.mock.calls[0][0], "deletedAt")).toBe(true);+ });+it("returns the row on hit and bumps last_used_at", async () => {const chain: any = {};chain.select = vi.fn(() => chain);chain.from = vi.fn(() => chain);+ chain.innerJoin = vi.fn(() => chain);chain.where = vi.fn(() => chain);chain.limit = vi.fn(() =>Promise.resolve([@@ -942,6 +972,7 @@ describe("findActiveCredentialByBearer", () => {const chain: any = {};chain.select = vi.fn(() => chain);chain.from = vi.fn(() => chain);+ chain.innerJoin = vi.fn(() => chain);chain.where = vi.fn(() => chain);// The .where call receives the drizzle condition; we can't easily peek at// the compiled value, so we just assert the limit returns a shaped row.@@ -1028,6 +1059,18 @@ describe("findActiveAgentRunnerKeyByBearer", () => {expect(await q.findActiveAgentRunnerKeyByBearer(chain, "cmk_wrong")).toBeNull();expect(chain.select).not.toHaveBeenCalled();});++ it("joins `user` and filters the owner's `user.deletedAt` so a banned owner's runner keys stop authenticating", async () => {+ const chain: any = {};+ chain.select = vi.fn(() => chain);+ chain.from = vi.fn(() => chain);+ chain.innerJoin = vi.fn(() => chain);+ chain.where = vi.fn(() => chain);+ chain.limit = vi.fn(() => Promise.resolve([]));+ await q.findActiveAgentRunnerKeyByBearer(chain, "crk_x");+ expect(chain.innerJoin).toHaveBeenCalled();+ expect(whereRefsColumn(chain.where.mock.calls[0][0], "deletedAt")).toBe(true);+ });});// ---------------------------------------------------------------------------diff --git a/src/shared/test/queries/machine-token.test.ts b/src/shared/test/queries/machine-token.test.tsindex f92c79437..f35af1d07 100644--- a/src/shared/test/queries/machine-token.test.ts+++ b/src/shared/test/queries/machine-token.test.ts@@ -40,6 +40,22 @@ describe("createMachineToken", () => {});});+function referencesColumn(node: unknown, columnName: string, seen = new Set<unknown>()): boolean {+ if (node === null || typeof node !== "object") return false;+ if (seen.has(node)) return false;+ seen.add(node);+ if ((node as { name?: unknown }).name === columnName) return true;+ for (const [key, value] of Object.entries(node as Record<string, unknown>)) {+ if (key === "table") continue;+ if (Array.isArray(value)) {+ if (value.some((v) => referencesColumn(v, columnName, seen))) return true;+ } else if (referencesColumn(value, columnName, seen)) {+ return true;+ }+ }+ return false;+}+describe("getMachineTokenByToken", () => {it("returns null when not found", async () => { expect(await mt.getMachineTokenByToken(createSelectMock([]), "x")).toBeNull(); });it("returns token with join", async () => {@@ -48,6 +64,11 @@ describe("getMachineTokenByToken", () => {expect(await mt.getMachineTokenByToken(mockDb, "tok")).toEqual(t);expect(mockDb.innerJoin).toHaveBeenCalled();});+ it("filters on `user.deletedAt` in the WHERE so a soft-deleted owner's token stops authenticating", async () => {+ const mockDb = createSelectMock([{ id: "mt_1" }]);+ await mt.getMachineTokenByToken(mockDb, "tok");+ expect(referencesColumn(mockDb.where.mock.calls[0][0], "deletedAt")).toBe(true);+ });});describe("getPendingMachineToken", () => {diff --git a/src/web/src/app/(app)/w/[slug]/agents/[id]/email/page.tsx b/src/web/src/app/(app)/w/[slug]/agents/[id]/email/page.tsxindex 0a26d7919..e47449af6 100644--- a/src/web/src/app/(app)/w/[slug]/agents/[id]/email/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/agents/[id]/email/page.tsx@@ -461,6 +461,15 @@ export default function AgentEmailPage() {{folder === "sent" ? email.to_email : email.from_email}</p><div className="flex items-center gap-2 shrink-0">+ {folder === "sent" && email.status === "blocked" && (+ <Tooltip>+ <TooltipTrigger render={<span className="inline-flex items-center gap-1 text-[10px] rounded-full px-2 py-1 leading-none font-medium bg-destructive/10 text-destructive" />}>+ <ShieldAlert className="size-3" />+ Blocked+ </TooltipTrigger>+ <TooltipContent>Blocked — not sent</TooltipContent>+ </Tooltip>+ )}{folder !== "sent" && (<span className={cn("text-[10px] rounded-full px-2 py-1 leading-none font-medium",diff --git a/src/web/src/app/api/email/route.ts b/src/web/src/app/api/email/route.tsindex 64a3fa4d7..52ddeaa03 100644--- a/src/web/src/app/api/email/route.ts+++ b/src/web/src/app/api/email/route.ts@@ -6,7 +6,7 @@ import { withWorkspaceMember } from "@/lib/middleware/workspace";import { writeJSON, writeError } from "@/lib/middleware/helpers";import { emailToResponse } from "@/lib/api/responses";-const VALID_STATUSES = ["unread", "read", "archived", "sent"];+const VALID_STATUSES = ["unread", "read", "archived", "sent", "blocked"];export const GET = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);diff --git a/src/web/src/app/api/email/send/route.test.ts b/src/web/src/app/api/email/send/route.test.tsindex 9f7f89105..ad08b42ad 100644--- a/src/web/src/app/api/email/send/route.test.ts+++ b/src/web/src/app/api/email/send/route.test.ts@@ -635,6 +635,99 @@ describe("POST /api/email/send", () => {});});+ describe("sensitive recipient domain blocking", () => {+ it("blocks a sensitive recipient: persists status:blocked outbound record and does NOT send", async () => {+ mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1" });+ mockCreateEmail.mockResolvedValue({ id: "e1", status: "blocked", direction: "outbound" });++ const req = makeReq({+ agentId: "a1",+ to: "[email protected]",+ subject: "Sensitive",+ htmlBody: "<p>Hi</p>",+ });++ const res = await POST(req, {} as any);+ expect(res.status).toBe(200);++ expect(mockEmailWorkerFetch).not.toHaveBeenCalled();+ expect(mockWorkerSelfRefFetch).not.toHaveBeenCalled();+ expect(mockGetAgentByHandle).not.toHaveBeenCalled();++ expect(mockCreateEmail).toHaveBeenCalledOnce();+ const createArgs = mockCreateEmail.mock.calls[0]![1] as any;+ expect(createArgs.status).toBe("blocked");+ expect(createArgs.direction).toBe("outbound");+ expect(createArgs.r2Key).toBe("");+ expect(createArgs.toEmail).toBe("[email protected]");+ });++ it("blocks a display-name-wrapped sensitive recipient", async () => {+ mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1" });+ mockCreateEmail.mockResolvedValue({ id: "e1", status: "blocked", direction: "outbound" });++ const req = makeReq({+ agentId: "a1",+ to: "Gov <[email protected]>",+ subject: "Wrapped",+ htmlBody: "<p>Hi</p>",+ });++ const res = await POST(req, {} as any);+ expect(res.status).toBe(200);++ expect(mockEmailWorkerFetch).not.toHaveBeenCalled();+ expect(mockWorkerSelfRefFetch).not.toHaveBeenCalled();++ const createArgs = mockCreateEmail.mock.calls[0]![1] as any;+ expect(createArgs.status).toBe("blocked");+ expect(createArgs.toEmail).toBe("Gov <[email protected]>");+ });++ it("does not block a normal external recipient (regression)", async () => {+ mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1" });+ mockEmailWorkerFetch.mockResolvedValue(Response.json({ ok: true, r2Key: "emails/x/raw" }));+ mockCreateEmail.mockResolvedValue({ id: "e1" });++ const req = makeReq({+ agentId: "a1",+ to: "[email protected]",+ subject: "Normal",+ htmlBody: "<p>Hi</p>",+ });++ const res = await POST(req, {} as any);+ expect(res.status).toBe(200);++ expect(mockEmailWorkerFetch).toHaveBeenCalledOnce();+ const createArgs = mockCreateEmail.mock.calls[0]![1] as any;+ expect(createArgs.status).toBe("sent");+ });++ it("does not block same-workspace @alook.ai internal delivery (regression)", async () => {+ mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1" });+ mockGetAgentByHandle.mockResolvedValue({ id: "a2", emailHandle: "agent-b", workspaceId: "ws1" });+ mockIsWhitelisted.mockResolvedValue(false);+ mockWorkerSelfRefFetch.mockResolvedValue(Response.json({ ok: true }));+ mockCreateEmail.mockResolvedValue({ id: "e1", direction: "outbound" });++ const req = makeReq({+ agentId: "a1",+ to: "[email protected]",+ subject: "Internal",+ htmlBody: "<p>Hi</p>",+ });++ const res = await POST(req, {} as any);+ expect(res.status).toBe(200);++ expect(mockEmailWorkerFetch).not.toHaveBeenCalled();+ expect(mockWorkerSelfRefFetch).toHaveBeenCalledOnce();+ const createArgs = mockCreateEmail.mock.calls[0]![1] as any;+ expect(createArgs.status).toBe("sent");+ });+ });+describe("conversation_map mapping creation", () => {it("creates mapping on local delivery when conversationId is provided", async () => {mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1" });diff --git a/src/web/src/app/api/email/send/route.ts b/src/web/src/app/api/email/send/route.tsindex bfe06a4e8..b0c775e78 100644--- a/src/web/src/app/api/email/send/route.ts+++ b/src/web/src/app/api/email/send/route.ts@@ -1,5 +1,5 @@import { NextRequest } from "next/server";-import { queries, DEV_EMAIL_WORKER_URL, DEV_WEB_URL, SendEmailRequestSchema, parseEmailHandle, toAlookAddress, buildMimeMessage, extractThreadId, buildEmailMapKey } from "@alook/shared";+import { queries, DEV_EMAIL_WORKER_URL, DEV_WEB_URL, SendEmailRequestSchema, parseEmailHandle, toAlookAddress, buildMimeMessage, extractThreadId, buildEmailMapKey, isSensitiveRecipient } from "@alook/shared";import { nanoid } from "nanoid";import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";@@ -100,6 +100,28 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const attachments = body.attachments ?? [];+ if (isSensitiveRecipient(body.to)) {+ const email = await queries.email.createEmail(db, {+ agentId: body.agentId,+ workspaceId: ws.workspaceId,+ fromEmail: fromAddress,+ toEmail: body.to,+ subject: body.subject,+ r2Key: "",+ isWhitelisted: false,+ forwarded: false,+ messageId: "",+ inReplyTo: body.inReplyTo ?? "",+ references: body.references ?? "",+ htmlBody: body.htmlBody || "",+ attachments: JSON.stringify(attachments),+ direction: "outbound",+ status: "blocked",+ });+ invalidate(cacheKeys.overviewEmailStats(ws.workspaceId)).catch(() => {});+ return writeJSON(emailToResponse(email));+ }+// Local delivery shortcut: same-workspace @alook.ai → @alook.aiconst senderHandle = parseEmailHandle(fromAddress);const recipientHandle = parseEmailHandle(body.to);