Email for professionals and teams
fix(security): require in-app approval for assistant calendar edits and deletes (#225)
Hieu Nguyen (Jack)94ab47504c3d
diff --git a/src/app/(dashboard)/agent/calendar-review/page.tsx b/src/app/(dashboard)/agent/calendar-review/page.tsxnew file mode 100644index 0000000..183af3d--- /dev/null+++ b/src/app/(dashboard)/agent/calendar-review/page.tsx@@ -0,0 +1,67 @@+"use client";++import { Suspense, useEffect, useState } from "react";+import { useRouter, useSearchParams } from "next/navigation";+import { useLanguage } from "@/components/language-provider";+import { Button } from "@/components/ui/button";+import { authFetch } from "@/lib/auth/client";++type Preview = {+ action: "delete" | "update";+ events: { id: string; title: string; repeats: boolean; startsAt: string }[];+ changes: Record<string, unknown>[] | null;+};++function CalendarReview() {+ const { t } = useLanguage();+ const router = useRouter();+ const token = useSearchParams().get("token") ?? "";+ const [preview, setPreview] = useState<Preview | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [done, setDone] = useState(false);+ const [busy, setBusy] = useState(false);++ useEffect(() => {+ void authFetch(`/api/agent/calendar-confirmation?token=${encodeURIComponent(token)}`).then(async (response) => {+ const data = await response.json() as Preview & { error?: string };+ if (!response.ok) throw new Error(data.error || t("agent.calendarReview.loadFailed"));+ setPreview(data);+ }).catch((cause) => setError(cause instanceof Error ? cause.message : t("agent.calendarReview.loadFailed")));+ }, [token, t]);++ async function confirm() {+ setBusy(true);+ try {+ const response = await authFetch("/api/agent/calendar-confirmation", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ token }) });+ const data = await response.json() as { error?: string };+ if (!response.ok) throw new Error(data.error || t("agent.calendarReview.failed"));+ setDone(true);+ } catch (cause) {+ setError(cause instanceof Error ? cause.message : t("agent.calendarReview.failed"));+ } finally {+ setBusy(false);+ }+ }++ return <div className="max-w-2xl p-8">+ <h1 className="text-2xl font-semibold">{t("agent.calendarReview.title")}</h1>+ {error && <p role="alert" className="mt-4 text-red-600">{error}</p>}+ {!error && !preview && <p className="mt-4">{t("agent.calendarReview.loading")}</p>}+ {done && <p className="mt-4">{t("agent.calendarReview.done")}</p>}+ {preview && !done && <>+ <p className="mt-4">{preview.action === "delete" ? t("agent.calendarReview.deleteIntro") : t("agent.calendarReview.updateIntro")}</p>+ <ul className="mt-2 list-disc pl-6">+ {preview.events.map((event) => <li key={event.id}>{event.title} · {new Date(event.startsAt).toLocaleString()}{event.repeats ? ` · ${t("agent.calendarReview.repeats")}` : ""}</li>)}+ </ul>+ {preview.changes && <pre className="mt-4 overflow-x-auto rounded bg-muted p-3 text-xs">{JSON.stringify(preview.changes, null, 2)}</pre>}+ <div className="mt-6 flex gap-2">+ <Button onClick={confirm} disabled={busy} variant={preview.action === "delete" ? "destructive" : "default"}>{preview.action === "delete" ? t("agent.calendarReview.confirmDelete") : t("agent.calendarReview.confirmUpdate")}</Button>+ <Button variant="outline" onClick={() => router.back()}>{t("agent.calendarReview.cancel")}</Button>+ </div>+ </>}+ </div>;+}++export default function CalendarReviewPage() {+ return <Suspense><CalendarReview /></Suspense>;+}diff --git a/src/app/api/agent/calendar-confirmation/route.ts b/src/app/api/agent/calendar-confirmation/route.tsnew file mode 100644index 0000000..084761c--- /dev/null+++ b/src/app/api/agent/calendar-confirmation/route.ts@@ -0,0 +1,41 @@+import { and, eq, inArray } from "drizzle-orm";+import { getDb } from "@/db";+import { calendarEvents } from "@/db/schema";+import { getEnv } from "@/lib/cloudflare";+import { getCurrentUser } from "@/lib/auth/cookies";+import { hasValidSessionMutationOrigin } from "@/lib/auth/origin";+import { readCalendarConfirmation } from "@/lib/calendar/confirmation";+import { runCalendarTool } from "@/lib/calendar/tools";++async function describe(env: CloudflareEnv, userId: string, name: string, input: unknown) {+ const body = input as { updates?: { eventId: string }[]; eventIds?: string[] };+ const ids = body.updates?.map((item) => item.eventId) ?? body.eventIds ?? [];+ const rows = ids.length ? await getDb(env).select({ id: calendarEvents.id, title: calendarEvents.title, repeat: calendarEvents.repeat, startsAt: calendarEvents.startsAt }).from(calendarEvents).where(and(eq(calendarEvents.userId, userId), inArray(calendarEvents.id, ids))) : [];+ return { action: name === "delete_events" ? "delete" : "update", events: rows.map((row) => ({ id: row.id, title: row.title, repeats: row.repeat !== "none", startsAt: row.startsAt.toISOString() })), changes: body.updates ?? null };+}++/** Preview what an assistant asked to do to the calendar. */+export async function GET(request: Request) {+ const env = getEnv();+ const user = await getCurrentUser(env, request);+ if (!user) return Response.json({ error: "Unauthorized" }, { status: 401 });+ const confirmation = await readCalendarConfirmation(env, new URL(request.url).searchParams.get("token") ?? "", user.id);+ if (!confirmation) return Response.json({ error: "This request has expired or is not valid" }, { status: 404 });+ return Response.json(await describe(env, user.id, confirmation.name, confirmation.input));+}++/** The signed-in user approves it; only now does the change run. */+export async function POST(request: Request) {+ const env = getEnv();+ const user = await getCurrentUser(env, request);+ if (!user) return Response.json({ error: "Unauthorized" }, { status: 401 });+ if (!hasValidSessionMutationOrigin(request)) return Response.json({ error: "Invalid origin" }, { status: 403 });+ const { token } = (await request.json().catch(() => ({}))) as { token?: string };+ const confirmation = await readCalendarConfirmation(env, token ?? "", user.id);+ if (!confirmation) return Response.json({ error: "This request has expired or is not valid" }, { status: 404 });+ try {+ return Response.json(await runCalendarTool({ env, user, confirmed: true }, confirmation.name, confirmation.input));+ } catch (error) {+ return Response.json({ error: error instanceof Error ? error.message : "The change could not be applied" }, { status: 409 });+ }+}diff --git a/src/lib/calendar/confirmation.ts b/src/lib/calendar/confirmation.tsnew file mode 100644index 0000000..49e2a77--- /dev/null+++ b/src/lib/calendar/confirmation.ts@@ -0,0 +1,40 @@+import { getServerSecret } from "@/lib/security/server-secret";+import type { CalendarToolName } from "./tool-types";++/** Calendar tools that change or remove existing events; an assistant may only propose these. */+export const CONFIRMED_CALENDAR_TOOLS: ReadonlySet<CalendarToolName> = new Set(["update_events", "delete_events"]);++const LIFETIME_MS = 15 * 60_000;++export type CalendarConfirmation = { userId: string; name: CalendarToolName; input: unknown; expiresAt: number };++const encode = (value: string) => btoa(String.fromCharCode(...new TextEncoder().encode(value))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");+const decode = (value: string) => new TextDecoder().decode(Uint8Array.from(atob(value.replace(/-/g, "+").replace(/_/g, "/")), (char) => char.charCodeAt(0)));++async function mac(env: CloudflareEnv, payload: string): Promise<string> {+ const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(`calendar-confirmation\n${await getServerSecret(env)}`), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);+ return encode(String.fromCharCode(...new Uint8Array(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(payload)))));+}++/** A token the signed-in user opens in the app to approve exactly this change; the model cannot redeem it. */+export async function createCalendarConfirmation(env: CloudflareEnv, userId: string, name: CalendarToolName, input: unknown, now = Date.now()): Promise<string> {+ const payload = encode(JSON.stringify({ userId, name, input, expiresAt: now + LIFETIME_MS } satisfies CalendarConfirmation));+ return `${payload}.${await mac(env, payload)}`;+}++export async function readCalendarConfirmation(env: CloudflareEnv, token: string, userId: string, now = Date.now()): Promise<CalendarConfirmation | null> {+ const [payload, signature] = token.split(".");+ if (!payload || !signature) return null;+ const expected = await mac(env, payload);+ if (expected.length !== signature.length) return null;+ let diff = 0;+ for (let index = 0; index < expected.length; index += 1) diff |= expected.charCodeAt(index) ^ signature.charCodeAt(index);+ if (diff !== 0) return null;+ try {+ const parsed = JSON.parse(decode(payload)) as CalendarConfirmation;+ if (parsed.userId !== userId || parsed.expiresAt < now || !CONFIRMED_CALENDAR_TOOLS.has(parsed.name)) return null;+ return parsed;+ } catch {+ return null;+ }+}diff --git a/src/lib/calendar/tool-types.d.ts b/src/lib/calendar/tool-types.d.tsindex c444ef2..04b9d97 100644--- a/src/lib/calendar/tool-types.d.ts+++ b/src/lib/calendar/tool-types.d.ts@@ -1,4 +1,10 @@import type { SessionUser } from "@/lib/auth/types";-export type CalendarToolContext = { env: CloudflareEnv; user: SessionUser; timeZone?: string };+export type CalendarToolContext = {+ env: CloudflareEnv;+ user: SessionUser;+ timeZone?: string;+ /** Set only by the in-app confirmation endpoint after the signed-in user approved this exact change. */+ confirmed?: boolean;+};export type CalendarToolName = "get_schedule" | "search_events" | "get_event" | "create_event" | "update_events" | "delete_events" | "find_free_time" | "get_calendars";diff --git a/src/lib/calendar/tools.ts b/src/lib/calendar/tools.tsindex 1abb820..aeb7209 100644--- a/src/lib/calendar/tools.ts+++ b/src/lib/calendar/tools.ts@@ -8,6 +8,7 @@ import { normalizeTimeZone, zonedDateFields } from "@/lib/time/utils";import { normalizeCalendarColor } from "./colors";import { DEFAULT_REPEAT_DAYS, normalizeCalendarRepeatDays, parseCalendarOccurrenceId } from "./recurrence";import { expandToolEvents } from "./tool-occurrences";+import { CONFIRMED_CALENDAR_TOOLS, createCalendarConfirmation } from "./confirmation";import type { CalendarToolContext, CalendarToolName } from "./tool-types";const id = z.string().min(1).max(160);@@ -37,8 +38,8 @@ export const calendarToolDescriptions: Record<CalendarToolName, string> = {search_events: "Search event title, description, and location in an ISO 8601 time range, up to 90 days.",get_event: "Get an event or recurring occurrence by ID. Returns its series ID for edits.",create_event: "Create an event in the user's personal calendar. This saves immediately; attendees are recorded but invitations are not sent.",- update_events: "Update up to 20 owned event series by series ID. Changes apply to the whole series and save immediately; invitations are not sent.",- delete_events: "Delete up to 20 owned event series by series ID. This saves immediately and does not send cancellations.",+ update_events: "Propose changes to up to 20 owned event series by series ID. Nothing changes until the user approves it at the returned reviewUrl in Mailflare; changes apply to whole series and no invitations are sent.",+ delete_events: "Propose deleting up to 20 owned event series by series ID. Nothing is deleted until the user approves it at the returned reviewUrl in Mailflare; no cancellations are sent.",find_free_time: "Find available slots using the user's events in an ISO 8601 time range, up to 90 days. Returns UTC instants.",get_calendars: "List the calendars available here. Mailflare currently has one personal calendar per user.",};@@ -60,6 +61,17 @@ async function eventsInRange(context: CalendarToolContext, from: Date, to: Date)export async function runCalendarTool(context: CalendarToolContext, name: CalendarToolName, rawInput: unknown): Promise<unknown> {const input = calendarToolSchemas[name].parse(rawInput) as Record<string, unknown>;const db = getDb(context.env);+ // Editing or deleting events is only proposed by an assistant; the user approves it in the app.+ if (CONFIRMED_CALENDAR_TOOLS.has(name) && !context.confirmed) {+ const token = await createCalendarConfirmation(context.env, context.user.id, name, rawInput);+ const count = ((input.updates ?? input.eventIds) as unknown[]).length;+ return {+ status: "confirmation_required",+ message: `${count} event series would be ${name === "delete_events" ? "deleted" : "changed"}. Nothing happened yet: ask the user to review and approve it in Mailflare.`,+ reviewUrl: `/agent/calendar-review?token=${encodeURIComponent(token)}`,+ expiresInMinutes: 15,+ };+ }if (name === "get_calendars") return { calendars: [{ id: "personal", name: "Personal calendar", timeZone: normalizeTimeZone(context.user.timeZone), writable: true }] };if (name === "get_schedule" || name === "search_events" || name === "find_free_time") {const { from, to } = dates(input.start as string, input.end as string);diff --git a/src/lib/i18n/en.json b/src/lib/i18n/en.jsonindex 9ea781f..ada70ee 100644--- a/src/lib/i18n/en.json+++ b/src/lib/i18n/en.json@@ -794,6 +794,17 @@"agent.review.loading": "Loading review…","agent.review.stale": "This review is out of date. Open the draft and request a new review if needed.","agent.review.status": "This review is {status}. Open the draft and request a new review if needed.",+ "agent.calendarReview.title": "Calendar change requested by the assistant",+ "agent.calendarReview.loading": "Loading request…",+ "agent.calendarReview.loadFailed": "Could not load this request",+ "agent.calendarReview.deleteIntro": "The assistant wants to delete these events:",+ "agent.calendarReview.updateIntro": "The assistant wants to change these events:",+ "agent.calendarReview.repeats": "repeating series",+ "agent.calendarReview.confirmDelete": "Delete events",+ "agent.calendarReview.confirmUpdate": "Apply changes",+ "agent.calendarReview.cancel": "Cancel",+ "agent.calendarReview.done": "Done. The calendar was updated.",+ "agent.calendarReview.failed": "The change could not be applied","agent.assistant.close": "Close email assistant","agent.assistant.open": "Open email assistant","message.notFound": "Message not found",diff --git a/src/lib/mcp/server.ts b/src/lib/mcp/server.tsindex eab94d8..f9846ec 100644--- a/src/lib/mcp/server.ts+++ b/src/lib/mcp/server.ts@@ -29,7 +29,7 @@ export function createMailflareMcpHandler(env: CloudflareEnv, principal: McpPrin});if (principal.scopes.some((scope) => scope.startsWith("mcp:"))) {for (const name of CALENDAR_TOOL_NAMES) {- server.registerTool(name, { description: calendarToolDescriptions[name], inputSchema: calendarToolSchemas[name] }, async (args) => {+ server.registerTool(name, { description: calendarToolDescriptions[name], inputSchema: calendarToolSchemas[name], annotations: { readOnlyHint: calendarToolScope(name) === "mcp:calendar-read", destructiveHint: name === "update_events" || name === "delete_events", openWorldHint: false } }, async (args) => {if (!principal.scopes.includes(calendarToolScope(name))) return output({ error: "Permission denied" }, true);try { return output(await runCalendarTool({ env, user: principal.user }, name, args)); }catch (error) { return output({ error: error instanceof Error ? error.message : "Calendar tool failed" }, true); }diff --git a/src/lib/security/server-secret.ts b/src/lib/security/server-secret.tsnew file mode 100644index 0000000..711eea3--- /dev/null+++ b/src/lib/security/server-secret.ts@@ -0,0 +1,21 @@+const OBJECT_KEY = "config/signing-secret";++function hex(bytes: Uint8Array): string {+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");+}++/**+ * A secret only this installation knows, for signing short-lived tokens. Deployment secrets are+ * preferred; otherwise one is generated once and kept in the bucket, so no setup is required.+ */+export async function getServerSecret(env: CloudflareEnv): Promise<string> {+ const configured = env.CF_TOKEN || env.CF_API_KEY || env.INBOUND_WEBHOOK_SECRET;+ if (configured) return configured;+ const existing = await env.BUCKET.get(OBJECT_KEY);+ if (existing) return (await existing.text()).trim();+ const generated = hex(crypto.getRandomValues(new Uint8Array(32)));+ await env.BUCKET.put(OBJECT_KEY, generated);+ // Two first requests can race; whichever object won is the secret both must use.+ const stored = await env.BUCKET.get(OBJECT_KEY);+ return stored ? (await stored.text()).trim() : generated;+}diff --git a/tests/calendar-confirmation.test.mjs b/tests/calendar-confirmation.test.mjsnew file mode 100644index 0000000..bbdc7b1--- /dev/null+++ b/tests/calendar-confirmation.test.mjs@@ -0,0 +1,35 @@+import assert from "node:assert/strict";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import test, { after } from "node:test";+import { fileURLToPath, pathToFileURL } from "node:url";+import { build } from "esbuild";++const root = join(dirname(fileURLToPath(import.meta.url)), "..");+const dir = mkdtempSync(join(tmpdir(), "mailflare-calendar-confirm-"));+after(() => rmSync(dir, { recursive: true, force: true }));+await build({ entryPoints: [join(root, "src/lib/calendar/confirmation.ts")], outfile: join(dir, "c.mjs"), bundle: true, platform: "node", format: "esm", logLevel: "silent", alias: { "@": join(root, "src") } });+const { createCalendarConfirmation, readCalendarConfirmation } = await import(pathToFileURL(join(dir, "c.mjs")).href);++const env = { CF_TOKEN: "test-secret" };+const input = { eventIds: ["evt_1", "evt_2"] };++test("a confirmation token binds user, action, input and lifetime", async () => {+ const now = 1_900_000_000_000;+ const token = await createCalendarConfirmation(env, "usr_1", "delete_events", input, now);+ const read = await readCalendarConfirmation(env, token, "usr_1", now + 1000);+ assert.deepEqual({ name: read.name, input: read.input }, { name: "delete_events", input });+ assert.equal(await readCalendarConfirmation(env, token, "usr_2", now + 1000), null, "other user");+ assert.equal(await readCalendarConfirmation(env, token, "usr_1", now + 16 * 60_000), null, "expired");+ assert.equal(await readCalendarConfirmation({ CF_TOKEN: "other" }, token, "usr_1", now + 1000), null, "other installation");+ const [payload, signature] = token.split(".");+ const forged = Buffer.from(JSON.stringify({ userId: "usr_1", name: "delete_events", input: { eventIds: ["evt_9"] }, expiresAt: now + 60_000 })).toString("base64url");+ assert.equal(await readCalendarConfirmation(env, `${forged}.${signature}`, "usr_1", now + 1000), null, "tampered input");+ assert.ok(payload);+});++test("a read-only tool cannot be confirmed into existence", async () => {+ const token = await createCalendarConfirmation(env, "usr_1", "get_schedule", {}, Date.now());+ assert.equal(await readCalendarConfirmation(env, token, "usr_1"), null);+});