Email for professionals and teams
fix(security): flag AI origin and unfamiliar recipients in the send review (#225)
Hieu Nguyen (Jack)9475abef8b44
diff --git a/src/app/(dashboard)/agent/review/[id]/page.tsx b/src/app/(dashboard)/agent/review/[id]/page.tsxindex 49df7f6..c1b08e3 100644--- a/src/app/(dashboard)/agent/review/[id]/page.tsx+++ b/src/app/(dashboard)/agent/review/[id]/page.tsx@@ -25,6 +25,6 @@ export default function AgentReviewPage() {{error && <p role="alert" className="mt-4 text-red-600">{error}</p>}{!error && !request && <p className="mt-4">{t("agent.review.loading")}</p>}{request && (request.status !== "pending" || request.stale || !request.snapshot) && <p className="mt-4">{request.stale ? t("agent.review.stale") : t("agent.review.status", { status: request.status })}</p>}- {request?.status === "pending" && !request.stale && request.snapshot && <SendReview approvalId={id} snapshot={request.snapshot} onClose={() => router.push("/drafts")} onSent={() => router.push("/sent")} />}+ {request?.status === "pending" && !request.stale && request.snapshot && <SendReview approvalId={id} snapshot={request.snapshot} unfamiliarRecipients={request.unfamiliarRecipients} onClose={() => router.push("/drafts")} onSent={() => router.push("/sent")} />}</div>;}diff --git a/src/components/agent/send-review-types.d.ts b/src/components/agent/send-review-types.d.tsindex 60ec539..5d0bcc3 100644--- a/src/components/agent/send-review-types.d.ts+++ b/src/components/agent/send-review-types.d.ts@@ -13,8 +13,10 @@ export type ReviewSnapshot = {export type SendReviewProps = {approvalId: string;snapshot: ReviewSnapshot;+ /** Recipients that are not saved contacts or people the user has written to before. */+ unfamiliarRecipients?: string[];onClose?: () => void;onSent?: (messageId: string) => void;};-export type AgentReviewResponse = { status: string; snapshot: ReviewSnapshot | null; stale: boolean; error?: string };+export type AgentReviewResponse = { status: string; snapshot: ReviewSnapshot | null; stale: boolean; unfamiliarRecipients?: string[]; error?: string };diff --git a/src/components/agent/send-review.tsx b/src/components/agent/send-review.tsxindex de6067d..8da3246 100644--- a/src/components/agent/send-review.tsx+++ b/src/components/agent/send-review.tsx@@ -1,14 +1,24 @@"use client";-import { useState } from "react";+import { useEffect, useState } from "react";import { useLanguage } from "@/components/language-provider";import { authFetch } from "@/lib/auth/client";import { formatUserDate } from "@/lib/time/utils";import { htmlToPlainText } from "@/components/compose/rich-text-utils";import type { SendReviewProps } from "./send-review-types";-export function SendReview({ approvalId, snapshot, onClose, onSent }: SendReviewProps) {+export function SendReview({ approvalId, snapshot, unfamiliarRecipients: provided, onClose, onSent }: SendReviewProps) {const { t } = useLanguage();+ const [fetched, setFetched] = useState<string[]>([]);+ const unfamiliarRecipients = provided ?? fetched;+ useEffect(() => {+ if (provided) return;+ // Callers that only hold the snapshot still get the "never written to" warning.+ void authFetch(`/api/agent/approvals/${approvalId}`).then(async (response) => {+ const data = await response.json() as { unfamiliarRecipients?: string[] };+ if (response.ok) setFetched(data.unfamiliarRecipients ?? []);+ }).catch(() => undefined);+ }, [approvalId, provided]);const [busy, setBusy] = useState(false);const [error, setError] = useState<string | null>(null);async function confirm() {@@ -27,6 +37,8 @@ export function SendReview({ approvalId, snapshot, onClose, onSent }: SendReview<div className="max-h-[90vh] w-full max-w-2xl overflow-y-auto rounded-xl bg-white p-5 shadow-2xl"><h2 className="text-lg font-semibold">{snapshot.scheduledAt ? t("agent.review.reviewSchedule") : t("agent.review.reviewSend")}</h2><p className="mt-1 text-sm text-neutral-500">{snapshot.scheduledAt ? t("agent.review.confirmScheduled") : t("agent.review.confirmDelivered")}</p>+ <p className="mt-3 rounded-lg bg-amber-50 p-2 text-sm text-amber-900">{t("agent.review.aiWritten")}</p>+ {unfamiliarRecipients.length > 0 && <p role="alert" className="mt-2 rounded-lg bg-red-50 p-2 text-sm text-red-800">{t("agent.review.unfamiliarRecipients", { list: unfamiliarRecipients.join(", ") })}</p>}<dl className="mt-4 grid grid-cols-[5rem_1fr] gap-2 text-sm break-words"><dt className="text-neutral-500">{t("agent.review.from")}</dt><dd>{snapshot.from}</dd><dt className="text-neutral-500">{t("agent.review.to")}</dt><dd>{snapshot.to}</dd>@@ -36,7 +48,7 @@ export function SendReview({ approvalId, snapshot, onClose, onSent }: SendReview{snapshot.scheduledAt && <><dt className="text-neutral-500">{t("agent.review.sendAt")}</dt><dd>{formatUserDate(snapshot.scheduledAt, { dateStyle: "medium", timeStyle: "short" })}</dd></>}</dl><pre className="mt-4 max-h-72 overflow-auto whitespace-pre-wrap rounded-lg border border-neutral-200 p-3 text-sm">{snapshot.text || htmlToPlainText(snapshot.html || "")}</pre>- {snapshot.attachments.length > 0 && <p className="mt-3 text-sm">{t("agent.review.attachments", { list: snapshot.attachments.map((item) => item.filename).join(", ") })}</p>}+ {snapshot.attachments.length > 0 && <p className="mt-3 text-sm">{t("agent.review.attachments", { list: snapshot.attachments.map((item) => `${item.filename} (${Math.max(1, Math.round(item.size / 1024))} KB)`).join(", ") })}</p>}{error && <p role="alert" className="mt-3 text-sm text-red-600">{error}</p>}<div className="mt-5 flex justify-end gap-3">{onClose && <button type="button" className="rounded-lg border px-4 py-2" onClick={onClose} disabled={busy}>{t("common.cancel")}</button>}diff --git a/src/lib/agent/approvals/utils.ts b/src/lib/agent/approvals/utils.tsindex 8b105f1..02dc7ac 100644--- a/src/lib/agent/approvals/utils.ts+++ b/src/lib/agent/approvals/utils.ts@@ -1,6 +1,7 @@import { and, eq, inArray } from "drizzle-orm";import { getDb } from "@/db";-import { agentDraftMetadata, agentSendApprovals, messageAttachments, messages } from "@/db/schema";+import { agentDraftMetadata, agentSendApprovals, contacts, messageAttachments, messages } from "@/db/schema";+import { getEmailAddress, splitEmailAddressList } from "@/lib/email/address";import { getAuthorizedSenderAddress } from "@/lib/email/sender";import { loadMessageAttachmentContents } from "@/lib/email/attachments";import { sendEmail } from "@/lib/email/send";@@ -56,6 +57,15 @@ export async function requestAgentSend(env: CloudflareEnv, user: SessionUser, drreturn { approvalId: id, status: "pending_approval", expiresAt, snapshot: payload, reviewUrl: `/agent/review/${id}` };}+/** Recipients the user has never written to or saved: where an injected instruction would send private text. */+async function unfamiliarRecipients(env: CloudflareEnv, userId: string, snapshot: AgentSendSnapshot): Promise<string[]> {+ const addresses = [...new Set([snapshot.to, snapshot.cc, snapshot.bcc].flatMap((list) => splitEmailAddressList(list)).map((entry) => (getEmailAddress(entry) || entry).toLowerCase()).filter(Boolean))];+ if (!addresses.length) return [];+ const known = await getDb(env).select({ email: contacts.email }).from(contacts).where(and(eq(contacts.userId, userId), inArray(contacts.email, addresses), inArray(contacts.source, ["outbound", "manual"])));+ const familiar = new Set(known.map((row) => row.email));+ return addresses.filter((address) => !familiar.has(address));+}+export async function getAgentSendRequest(env: CloudflareEnv, user: SessionUser, approvalId: string) {const [approval] = await getDb(env).select().from(agentSendApprovals).where(and(eq(agentSendApprovals.id, approvalId), eq(agentSendApprovals.userId, user.id))).limit(1);if (!approval) throw new Error("Approval not found");@@ -69,7 +79,8 @@ export async function getAgentSendRequest(env: CloudflareEnv, user: SessionUser,if (!stale) current = read.payload;} catch { stale = true; }}- return { approvalId, status: approval.status, draftId: approval.draftId, messageId: approval.messageId, expiresAt: approval.expiresAt, snapshot: current, stale };+ const unfamiliar = current ? await unfamiliarRecipients(env, user.id, current) : [];+ return { approvalId, status: approval.status, draftId: approval.draftId, messageId: approval.messageId, expiresAt: approval.expiresAt, snapshot: current, stale, unfamiliarRecipients: unfamiliar };}export async function confirmAgentSend(env: CloudflareEnv, user: SessionUser, approvalId: string, publicOrigin?: string) {diff --git a/src/lib/i18n/en.json b/src/lib/i18n/en.jsonindex ada70ee..39148bd 100644--- a/src/lib/i18n/en.json+++ b/src/lib/i18n/en.json@@ -1984,6 +1984,8 @@"agent.review.subject": "Subject","agent.review.sendAt": "Send at","agent.review.attachments": "Attachments: {list}",+ "agent.review.aiWritten": "This message was written by the AI assistant from email content that anyone could have written. Read it before sending.",+ "agent.review.unfamiliarRecipients": "You have not written to or saved: {list}. Check that you intend to send this to them.","agent.review.deliveryNeedsReview": "Delivery needs review","agent.review.couldNotSend": "Could not send","agent.review.scheduling": "Scheduling…",