Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(web): add minimal account deletion

Genere8edf48b055f
diff --git a/scripts/ci/fixtures/d1-dynamic-bind-sites.json b/scripts/ci/fixtures/d1-dynamic-bind-sites.json
index 357ef3507..9db3ef9ff 100644
--- a/scripts/ci/fixtures/d1-dynamic-bind-sites.json
+++ b/scripts/ci/fixtures/d1-dynamic-bind-sites.json
@@ -1,4 +1,305 @@
[
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:1",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:10",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:11",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:12",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:13",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:14",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:15",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:16",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:17",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:18",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:19",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:2",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:20",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:21",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:22",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:23",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:24",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:25",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:26",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:27",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:28",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:29",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:3",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:30",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:31",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:32",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:33",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:34",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:35",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:36",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:37",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:4",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:5",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:6",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:7",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:8",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:deleteAccountRows:inArray:9",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:1",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:10",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:11",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:12",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:13",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:14",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:15",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:16",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:17",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:18",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:19",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:2",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:20",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:21",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:22",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:23",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:24",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:25",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:26",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:27",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:28",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:29",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:3",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:30",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:31",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:32",
+ "strategy": "exact-chunk",
+ "fixedParams": 10
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:33",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:34",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:35",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:36",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:37",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:38",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:4",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:5",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:6",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:7",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:8",
+ "strategy": "subquery"
+ },
+ {
+ "key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:9",
+ "strategy": "subquery"
+ },
{
"key": "src/shared/src/db/queries/agent-skill.ts:syncAgentSkills:values:1",
"strategy": "exact-chunk",
diff --git a/src/shared/src/db/queries-index.ts b/src/shared/src/db/queries-index.ts
index 50cc553ec..483de04d2 100644
--- a/src/shared/src/db/queries-index.ts
+++ b/src/shared/src/db/queries-index.ts
@@ -32,6 +32,7 @@ export * as inbox from "./queries/inbox";
export * as issue from "./queries/issue";
export * as issueComment from "./queries/issue-comment";
export * as messageFlag from "./queries/message-flag";
+export * as accountDeletion from "./queries/account-deletion";
export * as communityServer from "./queries/community/server";
export * as communityChannel from "./queries/community/channel";
export * as communityCategory from "./queries/community/category";
diff --git a/src/shared/src/db/queries/account-deletion.test.ts b/src/shared/src/db/queries/account-deletion.test.ts
new file mode 100644
index 000000000..40a332c8a
--- /dev/null
+++ b/src/shared/src/db/queries/account-deletion.test.ts
@@ -0,0 +1,350 @@
+import { readFileSync, readdirSync } from "node:fs"
+import { resolve } from "node:path"
+import Sqlite from "better-sqlite3"
+import { drizzle } from "drizzle-orm/better-sqlite3"
+import { afterEach, beforeEach, describe, expect, it } from "vitest"
+import * as coreSchema from "../schema"
+import * as communitySchema from "../community-schema"
+import * as machineSchema from "../community-machine-schema"
+import type { Database } from "../index"
+import {
+ deleteAccountRows,
+ deleteDeletionChallengeIfMatches,
+ getAccountDeletionSnapshot,
+ restoreDeletionChallenge,
+ takeDeletionChallenge,
+ upsertDeletionChallenge,
+ type DeletionChallenge,
+} from "./account-deletion"
+
+const schema = { ...coreSchema, ...communitySchema, ...machineSchema }
+
+function challenge(overrides: Partial<DeletionChallenge> = {}): DeletionChallenge {
+ return {
+ id: "account-deletion:test",
+ identifier: "account-deletion-otp:user-1:[email protected]",
+ value: "123456:0",
+ expiresAt: "2026-09-07T15:05:00.000Z",
+ createdAt: "2026-09-07T15:00:00.000Z",
+ updatedAt: "2026-09-07T15:00:00.000Z",
+ ...overrides,
+ }
+}
+
+describe("account deletion challenge queries", () => {
+ let sqlite: Sqlite.Database
+ let db: Database
+
+ beforeEach(() => {
+ sqlite = new Sqlite(":memory:")
+ sqlite.exec(`
+ CREATE TABLE verification (
+ id TEXT PRIMARY KEY NOT NULL,
+ identifier TEXT NOT NULL,
+ value TEXT NOT NULL,
+ expiresAt TEXT NOT NULL,
+ createdAt TEXT NOT NULL,
+ updatedAt TEXT NOT NULL
+ )
+ `)
+ db = drizzle(sqlite, { schema }) as unknown as Database
+ })
+
+ afterEach(() => sqlite.close())
+
+ it("keeps exactly one active row and makes the latest code authoritative", async () => {
+ await upsertDeletionChallenge(db, challenge())
+ await upsertDeletionChallenge(db, challenge({
+ value: "654321:0",
+ expiresAt: "2026-09-07T15:06:00.000Z",
+ updatedAt: "2026-09-07T15:01:00.000Z",
+ }))
+
+ expect(sqlite.prepare("SELECT COUNT(*) AS count FROM verification").get()).toEqual({ count: 1 })
+ expect(sqlite.prepare("SELECT value, expiresAt FROM verification").get()).toEqual({
+ value: "654321:0",
+ expiresAt: "2026-09-07T15:06:00.000Z",
+ })
+ })
+
+ it("fails closed when RETURNING does not yield the persisted challenge", async () => {
+ const emptyReturningDb = {
+ insert: () => ({
+ values: () => ({
+ onConflictDoUpdate: () => ({ returning: async () => [] }),
+ }),
+ }),
+ } as unknown as Database
+
+ await expect(upsertDeletionChallenge(emptyReturningDb, challenge()))
+ .rejects.toThrow("account deletion challenge was not persisted")
+ })
+
+ it("atomically takes a challenge only once", async () => {
+ await upsertDeletionChallenge(db, challenge())
+
+ await expect(takeDeletionChallenge(db, challenge())).resolves.toMatchObject({ value: "123456:0" })
+ await expect(takeDeletionChallenge(db, challenge())).resolves.toBeNull()
+ })
+
+ it("restores only when a newer resend has not won the primary key", async () => {
+ const original = challenge()
+ await expect(restoreDeletionChallenge(db, original)).resolves.toBe(true)
+ await upsertDeletionChallenge(db, challenge({ value: "654321:0" }))
+ await expect(restoreDeletionChallenge(db, original)).resolves.toBe(false)
+ expect(sqlite.prepare("SELECT value FROM verification").get()).toEqual({ value: "654321:0" })
+ })
+
+ it("rolls back only the exact challenge written by a failed send", async () => {
+ const original = challenge()
+ await upsertDeletionChallenge(db, original)
+ await upsertDeletionChallenge(db, challenge({ value: "654321:0" }))
+
+ await expect(deleteDeletionChallengeIfMatches(db, original)).resolves.toBe(false)
+ await expect(deleteDeletionChallengeIfMatches(db, challenge({ value: "654321:0" }))).resolves.toBe(true)
+ })
+})
+
+describe("account deletion snapshot and delete queries", () => {
+ let sqlite: Sqlite.Database
+ let db: Database
+
+ beforeEach(() => {
+ sqlite = new Sqlite(":memory:")
+ const migrationRoot = resolve(import.meta.dirname, "../../../../web/migrations")
+ for (const filename of readdirSync(migrationRoot).filter((name) => name.endsWith(".sql")).sort()) {
+ sqlite.exec(readFileSync(resolve(migrationRoot, filename), "utf8"))
+ }
+ sqlite.pragma("foreign_keys = ON")
+ const sqliteDb = drizzle(sqlite, { schema })
+ Object.assign(sqliteDb, {
+ batch: async (statements: Array<{
+ config: { returning?: unknown }
+ all: () => unknown[]
+ run: () => unknown
+ }>) => sqlite.transaction(() => statements.map((statement) =>
+ statement.config.returning ? statement.all() : statement.run(),
+ ))(),
+ })
+ db = sqliteDb as unknown as Database
+ })
+
+ afterEach(() => sqlite.close())
+
+ function run(statement: string, ...bindings: unknown[]): void {
+ sqlite.prepare(statement).run(...bindings)
+ }
+
+ it("snapshots every attributable root and deletes it without damaging shared data", async () => {
+ const now = "2026-09-08T00:00:00.000Z"
+ const owner = "delete_owner"
+ const bot = "delete_bot"
+ const reader = "surviving_reader"
+ const earlyReader = "surviving_early_reader"
+ const ownedWorkspace = "owned_workspace"
+ const sharedWorkspace = "shared_workspace"
+ const ownedAgent = "owned_agent"
+ const sharedOwnedAgent = "shared_owned_agent"
+ const survivingAgent = "surviving_agent"
+ const runtime = "owned_runtime"
+ const daemon = "owned_daemon"
+ const dm = "surviving_dm"
+ const priorMessage = "prior_message"
+ const authoredMessage = "authored_message"
+ const botMessage = "bot_message"
+ const forum = "surviving_forum"
+ const opener = "owned_opener"
+ const thread = "doomed_thread"
+ const reply = "thread_reply"
+ const ownedServer = "owned_server"
+ const emptyOwnedServer = "empty_owned_server"
+ const serverChannel = "owned_server_channel"
+ const sharedAttachmentKey = "emails/drafts/shared.txt"
+ const privateAttachmentKey = "emails/drafts/private.txt"
+
+ run(
+ "INSERT INTO user (id, email, name, discriminator, avatarObjectKey) VALUES (?, ?, 'Owner', '8101', ?), (?, ?, 'Bot', '8102', ?), (?, ?, 'Reader', '8103', NULL), (?, ?, 'Early reader', '8104', NULL)",
+ owner, `${owner}@example.com`, `users/${owner}/avatar`,
+ bot, `${bot}@example.com`, `bots/${bot}/avatar`,
+ reader, `${reader}@example.com`, earlyReader, `${earlyReader}@example.com`,
+ )
+ run("UPDATE user SET isBot = 1, ownerUserId = ? WHERE id = ?", owner, bot)
+ run(
+ "INSERT INTO account (id, userId, accountId, providerId, accessToken, refreshToken, createdAt, updatedAt) VALUES ('account_1', ?, 'provider_account', 'github', 'access', 'refresh', ?, ?)",
+ owner, now, now,
+ )
+ run(
+ "INSERT INTO workspace (id, name, slug, created_at, updated_at) VALUES (?, 'Owned', ?, ?, ?), (?, 'Shared', ?, ?, ?)",
+ ownedWorkspace, ownedWorkspace, now, now, sharedWorkspace, sharedWorkspace, now, now,
+ )
+ run(
+ "INSERT INTO member (id, workspace_id, user_id, role, created_at) VALUES ('member_owner', ?, ?, 'owner', ?), ('member_coowner', ?, ?, 'owner', ?), ('member_shared_owner', ?, ?, 'owner', ?), ('member_shared_user', ?, ?, 'member', ?)",
+ ownedWorkspace, owner, now, ownedWorkspace, reader, now,
+ sharedWorkspace, reader, now, sharedWorkspace, owner, now,
+ )
+ run(
+ "INSERT INTO machine_token (id, user_id, workspace_id, token, name, status, created_at) VALUES ('token_owner', ?, ?, 'al_owner_token', 'Owner', 'active', ?), ('token_workspace', ?, ?, 'al_workspace_token', 'Workspace', 'active', ?)",
+ owner, sharedWorkspace, now, reader, ownedWorkspace, now,
+ )
+ run(
+ "INSERT INTO agent (id, workspace_id, name, owner_id, created_at, updated_at) VALUES (?, ?, 'Owned', ?, ?, ?), (?, ?, 'Shared owned', ?, ?, ?)",
+ ownedAgent, ownedWorkspace, owner, now, now,
+ sharedOwnedAgent, sharedWorkspace, owner, now, now,
+ )
+ run(
+ "INSERT INTO machine (daemon_id, workspace_id, owner_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?)",
+ daemon, sharedWorkspace, owner, now, now,
+ )
+ run(
+ "INSERT INTO agent_runtime (id, workspace_id, daemon_id, provider, created_at, updated_at) VALUES (?, ?, ?, 'codex', ?, ?)",
+ runtime, sharedWorkspace, daemon, now, now,
+ )
+ run(
+ "INSERT INTO agent (id, workspace_id, name, runtime_id, owner_id, created_at, updated_at) VALUES (?, ?, 'Survivor', ?, ?, ?, ?)",
+ survivingAgent, sharedWorkspace, runtime, reader, now, now,
+ )
+ run(
+ "INSERT INTO conversation (id, workspace_id, agent_id, user_id, title, type, channel, created_at) VALUES ('owned_conversation', ?, ?, ?, '', 'user_dm_message', 'default', ?)",
+ ownedWorkspace, ownedAgent, owner, now,
+ )
+ run(
+ "INSERT INTO artifact (id, conversation_id, agent_id, workspace_id, filename, size, r2_key, thumbnail_r2_key, created_at) VALUES ('owned_artifact', 'owned_conversation', ?, ?, 'artifact.txt', 1, 'artifacts/raw', 'artifacts/thumb', ?)",
+ ownedAgent, ownedWorkspace, now,
+ )
+ run(
+ "INSERT INTO meeting_session (id, agent_id, workspace_id, meeting_url, transcript_r2_key, created_at, updated_at) VALUES ('owned_meeting', ?, ?, 'https://example.com', 'meetings/transcript', ?, ?)",
+ ownedAgent, ownedWorkspace, now, now,
+ )
+ run(
+ "INSERT INTO emails (id, agent_id, workspace_id, from_email, to_email, r2_key, attachments, created_at) VALUES ('deleting_email', ?, ?, '[email protected]', '[email protected]', 'emails/deleting/raw', ?, ?), ('invalid_email', ?, ?, '[email protected]', '[email protected]', 'emails/invalid/raw', 'not-json', ?), ('non_array_email', ?, ?, '[email protected]', '[email protected]', 'emails/non-array/raw', '{}', ?), ('surviving_email', ?, ?, '[email protected]', '[email protected]', 'emails/surviving/raw', ?, ?)",
+ ownedAgent, ownedWorkspace, JSON.stringify([{ key: sharedAttachmentKey }, { key: privateAttachmentKey }, { nope: true }, null]), now,
+ ownedAgent, ownedWorkspace, now,
+ ownedAgent, ownedWorkspace, now,
+ survivingAgent, sharedWorkspace, JSON.stringify([{ key: sharedAttachmentKey }]), now,
+ )
+ run("INSERT INTO community_machine (id, user_id, created_at, updated_at) VALUES ('community_machine_1', ?, ?, ?)", owner, now, now)
+ run(
+ "INSERT INTO community_machine_credential (id, user_id, machine_id, credential_hash, do_name, created_at) VALUES ('credential_1', ?, 'community_machine_1', ?, ?, ?)",
+ owner, "a".repeat(64), "b".repeat(32), now,
+ )
+ run(
+ "INSERT INTO community_bot_binding (user_id, machine_id, runtime, instruction, created_at) VALUES (?, 'community_machine_1', 'codex', '', ?)",
+ bot, now,
+ )
+ run(
+ "INSERT INTO community_server (id, name, discriminator, owner_id, icon, created_at) VALUES (?, 'Owned', '8201', ?, 'servers/owned/icon', ?), (?, 'Empty', '8202', ?, NULL, ?)",
+ ownedServer, owner, now, emptyOwnedServer, owner, now,
+ )
+ run(
+ "INSERT INTO community_server_member (id, server_id, user_id, role, joined_at) VALUES ('server_member', ?, ?, 'member', ?)",
+ ownedServer, reader, now,
+ )
+ run("INSERT INTO community_channel (id, server_id, name, type, message_count, created_at) VALUES (?, ?, 'owned', 'text', 0, ?)", serverChannel, ownedServer, now)
+ run("INSERT INTO community_channel (id, type, message_count, last_message_at, created_at) VALUES (?, 'dm', 3, ?, ?)", dm, now, now)
+ run(
+ "INSERT INTO community_message (id, author_id, content, created_at, channel_id, seq) VALUES (?, ?, 'prior', ?, ?, 1), (?, ?, 'authored', ?, ?, 2), (?, ?, 'bot authored', ?, ?, 3)",
+ priorMessage, reader, now, dm,
+ authoredMessage, owner, now, dm,
+ botMessage, bot, now, dm,
+ )
+ run(
+ "INSERT INTO community_read_state (id, user_id, channel_id, last_read_at, last_read_message_id, last_read_seq) VALUES ('reader_state', ?, ?, ?, ?, 3), ('early_state', ?, ?, ?, ?, 1)",
+ reader, dm, now, botMessage, earlyReader, dm, now, priorMessage,
+ )
+ run(
+ "INSERT INTO community_mention (id, message_id, user_id, kind, read) VALUES ('reader_mention', ?, ?, 'mention', 0)",
+ authoredMessage, reader,
+ )
+ run("INSERT INTO community_channel (id, name, type, message_count, last_message_at, created_at) VALUES (?, 'forum', 'forum', 1, ?, ?)", forum, now, now)
+ run("INSERT INTO community_message (id, author_id, content, created_at, channel_id, seq) VALUES (?, ?, 'opener', ?, ?, 1)", opener, owner, now, forum)
+ run(
+ "INSERT INTO community_channel (id, name, type, parent_channel_id, parent_message_id, message_count, last_message_at, created_at) VALUES (?, 'thread', 'thread', ?, ?, 1, ?, ?)",
+ thread, forum, opener, now, now,
+ )
+ run("INSERT INTO community_message (id, author_id, content, created_at, channel_id, seq) VALUES (?, ?, 'reply', ?, ?, 1)", reply, reader, now, thread)
+ run(
+ "INSERT INTO community_attachment (id, message_id, uploader_id, target_id, r2_key, thumbnail_r2_key, filename, position, created_at) VALUES ('thread_attachment', ?, ?, ?, 'community/thread/raw', 'community/thread/thumb', 'reply.txt', 0, ?), ('owner_attachment', ?, ?, ?, 'community/owner/raw', NULL, 'owner.txt', 0, ?), ('pending_server_attachment', NULL, ?, ?, 'community/pending-server/raw', NULL, 'pending-server.txt', 0, ?), ('pending_thread_attachment', NULL, ?, ?, 'community/pending-thread/raw', 'community/pending-thread/thumb', 'pending-thread.txt', 0, ?)",
+ reply, reader, thread, now,
+ authoredMessage, owner, dm, now,
+ reader, serverChannel, now,
+ reader, thread, now,
+ )
+ const createdAtMs = Date.parse(now)
+ run(
+ "INSERT INTO community_diagnostic_report (id, owner_user_id, agent_id, machine_id, client_nonce, rate_bucket, status, from_ms, created_at, deadline_at) VALUES ('dbr_owned', ?, ?, 'community_machine_1', 'nonce_123456789012', ?, 'pending', ?, ?, ?)",
+ owner, bot, Math.trunc(createdAtMs / 60_000), createdAtMs - 86_400_000, createdAtMs, createdAtMs + 600_000,
+ )
+
+ expect(await getAccountDeletionSnapshot(db, bot)).toBeNull()
+ expect(await getAccountDeletionSnapshot(db, "missing_user")).toBeNull()
+ const snapshot = await getAccountDeletionSnapshot(db, owner)
+
+ expect(snapshot).not.toBeNull()
+ expect(snapshot!.identities.map((row) => row.id).sort()).toEqual([bot, owner])
+ expect(snapshot!.providers).toHaveLength(1)
+ expect(snapshot!.ownedWorkspaceIds).toEqual([ownedWorkspace])
+ expect(snapshot!.ownedAgentIds.sort()).toEqual([ownedAgent, sharedOwnedAgent].sort())
+ expect(snapshot!.legacyDaemons).toEqual([{ workspaceId: sharedWorkspace, daemonId: daemon }])
+ expect(snapshot!.machineTokens.sort()).toEqual(["al_owner_token", "al_workspace_token"])
+ expect(snapshot!.machineDoNames).toEqual(["b".repeat(32)])
+ expect(snapshot!.botBindings).toEqual([{ botId: bot, machineId: "community_machine_1" }])
+ expect(snapshot!.ownedServers).toEqual(expect.arrayContaining([
+ expect.objectContaining({ id: ownedServer, memberIds: [reader] }),
+ expect.objectContaining({ id: emptyOwnedServer, memberIds: [] }),
+ ]))
+ expect(snapshot!.readStateUserIds.sort()).toEqual([earlyReader, reader].sort())
+ expect(snapshot!.media.communityExactKeys).toEqual(expect.arrayContaining([
+ `user-avatar/${owner}`,
+ `bot-avatar/${bot}`,
+ "community/thread/raw",
+ "community/thread/thumb",
+ "community/owner/raw",
+ "community/pending-server/raw",
+ "community/pending-thread/raw",
+ "community/pending-thread/thumb",
+ ]))
+ expect(snapshot!.media.emailExactKeys).toEqual(expect.arrayContaining([
+ "artifacts/raw",
+ "artifacts/thumb",
+ "emails/deleting/raw",
+ "meetings/transcript",
+ ]))
+ expect(snapshot!.media.survivingEmailAttachments).toEqual([
+ JSON.stringify([{ key: sharedAttachmentKey }]),
+ ])
+ expect(snapshot!.media.bugReportPrefixes).toEqual(expect.arrayContaining([
+ `bug-reports/${owner}/`,
+ `bug-reports/${bot}/`,
+ ]))
+
+ const result = await deleteAccountRows(db, snapshot!)
+ expect(result.deleted).toBe(true)
+ expect(result.readStateRevisions.sort((left, right) => left.userId.localeCompare(right.userId)))
+ .toEqual([
+ { userId: earlyReader, revision: 1 },
+ { userId: reader, revision: 1 },
+ ].sort((left, right) => left.userId.localeCompare(right.userId)))
+ expect(sqlite.prepare("SELECT id FROM user WHERE id IN (?, ?)").get(owner, bot)).toBeUndefined()
+ expect(sqlite.prepare("SELECT id FROM workspace WHERE id = ?").get(ownedWorkspace)).toBeUndefined()
+ expect(sqlite.prepare("SELECT id FROM workspace WHERE id = ?").get(sharedWorkspace)).toEqual({ id: sharedWorkspace })
+ expect(sqlite.prepare("SELECT runtime_id FROM agent WHERE id = ?").get(survivingAgent)).toEqual({ runtime_id: null })
+ expect(sqlite.prepare("SELECT id FROM community_attachment WHERE id IN (?, ?)").get(
+ "pending_server_attachment",
+ "pending_thread_attachment",
+ )).toBeUndefined()
+ expect(sqlite.prepare("SELECT id FROM user WHERE id = ?").get(reader)).toEqual({ id: reader })
+ expect(sqlite.prepare("SELECT message_count FROM community_channel WHERE id = ?").get(dm)).toEqual({ message_count: 1 })
+ expect(sqlite.prepare("PRAGMA foreign_key_check").all()).toEqual([])
+ })
+
+ it("returns an empty revision list when deleting a user with no affected readers", async () => {
+ run("INSERT INTO user (id, email, name, discriminator) VALUES ('lonely_user', '[email protected]', 'Lonely', '8301')")
+ const snapshot = await getAccountDeletionSnapshot(db, "lonely_user")
+
+ expect(snapshot).not.toBeNull()
+ await expect(deleteAccountRows(db, snapshot!)).resolves.toEqual({
+ deleted: true,
+ readStateRevisions: [],
+ })
+ })
+})
diff --git a/src/shared/src/db/queries/account-deletion.ts b/src/shared/src/db/queries/account-deletion.ts
new file mode 100644
index 000000000..c7d0ae1df
--- /dev/null
+++ b/src/shared/src/db/queries/account-deletion.ts
@@ -0,0 +1,586 @@
+import { and, eq, inArray, isNull, or, sql } from "drizzle-orm"
+import { sqliteTable, text } from "drizzle-orm/sqlite-core"
+import {
+ account,
+ agent,
+ agentRuntime,
+ artifact,
+ conversation,
+ emails,
+ issueComment,
+ machine,
+ machineToken,
+ meetingSession,
+ member,
+ session,
+ user,
+ verification,
+ workspace,
+} from "../schema"
+import {
+ communityAttachment,
+ communityChannel,
+ communityFriendship,
+ communityMention,
+ communityMessage,
+ communityReadState,
+ communityServer,
+ communityServerMember,
+} from "../community-schema"
+import {
+ communityBotBinding,
+ communityDiagnosticReport,
+ communityMachineCredential,
+} from "../community-machine-schema"
+import type { Database } from "../index"
+import { advanceReadStateRevisionsForUsersBuilder } from "./community/read-state"
+
+const deviceCode = sqliteTable("deviceCode", {
+ id: text("id").primaryKey(),
+ userId: text("userId"),
+})
+
+export type DeletionChallenge = typeof verification.$inferSelect
+
+export async function upsertDeletionChallenge(
+ db: Database,
+ input: DeletionChallenge,
+): Promise<DeletionChallenge> {
+ const rows = await db
+ .insert(verification)
+ .values(input)
+ .onConflictDoUpdate({
+ target: verification.id,
+ set: {
+ identifier: input.identifier,
+ value: input.value,
+ expiresAt: input.expiresAt,
+ createdAt: input.createdAt,
+ updatedAt: input.updatedAt,
+ },
+ })
+ .returning()
+ const row = rows[0]
+ if (!row) throw new Error("account deletion challenge was not persisted")
+ return row
+}
+
+export async function takeDeletionChallenge(
+ db: Database,
+ input: { id: string; identifier: string },
+): Promise<DeletionChallenge | null> {
+ const rows = await db
+ .delete(verification)
+ .where(and(
+ eq(verification.id, input.id),
+ eq(verification.identifier, input.identifier),
+ ))
+ .returning()
+ return rows[0] ?? null
+}
+
+export async function restoreDeletionChallenge(
+ db: Database,
+ challenge: DeletionChallenge,
+): Promise<boolean> {
+ const rows = await db
+ .insert(verification)
+ .values(challenge)
+ .onConflictDoNothing({ target: verification.id })
+ .returning({ id: verification.id })
+ return rows.length > 0
+}
+
+export async function deleteDeletionChallengeIfMatches(
+ db: Database,
+ challenge: DeletionChallenge,
+): Promise<boolean> {
+ const rows = await db
+ .delete(verification)
+ .where(and(
+ eq(verification.id, challenge.id),
+ eq(verification.identifier, challenge.identifier),
+ eq(verification.value, challenge.value),
+ eq(verification.expiresAt, challenge.expiresAt),
+ ))
+ .returning({ id: verification.id })
+ return rows.length > 0
+}
+
+export type AccountDeletionIdentity = {
+ id: string
+ email: string
+ isBot: boolean
+ avatarObjectKey: string | null
+}
+
+export type AccountDeletionSnapshot = {
+ identity: AccountDeletionIdentity
+ identities: AccountDeletionIdentity[]
+ providers: Array<{
+ accountId: string
+ providerId: string
+ accessToken: string | null
+ refreshToken: string | null
+ }>
+ ownedWorkspaceIds: string[]
+ ownedAgentIds: string[]
+ legacyDaemons: Array<{ workspaceId: string; daemonId: string }>
+ machineTokens: string[]
+ machineDoNames: string[]
+ botBindings: Array<{ botId: string; machineId: string }>
+ ownedServers: Array<{ id: string; icon: string | null; memberIds: string[] }>
+ readStateUserIds: string[]
+ media: {
+ communityExactKeys: string[]
+ communityPrefixes: string[]
+ emailExactKeys: string[]
+ emailPrefixes: string[]
+ deletingEmailAttachments: string[]
+ survivingEmailAttachments: string[]
+ bugReportExactKeys: string[]
+ bugReportPrefixes: string[]
+ }
+}
+
+function unique(values: Array<string | null | undefined>): string[] {
+ return [...new Set(values.filter((value): value is string => !!value))]
+}
+
+export async function getAccountDeletionSnapshot(
+ db: Database,
+ userId: string,
+): Promise<AccountDeletionSnapshot | null> {
+ const identitiesQuery = db
+ .select({ id: user.id })
+ .from(user)
+ .where(or(
+ eq(user.id, userId),
+ and(eq(user.ownerUserId, userId), eq(user.isBot, true)),
+ ))
+ const ownedWorkspaceIdsQuery = db
+ .select({ id: member.workspaceId })
+ .from(member)
+ .where(and(inArray(member.userId, identitiesQuery), eq(member.role, "owner")))
+ const ownedAgentRowsQuery = db
+ .select({ id: agent.id, workspaceId: agent.workspaceId })
+ .from(agent)
+ .where(or(
+ inArray(agent.workspaceId, ownedWorkspaceIdsQuery),
+ inArray(agent.ownerId, identitiesQuery),
+ ))
+ const ownedAgentIdsQuery = ownedAgentRowsQuery.as("owned_agent")
+ const ownedServerIdsQuery = db
+ .select({ id: communityServer.id })
+ .from(communityServer)
+ .where(inArray(communityServer.ownerId, identitiesQuery))
+ const authoredMessageIdsQuery = db
+ .select({ id: communityMessage.id })
+ .from(communityMessage)
+ .where(inArray(communityMessage.authorId, identitiesQuery))
+ const authoredChannelIdsQuery = db
+ .selectDistinct({ id: communityMessage.channelId })
+ .from(communityMessage)
+ .where(inArray(communityMessage.authorId, identitiesQuery))
+ const doomedChannelIdsQuery = db
+ .select({ id: communityChannel.id })
+ .from(communityChannel)
+ .where(or(
+ inArray(communityChannel.serverId, ownedServerIdsQuery),
+ inArray(communityChannel.parentMessageId, authoredMessageIdsQuery),
+ ))
+ const doomedMessageIdsQuery = db
+ .select({ id: communityMessage.id })
+ .from(communityMessage)
+ .where(or(
+ inArray(communityMessage.authorId, identitiesQuery),
+ inArray(communityMessage.channelId, doomedChannelIdsQuery),
+ ))
+ const ownedConversationIdsQuery = db
+ .select({ id: conversation.id })
+ .from(conversation)
+ .where(or(
+ inArray(conversation.userId, identitiesQuery),
+ inArray(conversation.workspaceId, ownedWorkspaceIdsQuery),
+ inArray(conversation.agentId, db.select({ id: ownedAgentIdsQuery.id }).from(ownedAgentIdsQuery)),
+ ))
+ const affectedArtifactCondition = or(
+ inArray(artifact.workspaceId, ownedWorkspaceIdsQuery),
+ inArray(artifact.agentId, db.select({ id: ownedAgentIdsQuery.id }).from(ownedAgentIdsQuery)),
+ inArray(artifact.conversationId, ownedConversationIdsQuery),
+ )!
+ const affectedEmailCondition = or(
+ inArray(emails.workspaceId, ownedWorkspaceIdsQuery),
+ inArray(emails.agentId, db.select({ id: ownedAgentIdsQuery.id }).from(ownedAgentIdsQuery)),
+ )!
+ const affectedMeetingCondition = or(
+ inArray(meetingSession.workspaceId, ownedWorkspaceIdsQuery),
+ inArray(meetingSession.agentId, db.select({ id: ownedAgentIdsQuery.id }).from(ownedAgentIdsQuery)),
+ )!
+
+ const [
+ identities,
+ providers,
+ ownedWorkspaceRows,
+ ownedAgentRows,
+ legacyDaemons,
+ machineTokens,
+ machineCredentials,
+ botBindings,
+ serverRows,
+ serverMemberRows,
+ channelRows,
+ impactedReadStateRows,
+ impactedMentionRows,
+ attachmentRows,
+ artifactRows,
+ deletingEmailRows,
+ meetingRows,
+ diagnosticRows,
+ ] = await Promise.all([
+ db.select({
+ id: user.id,
+ email: user.email,
+ isBot: user.isBot,
+ avatarObjectKey: user.avatarObjectKey,
+ }).from(user).where(or(
+ eq(user.id, userId),
+ and(eq(user.ownerUserId, userId), eq(user.isBot, true)),
+ )),
+ db.select({
+ accountId: account.accountId,
+ providerId: account.providerId,
+ accessToken: account.accessToken,
+ refreshToken: account.refreshToken,
+ }).from(account).where(inArray(account.userId, identitiesQuery)),
+ ownedWorkspaceIdsQuery,
+ ownedAgentRowsQuery,
+ db.select({ workspaceId: machine.workspaceId, daemonId: machine.daemonId })
+ .from(machine)
+ .where(or(
+ inArray(machine.workspaceId, ownedWorkspaceIdsQuery),
+ inArray(machine.ownerId, identitiesQuery),
+ )),
+ db.select({ token: machineToken.token })
+ .from(machineToken)
+ .where(or(
+ inArray(machineToken.userId, identitiesQuery),
+ inArray(machineToken.workspaceId, ownedWorkspaceIdsQuery),
+ )),
+ db.select({ doName: communityMachineCredential.doName })
+ .from(communityMachineCredential)
+ .where(inArray(communityMachineCredential.userId, identitiesQuery)),
+ db.select({ botId: communityBotBinding.userId, machineId: communityBotBinding.machineId })
+ .from(communityBotBinding)
+ .where(inArray(communityBotBinding.userId, identitiesQuery)),
+ db.select({ id: communityServer.id, icon: communityServer.icon })
+ .from(communityServer)
+ .where(inArray(communityServer.ownerId, identitiesQuery)),
+ db.select({ serverId: communityServerMember.serverId, userId: communityServerMember.userId })
+ .from(communityServerMember)
+ .where(inArray(communityServerMember.serverId, ownedServerIdsQuery)),
+ db.select({ id: communityChannel.id, type: communityChannel.type })
+ .from(communityChannel)
+ .where(inArray(communityChannel.id, doomedChannelIdsQuery)),
+ db.selectDistinct({ userId: communityReadState.userId })
+ .from(communityReadState)
+ .innerJoin(user, eq(user.id, communityReadState.userId))
+ .where(and(
+ eq(user.isBot, false),
+ isNull(user.deletedAt),
+ or(
+ inArray(communityReadState.channelId, doomedChannelIdsQuery),
+ inArray(communityReadState.channelId, authoredChannelIdsQuery),
+ inArray(communityReadState.lastReadMessageId, doomedMessageIdsQuery),
+ ),
+ )),
+ db.selectDistinct({ userId: communityMention.userId })
+ .from(communityMention)
+ .innerJoin(user, eq(user.id, communityMention.userId))
+ .where(and(
+ eq(user.isBot, false),
+ isNull(user.deletedAt),
+ inArray(communityMention.messageId, doomedMessageIdsQuery),
+ )),
+ db.select({
+ r2Key: communityAttachment.r2Key,
+ thumbnailR2Key: communityAttachment.thumbnailR2Key,
+ }).from(communityAttachment).where(or(
+ inArray(communityAttachment.uploaderId, identitiesQuery),
+ inArray(communityAttachment.targetId, doomedChannelIdsQuery),
+ inArray(communityAttachment.messageId, doomedMessageIdsQuery),
+ )),
+ db.select({ r2Key: artifact.r2Key, thumbnailR2Key: artifact.thumbnailR2Key })
+ .from(artifact)
+ .where(affectedArtifactCondition),
+ db.select({ r2Key: emails.r2Key, attachments: emails.attachments })
+ .from(emails)
+ .where(affectedEmailCondition),
+ db.select({ transcriptR2Key: meetingSession.transcriptR2Key })
+ .from(meetingSession)
+ .where(affectedMeetingCondition),
+ db.select({ r2Key: communityDiagnosticReport.r2Key })
+ .from(communityDiagnosticReport)
+ .where(inArray(communityDiagnosticReport.ownerUserId, identitiesQuery)),
+ ])
+
+ const candidateAttachmentKeys = unique(deletingEmailRows.flatMap((row) => {
+ try {
+ const parsed: unknown = JSON.parse(row.attachments)
+ return Array.isArray(parsed)
+ ? parsed.map((value) => value && typeof value === "object" && "key" in value
+ ? (value as { key?: unknown }).key
+ : null).filter((value): value is string => typeof value === "string")
+ : []
+ } catch {
+ return []
+ }
+ }))
+ const survivingEmailRows = candidateAttachmentKeys.length > 0
+ ? await db.select({ attachments: emails.attachments })
+ .from(emails)
+ .where(and(
+ sql<boolean>`NOT (${affectedEmailCondition})`,
+ sql<boolean>`EXISTS (
+ SELECT 1 FROM json_each(${emails.attachments}) AS attachment
+ WHERE json_extract(attachment.value, '$.key') IN (
+ SELECT CAST(value AS TEXT) FROM json_each(${JSON.stringify(candidateAttachmentKeys)})
+ )
+ )`,
+ ))
+ : []
+
+ const identity = identities.find((row) => row.id === userId)
+ if (!identity || identity.isBot) return null
+ const membersByServer = new Map<string, string[]>()
+ for (const row of serverMemberRows) {
+ const members = membersByServer.get(row.serverId) ?? []
+ members.push(row.userId)
+ membersByServer.set(row.serverId, members)
+ }
+
+ return {
+ identity,
+ identities,
+ providers,
+ ownedWorkspaceIds: ownedWorkspaceRows.map((row) => row.id),
+ ownedAgentIds: ownedAgentRows.map((row) => row.id),
+ legacyDaemons,
+ machineTokens: unique(machineTokens.map((row) => row.token)),
+ machineDoNames: unique(machineCredentials.map((row) => row.doName)),
+ botBindings,
+ ownedServers: serverRows.map((row) => ({
+ ...row,
+ memberIds: unique(membersByServer.get(row.id) ?? []),
+ })),
+ readStateUserIds: unique([
+ ...impactedReadStateRows.map((row) => row.userId),
+ ...impactedMentionRows.map((row) => row.userId),
+ ]).filter((id) => id !== userId),
+ media: {
+ communityExactKeys: unique([
+ ...identities.map((row) => `${row.isBot ? "bot" : "user"}-avatar/${row.id}`),
+ ...identities.map((row) => row.avatarObjectKey),
+ ...serverRows.map((row) => row.icon),
+ ...attachmentRows.flatMap((row) => [row.r2Key, row.thumbnailR2Key]),
+ ]),
+ communityPrefixes: unique([
+ ...identities.map((row) => `${row.isBot ? "bot" : "user"}-avatar/${row.id}/`),
+ ...serverRows.map((row) => `server-icon/${row.id}/`),
+ ...channelRows.map((row) => `${row.type === "dm" ? "dm" : row.type === "thread" ? "thread" : "channel"}/${row.id}/`),
+ ]),
+ emailExactKeys: unique([
+ ...artifactRows.flatMap((row) => [row.r2Key, row.thumbnailR2Key]),
+ ...deletingEmailRows.map((row) => row.r2Key),
+ ...meetingRows.map((row) => row.transcriptR2Key),
+ ]),
+ emailPrefixes: ownedWorkspaceRows.map((row) => `artifacts/${row.id}/`),
+ deletingEmailAttachments: deletingEmailRows.map((row) => row.attachments),
+ survivingEmailAttachments: survivingEmailRows.map((row) => row.attachments),
+ bugReportExactKeys: unique(diagnosticRows.map((row) => row.r2Key)),
+ bugReportPrefixes: identities.map((row) => `bug-reports/${row.id}/`),
+ },
+ }
+}
+
+export async function deleteAccountRows(
+ db: Database,
+ snapshot: AccountDeletionSnapshot,
+): Promise<{ deleted: boolean; readStateRevisions: Array<{ userId: string; revision: number }> }> {
+ const userId = snapshot.identity.id
+ const identitiesQuery = db
+ .select({ id: user.id })
+ .from(user)
+ .where(or(
+ eq(user.id, userId),
+ and(eq(user.ownerUserId, userId), eq(user.isBot, true)),
+ ))
+ const ownedWorkspaceIdsQuery = db
+ .select({ id: member.workspaceId })
+ .from(member)
+ .where(and(inArray(member.userId, identitiesQuery), eq(member.role, "owner")))
+ const ownedAgentIdsQuery = db
+ .select({ id: agent.id })
+ .from(agent)
+ .where(or(
+ inArray(agent.workspaceId, ownedWorkspaceIdsQuery),
+ inArray(agent.ownerId, identitiesQuery),
+ ))
+ const ownedServerIdsQuery = db
+ .select({ id: communityServer.id })
+ .from(communityServer)
+ .where(inArray(communityServer.ownerId, identitiesQuery))
+ const authoredMessagesQuery = db
+ .select({ id: communityMessage.id })
+ .from(communityMessage)
+ .where(inArray(communityMessage.authorId, identitiesQuery))
+ const doomedChannelIdsQuery = db
+ .select({ id: communityChannel.id })
+ .from(communityChannel)
+ .where(or(
+ inArray(communityChannel.serverId, ownedServerIdsQuery),
+ inArray(communityChannel.parentMessageId, authoredMessagesQuery),
+ ))
+ const affectedChannelIdsQuery = db
+ .select({ id: communityMessage.channelId })
+ .from(communityMessage)
+ .where(inArray(communityMessage.authorId, identitiesQuery))
+ const ownedRuntimeIdsQuery = db
+ .select({ id: agentRuntime.id })
+ .from(agentRuntime)
+ .innerJoin(machine, and(
+ eq(machine.workspaceId, agentRuntime.workspaceId),
+ eq(machine.daemonId, agentRuntime.daemonId),
+ ))
+ .where(inArray(machine.ownerId, identitiesQuery))
+
+ const statements = [
+ db.update(communityChannel).set({
+ messageCount: sql<number>`(
+ SELECT COUNT(*) FROM ${communityMessage} AS remaining_message
+ WHERE remaining_message.channel_id = ${communityChannel.id}
+ AND remaining_message.author_id NOT IN (${identitiesQuery})
+ )`,
+ lastMessageAt: sql<string | null>`(
+ SELECT MAX(remaining_message.created_at) FROM ${communityMessage} AS remaining_message
+ WHERE remaining_message.channel_id = ${communityChannel.id}
+ AND remaining_message.author_id NOT IN (${identitiesQuery})
+ )`,
+ }).where(and(
+ inArray(communityChannel.id, affectedChannelIdsQuery),
+ or(isNull(communityChannel.serverId), sql`${communityChannel.serverId} NOT IN (${ownedServerIdsQuery})`),
+ )),
+ db.update(communityReadState).set({
+ lastReadMessageId: sql<string>`(
+ SELECT remaining_message.id FROM ${communityMessage} AS remaining_message
+ WHERE remaining_message.channel_id = ${communityReadState.channelId}
+ AND remaining_message.seq <= ${communityReadState.lastReadSeq}
+ AND remaining_message.author_id NOT IN (${identitiesQuery})
+ ORDER BY remaining_message.seq DESC LIMIT 1
+ )`,
+ lastReadSeq: sql<number>`(
+ SELECT remaining_message.seq FROM ${communityMessage} AS remaining_message
+ WHERE remaining_message.channel_id = ${communityReadState.channelId}
+ AND remaining_message.seq <= ${communityReadState.lastReadSeq}
+ AND remaining_message.author_id NOT IN (${identitiesQuery})
+ ORDER BY remaining_message.seq DESC LIMIT 1
+ )`,
+ lastReadAt: sql<string>`(
+ SELECT remaining_message.created_at FROM ${communityMessage} AS remaining_message
+ WHERE remaining_message.channel_id = ${communityReadState.channelId}
+ AND remaining_message.seq <= ${communityReadState.lastReadSeq}
+ AND remaining_message.author_id NOT IN (${identitiesQuery})
+ ORDER BY remaining_message.seq DESC LIMIT 1
+ )`,
+ }).where(and(
+ inArray(communityReadState.lastReadMessageId, authoredMessagesQuery),
+ sql<boolean>`EXISTS (
+ SELECT 1 FROM ${communityMessage} AS remaining_message
+ WHERE remaining_message.channel_id = ${communityReadState.channelId}
+ AND remaining_message.seq <= ${communityReadState.lastReadSeq}
+ AND remaining_message.author_id NOT IN (${identitiesQuery})
+ )`,
+ )),
+ db.delete(communityReadState).where(and(
+ inArray(communityReadState.lastReadMessageId, authoredMessagesQuery),
+ sql<boolean>`NOT EXISTS (
+ SELECT 1 FROM ${communityMessage} AS remaining_message
+ WHERE remaining_message.channel_id = ${communityReadState.channelId}
+ AND remaining_message.seq <= ${communityReadState.lastReadSeq}
+ AND remaining_message.author_id NOT IN (${identitiesQuery})
+ )`,
+ )),
+ ...(snapshot.readStateUserIds.length > 0
+ ? [advanceReadStateRevisionsForUsersBuilder(
+ db,
+ snapshot.readStateUserIds,
+ sql<boolean>`EXISTS (
+ SELECT 1 FROM ${user} AS revision_user
+ WHERE revision_user.id = CAST(value AS TEXT)
+ AND revision_user.isBot = 0
+ AND revision_user.deletedAt IS NULL
+ )`,
+ )]
+ : []),
+ db.delete(issueComment).where(or(
+ and(eq(issueComment.authorType, "user"), inArray(issueComment.authorId, identitiesQuery)),
+ and(eq(issueComment.authorType, "agent"), inArray(issueComment.authorId, ownedAgentIdsQuery)),
+ )),
+ db.update(agent).set({ runtimeId: null }).where(inArray(agent.runtimeId, ownedRuntimeIdsQuery)),
+ db.delete(agentRuntime).where(inArray(agentRuntime.id, ownedRuntimeIdsQuery)),
+ db.delete(machine).where(inArray(machine.ownerId, identitiesQuery)),
+ db.delete(workspace).where(inArray(workspace.id, ownedWorkspaceIdsQuery)),
+ db.delete(agent).where(inArray(agent.ownerId, identitiesQuery)),
+ db.delete(communityAttachment).where(and(
+ isNull(communityAttachment.messageId),
+ inArray(communityAttachment.targetId, doomedChannelIdsQuery),
+ )),
+ db.delete(communityServer).where(inArray(communityServer.ownerId, identitiesQuery)),
+ db.delete(communityAttachment).where(inArray(communityAttachment.uploaderId, identitiesQuery)),
+ db.delete(communityDiagnosticReport).where(inArray(communityDiagnosticReport.ownerUserId, identitiesQuery)),
+ db.delete(communityFriendship).where(inArray(communityFriendship.needsOwnerApproval, identitiesQuery)),
+ db.delete(deviceCode).where(inArray(deviceCode.userId, identitiesQuery)),
+ db.delete(verification).where(or(
+ inArray(verification.identifier, db
+ .select({ identifier: sql<string>`'sign-in-otp-' || lower(${user.email})` })
+ .from(user)
+ .where(inArray(user.id, identitiesQuery))),
+ inArray(verification.identifier, db
+ .select({ identifier: sql<string>`'email-verification-otp-' || lower(${user.email})` })
+ .from(user)
+ .where(inArray(user.id, identitiesQuery))),
+ inArray(verification.identifier, db
+ .select({ identifier: sql<string>`'forget-password-otp-' || lower(${user.email})` })
+ .from(user)
+ .where(inArray(user.id, identitiesQuery))),
+ inArray(verification.identifier, db
+ .select({ identifier: sql<string>`'change-email-otp-' || lower(${user.email})` })
+ .from(user)
+ .where(inArray(user.id, identitiesQuery))),
+ inArray(verification.identifier, db
+ .select({ identifier: sql<string>`'account-deletion-otp:' || ${user.id} || ':' || lower(${user.email})` })
+ .from(user)
+ .where(inArray(user.id, identitiesQuery))),
+ and(
+ sql<boolean>`${verification.identifier} LIKE 'one-time-token:%'`,
+ inArray(verification.value, db
+ .select({ token: session.token })
+ .from(session)
+ .where(inArray(session.userId, identitiesQuery))),
+ ),
+ )),
+ db.delete(user).where(and(eq(user.ownerUserId, userId), eq(user.isBot, true))),
+ db.delete(user).where(and(eq(user.id, userId), eq(user.isBot, false))).returning({ id: user.id }),
+ ]
+
+ const results = await db.batch(statements as any) as unknown[]
+ const revisionIndex = 3
+ const deleteIndex = statements.length - 1
+ const deletedRows = results[deleteIndex] as Array<{ id: string }>
+ return {
+ deleted: deletedRows.length > 0,
+ readStateRevisions: snapshot.readStateUserIds.length > 0
+ ? results[revisionIndex] as Array<{ userId: string; revision: number }>
+ : [],
+ }
+}
diff --git a/src/web/src/app/(auth)/sign-in/sign-in-client.tsx b/src/web/src/app/(auth)/sign-in/sign-in-client.tsx
index 7a6403d87..7178d66ec 100644
--- a/src/web/src/app/(auth)/sign-in/sign-in-client.tsx
+++ b/src/web/src/app/(auth)/sign-in/sign-in-client.tsx
@@ -4,6 +4,7 @@ import { useEffect, useState } from "react"
import { useSearchParams } from "next/navigation"
import { signIn, signUp, authClient } from "@/lib/auth-client"
import { parseRetryAfterSeconds } from "@/lib/retry-after"
+import { tid } from "@/lib/community/testids"
import { Button } from "@/components/ui/button"
import { Card, CardContent } from "@/components/ui/card"
import {
@@ -22,6 +23,7 @@ import {
} from "@/components/home/landing-shell-motion-timeline"
import galleryStyles from "@/components/home/landing-shell-motion.module.css"
import { DEV_PASSWORD } from "@alook/shared"
+import { CircleCheck } from "lucide-react"
// Default post-login landing when no explicit `?redirect=` is present. Points
// at the community home (/c/me); the old `/workspaces` target was the legacy
@@ -35,7 +37,7 @@ function safeRedirectUrl(redirect: string | null): string {
return DEFAULT_POST_LOGIN
}
-function SignInForm({ postLoginUrl, isProd }: { postLoginUrl: string; isProd: boolean }) {
+function SignInForm({ postLoginUrl, isProd, accountDeleted }: { postLoginUrl: string; isProd: boolean; accountDeleted: boolean }) {
const [email, setEmail] = useState("")
const [emailError, setEmailError] = useState("")
const [otpError, setOtpError] = useState("")
@@ -154,6 +156,21 @@ function SignInForm({ postLoginUrl, isProd }: { postLoginUrl: string; isProd: bo
return (
<FieldGroup>
+ {accountDeleted ? (
+ <div
+ className="flex gap-3 rounded-xl bg-muted/70 p-4 text-left"
+ role="status"
+ data-testid={tid.accountDeletionComplete}
+ >
+ <CircleCheck className="mt-0.5 size-5 shrink-0 text-muted-foreground" aria-hidden />
+ <div>
+ <div className="text-sm font-medium">Account deleted</div>
+ <p className="mt-0.5 text-sm text-muted-foreground">
+ Your account and its data were removed.
+ </p>
+ </div>
+ </div>
+ ) : null}
<div className="flex flex-col items-center gap-2 text-center">
<h1 className="text-2xl font-bold">Sign in</h1>
<p className="text-sm text-muted-foreground">or create an account to get started</p>
@@ -347,6 +364,7 @@ function ProductGallery() {
export default function SignInPageClient({ isProd }: { isProd: boolean }) {
const searchParams = useSearchParams()
const postLoginUrl = safeRedirectUrl(searchParams.get("redirect"))
+ const accountDeleted = searchParams.get("account_deleted") === "1"
return (
<div className="relative flex min-h-svh flex-col items-center justify-center p-6 sm:p-10">
@@ -359,7 +377,7 @@ export default function SignInPageClient({ isProd }: { isProd: boolean }) {
<Card className="overflow-hidden p-0">
<CardContent className="grid p-0 sm:grid-cols-[minmax(320px,0.82fr)_minmax(0,1.35fr)]">
<div className="flex flex-col justify-center p-6 sm:min-h-120 sm:p-8">
- <SignInForm postLoginUrl={postLoginUrl} isProd={isProd} />
+ <SignInForm postLoginUrl={postLoginUrl} isProd={isProd} accountDeleted={accountDeleted} />
</div>
<div className="relative hidden min-h-120 overflow-hidden bg-muted sm:block">
<ProductGallery />
diff --git a/src/web/src/app/api/community/users/me/account-deletion/code/route.test.ts b/src/web/src/app/api/community/users/me/account-deletion/code/route.test.ts
new file mode 100644
index 000000000..805669125
--- /dev/null
+++ b/src/web/src/app/api/community/users/me/account-deletion/code/route.test.ts
@@ -0,0 +1,57 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { NextRequest } from "next/server"
+
+const sendDeletionCode = vi.fn()
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withCookieHumanAuth: (handler: (...args: any[]) => Promise<Response>) =>
+ (request: NextRequest) => handler(request, {
+ env: { DB: {} },
+ userId: "user-1",
+ email: "[email protected]",
+ }),
+}))
+vi.mock("@/lib/db", () => ({ getPrimaryDb: () => ({}) }))
+vi.mock("@/lib/account-deletion/challenge", () => ({
+ sendDeletionCode: (...args: unknown[]) => sendDeletionCode(...args),
+}))
+
+import { POST } from "./route"
+
+function request() {
+ return new NextRequest("https://alook.ai/api/community/users/me/account-deletion/code", {
+ method: "POST",
+ })
+}
+
+describe("account deletion code route", () => {
+ beforeEach(() => vi.clearAllMocks())
+
+ it("uses only the authenticated identity and returns the locked success shape", async () => {
+ sendDeletionCode.mockResolvedValue({ kind: "sent", expiresIn: 300, resendAfter: 60 })
+ const response = await POST(request(), {} as never)
+
+ expect(response.status).toBe(200)
+ expect(await response.json()).toEqual({ ok: true, expires_in: 300, resend_after: 60 })
+ expect(sendDeletionCode).toHaveBeenCalledWith(expect.anything(), expect.anything(), {
+ userId: "user-1",
+ email: "[email protected]",
+ })
+ })
+
+ it("returns Retry-After for the reused limiter", async () => {
+ sendDeletionCode.mockResolvedValue({ kind: "rate_limited", retryAfter: 47 })
+ const response = await POST(request(), {} as never)
+
+ expect(response.status).toBe(429)
+ expect(response.headers.get("Retry-After")).toBe("47")
+ expect(await response.json()).toEqual({ error: "RATE_LIMITED" })
+ })
+
+ it("returns a retryable send failure", async () => {
+ sendDeletionCode.mockResolvedValue({ kind: "send_failed" })
+ const response = await POST(request(), {} as never)
+ expect(response.status).toBe(503)
+ expect(await response.json()).toEqual({ error: "CODE_SEND_FAILED" })
+ })
+})
diff --git a/src/web/src/app/api/community/users/me/account-deletion/code/route.ts b/src/web/src/app/api/community/users/me/account-deletion/code/route.ts
new file mode 100644
index 000000000..a39dbe2b6
--- /dev/null
+++ b/src/web/src/app/api/community/users/me/account-deletion/code/route.ts
@@ -0,0 +1,37 @@
+import { withCookieHumanAuth } from "@/lib/middleware/auth"
+import { getPrimaryDb } from "@/lib/db"
+import { sendDeletionCode } from "@/lib/account-deletion/challenge"
+
+export const POST = withCookieHumanAuth(async (_request, context) => {
+ const result = await sendDeletionCode(getPrimaryDb(context.env.DB), context.env, {
+ userId: context.userId,
+ email: context.email,
+ })
+
+ if (result.kind === "rate_limited") {
+ return Response.json(
+ { error: "RATE_LIMITED" },
+ {
+ status: 429,
+ headers: {
+ "Cache-Control": "no-store, max-age=0",
+ "Retry-After": String(result.retryAfter),
+ },
+ },
+ )
+ }
+ if (result.kind === "send_failed") {
+ return Response.json(
+ { error: "CODE_SEND_FAILED" },
+ { status: 503, headers: { "Cache-Control": "no-store, max-age=0" } },
+ )
+ }
+ return Response.json(
+ {
+ ok: true,
+ expires_in: result.expiresIn,
+ resend_after: result.resendAfter,
+ },
+ { headers: { "Cache-Control": "no-store, max-age=0" } },
+ )
+})
diff --git a/src/web/src/app/api/community/users/me/account-deletion/route.test.ts b/src/web/src/app/api/community/users/me/account-deletion/route.test.ts
new file mode 100644
index 000000000..988ffc6dd
--- /dev/null
+++ b/src/web/src/app/api/community/users/me/account-deletion/route.test.ts
@@ -0,0 +1,134 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { NextRequest } from "next/server"
+
+const verifyDeletionCode = vi.fn()
+const executeAccountDeletion = vi.fn()
+const restoreVerifiedDeletionCode = vi.fn()
+const getPrimaryDb = vi.fn()
+const signOut = vi.fn()
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withCookieHumanAuth: (handler: (...args: any[]) => Promise<Response>) =>
+ (request: NextRequest) => handler(request, {
+ env: { DB: {} },
+ executionContext: { waitUntil: vi.fn() },
+ userId: "user-1",
+ email: "[email protected]",
+ }),
+}))
+vi.mock("@/lib/db", () => ({ getPrimaryDb: (...args: unknown[]) => getPrimaryDb(...args) }))
+vi.mock("@/lib/auth", () => ({ createAuth: () => ({ api: { signOut } }) }))
+vi.mock("@/lib/account-deletion/challenge", () => ({
+ verifyDeletionCode: (...args: unknown[]) => verifyDeletionCode(...args),
+ restoreVerifiedDeletionCode: (...args: unknown[]) => restoreVerifiedDeletionCode(...args),
+}))
+vi.mock("@/lib/account-deletion/execution", () => ({
+ executeAccountDeletion: (...args: unknown[]) => executeAccountDeletion(...args),
+}))
+
+import { POST } from "./route"
+
+const challenge = { id: "challenge", identifier: "identifier", value: "123456:0" }
+
+function request(body: unknown) {
+ return new NextRequest("https://alook.ai/api/community/users/me/account-deletion", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body),
+ })
+}
+
+describe("account deletion submit route", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ getPrimaryDb.mockReturnValue({
+ query: {
+ user: {
+ findFirst: vi.fn().mockImplementation(async ({ where }) => {
+ where({ id: "user-1" }, { eq: (left: unknown, right: unknown) => left === right })
+ return { id: "user-1" }
+ }),
+ },
+ },
+ })
+ verifyDeletionCode.mockResolvedValue({ kind: "verified", challenge })
+ executeAccountDeletion.mockResolvedValue({ kind: "deleted" })
+ restoreVerifiedDeletionCode.mockResolvedValue(undefined)
+ const headers = new Headers()
+ headers.append("Set-Cookie", "better-auth.session_token=; Max-Age=0; Path=/")
+ signOut.mockResolvedValue({ headers })
+ })
+
+ it("rejects everything except strict six-digit JSON without consuming a challenge", async () => {
+ for (const body of [{ otp: "12345" }, { otp: "123456", extra: true }, { otp: 123456 }]) {
+ const response = await POST(request(body), {} as never)
+ expect(response.status).toBe(400)
+ expect(await response.json()).toEqual({ error: "INVALID_OTP" })
+ }
+ expect(verifyDeletionCode).not.toHaveBeenCalled()
+ })
+
+ it.each([
+ ["invalid", 400, "INVALID_OTP"],
+ ["expired", 400, "OTP_EXPIRED"],
+ ["too_many_attempts", 403, "TOO_MANY_ATTEMPTS"],
+ ])("maps %s without running deletion", async (kind, status, error) => {
+ verifyDeletionCode.mockResolvedValue({ kind })
+ const response = await POST(request({ otp: "123456" }), {} as never)
+ expect(response.status).toBe(status)
+ expect(await response.json()).toEqual({ error })
+ expect(executeAccountDeletion).not.toHaveBeenCalled()
+ })
+
+ it("deletes explicitly and clears Better Auth cookies", async () => {
+ const response = await POST(request({ otp: "123456" }), {} as never)
+
+ expect(response.status).toBe(200)
+ expect(await response.json()).toEqual({ ok: true })
+ expect(executeAccountDeletion).toHaveBeenCalled()
+ expect(response.headers.getSetCookie().join("\n")).toContain("better-auth.session_token=")
+ })
+
+ it("restores the consumed code when cleanup fails while the user remains", async () => {
+ executeAccountDeletion.mockResolvedValue({ kind: "failed" })
+ const response = await POST(request({ otp: "123456" }), {} as never)
+
+ expect(response.status).toBe(503)
+ expect(await response.json()).toEqual({ error: "ACCOUNT_DELETION_FAILED" })
+ expect(restoreVerifiedDeletionCode).toHaveBeenCalledWith(expect.anything(), challenge)
+ })
+
+ it("keeps the retryable response when restoring the consumed code fails", async () => {
+ executeAccountDeletion.mockResolvedValue({ kind: "failed" })
+ restoreVerifiedDeletionCode.mockRejectedValue(new Error("primary down"))
+
+ const response = await POST(request({ otp: "123456" }), {} as never)
+
+ expect(response.status).toBe(503)
+ expect(await response.json()).toEqual({ error: "ACCOUNT_DELETION_FAILED" })
+ })
+
+ it("does not restore a consumed code when the failed cleanup already removed the user", async () => {
+ executeAccountDeletion.mockResolvedValue({ kind: "failed" })
+ getPrimaryDb.mockReturnValue({
+ query: { user: { findFirst: vi.fn().mockResolvedValue(null) } },
+ })
+
+ const response = await POST(request({ otp: "123456" }), {} as never)
+
+ expect(response.status).toBe(503)
+ expect(restoreVerifiedDeletionCode).not.toHaveBeenCalled()
+ })
+
+ it("does not restore a consumed code when the live-user retry check fails", async () => {
+ executeAccountDeletion.mockResolvedValue({ kind: "failed" })
+ getPrimaryDb.mockReturnValue({
+ query: { user: { findFirst: vi.fn().mockRejectedValue(new Error("primary down")) } },
+ })
+
+ const response = await POST(request({ otp: "123456" }), {} as never)
+
+ expect(response.status).toBe(503)
+ expect(restoreVerifiedDeletionCode).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/app/api/community/users/me/account-deletion/route.ts b/src/web/src/app/api/community/users/me/account-deletion/route.ts
new file mode 100644
index 000000000..4caa43a4a
--- /dev/null
+++ b/src/web/src/app/api/community/users/me/account-deletion/route.ts
@@ -0,0 +1,84 @@
+import { NextResponse } from "next/server"
+import { z } from "zod"
+import { withCookieHumanAuth } from "@/lib/middleware/auth"
+import { getPrimaryDb } from "@/lib/db"
+import { createAuth } from "@/lib/auth"
+import {
+ restoreVerifiedDeletionCode,
+ verifyDeletionCode,
+} from "@/lib/account-deletion/challenge"
+import { executeAccountDeletion } from "@/lib/account-deletion/execution"
+
+const bodySchema = z.object({
+ otp: z.string().regex(/^\d{6}$/u),
+}).strict()
+
+function errorResponse(error: string, status: number): NextResponse {
+ return NextResponse.json(
+ { error },
+ { status, headers: { "Cache-Control": "no-store, max-age=0" } },
+ )
+}
+
+function clearAuthCookies(response: NextResponse): void {
+ for (const name of ["better-auth.session_token", "better-auth.session_data"]) {
+ response.cookies.set(name, "", { maxAge: 0, path: "/" })
+ response.cookies.set(`__Secure-${name}`, "", { maxAge: 0, path: "/", secure: true })
+ }
+}
+
+export const POST = withCookieHumanAuth(async (request, context) => {
+ let input: z.infer<typeof bodySchema>
+ try {
+ input = bodySchema.parse(await request.json())
+ } catch {
+ return errorResponse("INVALID_OTP", 400)
+ }
+
+ const db = getPrimaryDb(context.env.DB)
+ const verification = await verifyDeletionCode(db, {
+ userId: context.userId,
+ email: context.email,
+ otp: input.otp,
+ })
+ if (verification.kind === "invalid") return errorResponse("INVALID_OTP", 400)
+ if (verification.kind === "expired") return errorResponse("OTP_EXPIRED", 400)
+ if (verification.kind === "too_many_attempts") {
+ return errorResponse("TOO_MANY_ATTEMPTS", 403)
+ }
+
+ const deletion = await executeAccountDeletion(
+ db,
+ context.env,
+ context.executionContext,
+ context.userId,
+ )
+ if (deletion.kind === "failed") {
+ const liveUser = await getPrimaryDb(context.env.DB)
+ .query.user.findFirst({ where: (row, { eq }) => eq(row.id, context.userId) })
+ .catch(() => null)
+ if (liveUser) {
+ await restoreVerifiedDeletionCode(
+ getPrimaryDb(context.env.DB),
+ verification.challenge,
+ ).catch(() => {})
+ }
+ return errorResponse("ACCOUNT_DELETION_FAILED", 503)
+ }
+
+ const response = NextResponse.json(
+ { ok: true },
+ { headers: { "Cache-Control": "no-store, max-age=0" } },
+ )
+ clearAuthCookies(response)
+ try {
+ const signOut = await createAuth(context.env).api.signOut({
+ headers: request.headers,
+ returnHeaders: true,
+ }) as { headers: Headers }
+ for (const cookie of signOut.headers.getSetCookie()) {
+ response.headers.append("Set-Cookie", cookie)
+ }
+ } catch {}
+ return response
+})
diff --git a/src/web/src/components/community/settings/account-deletion-flow.dom.test.tsx b/src/web/src/components/community/settings/account-deletion-flow.dom.test.tsx
new file mode 100644
index 000000000..08d300c1e
--- /dev/null
+++ b/src/web/src/components/community/settings/account-deletion-flow.dom.test.tsx
@@ -0,0 +1,130 @@
+import { act, fireEvent, render, screen, setupUser, waitFor } from "@/test/react-dom-harness"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { tid } from "@/lib/community/testids"
+import { AccountDeletionFlow } from "./account-deletion-flow"
+
+const authTransition = vi.hoisted(() => ({
+ begin: vi.fn(),
+ cancel: vi.fn(),
+}))
+
+vi.mock("@/lib/api/client", () => ({
+ ACCOUNT_DELETED_SIGN_IN_PATH: "/sign-in?account_deleted=1",
+ beginAccountDeletionAuthTransition: authTransition.begin,
+ cancelAccountDeletionAuthTransition: authTransition.cancel,
+}))
+
+describe("AccountDeletionFlow", () => {
+ beforeEach(() => {
+ authTransition.begin.mockReset()
+ authTransition.cancel.mockReset()
+ vi.useFakeTimers({ shouldAdvanceTime: true })
+ vi.stubGlobal("ResizeObserver", class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ })
+ document.elementFromPoint = vi.fn(() => null)
+ })
+
+ afterEach(async () => {
+ await act(() => vi.runOnlyPendingTimersAsync())
+ vi.clearAllTimers()
+ vi.useRealTimers()
+ vi.unstubAllGlobals()
+ })
+
+ it("does not send on open and never deletes when digit six is entered", async () => {
+ const user = setupUser({ advanceTimers: (delay) => vi.advanceTimersByTime(delay) })
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(Response.json({ ok: true, expires_in: 300, resend_after: 60 }))
+ .mockResolvedValueOnce(Response.json({ ok: true }))
+ vi.stubGlobal("fetch", fetchMock)
+ const onDeleted = vi.fn().mockResolvedValue(undefined)
+ render(<AccountDeletionFlow email="[email protected]" onCancel={vi.fn()} onDeleted={onDeleted} />)
+
+ expect(fetchMock).not.toHaveBeenCalled()
+ await user.click(screen.getByTestId(tid.accountDeletionSendCode))
+ const input = await screen.findByTestId(tid.accountDeletionOtp)
+ expect(input).toHaveFocus()
+ fireEvent.change(input, { target: { value: "123456" } })
+
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ expect(onDeleted).not.toHaveBeenCalled()
+ await user.click(screen.getByTestId(tid.accountDeletionSubmit))
+ await waitFor(() => expect(onDeleted).toHaveBeenCalledTimes(1))
+ expect(authTransition.begin).toHaveBeenCalledTimes(1)
+ expect(authTransition.begin.mock.invocationCallOrder[0]).toBeLessThan(fetchMock.mock.invocationCallOrder[1]!)
+ expect(authTransition.cancel).not.toHaveBeenCalled()
+ expect(fetchMock).toHaveBeenLastCalledWith(
+ "/api/community/users/me/account-deletion",
+ expect.objectContaining({ body: JSON.stringify({ otp: "123456" }) }),
+ )
+ })
+
+ it("clears an invalid code, returns focus to the OTP, and preserves the resend cooldown after Back", async () => {
+ const user = setupUser({ advanceTimers: (delay) => vi.advanceTimersByTime(delay) })
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(Response.json({ ok: true, expires_in: 300, resend_after: 60 }))
+ .mockResolvedValueOnce(Response.json({ error: "INVALID_OTP" }, { status: 400 }))
+ vi.stubGlobal("fetch", fetchMock)
+ render(<AccountDeletionFlow email="[email protected]" onCancel={vi.fn()} onDeleted={vi.fn()} />)
+
+ await user.click(screen.getByTestId(tid.accountDeletionSendCode))
+ const input = await screen.findByTestId(tid.accountDeletionOtp)
+ fireEvent.change(input, { target: { value: "000000" } })
+ await user.click(screen.getByTestId(tid.accountDeletionSubmit))
+
+ await waitFor(() => {
+ expect(input).toHaveValue("")
+ expect(input).toHaveFocus()
+ })
+ expect(screen.getByRole("alert")).toHaveTextContent("That code is incorrect")
+
+ await user.click(screen.getByRole("button", { name: "Back" }))
+ expect(screen.getByRole("button", { name: "Send deletion code in 60s" })).toBeDisabled()
+ expect(authTransition.begin).toHaveBeenCalledTimes(1)
+ expect(authTransition.cancel).toHaveBeenCalledTimes(1)
+ })
+
+ it("restores normal auth navigation when the deletion request cannot complete", async () => {
+ const user = setupUser({ advanceTimers: (delay) => vi.advanceTimersByTime(delay) })
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(Response.json({ ok: true, expires_in: 300, resend_after: 60 }))
+ .mockRejectedValueOnce(new TypeError("offline"))
+ vi.stubGlobal("fetch", fetchMock)
+ render(<AccountDeletionFlow email="[email protected]" onCancel={vi.fn()} onDeleted={vi.fn()} />)
+
+ await user.click(screen.getByTestId(tid.accountDeletionSendCode))
+ const input = await screen.findByTestId(tid.accountDeletionOtp)
+ fireEvent.change(input, { target: { value: "123456" } })
+ await user.click(screen.getByTestId(tid.accountDeletionSubmit))
+
+ await waitFor(() => expect(screen.getByRole("alert")).toHaveTextContent("Check your connection"))
+ expect(authTransition.begin).toHaveBeenCalledTimes(1)
+ expect(authTransition.cancel).toHaveBeenCalledTimes(1)
+ })
+
+ it("falls back to the persistent completion URL when local cleanup rejects", async () => {
+ const user = setupUser({ advanceTimers: (delay) => vi.advanceTimersByTime(delay) })
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(Response.json({ ok: true, expires_in: 300, resend_after: 60 }))
+ .mockResolvedValueOnce(Response.json({ ok: true }))
+ vi.stubGlobal("fetch", fetchMock)
+ const replace = vi.fn()
+ vi.stubGlobal("location", { replace })
+ render(<AccountDeletionFlow
+ onCancel={vi.fn()}
+ onDeleted={vi.fn().mockRejectedValue(new Error("cleanup"))}
+ />)
+
+ await user.click(screen.getByTestId(tid.accountDeletionSendCode))
+ const input = await screen.findByTestId(tid.accountDeletionOtp)
+ fireEvent.change(input, { target: { value: "123456" } })
+ await user.click(screen.getByTestId(tid.accountDeletionSubmit))
+
+ await waitFor(() => expect(replace).toHaveBeenCalledWith("/sign-in?account_deleted=1"))
+ expect(authTransition.cancel).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/components/community/settings/account-deletion-flow.tsx b/src/web/src/components/community/settings/account-deletion-flow.tsx
new file mode 100644
index 000000000..3e315e800
--- /dev/null
+++ b/src/web/src/components/community/settings/account-deletion-flow.tsx
@@ -0,0 +1,250 @@
+"use client"
+
+import { useEffect, useRef, useState } from "react"
+import { MailWarning, Trash2 } from "lucide-react"
+import { Button } from "@/components/ui/button"
+import { InputOTP, InputOTPGroup, InputOTPSlot } from "@/components/ui/input-otp"
+import {
+ ACCOUNT_DELETED_SIGN_IN_PATH,
+ beginAccountDeletionAuthTransition,
+ cancelAccountDeletionAuthTransition,
+} from "@/lib/api/client"
+import { parseRetryAfterSeconds } from "@/lib/retry-after"
+import { tid } from "@/lib/community/testids"
+
+type Step = "notice" | "code"
+
+type Props = {
+ email: string
+ onCancel: () => void
+ onDeleted: () => Promise<void>
+}
+
+async function responseError(response: Response): Promise<string> {
+ try {
+ const body = await response.json() as { error?: string }
+ switch (body.error) {
+ case "INVALID_OTP": return "That code is incorrect. Try again."
+ case "OTP_EXPIRED": return "That code expired. Send a new code."
+ case "TOO_MANY_ATTEMPTS": return "Too many incorrect attempts. Send a new code."
+ case "RATE_LIMITED": return "Too many requests. Try again when the timer ends."
+ case "CODE_SEND_FAILED": return "We couldn’t send the code. Try again."
+ case "ACCOUNT_DELETION_FAILED": return "Your account wasn’t deleted. Try again."
+ }
+ } catch {}
+ return "Something went wrong. Try again."
+}
+
+export function AccountDeletionFlow({ email, onCancel, onDeleted }: Props) {
+ const [step, setStep] = useState<Step>("notice")
+ const [otp, setOtp] = useState("")
+ const [sending, setSending] = useState(false)
+ const [deleting, setDeleting] = useState(false)
+ const [resendAfter, setResendAfter] = useState(0)
+ const [error, setError] = useState("")
+ const titleRef = useRef<HTMLHeadingElement>(null)
+ const otpRef = useRef<HTMLInputElement>(null)
+ const errorRef = useRef<HTMLParagraphElement>(null)
+
+ useEffect(() => {
+ if (step === "code") otpRef.current?.focus()
+ else titleRef.current?.focus()
+ }, [step])
+
+ useEffect(() => {
+ if (!error) return
+ if (step === "code") otpRef.current?.focus()
+ else errorRef.current?.focus()
+ }, [error, step])
+
+ useEffect(() => {
+ if (resendAfter <= 0) return
+ const timer = window.setTimeout(() => {
+ setResendAfter((seconds) => Math.max(0, seconds - 1))
+ }, 1000)
+ return () => window.clearTimeout(timer)
+ }, [resendAfter])
+
+ const sendCode = async () => {
+ setSending(true)
+ setError("")
+ try {
+ const response = await fetch("/api/community/users/me/account-deletion/code", {
+ method: "POST",
+ credentials: "include",
+ headers: { "Content-Type": "application/json" },
+ body: "{}",
+ })
+ if (!response.ok) {
+ const retryAfter = response.status === 429
+ ? parseRetryAfterSeconds(response.headers)
+ : null
+ if (retryAfter) setResendAfter(retryAfter)
+ setError(await responseError(response))
+ return
+ }
+ const body = await response.json() as { resend_after: number }
+ setOtp("")
+ setResendAfter(body.resend_after)
+ setStep("code")
+ } catch {
+ setError("We couldn’t send the code. Check your connection and try again.")
+ } finally {
+ setSending(false)
+ }
+ }
+
+ const deleteAccount = async () => {
+ if (!/^\d{6}$/u.test(otp)) return
+ setDeleting(true)
+ setError("")
+ beginAccountDeletionAuthTransition()
+ let response: Response
+ try {
+ response = await fetch("/api/community/users/me/account-deletion", {
+ method: "POST",
+ credentials: "include",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ otp }),
+ })
+ } catch {
+ cancelAccountDeletionAuthTransition()
+ setOtp("")
+ setError("Your account wasn’t deleted. Check your connection and try again.")
+ setDeleting(false)
+ return
+ }
+ if (!response.ok) {
+ cancelAccountDeletionAuthTransition()
+ setOtp("")
+ setError(await responseError(response))
+ setDeleting(false)
+ return
+ }
+ try {
+ await onDeleted()
+ } catch {
+ globalThis.location.replace(ACCOUNT_DELETED_SIGN_IN_PATH)
+ }
+ }
+
+ return (
+ <div
+ className="mx-auto w-full max-w-md animate-in fade-in duration-150 motion-reduce:animate-none"
+ data-testid={tid.accountDeletionFlow}
+ >
+ {step === "notice" ? (
+ <section className="space-y-8">
+ <div className="space-y-3">
+ <span className="flex size-10 items-center justify-center rounded-full bg-destructive/10 text-destructive">
+ <Trash2 className="size-5" />
+ </span>
+ <h2 ref={titleRef} tabIndex={-1} className="text-xl font-medium tracking-tight outline-none">
+ Delete your account?
+ </h2>
+ <p className="text-sm leading-6 text-muted-foreground">
+ Your profile, messages, agents, and account data will be permanently removed.
+ </p>
+ <p className="text-sm font-medium">This can’t be undone.</p>
+ </div>
+ <div className="rounded-xl bg-muted/60 p-4">
+ <div className="text-xs text-muted-foreground">Deletion code will be sent to</div>
+ <div className="mt-1 break-all text-sm font-medium">{email}</div>
+ </div>
+ {error ? (
+ <p ref={errorRef} tabIndex={-1} role="alert" className="text-sm text-destructive outline-none">
+ {error}
+ </p>
+ ) : null}
+ <div className="flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">
+ <Button variant="ghost" className="h-11 sm:h-9" onClick={onCancel} disabled={sending}>
+ Cancel
+ </Button>
+ <Button
+ className="h-11 sm:h-9"
+ onClick={sendCode}
+ disabled={sending || resendAfter > 0}
+ data-testid={tid.accountDeletionSendCode}
+ >
+ {sending
+ ? "Sending code…"
+ : resendAfter > 0
+ ? `Send deletion code in ${resendAfter}s`
+ : "Send deletion code"}
+ </Button>
+ </div>
+ </section>
+ ) : (
+ <section className="space-y-8">
+ <div className="space-y-3">
+ <span className="flex size-10 items-center justify-center rounded-full bg-destructive/10 text-destructive">
+ <MailWarning className="size-5" />
+ </span>
+ <h2 ref={titleRef} tabIndex={-1} className="text-xl font-medium tracking-tight outline-none">
+ Enter deletion code
+ </h2>
+ <p className="text-sm leading-6 text-muted-foreground">
+ We sent a 6-digit code to <span className="font-medium text-foreground">{email}</span>.
+ </p>
+ </div>
+ <InputOTP
+ ref={otpRef}
+ value={otp}
+ onChange={(value) => { setOtp(value); setError("") }}
+ maxLength={6}
+ autoFocus
+ disabled={deleting}
+ aria-label="Deletion code"
+ aria-invalid={!!error}
+ containerClassName="justify-center sm:justify-start"
+ data-testid={tid.accountDeletionOtp}
+ >
+ <InputOTPGroup>
+ {Array.from({ length: 6 }, (_, index) => (
+ <InputOTPSlot key={index} index={index} className="size-11 text-base" />
+ ))}
+ </InputOTPGroup>
+ </InputOTP>
+ {error ? (
+ <p ref={errorRef} tabIndex={-1} role="alert" className="text-sm text-destructive outline-none">
+ {error}
+ </p>
+ ) : null}
+ <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
+ <div className="flex flex-col gap-1 sm:flex-row">
+ <Button
+ variant="ghost"
+ className="h-11 sm:h-9"
+ onClick={() => { setError(""); setStep("notice") }}
+ disabled={deleting}
+ >
+ Back
+ </Button>
+ <Button
+ variant="ghost"
+ className="h-11 sm:h-9"
+ onClick={sendCode}
+ disabled={deleting || sending || resendAfter > 0}
+ >
+ {sending
+ ? "Sending…"
+ : resendAfter > 0
+ ? `Resend code in ${resendAfter}s`
+ : "Resend code"}
+ </Button>
+ </div>
+ <Button
+ variant="destructive"
+ className="h-11 sm:h-9"
+ onClick={deleteAccount}
+ disabled={deleting || otp.length !== 6}
+ data-testid={tid.accountDeletionSubmit}
+ >
+ {deleting ? "Deleting account…" : "Delete account"}
+ </Button>
+ </div>
+ </section>
+ )}
+ </div>
+ )
+}
diff --git a/src/web/src/components/community/settings/settings-navigation.test.ts b/src/web/src/components/community/settings/settings-navigation.test.ts
index 60ff88810..6098c1499 100644
--- a/src/web/src/components/community/settings/settings-navigation.test.ts
+++ b/src/web/src/components/community/settings/settings-navigation.test.ts
@@ -28,7 +28,8 @@ describe("responsive settings navigation", () => {
expect(SETTINGS_NAV_LABEL_CLASS).toContain("sr-only")
expect(SETTINGS_NAV_LABEL_CLASS).toContain("sm:not-sr-only")
expect(SETTINGS_NAV_LABEL_CLASS).toContain("truncate")
- expect(SETTINGS_NAV_FOOTER_CLASS).not.toContain("border")
+ expect(SETTINGS_NAV_FOOTER_CLASS).toContain("sm:border-t")
+ expect(SETTINGS_NAV_FOOTER_CLASS).toContain("sm:flex-col")
expect(SETTINGS_LOGOUT_CLASS).toContain("size-11")
expect(SETTINGS_LOGOUT_CLASS).toContain("sm:h-9")
expect(SETTINGS_LOGOUT_CLASS).not.toContain("px-0")
diff --git a/src/web/src/components/community/settings/settings-navigation.ts b/src/web/src/components/community/settings/settings-navigation.ts
index 59470a525..c48617aeb 100644
--- a/src/web/src/components/community/settings/settings-navigation.ts
+++ b/src/web/src/components/community/settings/settings-navigation.ts
@@ -14,4 +14,4 @@ export const SETTINGS_LOGOUT_CLASS =
"size-11 shrink-0 justify-center text-destructive hover:text-destructive sm:h-9 sm:w-full sm:justify-start"
export const SETTINGS_NAV_FOOTER_CLASS =
- "shrink-0 sm:mt-auto sm:w-full sm:pt-2"
+ "flex shrink-0 gap-1 sm:mt-auto sm:w-full sm:flex-col sm:border-t sm:border-border/60 sm:pt-2"
diff --git a/src/web/src/components/community/settings/settings-refinement.contract.test.ts b/src/web/src/components/community/settings/settings-refinement.contract.test.ts
index fe2cdda91..4adbb09f8 100644
--- a/src/web/src/components/community/settings/settings-refinement.contract.test.ts
+++ b/src/web/src/components/community/settings/settings-refinement.contract.test.ts
@@ -29,13 +29,15 @@ describe("settings refinement", () => {
expect(user).not.toContain("rounded-lg border p-4")
})
- it("keeps form actions on the content axis and preserves focus and readable contrast", () => {
+ it("keeps each form action group on its intended axis and preserves focus and contrast", () => {
const user = readSettings("user-settings.tsx")
const server = readSettings("server-settings.tsx")
+ expect(user).toContain("flex flex-wrap items-center gap-x-4 gap-y-2")
+ expect(user).toContain("ml-auto flex shrink-0 items-center gap-2")
+ expect(server).toContain("items-center justify-start gap-2")
+ expect(server).not.toContain("items-center justify-end gap-2")
for (const source of [user, server]) {
- expect(source).toContain("items-center justify-start gap-2")
- expect(source).not.toContain("items-center justify-end gap-2")
expect(source).toContain("focus-visible:ring-2")
expect(source).not.toContain("placeholder:text-muted-foreground/40")
expect(source).not.toContain("focus-visible:ring-0")
diff --git a/src/web/src/components/community/settings/settings-shell.contract.test.ts b/src/web/src/components/community/settings/settings-shell.contract.test.ts
index 2d997afe8..3ed20a694 100644
--- a/src/web/src/components/community/settings/settings-shell.contract.test.ts
+++ b/src/web/src/components/community/settings/settings-shell.contract.test.ts
@@ -36,14 +36,29 @@ describe("shared settings shell", () => {
}
})
- it("keeps Privacy last above the existing Log Out footer", () => {
+ it("keeps Privacy last, the nav footer limited to Log Out, and profile actions aligned", () => {
const source = readSettings("user-settings.tsx")
const privacyTab = source.indexOf('{ value: "privacy", label: "Privacy"')
const advancedTab = source.indexOf('{ value: "advanced", label: "Advanced"')
- const logout = source.indexOf('aria-label="Log out"')
+ const navFooterStart = source.indexOf("navFooter={")
+ const navFooter = source.slice(navFooterStart, source.indexOf("\n >", navFooterStart))
+ const profileStart = source.indexOf('<SettingsShellPanel value="profile">')
+ const profile = source.slice(profileStart, source.indexOf('<SettingsShellPanel value="appearance">'))
+ const accountDeletion = profile.indexOf('aria-label="Delete account"')
+ const cancel = profile.indexOf(">Cancel</Button>")
+ const save = profile.indexOf(">Save changes</Button>")
expect(privacyTab).toBeGreaterThan(advancedTab)
- expect(logout).toBeGreaterThan(privacyTab)
+ expect(navFooter).toContain('aria-label="Log out"')
+ expect(navFooter).not.toContain('aria-label="Delete account"')
+ expect(accountDeletion).toBeGreaterThan(-1)
+ expect(cancel).toBeGreaterThan(accountDeletion)
+ expect(save).toBeGreaterThan(cancel)
expect(source).toContain("<PrivacyPolicyContent />")
+ expect(source).not.toContain("Trash2")
+ expect(profile).toContain('className="flex flex-wrap items-center gap-x-4 gap-y-2"')
+ expect(profile).toContain('className="ml-auto flex shrink-0 items-center gap-2"')
+ expect(profile).toContain('className="h-11 shrink-0 px-3 text-destructive hover:text-destructive sm:h-8"')
+ expect(profile).toMatch(/data-testid=\{tid\.accountDeletionOpen\}[\s\S]*?>\s*Delete account\s*<\/Button>/u)
})
})
diff --git a/src/web/src/components/community/settings/settings-shell.tsx b/src/web/src/components/community/settings/settings-shell.tsx
index 65c06a709..bd35457ae 100644
--- a/src/web/src/components/community/settings/settings-shell.tsx
+++ b/src/web/src/components/community/settings/settings-shell.tsx
@@ -35,6 +35,7 @@ export function SettingsShell<Value extends string>({
tabs,
onClose,
navFooter,
+ disabled = false,
children,
}: {
value: Value
@@ -44,6 +45,7 @@ export function SettingsShell<Value extends string>({
tabs: SettingsShellTab<Value>[]
onClose: () => void
navFooter?: ReactNode
+ disabled?: boolean
children: ReactNode
}) {
const breakpoint = useBreakpoint()
@@ -63,6 +65,7 @@ export function SettingsShell<Value extends string>({
size="icon-sm"
className="size-11 sm:size-8"
onClick={onClose}
+ disabled={disabled}
aria-label="Close settings"
data-testid={tid.settingsClose}
>
@@ -81,6 +84,7 @@ export function SettingsShell<Value extends string>({
<TabsTrigger
key={tabValue}
value={tabValue}
+ disabled={disabled}
className={SETTINGS_TAB_CLASS}
data-testid={tid.settingsTab(tabValue)}
>
diff --git a/src/web/src/components/community/settings/user-settings.tsx b/src/web/src/components/community/settings/user-settings.tsx
index 156c0243f..d34a5c9ce 100644
--- a/src/web/src/components/community/settings/user-settings.tsx
+++ b/src/web/src/components/community/settings/user-settings.tsx
@@ -18,6 +18,7 @@ import {
SETTINGS_LOGOUT_CLASS,
} from "./settings-navigation"
import { SettingsShell, SettingsShellPanel, type SettingsShellTab } from "./settings-shell"
+import { AccountDeletionFlow } from "./account-deletion-flow"
const THEME_OPTIONS = [
{ value: "light", label: "Light", icon: Sun },
@@ -132,16 +133,18 @@ function AdvancedSettings({ userId }: { userId: string | null }) {
)
}
-export function UserSettings({ onClose, userId, userName, aboutMe, avatar, statusEmoji, statusText, onSave, onLogout, onUploadAvatar }: {
+export function UserSettings({ onClose, userId, userName, userEmail, aboutMe, avatar, statusEmoji, statusText, onSave, onLogout, onAccountDeleted, onUploadAvatar }: {
onClose: () => void
userId: string | null
userName: string
+ userEmail: string
aboutMe: string
avatar: string
statusEmoji?: string | null
statusText?: string | null
onSave: (data: { name?: string; aboutMe?: string; statusEmoji?: string | null; statusText?: string | null }) => void
onLogout?: () => void
+ onAccountDeleted: () => Promise<void>
onUploadAvatar?: () => void
}) {
// Draft + saved baseline are mount-only on purpose — a WS-driven prop change
@@ -157,6 +160,7 @@ export function UserSettings({ onClose, userId, userName, aboutMe, avatar, statu
text: statusText ?? null,
})
const [tab, setTab] = useState<UserSettingsTab>("profile")
+ const [deletionOpen, setDeletionOpen] = useState(false)
const dirty =
name !== baseline.name ||
@@ -192,82 +196,105 @@ export function UserSettings({ onClose, userId, userName, aboutMe, avatar, statu
value={tab}
onValueChange={setTab}
label="User Settings"
- title={tab === "appearance" ? "Appearance" : tab === "advanced" ? "Advanced" : tab === "privacy" ? "Privacy Policy" : "My Profile"}
+ title={deletionOpen ? "Delete account" : tab === "appearance" ? "Appearance" : tab === "advanced" ? "Advanced" : tab === "privacy" ? "Privacy Policy" : "My Profile"}
tabs={USER_SETTINGS_TABS}
onClose={onClose}
+ disabled={deletionOpen}
navFooter={
- <Button variant="ghost" className={SETTINGS_LOGOUT_CLASS} size="sm" onClick={onLogout} aria-label="Log out">
+ <Button variant="ghost" className={SETTINGS_LOGOUT_CLASS} size="sm" onClick={onLogout} aria-label="Log out" disabled={deletionOpen}>
<LogOut className="size-4" /> <span className="sr-only sm:not-sr-only">Log Out</span>
</Button>
}
>
- <SettingsShellPanel value="profile">
- <div className="mx-auto w-full max-w-md space-y-8">
- {/* Avatar — centered in a soft rounded frame, with a hand-rolled
- pill button beneath (matches the bot create/edit sheet; a stock
- secondary Button reads as the old square style). */}
- <div className="flex flex-col items-center gap-2">
- <span className="block size-24 overflow-hidden rounded-full ring-1 ring-border/50">
- <Avatar label={avatar} seed={userId ?? undefined} size={96} />
- </span>
- <button
- type="button"
- onClick={onUploadAvatar}
- className="flex min-h-11 items-center gap-2 rounded-full border border-border/50 px-3 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none sm:min-h-8"
- >
- <Camera className="size-3.5" /> Change photo
- </button>
- </div>
- {/* Display name — inline title input, borderless (name-as-heading,
- like the agent name on the bot page). */}
- <input
- value={name}
- onChange={(e) => setName(e.target.value)}
- placeholder="Your name"
- aria-label="Display name"
- className="min-h-11 w-full rounded-sm border-0 bg-transparent px-0 py-1 text-xl font-medium leading-[1.2] tracking-tight shadow-none outline-none placeholder:font-normal placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring/60 focus-visible:ring-offset-4 focus-visible:ring-offset-background sm:text-2xl"
- />
- {/* About — borderless auto-resizing textarea. */}
- <div className="space-y-2">
- <div className="text-xs text-muted-foreground">About</div>
- <AutoResizeTextarea
- value={value}
- onChange={(e) => setValue(e.target.value)}
- placeholder="Add a bit about yourself…"
- className="min-h-11 w-full rounded-sm border-0 bg-transparent px-0 py-1 text-sm leading-6 text-foreground shadow-none outline-none placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring/60 focus-visible:ring-offset-4 focus-visible:ring-offset-background"
- />
- </div>
- {/* Status — quiet label + a soft chip (more formed than a bare
- borderless button, still in the frameless language). */}
- <div className="space-y-2">
- <div className="text-xs text-muted-foreground">Status</div>
- <StatusEditor emoji={status.emoji} text={status.text} onChange={(emoji, text) => setStatus({ emoji, text })}>
- <button className="inline-flex min-h-11 items-center gap-2 rounded-full border border-border/50 px-3 text-sm transition-colors hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none sm:min-h-8">
- {hasStatus(status.emoji, status.text) ? (
- <span>{status.emoji} {status.text}</span>
- ) : (
- <span className="text-muted-foreground">Set a status</span>
- )}
- </button>
- </StatusEditor>
- </div>
- <div className="flex items-center justify-start gap-2">
- <Button variant="ghost" size="sm" className="h-11 sm:h-8" onClick={handleCancel} disabled={!dirty}>Cancel</Button>
- <Button size="sm" className="h-11 sm:h-8" onClick={handleSave} disabled={!dirty}>Save changes</Button>
- </div>
- </div>
- </SettingsShellPanel>
- <SettingsShellPanel value="appearance">
- <AppearanceSettings />
- </SettingsShellPanel>
- <SettingsShellPanel value="advanced" className="h-full">
- <AdvancedSettings userId={userId} />
- </SettingsShellPanel>
- <SettingsShellPanel value="privacy">
- <div className="mx-auto w-full max-w-2xl pb-8">
- <PrivacyPolicyContent />
- </div>
- </SettingsShellPanel>
+ {deletionOpen ? (
+ <AccountDeletionFlow
+ email={userEmail}
+ onCancel={() => setDeletionOpen(false)}
+ onDeleted={onAccountDeleted}
+ />
+ ) : (
+ <>
+ <SettingsShellPanel value="profile">
+ <div className="mx-auto w-full max-w-md space-y-8">
+ {/* Avatar — centered in a soft rounded frame, with a hand-rolled
+ pill button beneath (matches the bot create/edit sheet; a stock
+ secondary Button reads as the old square style). */}
+ <div className="flex flex-col items-center gap-2">
+ <span className="block size-24 overflow-hidden rounded-full ring-1 ring-border/50">
+ <Avatar label={avatar} seed={userId ?? undefined} size={96} />
+ </span>
+ <button
+ type="button"
+ onClick={onUploadAvatar}
+ className="flex min-h-11 items-center gap-2 rounded-full border border-border/50 px-3 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none sm:min-h-8"
+ >
+ <Camera className="size-3.5" /> Change photo
+ </button>
+ </div>
+ {/* Display name — inline title input, borderless (name-as-heading,
+ like the agent name on the bot page). */}
+ <input
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ placeholder="Your name"
+ aria-label="Display name"
+ className="min-h-11 w-full rounded-sm border-0 bg-transparent px-0 py-1 text-xl font-medium leading-[1.2] tracking-tight shadow-none outline-none placeholder:font-normal placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring/60 focus-visible:ring-offset-4 focus-visible:ring-offset-background sm:text-2xl"
+ />
+ {/* About — borderless auto-resizing textarea. */}
+ <div className="space-y-2">
+ <div className="text-xs text-muted-foreground">About</div>
+ <AutoResizeTextarea
+ value={value}
+ onChange={(e) => setValue(e.target.value)}
+ placeholder="Add a bit about yourself…"
+ className="min-h-11 w-full rounded-sm border-0 bg-transparent px-0 py-1 text-sm leading-6 text-foreground shadow-none outline-none placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring/60 focus-visible:ring-offset-4 focus-visible:ring-offset-background"
+ />
+ </div>
+ {/* Status — quiet label + a soft chip (more formed than a bare
+ borderless button, still in the frameless language). */}
+ <div className="space-y-2">
+ <div className="text-xs text-muted-foreground">Status</div>
+ <StatusEditor emoji={status.emoji} text={status.text} onChange={(emoji, text) => setStatus({ emoji, text })}>
+ <button className="inline-flex min-h-11 items-center gap-2 rounded-full border border-border/50 px-3 text-sm transition-colors hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none sm:min-h-8">
+ {hasStatus(status.emoji, status.text) ? (
+ <span>{status.emoji} {status.text}</span>
+ ) : (
+ <span className="text-muted-foreground">Set a status</span>
+ )}
+ </button>
+ </StatusEditor>
+ </div>
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-2">
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-11 shrink-0 px-3 text-destructive hover:text-destructive sm:h-8"
+ onClick={() => setDeletionOpen(true)}
+ aria-label="Delete account"
+ data-testid={tid.accountDeletionOpen}
+ >
+ Delete account
+ </Button>
+ <div className="ml-auto flex shrink-0 items-center gap-2">
+ <Button variant="ghost" size="sm" className="h-11 sm:h-8" onClick={handleCancel} disabled={!dirty}>Cancel</Button>
+ <Button size="sm" className="h-11 sm:h-8" onClick={handleSave} disabled={!dirty}>Save changes</Button>
+ </div>
+ </div>
+ </div>
+ </SettingsShellPanel>
+ <SettingsShellPanel value="appearance">
+ <AppearanceSettings />
+ </SettingsShellPanel>
+ <SettingsShellPanel value="advanced" className="h-full">
+ <AdvancedSettings userId={userId} />
+ </SettingsShellPanel>
+ <SettingsShellPanel value="privacy">
+ <div className="mx-auto w-full max-w-2xl pb-8">
+ <PrivacyPolicyContent />
+ </div>
+ </SettingsShellPanel>
+ </>
+ )}
</SettingsShell>
)
}
diff --git a/src/web/src/components/community/shell/use-shell-profile-controller.dom.test.ts b/src/web/src/components/community/shell/use-shell-profile-controller.dom.test.ts
index abe63503a..0e6e4a7ce 100644
--- a/src/web/src/components/community/shell/use-shell-profile-controller.dom.test.ts
+++ b/src/web/src/components/community/shell/use-shell-profile-controller.dom.test.ts
@@ -7,6 +7,7 @@ const mocks = vi.hoisted(() => ({
currentUser: {
id: "self",
name: "Self",
+ email: "[email protected]",
avatar: "S",
avatarVersion: 0,
aboutMe: "About",
@@ -30,10 +31,14 @@ const mocks = vi.hoisted(() => ({
toastApiError: vi.fn(),
validate: vi.fn(),
disposeReconciliation: vi.fn(),
+ disposeCoordinator: vi.fn(),
}))
vi.mock("sonner", () => ({ toast: mocks.toast }))
-vi.mock("@/lib/api/client", () => ({ toastApiError: mocks.toastApiError }))
+vi.mock("@/lib/api/client", () => ({
+ ACCOUNT_DELETED_SIGN_IN_PATH: "/sign-in?account_deleted=1",
+ toastApiError: mocks.toastApiError,
+}))
vi.mock("@/hooks/community/use-user-profile", () => ({
userProfileQueryFn: (id: string) => () => Promise.resolve({ id }),
PROFILE_STALE_TIME_MS: 300_000,
@@ -98,6 +103,9 @@ vi.mock("@/lib/query-persister", () => ({ clearPersistedCache: mocks.clearCache
vi.mock("@/hooks/community/community-ws/read-state-reconciliation", () => ({
disposeAccountReadStateReconciliation: mocks.disposeReconciliation,
}))
+vi.mock("@/hooks/community/read-coordinator", () => ({
+ disposeReadCoordinator: mocks.disposeCoordinator,
+}))
vi.mock("@/lib/auth-client", () => ({ signOut: mocks.signOut }))
type Result = ReturnType<typeof useShellProfileController>
@@ -450,6 +458,38 @@ describe("useShellProfileController", () => {
expect(order.some((entry) => entry.startsWith("push:"))).toBe(false)
})
+ it("uses logout-equivalent local cleanup then replaces into the persistent deletion state", async () => {
+ const order: string[] = []
+ vi.stubGlobal("location", {
+ replace: (href: string) => { order.push(`replace:${href}`) },
+ })
+ const hook = await renderController()
+ hook.cancelPendingNavigation.mockImplementation(() => { order.push("cancel") })
+ mocks.communityReset.mockImplementation(() => { order.push("community") })
+ mocks.wsReset.mockImplementation(() => { order.push("ws") })
+ mocks.streamReset.mockImplementation(() => { order.push("stream") })
+ mocks.disposeCoordinator.mockImplementation(() => { order.push("coordinator") })
+ mocks.disposeReconciliation.mockImplementation(() => { order.push("reconcile") })
+ hook.queryClient.clear.mockImplementation(() => { order.push("query") })
+ mocks.clearCache.mockImplementation(async () => { order.push("cache") })
+
+ await act(async () => hook.current.userSettingsProps.onAccountDeleted())
+
+ expect(order).toEqual([
+ "cancel",
+ "community",
+ "ws",
+ "stream",
+ "coordinator",
+ "reconcile",
+ "query",
+ "cache",
+ "replace:/sign-in?account_deleted=1",
+ ])
+ expect(hook.router.replace).not.toHaveBeenCalled()
+ expect(mocks.signOut).not.toHaveBeenCalled()
+ })
+
it("starts avatar upload before revoking exactly once", async () => {
const order: string[] = []
let input: { files?: File[]; onchange?: () => void; click: () => void } | undefined
diff --git a/src/web/src/components/community/shell/use-shell-profile-controller.ts b/src/web/src/components/community/shell/use-shell-profile-controller.ts
index 9f5623195..aeb1f1779 100644
--- a/src/web/src/components/community/shell/use-shell-profile-controller.ts
+++ b/src/web/src/components/community/shell/use-shell-profile-controller.ts
@@ -3,7 +3,7 @@
import { useCallback, useState, type ComponentProps } from "react"
import { parseNameAndTag } from "@alook/shared"
import { toast } from "sonner"
-import { toastApiError } from "@/lib/api/client"
+import { ACCOUNT_DELETED_SIGN_IN_PATH, toastApiError } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
import { userProfileQueryFn, PROFILE_STALE_TIME_MS } from "@/hooks/community/use-user-profile"
import { validateIconSourceFile } from "@/lib/community/image-crop"
@@ -278,7 +278,7 @@ export function useShellProfileController({
}
}
- const onLogout = async () => {
+ const clearLocalAccountState = async () => {
cancelPendingNavigation()
useCommunityStore.getState().reset()
useCommunityWsStore.getState().reset()
@@ -287,14 +287,25 @@ export function useShellProfileController({
disposeAccountReadStateReconciliation(queryClient)
queryClient.clear()
await clearPersistedCache(currentUser.id).catch(() => {})
+ }
+
+ const onLogout = async () => {
+ await clearLocalAccountState()
await signOut()
router.push("/sign-in")
}
+ const onAccountDeleted = async () => {
+ await clearLocalAccountState()
+ setEditingProfile(false)
+ globalThis.location.replace(ACCOUNT_DELETED_SIGN_IN_PATH)
+ }
+
const userSettingsProps: ComponentProps<typeof UserSettings> = {
onClose: () => setEditingProfile(false),
userId: currentUser.id,
userName: currentUser.name,
+ userEmail: currentUser.email,
aboutMe: currentUser.aboutMe ?? "",
avatar: currentUser.avatar,
statusEmoji: currentUser.statusEmoji,
@@ -302,6 +313,7 @@ export function useShellProfileController({
onUploadAvatar,
onSave: onSaveProfile,
onLogout,
+ onAccountDeleted,
}
let pendingAvatarCropProps: Omit<ComponentProps<typeof ImageCropDialog>, "maskShape"> | null = null
diff --git a/src/web/src/lib/account-deletion/challenge.test.ts b/src/web/src/lib/account-deletion/challenge.test.ts
new file mode 100644
index 000000000..4b61d5513
--- /dev/null
+++ b/src/web/src/lib/account-deletion/challenge.test.ts
@@ -0,0 +1,205 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+
+const mocks = vi.hoisted(() => ({
+ upsert: vi.fn(),
+ take: vi.fn(),
+ restore: vi.fn(),
+ deleteIfMatches: vi.fn(),
+ rate: vi.fn(),
+ sendEmail: vi.fn(),
+}))
+
+vi.mock("@alook/shared", () => ({
+ queries: {
+ accountDeletion: {
+ upsertDeletionChallenge: mocks.upsert,
+ takeDeletionChallenge: mocks.take,
+ restoreDeletionChallenge: mocks.restore,
+ deleteDeletionChallengeIfMatches: mocks.deleteIfMatches,
+ },
+ },
+}))
+
+vi.mock("@/lib/auth", () => ({
+ getAuthOtpRateLimitPolicy: () => ({ max: 5, windowMs: 60_000 }),
+ sendOtpEmail: mocks.sendEmail,
+}))
+
+vi.mock("@/lib/rate-limit", () => ({ checkRateLimit: mocks.rate }))
+
+import {
+ deletionChallengeId,
+ deletionChallengeIdentifier,
+ generateDeletionOtp,
+ restoreVerifiedDeletionCode,
+ sendDeletionCode,
+ verifyDeletionCode,
+} from "./challenge"
+
+const db = {} as never
+const env = {} as Env
+const now = new Date("2026-09-07T15:00:00.000Z")
+
+function row(value = "123456:0", expiresAt = "2026-09-07T15:05:00.000Z") {
+ return {
+ id: "account-deletion:hash",
+ identifier: "account-deletion-otp:user-1:[email protected]",
+ value,
+ expiresAt,
+ createdAt: now.toISOString(),
+ updatedAt: now.toISOString(),
+ }
+}
+
+describe("account deletion challenge", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mocks.rate.mockResolvedValue({ allowed: true })
+ mocks.upsert.mockImplementation(async (_db, value) => value)
+ mocks.deleteIfMatches.mockResolvedValue(true)
+ mocks.restore.mockResolvedValue(true)
+ mocks.sendEmail.mockResolvedValue(undefined)
+ })
+
+ it("binds a deterministic challenge key to user and normalized email", async () => {
+ const identifier = deletionChallengeIdentifier("user-1", " [email protected] ")
+ expect(identifier).toBe("account-deletion-otp:user-1:[email protected]")
+ await expect(deletionChallengeId(identifier)).resolves.toMatch(/^account-deletion:[0-9a-f]{64}$/u)
+ await expect(deletionChallengeId(identifier)).resolves.toBe(await deletionChallengeId(identifier))
+ })
+
+ it("generates an unbiased six-digit code including leading zeroes", () => {
+ const fill = vi.fn((view: Uint32Array) => {
+ view[0] = 42
+ return view
+ })
+ expect(generateDeletionOtp(fill as typeof crypto.getRandomValues)).toBe("000042")
+ })
+
+ it("rejects out-of-range randomness before formatting the code", () => {
+ const fill = vi.fn()
+ .mockImplementationOnce((view: Uint32Array) => {
+ view[0] = 0xffff_ffff
+ return view
+ })
+ .mockImplementationOnce((view: Uint32Array) => {
+ view[0] = 7
+ return view
+ })
+
+ expect(generateDeletionOtp(fill as typeof crypto.getRandomValues)).toBe("000007")
+ expect(fill).toHaveBeenCalledTimes(2)
+ })
+
+ it("persists five-minute challenge before sending deletion-specific email", async () => {
+ const result = await sendDeletionCode(db, env, {
+ userId: "user-1",
+ email: "[email protected]",
+ now,
+ })
+
+ expect(result).toEqual({ kind: "sent", expiresIn: 300, resendAfter: 60 })
+ expect(mocks.upsert).toHaveBeenCalledOnce()
+ const persisted = mocks.upsert.mock.calls[0][1]
+ expect(persisted.identifier).toBe("account-deletion-otp:user-1:[email protected]")
+ expect(persisted.value).toMatch(/^\d{6}:0$/u)
+ expect(persisted.expiresAt).toBe("2026-09-07T15:05:00.000Z")
+ expect(mocks.sendEmail).toHaveBeenCalledWith(env, {
+ email: "[email protected]",
+ otp: persisted.value.slice(0, 6),
+ type: "account-deletion",
+ })
+ })
+
+ it("returns rate-limit retry without persisting or sending", async () => {
+ mocks.rate.mockResolvedValue({ allowed: false, retryAfterSec: 17 })
+
+ await expect(sendDeletionCode(db, env, {
+ userId: "user-1",
+ email: "[email protected]",
+ now,
+ })).resolves.toEqual({ kind: "rate_limited", retryAfter: 17 })
+ expect(mocks.upsert).not.toHaveBeenCalled()
+ expect(mocks.sendEmail).not.toHaveBeenCalled()
+ })
+
+ it("compare-deletes only its own challenge when email delivery fails", async () => {
+ mocks.sendEmail.mockRejectedValue(new Error("email down"))
+
+ await expect(sendDeletionCode(db, env, {
+ userId: "user-1",
+ email: "[email protected]",
+ now,
+ })).resolves.toEqual({ kind: "send_failed" })
+ expect(mocks.deleteIfMatches).toHaveBeenCalledWith(db, expect.objectContaining({
+ identifier: "account-deletion-otp:user-1:[email protected]",
+ value: expect.stringMatching(/^\d{6}:0$/u),
+ }))
+ })
+
+ it("consumes a correct code and returns the exact row for retry restoration", async () => {
+ const challenge = row()
+ mocks.take.mockResolvedValue(challenge)
+
+ await expect(verifyDeletionCode(db, {
+ userId: "user-1",
+ email: "[email protected]",
+ otp: "123456",
+ now,
+ })).resolves.toEqual({ kind: "verified", challenge })
+ expect(mocks.restore).not.toHaveBeenCalled()
+ })
+
+ it("increments wrong attempts while preserving the original expiry", async () => {
+ mocks.take.mockResolvedValue(row("123456:1"))
+
+ await expect(verifyDeletionCode(db, {
+ userId: "user-1",
+ email: "[email protected]",
+ otp: "000000",
+ now,
+ })).resolves.toEqual({ kind: "invalid" })
+ expect(mocks.restore).toHaveBeenCalledWith(db, expect.objectContaining({
+ value: "123456:2",
+ expiresAt: "2026-09-07T15:05:00.000Z",
+ }))
+ })
+
+ it("exhausts on the third wrong attempt without restoring", async () => {
+ mocks.take.mockResolvedValue(row("123456:2"))
+
+ await expect(verifyDeletionCode(db, {
+ userId: "user-1",
+ email: "[email protected]",
+ otp: "000000",
+ now,
+ })).resolves.toEqual({ kind: "too_many_attempts" })
+ expect(mocks.restore).not.toHaveBeenCalled()
+ })
+
+ it("distinguishes expired and missing challenges", async () => {
+ mocks.take.mockResolvedValueOnce(row("123456:0", now.toISOString())).mockResolvedValueOnce(null)
+
+ await expect(verifyDeletionCode(db, {
+ userId: "user-1", email: "[email protected]", otp: "123456", now,
+ })).resolves.toEqual({ kind: "expired" })
+ await expect(verifyDeletionCode(db, {
+ userId: "user-1", email: "[email protected]", otp: "123456", now,
+ })).resolves.toEqual({ kind: "invalid" })
+ })
+
+ it("rejects a stored challenge with an unsafe attempt count", async () => {
+ mocks.take.mockResolvedValue(row("123456:9007199254740992"))
+
+ await expect(verifyDeletionCode(db, {
+ userId: "user-1", email: "[email protected]", otp: "123456", now,
+ })).resolves.toEqual({ kind: "invalid" })
+ expect(mocks.restore).not.toHaveBeenCalled()
+ })
+
+ it("restores a verified challenge insert-if-absent after retryable failure", async () => {
+ const challenge = row()
+ await restoreVerifiedDeletionCode(db, challenge)
+ expect(mocks.restore).toHaveBeenCalledWith(db, challenge)
+ })
+})
diff --git a/src/web/src/lib/account-deletion/challenge.ts b/src/web/src/lib/account-deletion/challenge.ts
new file mode 100644
index 000000000..4901267dc
--- /dev/null
+++ b/src/web/src/lib/account-deletion/challenge.ts
@@ -0,0 +1,143 @@
+import { queries, type Database } from "@alook/shared"
+import { getAuthOtpRateLimitPolicy, sendOtpEmail } from "@/lib/auth"
+import { checkRateLimit } from "@/lib/rate-limit"
+
+const ACCOUNT_DELETION_OTP_EXPIRES_IN_SECONDS = 300
+const ACCOUNT_DELETION_OTP_MAX_ATTEMPTS = 3
+
+type RandomValues = <T extends ArrayBufferView | null>(array: T) => T
+
+export type VerifiedDeletionChallenge = queries.accountDeletion.DeletionChallenge
+
+export type SendDeletionCodeResult =
+ | { kind: "sent"; expiresIn: number; resendAfter: number }
+ | { kind: "rate_limited"; retryAfter: number }
+ | { kind: "send_failed" }
+
+export type VerifyDeletionCodeResult =
+ | { kind: "verified"; challenge: VerifiedDeletionChallenge }
+ | { kind: "invalid" }
+ | { kind: "expired" }
+ | { kind: "too_many_attempts" }
+
+function normalizeEmail(email: string): string {
+ return email.trim().toLowerCase()
+}
+
+export function deletionChallengeIdentifier(userId: string, email: string): string {
+ return `account-deletion-otp:${userId}:${normalizeEmail(email)}`
+}
+
+export async function deletionChallengeId(identifier: string): Promise<string> {
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(identifier))
+ return `account-deletion:${Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("")}`
+}
+
+export function generateDeletionOtp(
+ getRandomValues: RandomValues = crypto.getRandomValues.bind(crypto),
+): string {
+ const sample = new Uint32Array(1)
+ const maximum = 0x1_0000_0000 - (0x1_0000_0000 % 1_000_000)
+ do getRandomValues(sample)
+ while (sample[0] >= maximum)
+ return String(sample[0] % 1_000_000).padStart(6, "0")
+}
+
+function encodeChallengeValue(otp: string, attempts: number): string {
+ return `${otp}:${attempts}`
+}
+
+function parseChallengeValue(value: string): { otp: string; attempts: number } | null {
+ const match = /^(\d{6}):(\d+)$/u.exec(value)
+ if (!match) return null
+ const attempts = Number.parseInt(match[2], 10)
+ return Number.isSafeInteger(attempts) && attempts >= 0
+ ? { otp: match[1], attempts }
+ : null
+}
+
+async function equalOtp(provided: string, expected: string): Promise<boolean> {
+ const encoder = new TextEncoder()
+ const [providedHash, expectedHash] = await Promise.all([
+ crypto.subtle.digest("SHA-256", encoder.encode(provided)),
+ crypto.subtle.digest("SHA-256", encoder.encode(expected)),
+ ])
+ const left = new Uint8Array(providedHash)
+ const right = new Uint8Array(expectedHash)
+ let difference = 0
+ for (let index = 0; index < left.length; index++) difference |= left[index] ^ right[index]
+ return difference === 0
+}
+
+async function challengeKey(userId: string, email: string) {
+ const identifier = deletionChallengeIdentifier(userId, email)
+ return { id: await deletionChallengeId(identifier), identifier }
+}
+
+export async function sendDeletionCode(
+ db: Database,
+ env: Env,
+ input: { userId: string; email: string; now?: Date },
+): Promise<SendDeletionCodeResult> {
+ const email = normalizeEmail(input.email)
+ const policy = getAuthOtpRateLimitPolicy(env)
+ const rate = await checkRateLimit(env, "auth:otpSend", email, policy)
+ if (!rate.allowed) return { kind: "rate_limited", retryAfter: rate.retryAfterSec }
+
+ const otp = generateDeletionOtp()
+ const now = input.now ?? new Date()
+ const expiresAt = new Date(now.getTime() + ACCOUNT_DELETION_OTP_EXPIRES_IN_SECONDS * 1000)
+ const key = await challengeKey(input.userId, email)
+ const challenge = await queries.accountDeletion.upsertDeletionChallenge(db, {
+ ...key,
+ value: encodeChallengeValue(otp, 0),
+ expiresAt: expiresAt.toISOString(),
+ createdAt: now.toISOString(),
+ updatedAt: now.toISOString(),
+ })
+
+ try {
+ await sendOtpEmail(env, { email, otp, type: "account-deletion" })
+ } catch {
+ await queries.accountDeletion.deleteDeletionChallengeIfMatches(db, challenge)
+ return { kind: "send_failed" }
+ }
+
+ return {
+ kind: "sent",
+ expiresIn: ACCOUNT_DELETION_OTP_EXPIRES_IN_SECONDS,
+ resendAfter: Math.round(policy.windowMs / 1000),
+ }
+}
+
+export async function verifyDeletionCode(
+ db: Database,
+ input: { userId: string; email: string; otp: string; now?: Date },
+): Promise<VerifyDeletionCodeResult> {
+ const key = await challengeKey(input.userId, input.email)
+ const challenge = await queries.accountDeletion.takeDeletionChallenge(db, key)
+ if (!challenge) return { kind: "invalid" }
+
+ const parsed = parseChallengeValue(challenge.value)
+ if (!parsed) return { kind: "invalid" }
+ const now = input.now ?? new Date()
+ if (Date.parse(challenge.expiresAt) <= now.getTime()) return { kind: "expired" }
+ if (parsed.attempts >= ACCOUNT_DELETION_OTP_MAX_ATTEMPTS) return { kind: "too_many_attempts" }
+ if (await equalOtp(input.otp, parsed.otp)) return { kind: "verified", challenge }
+
+ const attempts = parsed.attempts + 1
+ if (attempts >= ACCOUNT_DELETION_OTP_MAX_ATTEMPTS) return { kind: "too_many_attempts" }
+ await queries.accountDeletion.restoreDeletionChallenge(db, {
+ ...challenge,
+ value: encodeChallengeValue(parsed.otp, attempts),
+ updatedAt: now.toISOString(),
+ })
+ return { kind: "invalid" }
+}
+
+export async function restoreVerifiedDeletionCode(
+ db: Database,
+ challenge: VerifiedDeletionChallenge,
+): Promise<void> {
+ await queries.accountDeletion.restoreDeletionChallenge(db, challenge)
+}
diff --git a/src/web/src/lib/account-deletion/execution.test.ts b/src/web/src/lib/account-deletion/execution.test.ts
new file mode 100644
index 000000000..a722be8a3
--- /dev/null
+++ b/src/web/src/lib/account-deletion/execution.test.ts
@@ -0,0 +1,250 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+
+const mocks = vi.hoisted(() => ({
+ getSnapshot: vi.fn(),
+ deleteRows: vi.fn(),
+ getUser: vi.fn(),
+ deleteStorage: vi.fn(),
+ forceClose: vi.fn(),
+ pushBot: vi.fn(),
+ broadcastDaemon: vi.fn(),
+ fanOut: vi.fn(),
+ broadcastUser: vi.fn(),
+ revokeProvider: vi.fn(),
+ invalidateMany: vi.fn(),
+ warn: vi.fn(),
+}))
+
+vi.mock("@alook/shared", () => ({
+ createLogger: () => ({ warn: mocks.warn }),
+ WS_EVENTS: {
+ SERVER_DELETE: "server:delete",
+ READ_STATE_ADVANCED: "read_state:advanced",
+ },
+ queries: {
+ accountDeletion: {
+ getAccountDeletionSnapshot: mocks.getSnapshot,
+ deleteAccountRows: mocks.deleteRows,
+ },
+ user: { getUserInternal: mocks.getUser },
+ },
+}))
+vi.mock("@/lib/db", () => ({ getPrimaryDb: () => ({ primary: true }) }))
+vi.mock("@/lib/cache", () => ({
+ cacheKeys: { machineToken: (token: string) => `mt:${token.slice(0, 20)}` },
+ invalidateMany: mocks.invalidateMany,
+}))
+vi.mock("@/lib/community/community-media-cleanup", () => ({ deleteCommunityMediaObjects: vi.fn() }))
+vi.mock("./storage", () => ({ deleteAccountStorage: mocks.deleteStorage }))
+vi.mock("./provider-revocation", () => ({ revokeProviderAccount: mocks.revokeProvider }))
+vi.mock("@/lib/community/machine-disconnect", () => ({
+ forceCloseCommunityMachinesByDoNames: mocks.forceClose,
+}))
+vi.mock("@/lib/community/bot-push", () => ({ pushBotEventToMachine: mocks.pushBot }))
+vi.mock("@/lib/broadcast", () => ({ broadcastToDaemon: mocks.broadcastDaemon }))
+vi.mock("@/lib/community/fanout", () => ({
+ fanOutToUsers: mocks.fanOut,
+ broadcastToUserSafe: mocks.broadcastUser,
+}))
+
+import { executeAccountDeletion } from "./execution"
+
+function snapshot(id: string) {
+ return {
+ identity: { id: "user-1", email: "[email protected]", isBot: false, avatarObjectKey: null },
+ identities: [],
+ providers: [],
+ ownedWorkspaceIds: [],
+ ownedAgentIds: [],
+ legacyDaemons: [],
+ machineTokens: [],
+ machineDoNames: [],
+ botBindings: [],
+ ownedServers: [],
+ readStateUserIds: [],
+ media: {
+ communityExactKeys: [id],
+ communityPrefixes: [],
+ emailExactKeys: [],
+ emailPrefixes: [],
+ deletingEmailAttachments: [],
+ survivingEmailAttachments: [],
+ bugReportExactKeys: [],
+ bugReportPrefixes: [],
+ },
+ }
+}
+
+describe("account deletion execution", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ for (const effect of [
+ mocks.deleteStorage,
+ mocks.forceClose,
+ mocks.pushBot,
+ mocks.broadcastDaemon,
+ mocks.fanOut,
+ mocks.broadcastUser,
+ mocks.revokeProvider,
+ mocks.invalidateMany,
+ ]) effect.mockResolvedValue(undefined)
+ })
+
+ it("cleans an initial and final primary snapshot before the D1 batch", async () => {
+ const initial = { ...snapshot("initial"), machineTokens: ["al_initial_token"] }
+ const final = { ...snapshot("final"), machineTokens: ["al_final_token"] }
+ mocks.getSnapshot.mockResolvedValueOnce(initial).mockResolvedValueOnce(final)
+ mocks.deleteRows.mockResolvedValue({ deleted: true, readStateRevisions: [] })
+ const waitUntil = vi.fn()
+
+ await expect(executeAccountDeletion(
+ {} as never,
+ {} as never,
+ { waitUntil },
+ "user-1",
+ )).resolves.toEqual({ kind: "deleted" })
+
+ expect(mocks.deleteStorage).toHaveBeenNthCalledWith(1, expect.anything(), initial)
+ expect(mocks.deleteStorage).toHaveBeenNthCalledWith(2, expect.anything(), final)
+ expect(mocks.deleteRows).toHaveBeenCalledWith({ primary: true }, final)
+ expect(mocks.deleteStorage.mock.invocationCallOrder[1])
+ .toBeLessThan(mocks.deleteRows.mock.invocationCallOrder[0])
+ expect(mocks.invalidateMany).toHaveBeenCalledWith([
+ "mt:al_initial_token",
+ "mt:al_final_token",
+ ])
+ expect(waitUntil).toHaveBeenCalledOnce()
+ })
+
+ it("invalidates the initial machine tokens when another request already removed the user", async () => {
+ const initial = { ...snapshot("initial"), machineTokens: ["al_initial_token"] }
+ mocks.getSnapshot.mockResolvedValueOnce(initial).mockResolvedValueOnce(null)
+
+ await expect(executeAccountDeletion(
+ {} as never,
+ {} as never,
+ { waitUntil: vi.fn() },
+ "user-1",
+ )).resolves.toEqual({ kind: "missing" })
+
+ expect(mocks.invalidateMany).toHaveBeenCalledWith(["mt:al_initial_token"])
+ expect(mocks.deleteRows).not.toHaveBeenCalled()
+ })
+
+ it("does not run the D1 batch after synchronous storage cleanup fails", async () => {
+ mocks.getSnapshot.mockResolvedValue(snapshot("initial"))
+ mocks.deleteStorage.mockRejectedValue(new Error("R2 unavailable"))
+
+ await expect(executeAccountDeletion(
+ {} as never,
+ {} as never,
+ { waitUntil: vi.fn() },
+ "user-1",
+ )).resolves.toEqual({ kind: "failed" })
+ expect(mocks.getSnapshot).toHaveBeenCalledOnce()
+ expect(mocks.deleteRows).not.toHaveBeenCalled()
+ })
+
+ it("treats an ambiguous D1 error as success only when a new primary no longer finds the user", async () => {
+ mocks.getSnapshot.mockResolvedValue(snapshot("current"))
+ mocks.deleteRows.mockRejectedValue(new Error("transport lost"))
+ mocks.getUser.mockResolvedValue(null)
+
+ await expect(executeAccountDeletion(
+ {} as never,
+ {} as never,
+ { waitUntil: vi.fn() },
+ "user-1",
+ )).resolves.toEqual({ kind: "deleted" })
+
+ mocks.getUser.mockResolvedValue({ id: "user-1" })
+ await expect(executeAccountDeletion(
+ {} as never,
+ {} as never,
+ { waitUntil: vi.fn() },
+ "user-1",
+ )).resolves.toEqual({ kind: "failed" })
+ })
+
+ it("keeps committed deletion successful when post-commit effects reject", async () => {
+ const current = {
+ ...snapshot("current"),
+ providers: [{ providerId: "github", accountId: "account", accessToken: "token", refreshToken: null }],
+ legacyDaemons: [{ daemonId: "daemon-1", workspaceId: "workspace-1" }],
+ machineTokens: ["al_1234567890abcdefghijklmnop"],
+ machineDoNames: ["machine-do"],
+ botBindings: [{ botId: "bot-1", machineId: "machine-1" }],
+ ownedServers: [{ id: "server-1", icon: null, memberIds: ["member-1"] }],
+ readStateUserIds: ["member-1"],
+ }
+ mocks.getSnapshot.mockResolvedValue(current)
+ mocks.deleteRows.mockResolvedValue({
+ deleted: true,
+ readStateRevisions: [{ userId: "member-1", revision: 7 }],
+ })
+ mocks.forceClose.mockRejectedValue(new Error("socket unavailable"))
+ let postCommit: Promise<unknown> | undefined
+
+ await expect(executeAccountDeletion(
+ {} as never,
+ {} as never,
+ { waitUntil: (promise) => { postCommit = promise } },
+ "user-1",
+ )).resolves.toEqual({ kind: "deleted" })
+ await expect(postCommit).resolves.toBeUndefined()
+
+ expect(mocks.pushBot).toHaveBeenCalled()
+ expect(mocks.broadcastDaemon).toHaveBeenCalled()
+ expect(mocks.fanOut).toHaveBeenCalled()
+ expect(mocks.broadcastUser).toHaveBeenCalled()
+ expect(mocks.revokeProvider).toHaveBeenCalled()
+ expect(mocks.invalidateMany).toHaveBeenCalledWith(["mt:al_1234567890abcdefg"])
+ expect(mocks.warn).toHaveBeenCalledWith(
+ "account_deletion_post_commit_effects_failed",
+ { failures: 1 },
+ )
+ })
+
+ it("keeps a committed deletion successful when machine-token invalidation fails", async () => {
+ const current = {
+ ...snapshot("current"),
+ machineTokens: ["al_stale_token"],
+ }
+ mocks.getSnapshot.mockResolvedValue(current)
+ mocks.deleteRows.mockResolvedValue({ deleted: true, readStateRevisions: [] })
+ mocks.invalidateMany.mockRejectedValue(new Error("KV unavailable"))
+
+ await expect(executeAccountDeletion(
+ {} as never,
+ {} as never,
+ { waitUntil: vi.fn() },
+ "user-1",
+ )).resolves.toEqual({ kind: "deleted" })
+ })
+
+ it("fails closed when the delete batch reports no deleted user and the user remains", async () => {
+ mocks.getSnapshot.mockResolvedValue(snapshot("current"))
+ mocks.deleteRows.mockResolvedValue({ deleted: false, readStateRevisions: [] })
+ mocks.getUser.mockResolvedValue({ id: "user-1" })
+
+ await expect(executeAccountDeletion(
+ {} as never,
+ {} as never,
+ { waitUntil: vi.fn() },
+ "user-1",
+ )).resolves.toEqual({ kind: "failed" })
+ })
+
+ it("keeps a committed deletion successful when waitUntil is unavailable", async () => {
+ mocks.getSnapshot.mockResolvedValue(snapshot("current"))
+ mocks.deleteRows.mockResolvedValue({ deleted: true, readStateRevisions: [] })
+
+ await expect(executeAccountDeletion(
+ {} as never,
+ {} as never,
+ { waitUntil: () => { throw new Error("unavailable") } },
+ "user-1",
+ )).resolves.toEqual({ kind: "deleted" })
+ expect(mocks.warn).toHaveBeenCalledWith("account_deletion_wait_until_unavailable")
+ })
+})
diff --git a/src/web/src/lib/account-deletion/execution.ts b/src/web/src/lib/account-deletion/execution.ts
new file mode 100644
index 000000000..fa63fb8d8
--- /dev/null
+++ b/src/web/src/lib/account-deletion/execution.ts
@@ -0,0 +1,106 @@
+import { createLogger, queries, WS_EVENTS, type Database } from "@alook/shared"
+import { cacheKeys, invalidateMany } from "@/lib/cache"
+import { getPrimaryDb } from "@/lib/db"
+import { broadcastToDaemon } from "@/lib/broadcast"
+import { pushBotEventToMachine } from "@/lib/community/bot-push"
+import { fanOutToUsers, broadcastToUserSafe } from "@/lib/community/fanout"
+import { forceCloseCommunityMachinesByDoNames } from "@/lib/community/machine-disconnect"
+import { deleteAccountStorage } from "./storage"
+import { revokeProviderAccount } from "./provider-revocation"
+
+const log = createLogger({ service: "account-deletion" })
+
+export type ExecuteAccountDeletionResult =
+ | { kind: "deleted" }
+ | { kind: "missing" }
+ | { kind: "failed" }
+
+async function invalidateMachineTokens(tokens: string[]): Promise<void> {
+ await invalidateMany(tokens.map((token) => cacheKeys.machineToken(token))).catch(() => {})
+}
+
+function scheduleAfterCommit(
+ env: Env,
+ executionContext: Pick<ExecutionContext, "waitUntil">,
+ snapshot: queries.accountDeletion.AccountDeletionSnapshot,
+ readStateRevisions: Array<{ userId: string; revision: number }>,
+): void {
+ const work = Promise.allSettled([
+ forceCloseCommunityMachinesByDoNames(env, snapshot.machineDoNames),
+ ...snapshot.botBindings.map((binding) => pushBotEventToMachine(env, binding.machineId, {
+ type: "bot:removed",
+ botId: binding.botId,
+ })),
+ ...snapshot.legacyDaemons.map((daemon) => broadcastToDaemon(daemon.daemonId, {
+ type: "daemon.evict",
+ workspaceId: daemon.workspaceId,
+ })),
+ ...snapshot.ownedServers.map((server) => fanOutToUsers(server.memberIds, {
+ type: WS_EVENTS.SERVER_DELETE,
+ serverId: server.id,
+ })),
+ ...readStateRevisions.map((revision) => broadcastToUserSafe(revision.userId, {
+ type: WS_EVENTS.READ_STATE_ADVANCED,
+ revision: revision.revision,
+ inboxChanged: true,
+ })),
+ ...snapshot.providers.map((provider) => revokeProviderAccount(env, provider)),
+ ]).then((results) => {
+ const failures = results.filter((result) => result.status === "rejected").length
+ if (failures > 0) log.warn("account_deletion_post_commit_effects_failed", { failures })
+ })
+ try {
+ executionContext.waitUntil(work)
+ } catch {
+ log.warn("account_deletion_wait_until_unavailable")
+ }
+}
+
+export async function executeAccountDeletion(
+ db: Database,
+ env: Env,
+ executionContext: Pick<ExecutionContext, "waitUntil">,
+ userId: string,
+): Promise<ExecuteAccountDeletionResult> {
+ try {
+ const firstSnapshot = await queries.accountDeletion.getAccountDeletionSnapshot(db, userId)
+ if (!firstSnapshot) return { kind: "missing" }
+ await deleteAccountStorage(env, firstSnapshot)
+
+ const finalDb = getPrimaryDb(env.DB)
+ const finalSnapshot = await queries.accountDeletion.getAccountDeletionSnapshot(finalDb, userId)
+ if (!finalSnapshot) {
+ await invalidateMachineTokens(firstSnapshot.machineTokens)
+ return { kind: "missing" }
+ }
+ const machineTokens = [...new Set([
+ ...firstSnapshot.machineTokens,
+ ...finalSnapshot.machineTokens,
+ ])]
+ await deleteAccountStorage(env, finalSnapshot)
+
+ let deletion: Awaited<ReturnType<typeof queries.accountDeletion.deleteAccountRows>>
+ try {
+ deletion = await queries.accountDeletion.deleteAccountRows(finalDb, finalSnapshot)
+ } catch (error) {
+ const remaining = await queries.user.getUserInternal(getPrimaryDb(env.DB), userId)
+ if (remaining) throw error
+ await invalidateMachineTokens(machineTokens)
+ scheduleAfterCommit(env, executionContext, finalSnapshot, [])
+ return { kind: "deleted" }
+ }
+ if (!deletion.deleted) {
+ const remaining = await queries.user.getUserInternal(getPrimaryDb(env.DB), userId)
+ if (remaining) return { kind: "failed" }
+ }
+
+ await invalidateMachineTokens(machineTokens)
+ scheduleAfterCommit(env, executionContext, finalSnapshot, deletion.readStateRevisions)
+ return { kind: "deleted" }
+ } catch (error) {
+ log.warn("account_deletion_failed", {
+ errorCategory: error instanceof Error ? error.name : "NonError",
+ })
+ return { kind: "failed" }
+ }
+}
diff --git a/src/web/src/lib/account-deletion/provider-revocation.test.ts b/src/web/src/lib/account-deletion/provider-revocation.test.ts
new file mode 100644
index 000000000..82f2c6d58
--- /dev/null
+++ b/src/web/src/lib/account-deletion/provider-revocation.test.ts
@@ -0,0 +1,58 @@
+import { afterEach, describe, expect, it, vi } from "vitest"
+import { revokeProviderAccount } from "./provider-revocation"
+
+describe("account deletion provider revocation", () => {
+ afterEach(() => vi.unstubAllGlobals())
+
+ it("revokes Google with the refresh token", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 200 }))
+ vi.stubGlobal("fetch", fetchMock)
+
+ await revokeProviderAccount({ GITHUB_CLIENT_ID: "id", GITHUB_CLIENT_SECRET: "secret" }, {
+ providerId: "google",
+ accountId: "account",
+ accessToken: "access",
+ refreshToken: "refresh",
+ })
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ "https://oauth2.googleapis.com/revoke",
+ expect.objectContaining({ body: new URLSearchParams({ token: "refresh" }) }),
+ )
+ })
+
+ it("revokes GitHub with the access token and app credentials", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 204 }))
+ vi.stubGlobal("fetch", fetchMock)
+
+ await revokeProviderAccount({ GITHUB_CLIENT_ID: "client", GITHUB_CLIENT_SECRET: "secret" }, {
+ providerId: "github",
+ accountId: "account",
+ accessToken: "access",
+ refreshToken: "refresh",
+ })
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ "https://api.github.com/applications/client/grant",
+ expect.objectContaining({
+ method: "DELETE",
+ body: JSON.stringify({ access_token: "access" }),
+ }),
+ )
+ })
+
+ it("reports only the provider status when revocation fails", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 401 }))
+ vi.stubGlobal("fetch", fetchMock)
+
+ const failure = revokeProviderAccount({ GITHUB_CLIENT_ID: "client", GITHUB_CLIENT_SECRET: "secret" }, {
+ providerId: "github",
+ accountId: "account",
+ accessToken: "private-access-token",
+ refreshToken: null,
+ })
+
+ await expect(failure).rejects.toThrow("provider revocation returned 401")
+ await expect(failure).rejects.not.toThrow("private-access-token")
+ })
+})
diff --git a/src/web/src/lib/account-deletion/provider-revocation.ts b/src/web/src/lib/account-deletion/provider-revocation.ts
new file mode 100644
index 000000000..7d5367f4e
--- /dev/null
+++ b/src/web/src/lib/account-deletion/provider-revocation.ts
@@ -0,0 +1,45 @@
+import type { queries } from "@alook/shared"
+
+type Provider = queries.accountDeletion.AccountDeletionSnapshot["providers"][number]
+
+const PROVIDER_TIMEOUT_MS = 10_000
+
+async function providerFetch(url: string, init: RequestInit): Promise<void> {
+ const response = await fetch(url, {
+ ...init,
+ signal: AbortSignal.timeout(PROVIDER_TIMEOUT_MS),
+ })
+ if (!response.ok) throw new Error(`provider revocation returned ${response.status}`)
+}
+
+export async function revokeProviderAccount(
+ env: Pick<Env, "GITHUB_CLIENT_ID" | "GITHUB_CLIENT_SECRET">,
+ provider: Provider,
+): Promise<void> {
+ if (provider.providerId === "google") {
+ const token = provider.refreshToken ?? provider.accessToken
+ if (!token) return
+ await providerFetch("https://oauth2.googleapis.com/revoke", {
+ method: "POST",
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
+ body: new URLSearchParams({ token }),
+ })
+ return
+ }
+
+ if (provider.providerId === "github") {
+ if (!provider.accessToken) return
+ const credentials = btoa(`${env.GITHUB_CLIENT_ID}:${env.GITHUB_CLIENT_SECRET}`)
+ await providerFetch(`https://api.github.com/applications/${encodeURIComponent(env.GITHUB_CLIENT_ID)}/grant`, {
+ method: "DELETE",
+ headers: {
+ Accept: "application/vnd.github+json",
+ Authorization: `Basic ${credentials}`,
+ "Content-Type": "application/json",
+ "User-Agent": "Alook",
+ "X-GitHub-Api-Version": "2022-11-28",
+ },
+ body: JSON.stringify({ access_token: provider.accessToken }),
+ })
+ }
+}
diff --git a/src/web/src/lib/account-deletion/storage.test.ts b/src/web/src/lib/account-deletion/storage.test.ts
new file mode 100644
index 000000000..3f24ac3dd
--- /dev/null
+++ b/src/web/src/lib/account-deletion/storage.test.ts
@@ -0,0 +1,99 @@
+import { describe, expect, it, vi } from "vitest"
+import {
+ deleteAccountStorage,
+ exclusiveEmailAttachmentKeys,
+ listAccountDeletionPrefix,
+} from "./storage"
+
+describe("account deletion storage", () => {
+ it("keeps shared draft objects and rejects untrusted keys", () => {
+ expect(exclusiveEmailAttachmentKeys([
+ JSON.stringify([
+ { key: "emails/drafts/a/private.txt" },
+ { key: "emails/drafts/a/shared.txt" },
+ { key: "server-icon/foreign/value" },
+ { key: "emails/drafts/../foreign" },
+ ]),
+ ], [JSON.stringify([{ key: "emails/drafts/a/shared.txt" }])])).toEqual([
+ "emails/drafts/a/private.txt",
+ ])
+ })
+
+ it("paginates prefix listings", async () => {
+ const list = vi.fn()
+ .mockResolvedValueOnce({ objects: [{ key: "a/1" }], truncated: true, cursor: "next" })
+ .mockResolvedValueOnce({ objects: [{ key: "a/2" }], truncated: false })
+
+ await expect(listAccountDeletionPrefix({ list }, "a/")).resolves.toEqual(["a/1", "a/2"])
+ expect(list).toHaveBeenNthCalledWith(2, { prefix: "a/", cursor: "next" })
+ })
+
+ it("deletes all three bucket snapshots synchronously", async () => {
+ const mediaDelete = vi.fn().mockResolvedValue(undefined)
+ const emailDelete = vi.fn().mockResolvedValue(undefined)
+ const bugDelete = vi.fn().mockResolvedValue(undefined)
+ const env = {
+ COMMUNITY_MEDIA: {
+ list: vi.fn().mockResolvedValue({ objects: [{ key: "user-avatar/u/objects/old" }], truncated: false }),
+ delete: mediaDelete,
+ },
+ EMAIL_BUCKET: {
+ list: vi.fn().mockResolvedValue({ objects: [], truncated: false }),
+ delete: emailDelete,
+ },
+ BUG_REPORTS: {
+ list: vi.fn().mockResolvedValue({ objects: [], truncated: false }),
+ delete: bugDelete,
+ },
+ }
+ const snapshot = {
+ media: {
+ communityExactKeys: ["user-avatar/u"],
+ communityPrefixes: ["user-avatar/u/"],
+ emailExactKeys: ["emails/e/raw"],
+ emailPrefixes: [],
+ deletingEmailAttachments: [JSON.stringify([{ key: "emails/drafts/d/a.txt" }])],
+ survivingEmailAttachments: [],
+ bugReportExactKeys: ["bug-reports/u/r.gz"],
+ bugReportPrefixes: [],
+ },
+ } as Parameters<typeof deleteAccountStorage>[1]
+
+ await deleteAccountStorage(env as Parameters<typeof deleteAccountStorage>[0], snapshot)
+ expect(mediaDelete).toHaveBeenCalledWith([
+ "user-avatar/u",
+ "user-avatar/u/objects/old",
+ ])
+ expect(emailDelete).toHaveBeenCalledWith(["emails/e/raw", "emails/drafts/d/a.txt"])
+ expect(bugDelete).toHaveBeenCalledWith(["bug-reports/u/r.gz"])
+ })
+
+ it("aborts later buckets after a synchronous R2 failure", async () => {
+ const env = {
+ COMMUNITY_MEDIA: {
+ list: vi.fn().mockRejectedValue(new Error("unavailable")),
+ delete: vi.fn(),
+ },
+ EMAIL_BUCKET: { list: vi.fn(), delete: vi.fn() },
+ BUG_REPORTS: { list: vi.fn(), delete: vi.fn() },
+ }
+ const snapshot = {
+ media: {
+ communityExactKeys: [],
+ communityPrefixes: ["user-avatar/u/"],
+ emailExactKeys: [],
+ emailPrefixes: [],
+ deletingEmailAttachments: [],
+ survivingEmailAttachments: [],
+ bugReportExactKeys: [],
+ bugReportPrefixes: [],
+ },
+ } as Parameters<typeof deleteAccountStorage>[1]
+
+ await expect(deleteAccountStorage(
+ env as Parameters<typeof deleteAccountStorage>[0],
+ snapshot,
+ )).rejects.toThrow("unavailable")
+ expect(env.EMAIL_BUCKET.list).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/lib/account-deletion/storage.ts b/src/web/src/lib/account-deletion/storage.ts
new file mode 100644
index 000000000..bc4512796
--- /dev/null
+++ b/src/web/src/lib/account-deletion/storage.ts
@@ -0,0 +1,95 @@
+import type { queries } from "@alook/shared"
+import { deleteCommunityMediaObjects } from "@/lib/community/community-media-cleanup"
+
+type Snapshot = queries.accountDeletion.AccountDeletionSnapshot
+type DeletionBucket = Pick<R2Bucket, "delete" | "list">
+
+function attachmentKeys(rows: string[]): Set<string> {
+ const keys = new Set<string>()
+ for (const value of rows) {
+ try {
+ const parsed: unknown = JSON.parse(value)
+ if (!Array.isArray(parsed)) continue
+ for (const item of parsed) {
+ if (!item || typeof item !== "object" || !("key" in item)) continue
+ const key = item.key
+ if (
+ typeof key === "string"
+ && key.startsWith("emails/drafts/")
+ && !key.includes("..")
+ && !key.includes("\\")
+ ) {
+ keys.add(key)
+ }
+ }
+ } catch {}
+ }
+ return keys
+}
+
+export function exclusiveEmailAttachmentKeys(
+ deletingRows: string[],
+ survivingRows: string[],
+): string[] {
+ const deleting = attachmentKeys(deletingRows)
+ const surviving = attachmentKeys(survivingRows)
+ return [...deleting].filter((key) => !surviving.has(key))
+}
+
+export async function listAccountDeletionPrefix(
+ bucket: Pick<R2Bucket, "list">,
+ prefix: string,
+): Promise<string[]> {
+ const keys: string[] = []
+ let cursor: string | undefined
+ do {
+ const page = await bucket.list({ prefix, cursor })
+ keys.push(...page.objects.map((object) => object.key))
+ if (page.truncated) {
+ if (!page.cursor) throw new Error("R2 prefix listing returned no cursor")
+ cursor = page.cursor
+ } else {
+ cursor = undefined
+ }
+ } while (cursor)
+ return keys
+}
+
+async function deleteBucketSnapshot(
+ bucket: DeletionBucket,
+ exactKeys: string[],
+ prefixes: string[],
+): Promise<void> {
+ const listed: string[] = []
+ for (const prefix of prefixes) {
+ listed.push(...await listAccountDeletionPrefix(bucket, prefix))
+ }
+ await deleteCommunityMediaObjects(bucket, [...exactKeys, ...listed])
+}
+
+export async function deleteAccountStorage(
+ env: Pick<Env, "EMAIL_BUCKET" | "COMMUNITY_MEDIA" | "BUG_REPORTS">,
+ snapshot: Snapshot,
+): Promise<void> {
+ await deleteBucketSnapshot(
+ env.COMMUNITY_MEDIA,
+ snapshot.media.communityExactKeys,
+ snapshot.media.communityPrefixes,
+ )
+ await deleteBucketSnapshot(
+ env.EMAIL_BUCKET,
+ [
+ ...snapshot.media.emailExactKeys,
+ ...exclusiveEmailAttachmentKeys(
+ snapshot.media.deletingEmailAttachments,
+ snapshot.media.survivingEmailAttachments,
+ ),
+ ],
+ snapshot.media.emailPrefixes,
+ )
+ await deleteBucketSnapshot(
+ env.BUG_REPORTS,
+ snapshot.media.bugReportExactKeys,
+ snapshot.media.bugReportPrefixes,
+ )
+}
diff --git a/src/web/src/lib/api.test.ts b/src/web/src/lib/api.test.ts
index 4aeb86e88..ca6257617 100644
--- a/src/web/src/lib/api.test.ts
+++ b/src/web/src/lib/api.test.ts
@@ -1,5 +1,9 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { ApiError } from "./errors";
+import {
+ beginAccountDeletionAuthTransition,
+ cancelAccountDeletionAuthTransition,
+} from "./api/client";
// Mock window globals needed by apiFetch
Object.defineProperty(globalThis, "document", {
@@ -26,6 +30,7 @@ Object.defineProperty(globalThis, "window", {
beforeEach(() => {
vi.clearAllMocks();
+ cancelAccountDeletionAuthTransition();
});
describe("ApiError class", () => {
@@ -219,6 +224,24 @@ describe("apiFetch", () => {
expect(locationAssignMock).toHaveBeenCalledWith(new URL("/sign-in", "https://alook.test"));
}
});
+
+ it("does not let an in-flight 401 replace the account-deletion navigation", async () => {
+ mockFetch.mockResolvedValue({
+ ok: false,
+ status: 401,
+ json: async () => ({ error: "unauthorized" }),
+ });
+
+ const { listAgents } = await getApiFetch();
+ beginAccountDeletionAuthTransition();
+
+ await expect(listAgents("w1")).rejects.toMatchObject({ status: 401 });
+ expect(locationAssignMock).not.toHaveBeenCalled();
+
+ cancelAccountDeletionAuthTransition();
+ await expect(listAgents("w1")).rejects.toMatchObject({ status: 401 });
+ expect(locationAssignMock).toHaveBeenCalledWith(new URL("/sign-in", "https://alook.test"));
+ });
});
describe("conversationInit — message_count serialization", () => {
diff --git a/src/web/src/lib/api/client.ts b/src/web/src/lib/api/client.ts
index d455ab935..ef6f478d4 100644
--- a/src/web/src/lib/api/client.ts
+++ b/src/web/src/lib/api/client.ts
@@ -1,10 +1,20 @@
import { ApiError } from "@/lib/errors";
const API_BASE = "";
+export const ACCOUNT_DELETED_SIGN_IN_PATH = "/sign-in?account_deleted=1";
const MOCK_NETWORK_ENABLED = process.env.NODE_ENV === "development" && process.env.NEXT_PUBLIC_MOCK_NETWORK === "true";
const MOCK_NETWORK_DELAY_MS = parseInt(process.env.NEXT_PUBLIC_MOCK_NETWORK_DELAY_MS || "300", 10) || 300;
let mockNetworkLogged = false;
+let accountDeletionAuthTransition = false;
+
+export function beginAccountDeletionAuthTransition() {
+ accountDeletionAuthTransition = true;
+}
+
+export function cancelAccountDeletionAuthTransition() {
+ accountDeletionAuthTransition = false;
+}
function humanizeValidationDetail(detail: string): string {
const [rawField, ...rest] = detail.split(":");
@@ -44,6 +54,7 @@ function getReadableErrorMessage(error: string | undefined, details: string[] |
*/
export function redirectToSignIn() {
if (typeof window === "undefined") return;
+ if (accountDeletionAuthTransition) return;
window.location.assign(new URL("/sign-in", window.location.origin));
}
diff --git a/src/web/src/lib/auth.test.ts b/src/web/src/lib/auth.test.ts
index ccc8e4270..f48a96221 100644
--- a/src/web/src/lib/auth.test.ts
+++ b/src/web/src/lib/auth.test.ts
@@ -1,4 +1,4 @@
-import { describe, it, expect, vi, beforeEach } from "vitest"
+import { afterEach, describe, it, expect, vi, beforeEach } from "vitest"
vi.mock("better-auth", () => ({
betterAuth: vi.fn((opts: unknown) => ({ __options: opts })),
@@ -204,6 +204,44 @@ describe("createAuth rate limiting", () => {
})
})
+describe("sendOtpEmail", () => {
+ afterEach(() => vi.unstubAllGlobals())
+
+ it("falls back to the development email endpoint when the service binding rejects", async () => {
+ const internalFetch = vi.fn().mockRejectedValue(new Error("binding unavailable"))
+ const fallbackFetch = vi.fn().mockResolvedValue(new Response("ok", { status: 200 }))
+ vi.stubGlobal("fetch", fallbackFetch)
+ const { sendOtpEmail } = await import("./auth")
+ const env = makeEnv({ EMAIL_WORKER: { fetch: internalFetch } })
+
+ await sendOtpEmail(env as never, {
+ email: "[email protected]",
+ otp: "123456",
+ type: "account-deletion",
+ })
+
+ expect(fallbackFetch).toHaveBeenCalledWith(
+ "http://localhost:0/send/otp",
+ expect.objectContaining({ method: "POST" }),
+ )
+ })
+
+ it("reports a non-successful email-worker response", async () => {
+ const env = makeEnv({
+ EMAIL_WORKER: {
+ fetch: vi.fn().mockResolvedValue(new Response("worker down", { status: 503 })),
+ },
+ })
+ const { sendOtpEmail } = await import("./auth")
+
+ await expect(sendOtpEmail(env as never, {
+ email: "[email protected]",
+ otp: "123456",
+ type: "account-deletion",
+ })).rejects.toThrow("EMAIL_WORKER /send/otp failed: 503 worker down")
+ })
+})
+
describe("createAuth native OAuth handoff", () => {
it.each(["production", "development"])(
"configures a server-only hashed two-minute OTT in %s",
diff --git a/src/web/src/lib/auth.ts b/src/web/src/lib/auth.ts
index 744cf4dd6..1f68955c2 100644
--- a/src/web/src/lib/auth.ts
+++ b/src/web/src/lib/auth.ts
@@ -12,7 +12,7 @@ import {
} from "@alook/shared"
import { getDb } from "@/lib/db"
import { checkRateLimit } from "@/lib/rate-limit"
-import { getOtpSubject, renderOtpEmail } from "./email-templates"
+import { getOtpSubject, renderOtpEmail, type OtpType } from "./email-templates"
const log = createLogger({ service: "auth" })
@@ -27,14 +27,52 @@ function parsePositiveInt(raw: string | undefined, fallback: number): number {
return Number.isFinite(n) && n > 0 ? n : fallback
}
+export function getAuthOtpRateLimitPolicy(env: Env): { max: number; windowMs: number } {
+ return {
+ max: parsePositiveInt(env.AUTH_OTP_RATE_LIMIT_MAX, DEFAULT_OTP_RATE_LIMIT_MAX),
+ windowMs: parsePositiveInt(
+ env.AUTH_OTP_RATE_LIMIT_WINDOW_SEC,
+ DEFAULT_OTP_RATE_LIMIT_WINDOW_SEC,
+ ) * 1000,
+ }
+}
+
+export async function sendOtpEmail(
+ env: Env,
+ input: { email: string; otp: string; type: OtpType },
+): Promise<void> {
+ log.info("sending OTP email", { to: input.email, type: input.type })
+ try {
+ const fetchOptions = {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ to: input.email,
+ subject: getOtpSubject(input.type),
+ html: renderOtpEmail(input.otp, input.type),
+ }),
+ }
+ let response: Response
+ try {
+ response = await env.EMAIL_WORKER.fetch("http://internal/send/otp", fetchOptions)
+ } catch {
+ response = await fetch(`${DEV_EMAIL_WORKER_URL}/send/otp`, fetchOptions)
+ }
+ if (!response.ok) {
+ const errorBody = await response.text()
+ throw new Error(`EMAIL_WORKER /send/otp failed: ${response.status} ${errorBody}`)
+ }
+ log.info("OTP email sent", { to: input.email, type: input.type })
+ } catch (error) {
+ log.error("OTP email failed", { to: input.email, type: input.type, error })
+ throw error
+ }
+}
+
export function createAuth(env: Env) {
const mode = resolveMode({ nodeEnv: env.NODE_ENV ?? process.env.NODE_ENV })
const isProd = mode === "production"
- const otpMax = parsePositiveInt(env.AUTH_OTP_RATE_LIMIT_MAX, DEFAULT_OTP_RATE_LIMIT_MAX)
- const otpWindow = parsePositiveInt(
- env.AUTH_OTP_RATE_LIMIT_WINDOW_SEC,
- DEFAULT_OTP_RATE_LIMIT_WINDOW_SEC,
- )
+ const otpPolicy = getAuthOtpRateLimitPolicy(env)
const validateClient = (clientId: string) => {
const allowed = (env.DEVICE_CLIENT_IDS || "").split(",").map((s) => s.trim()).filter(Boolean)
return allowed.includes(clientId)
@@ -234,8 +272,8 @@ export function createAuth(env: Env) {
// (the sender's target); anyone attempting to spam a
// specific inbox gets throttled per inbox.
const rate = await checkRateLimit(env, "auth:otpSend", email, {
- windowMs: otpWindow * 1000,
- max: otpMax,
+ windowMs: otpPolicy.windowMs,
+ max: otpPolicy.max,
})
if (!rate.allowed) {
log.warn("OTP send rate-limited", {
@@ -244,33 +282,7 @@ export function createAuth(env: Env) {
})
throw new Error(`OTP rate limit; retry in ${rate.retryAfterSec}s`)
}
- log.info("sending OTP email", { to: email, type })
- try {
- const otpPayload = JSON.stringify({
- to: email,
- subject: getOtpSubject(type),
- html: renderOtpEmail(otp, type),
- })
- const fetchOpts = {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: otpPayload,
- }
- let res: Response
- try {
- res = await env.EMAIL_WORKER.fetch("http://internal/send/otp", fetchOpts)
- } catch {
- res = await fetch(`${DEV_EMAIL_WORKER_URL}/send/otp`, fetchOpts)
- }
- if (!res.ok) {
- const errBody = await res.text()
- throw new Error(`EMAIL_WORKER /send/otp failed: ${res.status} ${errBody}`)
- }
- log.info("OTP email sent", { to: email, type })
- } catch (err) {
- log.error("OTP email failed", { to: email, type, err })
- throw err
- }
+ await sendOtpEmail(env, { email, otp, type })
},
}),
]
diff --git a/src/web/src/lib/community/testids.test.ts b/src/web/src/lib/community/testids.test.ts
index 2e73bcd47..b79d6dcb3 100644
--- a/src/web/src/lib/community/testids.test.ts
+++ b/src/web/src/lib/community/testids.test.ts
@@ -6,6 +6,15 @@ describe("community QA selectors", () => {
expect(tid.settingsWebVersion).toBe("community-settings-web-version")
})
+ it("exposes the account-deletion journey from the canonical registry", () => {
+ expect(tid.accountDeletionOpen).toBe("community-account-deletion-open")
+ expect(tid.accountDeletionFlow).toBe("community-account-deletion-flow")
+ expect(tid.accountDeletionSendCode).toBe("community-account-deletion-send-code")
+ expect(tid.accountDeletionOtp).toBe("community-account-deletion-otp")
+ expect(tid.accountDeletionSubmit).toBe("community-account-deletion-submit")
+ expect(tid.accountDeletionComplete).toBe("community-account-deletion-complete")
+ })
+
it("exposes the global reconnect overlay independently from its Retry action", () => {
expect(tid.wsReconnectOverlay).toBe("community-ws-reconnect-overlay")
expect(tid.wsRetry).toBe("community-ws-retry")
diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.ts
index 0561b6097..c9402e4ed 100644
--- a/src/web/src/lib/community/testids.ts
+++ b/src/web/src/lib/community/testids.ts
@@ -37,6 +37,12 @@ export const tid = {
settingsClose: "community-settings-close",
settingsLabel: "community-settings-label",
settingsWebVersion: "community-settings-web-version",
+ accountDeletionOpen: "community-account-deletion-open",
+ accountDeletionFlow: "community-account-deletion-flow",
+ accountDeletionSendCode: "community-account-deletion-send-code",
+ accountDeletionOtp: "community-account-deletion-otp",
+ accountDeletionSubmit: "community-account-deletion-submit",
+ accountDeletionComplete: "community-account-deletion-complete",
settingsTab: (value: string) => `community-settings-tab-${value}`,
userSettingsOpen: "community-user-settings-open",
serverSettingsOpen: "community-server-settings-open",
diff --git a/src/web/src/lib/email-templates.test.ts b/src/web/src/lib/email-templates.test.ts
index 3a1dbff4f..01acfd6bc 100644
--- a/src/web/src/lib/email-templates.test.ts
+++ b/src/web/src/lib/email-templates.test.ts
@@ -6,6 +6,7 @@ const otpTypes = [
"email-verification",
"forget-password",
"change-email",
+ "account-deletion",
] as const
describe("getOtpSubject", () => {
diff --git a/src/web/src/lib/email-templates.ts b/src/web/src/lib/email-templates.ts
index beee1ee8d..0bdeca126 100644
--- a/src/web/src/lib/email-templates.ts
+++ b/src/web/src/lib/email-templates.ts
@@ -1,14 +1,16 @@
-type OtpType =
+export type OtpType =
| "sign-in"
| "email-verification"
| "forget-password"
| "change-email"
+ | "account-deletion"
const subjectByType: Record<OtpType, string> = {
"sign-in": "Your Alook sign-in code",
"email-verification": "Verify your Alook email",
"forget-password": "Reset your Alook password",
"change-email": "Confirm your new email address",
+ "account-deletion": "Your Alook account deletion code",
}
const headingByType: Record<OtpType, string> = {
@@ -16,6 +18,7 @@ const headingByType: Record<OtpType, string> = {
"email-verification": "Verify your email",
"forget-password": "Reset your password",
"change-email": "Confirm email change",
+ "account-deletion": "Delete your Alook account",
}
const descriptionByType: Record<OtpType, string> = {
@@ -23,6 +26,7 @@ const descriptionByType: Record<OtpType, string> = {
"email-verification": "Enter this code to verify your email address.",
"forget-password": "Enter this code to reset your password.",
"change-email": "Enter this code to confirm your new email address.",
+ "account-deletion": "Enter this code in User Settings to permanently delete your account.",
}
export function getOtpSubject(type: OtpType): string {
diff --git a/src/web/src/lib/middleware/auth.test.ts b/src/web/src/lib/middleware/auth.test.ts
index 3bab2c49a..c94ce30ea 100644
--- a/src/web/src/lib/middleware/auth.test.ts
+++ b/src/web/src/lib/middleware/auth.test.ts
@@ -3,10 +3,13 @@ import { NextRequest, NextResponse } from "next/server";
import { getCloudflareContext } from "@opennextjs/cloudflare";
vi.mock("@opennextjs/cloudflare", () => ({
- getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),
+ getCloudflareContext: vi.fn(async () => ({ env: { DB: {} }, ctx: { waitUntil: vi.fn() } })),
}));
-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+vi.mock("@/lib/db", () => ({
+ getDb: vi.fn(() => ({})),
+ getPrimaryDb: vi.fn(() => ({ primary: true })),
+}));
vi.mock("@alook/shared", () => ({
createDb: vi.fn(() => ({})),
@@ -15,6 +18,9 @@ vi.mock("@alook/shared", () => ({
getMachineTokenByToken: vi.fn(),
updateMachineTokenLastUsed: vi.fn(),
},
+ user: {
+ getUserInternal: vi.fn(),
+ },
},
}));
@@ -25,13 +31,14 @@ vi.mock("@/lib/auth", () => ({
})),
}));
-import { withAuth, withOptionalAuth, warmMachineTokenCache } from "./auth";
+import { withAuth, withCookieHumanAuth, withOptionalAuth, warmMachineTokenCache } from "./auth";
import { queries } from "@alook/shared";
const mockGetMachineTokenByHash = queries.machineToken
.getMachineTokenByToken as ReturnType<typeof vi.fn>;
const mockUpdateMachineTokenLastUsed = queries.machineToken
.updateMachineTokenLastUsed as ReturnType<typeof vi.fn>;
+const mockGetUserInternal = queries.user.getUserInternal as ReturnType<typeof vi.fn>;
const mockGetCloudflareContext = getCloudflareContext as unknown as ReturnType<typeof vi.fn>;
/** Build a stub KV and point the CF context at it for one test. */
@@ -41,7 +48,7 @@ function bindMockKV(overrides?: { get?: ReturnType<typeof vi.fn> }) {
put: vi.fn().mockResolvedValue(undefined),
delete: vi.fn().mockResolvedValue(undefined),
};
- mockGetCloudflareContext.mockResolvedValue({ env: { DB: {}, CACHE_KV: kv } });
+ mockGetCloudflareContext.mockResolvedValue({ env: { DB: {}, CACHE_KV: kv }, ctx: { waitUntil: vi.fn() } });
return kv;
}
@@ -53,7 +60,7 @@ describe("withAuth middleware", () => {
beforeEach(() => {
vi.clearAllMocks();
// Default: no KV bound (cold-path every request), matching original tests.
- mockGetCloudflareContext.mockResolvedValue({ env: { DB: {} } });
+ mockGetCloudflareContext.mockResolvedValue({ env: { DB: {} }, ctx: { waitUntil: vi.fn() } });
});
const wrapped = withAuth(testHandler);
@@ -355,7 +362,7 @@ describe("withAuth middleware", () => {
describe("withOptionalAuth middleware", () => {
beforeEach(() => {
vi.clearAllMocks();
- mockGetCloudflareContext.mockResolvedValue({ env: { DB: {} } });
+ mockGetCloudflareContext.mockResolvedValue({ env: { DB: {} }, ctx: { waitUntil: vi.fn() } });
});
const wrapped = withOptionalAuth(testHandler);
@@ -457,6 +464,260 @@ describe("withOptionalAuth middleware", () => {
});
});
+describe("withCookieHumanAuth middleware", () => {
+ const wrapped = withCookieHumanAuth(testHandler);
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockGetCloudflareContext.mockResolvedValue({
+ env: { DB: {} },
+ ctx: { waitUntil: vi.fn() },
+ });
+ mockGetSession.mockResolvedValue({
+ headers: new Headers(),
+ response: { user: { id: "user-1", email: "[email protected]" } },
+ });
+ mockGetUserInternal.mockResolvedValue({
+ id: "user-1",
+ email: "[email protected]",
+ isBot: false,
+ deletedAt: null,
+ });
+ });
+
+ it("requires a same-origin POST before resolving the session", async () => {
+ const req = new NextRequest("https://alook.ai/api/test", {
+ method: "POST",
+ headers: { Origin: "https://evil.example" },
+ });
+
+ const res = await wrapped(req);
+
+ expect(res.status).toBe(403);
+ expect(await res.json()).toEqual({ error: "FORBIDDEN" });
+ expect(mockGetSession).not.toHaveBeenCalled();
+ });
+
+ it("accepts the exact preserved localhost Host through the development ingress", async () => {
+ const req = new NextRequest("http://127.0.0.1:3001/api/test", {
+ method: "POST",
+ headers: {
+ Host: "localhost:3000",
+ Origin: "http://localhost:3000",
+ "X-Forwarded-Host": "localhost:3000",
+ },
+ });
+
+ const res = await wrapped(req);
+
+ expect(res.status).toBe(200);
+ expect(testHandler).toHaveBeenCalledOnce();
+ });
+
+ it("rejects a mismatched Host and a non-loopback internal target", async () => {
+ for (const req of [
+ new NextRequest("http://127.0.0.1:3001/api/test", {
+ method: "POST",
+ headers: { Host: "evil.example", Origin: "http://localhost:3000" },
+ }),
+ new NextRequest("http://internal.example/api/test", {
+ method: "POST",
+ headers: { Host: "localhost:3000", Origin: "http://localhost:3000" },
+ }),
+ ]) {
+ const res = await wrapped(req);
+ expect(res.status).toBe(403);
+ }
+ expect(mockGetSession).not.toHaveBeenCalled();
+ });
+
+ it("rejects a malformed Origin without throwing", async () => {
+ const req = new NextRequest("http://127.0.0.1:3001/api/test", {
+ method: "POST",
+ headers: { Host: "localhost:3000", Origin: "not-an-origin" },
+ });
+
+ const res = await wrapped(req);
+
+ expect(res.status).toBe(403);
+ expect(mockGetSession).not.toHaveBeenCalled();
+ });
+
+ it("distinguishes an absent cookie from transient session validation failure", async () => {
+ const req = new NextRequest("https://alook.ai/api/test", {
+ method: "POST",
+ headers: { Origin: "https://alook.ai" },
+ });
+ mockGetSession.mockResolvedValueOnce({ headers: new Headers(), response: null });
+ const absent = await wrapped(req);
+ expect(absent.status).toBe(401);
+ expect(await absent.json()).toEqual({ error: "UNAUTHORIZED" });
+
+ mockGetSession.mockRejectedValue(new Error("auth unavailable"));
+ const transient = await wrapped(req);
+ expect(transient.status).toBe(503);
+ expect(await transient.json()).toEqual({ error: "SESSION_VALIDATION_FAILED" });
+ });
+
+ it("rejects an al_ bearer even when a browser cookie could also resolve", async () => {
+ const req = new NextRequest("https://alook.ai/api/test", {
+ method: "POST",
+ headers: {
+ Origin: "https://alook.ai",
+ Authorization: "Bearer al_machine_token",
+ },
+ });
+
+ const res = await wrapped(req);
+
+ expect(res.status).toBe(401);
+ expect(await res.json()).toEqual({ error: "UNAUTHORIZED" });
+ expect(mockGetSession).not.toHaveBeenCalled();
+ expect(mockGetMachineTokenByHash).not.toHaveBeenCalled();
+ });
+
+ it("rejects a Better Auth bearer because deletion is cookie-session only", async () => {
+ const req = new NextRequest("https://alook.ai/api/test", {
+ method: "POST",
+ headers: {
+ Origin: "https://alook.ai",
+ Authorization: "Bearer browser_session_token",
+ },
+ });
+
+ const res = await wrapped(req);
+
+ expect(res.status).toBe(401);
+ expect(await res.json()).toEqual({ error: "UNAUTHORIZED" });
+ expect(mockGetSession).not.toHaveBeenCalled();
+ });
+
+ it("uses the live primary human row and passes the execution context", async () => {
+ const waitUntil = vi.fn();
+ mockGetCloudflareContext.mockResolvedValue({ env: { DB: {} }, ctx: { waitUntil } });
+ const req = new NextRequest("https://alook.ai/api/test", {
+ method: "POST",
+ headers: { Origin: "https://alook.ai" },
+ });
+
+ const res = await wrapped(req);
+ const body = await res.json();
+
+ expect(res.status).toBe(200);
+ expect(mockGetUserInternal).toHaveBeenCalledWith({ primary: true }, "user-1");
+ expect(body.ctx.email).toBe("[email protected]");
+ expect(body.ctx.executionContext).toEqual({});
+ });
+
+ it("forwards both direct and promised route params", async () => {
+ const request = () => new NextRequest("https://alook.ai/api/test", {
+ method: "POST",
+ headers: { Origin: "https://alook.ai" },
+ });
+
+ const direct = await wrapped(request(), { params: { source: "direct" } });
+ expect((await direct.json()).ctx.params).toEqual({ source: "direct" });
+
+ const promised = await wrapped(request(), {
+ params: Promise.resolve({ source: "promised" }),
+ });
+ expect((await promised.json()).ctx.params).toEqual({ source: "promised" });
+ });
+
+ it("returns 503 when the primary live-user lookup fails", async () => {
+ mockGetUserInternal.mockRejectedValue(new Error("primary down"));
+ const req = new NextRequest("https://alook.ai/api/test", {
+ method: "POST",
+ headers: { Origin: "https://alook.ai" },
+ });
+
+ const res = await wrapped(req);
+
+ expect(res.status).toBe(503);
+ expect(await res.json()).toEqual({ error: "SESSION_VALIDATION_FAILED" });
+ expect(testHandler).not.toHaveBeenCalled();
+ });
+
+ it("rejects a bot or deleted live row and clears auth cookies", async () => {
+ mockGetUserInternal.mockResolvedValue({
+ id: "bot-1",
+ email: "[email protected]",
+ isBot: true,
+ deletedAt: null,
+ });
+ const req = new NextRequest("https://alook.ai/api/test", {
+ method: "POST",
+ headers: { Origin: "https://alook.ai" },
+ });
+
+ const res = await wrapped(req);
+
+ expect(res.status).toBe(401);
+ expect(res.headers.getSetCookie()).toHaveLength(4);
+ expect(testHandler).not.toHaveBeenCalled();
+ });
+
+ it("rejects a bot in the signed session before the live lookup and clears auth cookies", async () => {
+ mockGetSession.mockResolvedValue({
+ headers: new Headers(),
+ response: { user: { id: "bot-1", email: "[email protected]", isBot: true, deletedAt: null } },
+ });
+ const req = new NextRequest("https://alook.ai/api/test", {
+ method: "POST",
+ headers: { Origin: "https://alook.ai" },
+ });
+
+ const res = await wrapped(req);
+
+ expect(res.status).toBe(401);
+ expect(res.headers.getSetCookie()).toHaveLength(4);
+ expect(mockGetUserInternal).not.toHaveBeenCalled();
+ expect(testHandler).not.toHaveBeenCalled();
+ });
+
+ it("forwards Better Auth cookie refresh headers", async () => {
+ const headers = new Headers();
+ headers.append("Set-Cookie", "better-auth.session_data=fresh; Path=/");
+ mockGetSession.mockResolvedValue({
+ headers,
+ response: { user: { id: "user-1", email: "[email protected]" } },
+ });
+ const req = new NextRequest("https://alook.ai/api/test", {
+ method: "POST",
+ headers: { Origin: "https://alook.ai" },
+ });
+
+ const res = await wrapped(req);
+
+ expect(res.headers.getSetCookie()).toContain("better-auth.session_data=fresh; Path=/");
+ });
+
+ it("does not reissue a session cookie that the handler explicitly clears", async () => {
+ const headers = new Headers();
+ headers.append("Set-Cookie", "better-auth.session_data=fresh; Path=/");
+ mockGetSession.mockResolvedValue({
+ headers,
+ response: { user: { id: "user-1", email: "[email protected]" } },
+ });
+ const deletingHandler = vi.fn(async () => {
+ const response = NextResponse.json({ ok: true });
+ response.cookies.set("better-auth.session_data", "", { maxAge: 0, path: "/" });
+ return response;
+ });
+ const req = new NextRequest("https://alook.ai/api/test", {
+ method: "POST",
+ headers: { Origin: "https://alook.ai" },
+ });
+
+ const res = await withCookieHumanAuth(deletingHandler)(req);
+ const cookies = res.headers.getSetCookie();
+
+ expect(cookies).not.toContain("better-auth.session_data=fresh; Path=/");
+ expect(cookies.filter((cookie) => cookie.startsWith("better-auth.session_data=")))
+ .toHaveLength(1);
+ });
+});
+
describe("warmMachineTokenCache", () => {
beforeEach(() => vi.clearAllMocks());
diff --git a/src/web/src/lib/middleware/auth.ts b/src/web/src/lib/middleware/auth.ts
index bec55a5b4..b7e935ef8 100644
--- a/src/web/src/lib/middleware/auth.ts
+++ b/src/web/src/lib/middleware/auth.ts
@@ -1,7 +1,7 @@
import { NextRequest, NextResponse } from "next/server"
import { getCloudflareContext } from "@opennextjs/cloudflare"
import { queries } from "@alook/shared"
-import { getDb } from "@/lib/db"
+import { getDb, getPrimaryDb } from "@/lib/db"
import { createAuth } from "@/lib/auth"
import { getKV, cacheKeys, bindCacheKV } from "@/lib/cache"
@@ -20,6 +20,10 @@ export interface AuthContext {
user?: { isBot: boolean }
}
+interface CookieHumanAuthContext extends AuthContext {
+ executionContext: ExecutionContext
+}
+
/**
* Context for a `withOptionalAuth` handler: identical to `AuthContext` but
* `userId`/`email` are OPTIONAL — absent when the caller is anonymous (no
@@ -97,6 +101,11 @@ export type OptionalAuthHandler = (
ctx: OptionalAuthContext & { params?: Record<string, string> }
) => Promise<NextResponse | Response>
+export type CookieHumanAuthHandler = (
+ req: NextRequest,
+ ctx: CookieHumanAuthContext & { params?: Record<string, string> },
+) => Promise<NextResponse | Response>
+
/**
* Outcome of resolving a Better-Auth cookie session. Shared by `withAuth`
* (which turns everything but `ok` into a 401/503) and `withOptionalAuth`
@@ -189,6 +198,124 @@ function clearAuthCookies(res: NextResponse): void {
res.cookies.set("better-auth.session_data", "", { maxAge: 0, path: "/" })
}
+function clearCookieHumanAuthCookies(res: NextResponse): void {
+ clearAuthCookies(res)
+ res.cookies.set("__Secure-better-auth.session_token", "", {
+ maxAge: 0,
+ path: "/",
+ secure: true,
+ })
+ res.cookies.set("__Secure-better-auth.session_data", "", {
+ maxAge: 0,
+ path: "/",
+ secure: true,
+ })
+}
+
+function forwardSetCookies(res: NextResponse | Response, setCookies: string[]): NextResponse | Response {
+ if (setCookies.length === 0) return res
+ const cookieName = (cookie: string) => cookie.split("=", 1)[0].trim().toLowerCase()
+ const responseCookieNames = new Set(res.headers.getSetCookie().map(cookieName))
+ const forwarded = setCookies.filter((cookie) => !responseCookieNames.has(cookieName(cookie)))
+ if (forwarded.length === 0) return res
+ const mutableRes = new NextResponse(res.body, res)
+ for (const cookie of forwarded) mutableRes.headers.append("Set-Cookie", cookie)
+ return mutableRes
+}
+
+function accountDeletionAuthError(error: string, status: number): NextResponse {
+ return NextResponse.json(
+ { error },
+ {
+ status,
+ headers: { "Cache-Control": "no-store, max-age=0" },
+ },
+ )
+}
+
+function isLoopbackHostname(hostname: string): boolean {
+ return hostname === "localhost"
+ || hostname === "127.0.0.1"
+ || hostname === "[::1]"
+}
+
+function isCookieHumanSameOrigin(req: NextRequest): boolean {
+ const originHeader = req.headers.get("Origin")
+ if (!originHeader) return false
+ let originUrl: URL
+ try {
+ originUrl = new URL(originHeader)
+ } catch {
+ return false
+ }
+ if (originHeader !== originUrl.origin) return false
+ const requestUrl = new URL(req.url)
+ if (originUrl.origin === requestUrl.origin) return true
+ return isLoopbackHostname(originUrl.hostname)
+ && isLoopbackHostname(requestUrl.hostname)
+ && req.headers.get("Host") === originUrl.host
+}
+
+export function withCookieHumanAuth(handler: CookieHumanAuthHandler) {
+ return async (
+ req: NextRequest,
+ context?: { params?: Promise<Record<string, string>> | Record<string, string> },
+ ) => {
+ const resolvedParams = context?.params
+ ? context.params instanceof Promise
+ ? await context.params
+ : context.params
+ : undefined
+ if (req.method !== "POST" || !isCookieHumanSameOrigin(req)) {
+ return accountDeletionAuthError("FORBIDDEN", 403)
+ }
+ if (req.headers.has("Authorization")) {
+ return accountDeletionAuthError("UNAUTHORIZED", 401)
+ }
+
+ const cloudflare = await getCloudflareContext({ async: true })
+ const cloudflareEnv = cloudflare.env as Env
+ bindCacheKV(cloudflareEnv.CACHE_KV ?? null)
+ const resolved = await resolveSession(req, cloudflareEnv)
+ if (resolved.kind === "error") {
+ return accountDeletionAuthError("SESSION_VALIDATION_FAILED", 503)
+ }
+ if (resolved.kind === "none") {
+ return accountDeletionAuthError("UNAUTHORIZED", 401)
+ }
+ if (resolved.kind === "invalid") {
+ const response = accountDeletionAuthError("UNAUTHORIZED", 401)
+ clearCookieHumanAuthCookies(response)
+ return response
+ }
+
+ let liveUser: Awaited<ReturnType<typeof queries.user.getUserInternal>>
+ try {
+ liveUser = await queries.user.getUserInternal(
+ getPrimaryDb(cloudflareEnv.DB),
+ resolved.user.id,
+ )
+ } catch {
+ return accountDeletionAuthError("SESSION_VALIDATION_FAILED", 503)
+ }
+ if (!liveUser || liveUser.isBot || liveUser.deletedAt !== null) {
+ const response = accountDeletionAuthError("UNAUTHORIZED", 401)
+ clearCookieHumanAuthCookies(response)
+ return response
+ }
+
+ const response = await handler(req, {
+ env: cloudflareEnv,
+ executionContext: cloudflare.ctx,
+ userId: liveUser.id,
+ email: liveUser.email,
+ user: { isBot: false },
+ params: resolvedParams,
+ })
+ return forwardSetCookies(response, resolved.setCookies)
+ }
+}
+
export function withAuth(handler: AuthenticatedHandler) {
return async (
req: NextRequest,
@@ -313,15 +440,7 @@ export function withAuth(handler: AuthenticatedHandler) {
const res = await handler(req, { ...authCtx, params: resolvedParams })
// Forward Set-Cookie headers from Better Auth to refresh session_data cookie cache
- if (session.setCookies.length > 0) {
- const mutableRes = new NextResponse(res.body, res)
- for (const cookie of session.setCookies) {
- mutableRes.headers.append("Set-Cookie", cookie)
- }
- return mutableRes
- }
-
- return res
+ return forwardSetCookies(res, session.setCookies)
}
}
@@ -382,14 +501,6 @@ export function withOptionalAuth(handler: OptionalAuthHandler) {
const res = await handler(req, { ...authCtx, params: resolvedParams })
// Forward Set-Cookie headers from Better Auth to refresh session_data cookie cache
- if (session.setCookies.length > 0) {
- const mutableRes = new NextResponse(res.body, res)
- for (const cookie of session.setCookies) {
- mutableRes.headers.append("Set-Cookie", cookie)
- }
- return mutableRes
- }
-
- return res
+ return forwardSetCookies(res, session.setCookies)
}
}
diff --git a/src/web/src/test/architecture/account-deletion-minimal-contract.test.ts b/src/web/src/test/architecture/account-deletion-minimal-contract.test.ts
new file mode 100644
index 000000000..8f2bf2e85
--- /dev/null
+++ b/src/web/src/test/architecture/account-deletion-minimal-contract.test.ts
@@ -0,0 +1,53 @@
+import { readFileSync, readdirSync } from "node:fs"
+import { resolve } from "node:path"
+import { describe, expect, it } from "vitest"
+
+const root = resolve(import.meta.dirname, "../../..")
+const source = (path: string) => readFileSync(resolve(root, path), "utf8")
+
+describe("minimal account deletion architecture", () => {
+ it("adds exactly two cookie-authenticated user APIs", () => {
+ const apiRoot = resolve(root, "src/app/api/community/users/me/account-deletion")
+ expect(readdirSync(apiRoot, { recursive: true })
+ .filter((entry) => String(entry).endsWith("route.ts"))
+ .sort()).toEqual(["code/route.ts", "route.ts"])
+ for (const route of [
+ "src/app/api/community/users/me/account-deletion/code/route.ts",
+ "src/app/api/community/users/me/account-deletion/route.ts",
+ ]) {
+ expect(source(route)).toContain("withCookieHumanAuth")
+ }
+ })
+
+ it("uses existing persistence and bindings without a migration or workflow", () => {
+ const migrations = readdirSync(resolve(root, "migrations"))
+ expect(migrations.some((file) => file.includes("account_deletion"))).toBe(false)
+ const files = [
+ "src/lib/account-deletion/challenge.ts",
+ "src/lib/account-deletion/storage.ts",
+ "src/lib/account-deletion/execution.ts",
+ "../shared/src/db/queries/account-deletion.ts",
+ ].map(source).join("\n")
+ expect(files).toContain("verification")
+ expect(files).toContain("EMAIL_BUCKET")
+ expect(files).toContain("COMMUNITY_MEDIA")
+ expect(files).toContain("BUG_REPORTS")
+ expect(files).not.toContain("WorkflowEntrypoint")
+ expect(files).not.toContain("scheduled(")
+ })
+
+ it("requires an explicit final click after all six OTP digits", () => {
+ const flow = source("src/components/community/settings/account-deletion-flow.tsx")
+ expect(flow).toContain('onClick={deleteAccount}')
+ expect(flow).not.toContain("onComplete=")
+ expect(flow).toContain('variant="destructive"')
+ })
+
+ it("keeps the completion state in the sign-in URL across reloads", () => {
+ const signIn = source("src/app/(auth)/sign-in/sign-in-client.tsx")
+ expect(signIn).toContain('searchParams.get("account_deleted") === "1"')
+ expect(signIn).toContain("Account deleted")
+ expect(signIn).toContain("Your account and its data were removed.")
+ expect(signIn).toContain("data-testid={tid.accountDeletionComplete}")
+ })
+})
diff --git a/src/web/test-runtime/account-deletion-minimal.runtime.test.ts b/src/web/test-runtime/account-deletion-minimal.runtime.test.ts
new file mode 100644
index 000000000..dea941d1a
--- /dev/null
+++ b/src/web/test-runtime/account-deletion-minimal.runtime.test.ts
@@ -0,0 +1,241 @@
+/// <reference types="@cloudflare/vitest-plugin/types" />
+
+import { env } from "cloudflare:workers"
+import { afterEach, describe, expect, it } from "vitest"
+import { createDb, queries } from "@alook/shared"
+
+const runtimeEnv = env as unknown as CloudflareEnv
+const survivors: string[] = []
+const survivingChannels: string[] = []
+const survivingWorkspaces: string[] = []
+
+async function run(statement: string, ...bindings: unknown[]): Promise<void> {
+ await runtimeEnv.DB.prepare(statement).bind(...bindings).run()
+}
+
+async function first<T>(statement: string, ...bindings: unknown[]): Promise<T | null> {
+ return runtimeEnv.DB.prepare(statement).bind(...bindings).first<T>()
+}
+
+afterEach(async () => {
+ for (const channelId of survivingChannels.splice(0)) {
+ await run("DELETE FROM community_channel WHERE id = ?", channelId)
+ }
+ for (const workspaceId of survivingWorkspaces.splice(0)) {
+ await run("DELETE FROM workspace WHERE id = ?", workspaceId)
+ }
+ for (const userId of survivors.splice(0)) {
+ await run("DELETE FROM user WHERE id = ?", userId)
+ }
+})
+
+describe("minimal account deletion real D1 batch", () => {
+ it("clears blockers and repairs a surviving channel read pointer atomically", async () => {
+ const stamp = crypto.randomUUID().replaceAll("-", "")
+ const owner = `adm_owner_${stamp}`
+ const bot = `adm_bot_${stamp}`
+ const reader = `adm_reader_${stamp}`
+ const earlyReader = `adm_early_reader_${stamp}`
+ const dm = `adm_dm_${stamp}`
+ const prior = `adm_prior_${stamp}`
+ const authored = `adm_authored_${stamp}`
+ const botAuthored = `adm_bot_authored_${stamp}`
+ const workspace = `adm_workspace_${stamp}`
+ const sharedWorkspace = `adm_shared_workspace_${stamp}`
+ const daemon = `adm_daemon_${stamp}`
+ const ownerMachineToken = `al_owner_${stamp}`
+ const workspaceMachineToken = `al_workspace_${stamp}`
+ const runtime = `adm_runtime_${stamp}`
+ const survivingAgent = `adm_surviving_agent_${stamp}`
+ const ownedSharedAgent = `adm_owned_shared_agent_${stamp}`
+ const deletingEmail = `adm_deleting_email_${stamp}`
+ const survivingEmail = `adm_surviving_email_${stamp}`
+ const sharedDraftKey = `emails/drafts/${stamp}/shared.txt`
+ const privateDraftKey = `emails/drafts/${stamp}/private.txt`
+ const server = `adm_server_${stamp}`
+ const serverChannel = `adm_server_channel_${stamp}`
+ const forum = `adm_forum_${stamp}`
+ const opener = `adm_opener_${stamp}`
+ const thread = `adm_thread_${stamp}`
+ const reply = `adm_reply_${stamp}`
+ const threadAttachment = `adm_thread_attachment_${stamp}`
+ const pendingServerAttachment = `adm_pending_server_attachment_${stamp}`
+ const pendingThreadAttachment = `adm_pending_thread_attachment_${stamp}`
+ const pendingServerAttachmentKey = `community/pending-server/${stamp}`
+ const pendingThreadAttachmentKey = `community/pending-thread/${stamp}`
+ const now = "2026-09-08T00:00:00.000Z"
+ survivors.push(reader, earlyReader)
+ survivingChannels.push(dm, forum)
+ survivingWorkspaces.push(sharedWorkspace)
+
+ await run(
+ "INSERT INTO user (id, email, name, discriminator) VALUES (?, ?, 'Owner', '8101'), (?, ?, 'Bot', '8102'), (?, ?, 'Reader', '8103'), (?, ?, 'Early reader', '8105')",
+ owner, `${owner}@example.com`, bot, `${bot}@example.com`, reader, `${reader}@example.com`, earlyReader, `${earlyReader}@example.com`,
+ )
+ await run("UPDATE user SET isBot = 1, ownerUserId = ? WHERE id = ?", owner, bot)
+ await run(
+ "INSERT INTO session (id, userId, token, expiresAt, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?)",
+ `session_${stamp}`, owner, `token_${stamp}`, now, now, now,
+ )
+ await run(
+ "INSERT INTO account (id, userId, accountId, providerId, createdAt, updatedAt) VALUES (?, ?, ?, 'github', ?, ?)",
+ `account_${stamp}`, owner, `provider_${stamp}`, now, now,
+ )
+ await run(
+ "INSERT INTO verification (id, identifier, value, expiresAt, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?), (?, ?, ?, ?, ?, ?)",
+ `otp_${stamp}`, `sign-in-otp-${owner}@example.com`, "123456:0", now, now, now,
+ `ott_${stamp}`, `one-time-token:${stamp}`, `token_${stamp}`, now, now, now,
+ )
+ await run(
+ "INSERT INTO deviceCode (id, deviceCode, userCode, userId, expiresAt, status) VALUES (?, ?, ?, ?, ?, 'pending')",
+ `device_${stamp}`, `device_code_${stamp}`, `user_code_${stamp}`, owner, now,
+ )
+ await run(
+ "INSERT INTO workspace (id, name, slug, created_at, updated_at) VALUES (?, 'Owned', ?, ?, ?), (?, 'Shared', ?, ?, ?)",
+ workspace, workspace, now, now, sharedWorkspace, sharedWorkspace, now, now,
+ )
+ await run(
+ "INSERT INTO member (id, workspace_id, user_id, role, created_at) VALUES (?, ?, ?, 'owner', ?), (?, ?, ?, 'owner', ?), (?, ?, ?, 'owner', ?), (?, ?, ?, 'member', ?)",
+ `member_owner_${stamp}`, workspace, owner, now,
+ `member_coowner_${stamp}`, workspace, reader, now,
+ `member_shared_owner_${stamp}`, sharedWorkspace, reader, now,
+ `member_shared_user_${stamp}`, sharedWorkspace, owner, now,
+ )
+ await run(
+ "INSERT INTO machine_token (id, user_id, workspace_id, token, name, status, created_at) VALUES (?, ?, ?, ?, 'Owner token', 'active', ?), (?, ?, ?, ?, 'Workspace token', 'active', ?)",
+ `machine_token_owner_${stamp}`, owner, sharedWorkspace, ownerMachineToken, now,
+ `machine_token_workspace_${stamp}`, reader, workspace, workspaceMachineToken, now,
+ )
+ await run("INSERT INTO agent (id, workspace_id, name, owner_id, created_at, updated_at) VALUES (?, ?, 'Owned agent', ?, ?, ?)", `agent_${stamp}`, workspace, owner, now, now)
+ await run(
+ "INSERT INTO machine (daemon_id, workspace_id, owner_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?)",
+ daemon, sharedWorkspace, owner, now, now,
+ )
+ await run(
+ "INSERT INTO agent_runtime (id, workspace_id, daemon_id, provider, created_at, updated_at) VALUES (?, ?, ?, 'codex', ?, ?)",
+ runtime, sharedWorkspace, daemon, now, now,
+ )
+ await run(
+ "INSERT INTO agent (id, workspace_id, name, runtime_id, owner_id, created_at, updated_at) VALUES (?, ?, 'Survivor', ?, ?, ?, ?), (?, ?, 'Owned in shared', NULL, ?, ?, ?)",
+ survivingAgent, sharedWorkspace, runtime, reader, now, now,
+ ownedSharedAgent, sharedWorkspace, owner, now, now,
+ )
+ await run(
+ "INSERT INTO emails (id, agent_id, workspace_id, from_email, to_email, r2_key, attachments, created_at) VALUES (?, ?, ?, '[email protected]', '[email protected]', ?, ?, ?), (?, ?, ?, '[email protected]', '[email protected]', ?, ?, ?)",
+ deletingEmail, `agent_${stamp}`, workspace, `emails/${deletingEmail}/raw`, JSON.stringify([
+ { key: sharedDraftKey },
+ { key: privateDraftKey },
+ ]), now,
+ survivingEmail, survivingAgent, sharedWorkspace, `emails/${survivingEmail}/raw`, JSON.stringify([
+ { key: sharedDraftKey },
+ ]), now,
+ )
+ await run("INSERT INTO community_machine (id, user_id, created_at, updated_at) VALUES (?, ?, ?, ?)", `machine_${stamp}`, owner, now, now)
+ await run("INSERT INTO community_bot_binding (user_id, machine_id, runtime, instruction, created_at) VALUES (?, ?, 'codex', '', ?)", bot, `machine_${stamp}`, now)
+ await run("INSERT INTO community_server (id, name, discriminator, owner_id, created_at) VALUES (?, ?, '8104', ?, ?)", server, server, owner, now)
+ await run(
+ "INSERT INTO community_server_member (id, server_id, user_id, role, joined_at) VALUES (?, ?, ?, 'member', ?)",
+ `server_member_${stamp}`, server, reader, now,
+ )
+ await run(
+ "INSERT INTO community_channel (id, server_id, type, message_count, created_at) VALUES (?, ?, 'text', 0, ?)",
+ serverChannel, server, now,
+ )
+ await run("INSERT INTO community_channel (id, type, message_count, last_message_at, created_at) VALUES (?, 'dm', 3, ?, ?)", dm, now, now)
+ await run(
+ "INSERT INTO community_message (id, author_id, content, created_at, channel_id, seq) VALUES (?, ?, 'prior', ?, ?, 1), (?, ?, 'authored', ?, ?, 2), (?, ?, 'bot authored', ?, ?, 3)",
+ prior, reader, now, dm, authored, owner, now, dm, botAuthored, bot, now, dm,
+ )
+ await run(
+ "INSERT INTO community_read_state (id, user_id, channel_id, last_read_at, last_read_message_id, last_read_seq) VALUES (?, ?, ?, ?, ?, 3), (?, ?, ?, ?, ?, 1)",
+ `read_${stamp}`, reader, dm, now, botAuthored,
+ `read_early_${stamp}`, earlyReader, dm, now, prior,
+ )
+ await run(
+ "INSERT INTO community_channel (id, type, message_count, last_message_at, created_at) VALUES (?, 'forum', 1, ?, ?)",
+ forum, now, now,
+ )
+ await run(
+ "INSERT INTO community_message (id, author_id, content, created_at, channel_id, seq) VALUES (?, ?, 'opener', ?, ?, 1)",
+ opener, owner, now, forum,
+ )
+ await run(
+ "INSERT INTO community_channel (id, type, parent_channel_id, parent_message_id, message_count, last_message_at, created_at) VALUES (?, 'thread', ?, ?, 1, ?, ?)",
+ thread, forum, opener, now, now,
+ )
+ await run(
+ "INSERT INTO community_message (id, author_id, content, created_at, channel_id, seq) VALUES (?, ?, 'reply', ?, ?, 1)",
+ reply, reader, now, thread,
+ )
+ await run(
+ "INSERT INTO community_attachment (id, message_id, uploader_id, target_id, r2_key, filename, position, created_at) VALUES (?, ?, ?, ?, ?, 'reply.txt', 0, ?), (?, NULL, ?, ?, ?, 'pending-server.txt', 0, ?), (?, NULL, ?, ?, ?, 'pending-thread.txt', 0, ?)",
+ `attachment_${stamp}`, reply, reader, thread, threadAttachment, now,
+ pendingServerAttachment, reader, serverChannel, pendingServerAttachmentKey, now,
+ pendingThreadAttachment, reader, thread, pendingThreadAttachmentKey, now,
+ )
+
+ const db = createDb(runtimeEnv.DB)
+ const snapshot = await queries.accountDeletion.getAccountDeletionSnapshot(db, owner)
+ expect(snapshot?.identities.map((row) => row.id).sort()).toEqual([bot, owner].sort())
+ expect(snapshot?.ownedWorkspaceIds).toEqual([workspace])
+ expect(snapshot?.ownedAgentIds.sort()).toEqual([`agent_${stamp}`, ownedSharedAgent].sort())
+ expect(snapshot?.machineTokens.sort()).toEqual([ownerMachineToken, workspaceMachineToken].sort())
+ expect(snapshot?.media.communityExactKeys).toContain(threadAttachment)
+ expect(snapshot?.media.communityExactKeys).toContain(pendingServerAttachmentKey)
+ expect(snapshot?.media.communityExactKeys).toContain(pendingThreadAttachmentKey)
+ expect(snapshot?.media.deletingEmailAttachments).toContain(JSON.stringify([
+ { key: sharedDraftKey },
+ { key: privateDraftKey },
+ ]))
+ expect(snapshot?.media.survivingEmailAttachments).toContain(JSON.stringify([
+ { key: sharedDraftKey },
+ ]))
+ const result = await queries.accountDeletion.deleteAccountRows(db, snapshot!)
+
+ expect(result.deleted).toBe(true)
+ expect(await first("SELECT id FROM user WHERE id IN (?, ?)", owner, bot)).toBeNull()
+ expect(await first("SELECT id FROM workspace WHERE id = ?", workspace)).toBeNull()
+ expect(await first("SELECT id FROM workspace WHERE id = ?", sharedWorkspace)).toEqual({ id: sharedWorkspace })
+ expect(await first("SELECT id FROM machine_token WHERE token IN (?, ?)", ownerMachineToken, workspaceMachineToken)).toBeNull()
+ expect(await first("SELECT id FROM agent WHERE id = ?", ownedSharedAgent)).toBeNull()
+ expect(await first<{ id: string; runtime_id: string | null }>(
+ "SELECT id, runtime_id FROM agent WHERE id = ?",
+ survivingAgent,
+ )).toEqual({ id: survivingAgent, runtime_id: null })
+ expect(await first("SELECT id FROM agent_runtime WHERE id = ?", runtime)).toBeNull()
+ expect(await first("SELECT daemon_id FROM machine WHERE daemon_id = ? AND workspace_id = ?", daemon, sharedWorkspace)).toBeNull()
+ expect(await first("SELECT id FROM emails WHERE id = ?", deletingEmail)).toBeNull()
+ expect(await first("SELECT id FROM emails WHERE id = ?", survivingEmail)).toEqual({ id: survivingEmail })
+ expect(await first("SELECT id FROM community_server WHERE id = ?", server)).toBeNull()
+ expect(await first("SELECT id FROM community_channel WHERE id = ?", thread)).toBeNull()
+ expect(await first("SELECT id FROM community_attachment WHERE id = ?", `attachment_${stamp}`)).toBeNull()
+ expect(await first("SELECT id FROM community_attachment WHERE id IN (?, ?)", pendingServerAttachment, pendingThreadAttachment)).toBeNull()
+ expect(await first("SELECT id FROM user WHERE id = ?", reader)).toEqual({ id: reader })
+ expect(await first("SELECT id FROM deviceCode WHERE userId = ?", owner)).toBeNull()
+ expect(await first("SELECT id FROM verification WHERE id IN (?, ?)", `otp_${stamp}`, `ott_${stamp}`)).toBeNull()
+ expect(await first<{ message_count: number; last_message_at: string }>(
+ "SELECT message_count, last_message_at FROM community_channel WHERE id = ?",
+ dm,
+ )).toEqual({ message_count: 1, last_message_at: now })
+ expect(await first<{ last_read_message_id: string; last_read_seq: number }>(
+ "SELECT last_read_message_id, last_read_seq FROM community_read_state WHERE user_id = ? AND channel_id = ?",
+ reader,
+ dm,
+ )).toEqual({ last_read_message_id: prior, last_read_seq: 1 })
+ expect(result.readStateRevisions.sort((left, right) => left.userId.localeCompare(right.userId)))
+ .toEqual([
+ { userId: earlyReader, revision: 1 },
+ { userId: reader, revision: 1 },
+ ].sort((left, right) => left.userId.localeCompare(right.userId)))
+ expect(await first("SELECT revision FROM community_read_state_revision WHERE user_id = ?", reader))
+ .toEqual({ revision: 1 })
+ expect(await first<{ last_read_message_id: string; last_read_seq: number }>(
+ "SELECT last_read_message_id, last_read_seq FROM community_read_state WHERE user_id = ? AND channel_id = ?",
+ earlyReader,
+ dm,
+ )).toEqual({ last_read_message_id: prior, last_read_seq: 1 })
+ expect(await first("SELECT revision FROM community_read_state_revision WHERE user_id = ?", earlyReader))
+ .toEqual({ revision: 1 })
+ expect(await runtimeEnv.DB.prepare("PRAGMA foreign_key_check").all()).toMatchObject({ results: [] })
+ })
+})