Email for professionals and teams
fix(backups): list the drive and web-push tables missing from BACKUP_TABLES (#168)
yi1114738250ff82f
diff --git a/src/lib/backups/export.ts b/src/lib/backups/export.tsindex 00a8fe1..80504b7 100644--- a/src/lib/backups/export.ts+++ b/src/lib/backups/export.ts@@ -2,7 +2,7 @@ import type { BackupTableGroupId, DatabaseBackupDocument, DatabaseBackupTable, Dimport { mergeLegacyMessageBodies } from "./utils";import { BACKUP_TABLE_GROUPS, getSelectedBackupTables } from "./table-groups";-const BACKUP_TABLES: DatabaseBackupTable[] = ["users", "domains", "mailboxes", "mailbox_access", "contacts", "folders", "api_keys", "messages", "message_attachments", "shared_attachment_links", "outbound_jobs", "routing_rules", "webhooks", "webhook_deliveries", "sessions", "audit_logs", "backup_settings", "backups", "app_settings", "license_settings", "email_templates", "calendar_events", "booking_events", "auto_reply_deliveries", "spam_token_stats", "spam_reputation", "spam_feedback", "mailbox_aliases", "password_reset_tokens", "mfa_recovery_codes", "login_challenges", "mailbox_agent_settings", "agent_conversations", "agent_chat_messages", "agent_jobs", "agent_draft_metadata", "agent_send_approvals", "mcp_key_mailboxes", 'ai_usage'];+export const BACKUP_TABLES: DatabaseBackupTable[] = ["users", "domains", "mailboxes", "mailbox_access", "contacts", "folders", "api_keys", "messages", "message_attachments", "shared_attachment_links", "outbound_jobs", "routing_rules", "webhooks", "webhook_deliveries", "sessions", "audit_logs", "backup_settings", "backups", "app_settings", "license_settings", "email_templates", "calendar_events", "booking_events", "auto_reply_deliveries", "spam_token_stats", "spam_reputation", "spam_feedback", "mailbox_aliases", "password_reset_tokens", "mfa_recovery_codes", "login_challenges", "mailbox_agent_settings", "agent_conversations", "agent_chat_messages", "agent_jobs", "agent_draft_metadata", "agent_send_approvals", "mcp_key_mailboxes", "ai_usage", "drive_items", "drive_upload_parts", "drive_shares"];/*** Tables every backup document must contain. Tables added to BACKUP_TABLES* after the format shipped are absent from older documents, so they stay@@ -18,12 +18,12 @@ export function getBackupConfigurationStatus(_env?: CloudflareEnv) {/*** Tables D1 manages itself, which are intentionally absent from BACKUP_TABLES.*/-const INTERNAL_TABLE_PATTERNS = ["sqlite_%", "_cf%", "messages_fts%"];+export const INTERNAL_TABLE_PATTERNS = ["sqlite_%", "_cf%", "messages_fts%"];/*** The search index is derived data: its triggers repopulate it as messages are* restored, so it is neither exported nor part of the coverage check.*/-const INTERNAL_TABLES = [+export const INTERNAL_TABLES = ["d1_migrations",// JMAP state counters, also derived: the jmap_messages_* triggers on// `messages` insert and bump a row per mailbox as messages are restored.@@ -36,8 +36,20 @@ const INTERNAL_TABLES = ["jmap_change_floor",// Push registrations are re-sent by each app on launch."push_devices",+ // Web-push subscriptions are saved again by each client whenever it resolves+ // its push state, and they reference sessions whose rows a restore replaces.+ "push_subscriptions",];+/**+ * Groups a document of this format version was expected to cover. Format 1+ * writers could not have known the drive group, so restoring one only+ * requires the groups that existed when it was written.+ */+function groupsForDocumentVersion(version: DatabaseBackupDocument["version"]): typeof BACKUP_TABLE_GROUPS {+ return version === 2 ? BACKUP_TABLE_GROUPS : BACKUP_TABLE_GROUPS.filter((group) => group.id !== "drive");+}+/*** Fails the backup when the database contains a table BACKUP_TABLES does not* list. Without this, a migration that adds a table silently produces backups@@ -68,20 +80,22 @@ export async function exportDatabaseRecords(db: D1Database, excludedGroups: Backif (!includedTables.length) throw new Error("Select at least one backup table group");const tables: DatabaseBackupDocument["tables"] = {};for (const table of includedTables) {- if ((table === "shared_attachment_links" || table === "booking_events") && !databaseTables.has(table)) {+ if ((table === "shared_attachment_links" || table === "booking_events" || table.startsWith("drive_")) && !databaseTables.has(table)) {tables[table] = [];continue;}const result = await db.prepare(`SELECT * FROM ${table}`).all<DatabaseRecord>();tables[table] = result.results;}- const document: DatabaseBackupDocument = { format: "mailflare-database-backup", version: 1, createdAt: new Date().toISOString(), includedTables, tables };+ const document: DatabaseBackupDocument = { format: "mailflare-database-backup", version: 2, createdAt: new Date().toISOString(), includedTables, tables };return new TextEncoder().encode(JSON.stringify(document));}export async function restoreDatabaseRecords(db: D1Database, content: ArrayBuffer): Promise<void> {const document = parseDatabaseBackup(content);- if (document.includedTables && !BACKUP_TABLE_GROUPS.every((group) => group.tables.some((table) => document.includedTables?.includes(table)))) throw new Error("This backup contains selected table groups only. Restore requires a backup that includes every table group.");+ // Format 1 predates the drive group, so its writers could not have named its+ // tables in includedTables; only format 2 documents must cover every group.+ if (document.includedTables && !groupsForDocumentVersion(document.version).every((group) => group.tables.some((table) => document.includedTables?.includes(table)))) throw new Error("This backup contains selected table groups only. Restore requires a backup that includes every table group.");mergeLegacyMessageBodies(document);fillMissingBackupTables(document);validateDatabaseBackup(document);@@ -89,7 +103,12 @@ export async function restoreDatabaseRecords(db: D1Database, content: ArrayBuffeif (!sharedLinksTable && document.tables.shared_attachment_links?.length) throw new Error("Apply pending database migrations before restoring shared attachment links.");const bookingTable = await db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'booking_events'").first<{ name: string }>();if (!bookingTable && document.tables.booking_events?.length) throw new Error("Apply pending database migrations before restoring booking events.");- const restoreTables = BACKUP_TABLES.filter((table) => (table !== "shared_attachment_links" || sharedLinksTable) && (table !== "booking_events" || bookingTable));+ // Drive migrations ship later than the backup format, so an installation can have a database without them yet.+ const driveTableNames = (+ await db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name IN ('drive_items', 'drive_upload_parts', 'drive_shares')").all<{ name: string }>()+ ).results.map((row) => row.name);+ if (["drive_items", "drive_upload_parts", "drive_shares"].some((table) => document.tables[table]?.length) && driveTableNames.length !== 3) throw new Error("Apply pending database migrations before restoring the Drive tables.");+ const restoreTables = BACKUP_TABLES.filter((table) => (table !== "shared_attachment_links" || sharedLinksTable) && (table !== "booking_events" || bookingTable) && (!table.startsWith("drive_") || driveTableNames.includes(table)));const userColumns = new Set((await db.prepare("PRAGMA table_info(users)").all<{ name: string }>()).results.map((column) => column.name));const bookingColumns = bookingTable ? new Set((await db.prepare("PRAGMA table_info(booking_events)").all<{ name: string }>()).results.map((column) => column.name)) : null;for (const table of [...restoreTables].reverse()) await db.prepare(`DELETE FROM ${table}`).run();@@ -113,7 +132,7 @@ function parseDatabaseBackup(content: ArrayBuffer): DatabaseBackupDocument {function isDatabaseBackupDocument(value: unknown): value is DatabaseBackupDocument {if (!value || typeof value !== "object") return false;const document = value as Partial<DatabaseBackupDocument>;- if (document.format !== "mailflare-database-backup" || document.version !== 1 || !document.tables) return false;+ if (document.format !== "mailflare-database-backup" || typeof document.version !== "number" || ![1, 2].includes(document.version) || !document.tables) return false;if (document.includedTables) {if (!Array.isArray(document.includedTables) || !document.includedTables.length || new Set(document.includedTables).size !== document.includedTables.length) return false;if (!document.includedTables.every((table) => BACKUP_TABLES.includes(table) && Array.isArray(document.tables?.[table]))) return false;diff --git a/src/lib/backups/table-groups.ts b/src/lib/backups/table-groups.tsindex 44eaf2a..6ef41bb 100644--- a/src/lib/backups/table-groups.ts+++ b/src/lib/backups/table-groups.ts@@ -5,6 +5,7 @@ export const BACKUP_TABLE_GROUPS: { id: BackupTableGroupId; label: string; table{ id: "mail", label: "Mail and related data", tables: ["folders", "messages", "message_attachments", "shared_attachment_links", "outbound_jobs", "email_templates", "calendar_events", "booking_events", "auto_reply_deliveries", "spam_token_stats", "spam_reputation", "spam_feedback"] },{ id: "automation", label: "Routing and webhooks", tables: ["routing_rules", "webhooks", "webhook_deliveries"] },{ id: "assistant", label: "Assistant and AI usage", tables: ["mailbox_agent_settings", "agent_conversations", "agent_chat_messages", "agent_jobs", "agent_draft_metadata", "agent_send_approvals", "ai_usage"] },+ { id: "drive", label: "Drive uploads and shares", tables: ["drive_items", "drive_upload_parts", "drive_shares"] },{ id: "system", label: "App settings and history", tables: ["audit_logs", "backup_settings", "backups", "app_settings", "license_settings"] },];diff --git a/src/lib/backups/types.d.ts b/src/lib/backups/types.d.tsindex b0a56e3..a104c66 100644--- a/src/lib/backups/types.d.ts+++ b/src/lib/backups/types.d.ts@@ -1,6 +1,6 @@export type BackupScheduleType = "daily" | "weekly" | "monthly";-export type BackupTableGroupId = "accounts" | "mail" | "automation" | "assistant" | "system";+export type BackupTableGroupId = "accounts" | "mail" | "automation" | "assistant" | "drive" | "system";-export type DatabaseBackupTable = "users" | "domains" | "mailboxes" | "mailbox_access" | "contacts" | "folders" | "api_keys" | "messages" | "message_attachments" | "shared_attachment_links" | "outbound_jobs" | "routing_rules" | "webhooks" | "webhook_deliveries" | "sessions" | "audit_logs" | "backup_settings" | "backups" | "app_settings" | "license_settings" | "email_templates" | "calendar_events" | "booking_events" | "auto_reply_deliveries" | "spam_token_stats" | "spam_reputation" | "spam_feedback" | "mailbox_aliases" | "password_reset_tokens" | "mfa_recovery_codes" | "login_challenges" | "mailbox_agent_settings" | "agent_conversations" | "agent_chat_messages" | "agent_jobs" | "agent_draft_metadata" | "agent_send_approvals" | "mcp_key_mailboxes" | 'ai_usage';+export type DatabaseBackupTable = "users" | "domains" | "mailboxes" | "mailbox_access" | "contacts" | "folders" | "api_keys" | "messages" | "message_attachments" | "shared_attachment_links" | "outbound_jobs" | "routing_rules" | "webhooks" | "webhook_deliveries" | "sessions" | "audit_logs" | "backup_settings" | "backups" | "app_settings" | "license_settings" | "email_templates" | "calendar_events" | "booking_events" | "auto_reply_deliveries" | "spam_token_stats" | "spam_reputation" | "spam_feedback" | "mailbox_aliases" | "password_reset_tokens" | "mfa_recovery_codes" | "login_challenges" | "mailbox_agent_settings" | "agent_conversations" | "agent_chat_messages" | "agent_jobs" | "agent_draft_metadata" | "agent_send_approvals" | "mcp_key_mailboxes" | "ai_usage" | "drive_items" | "drive_upload_parts" | "drive_shares";export type DatabaseRecord = Record<string, string | number | null>;-export type DatabaseBackupDocument = { format: "mailflare-database-backup"; version: 1; createdAt: string; includedTables?: DatabaseBackupTable[]; tables: Partial<Record<DatabaseBackupTable, DatabaseRecord[]>>; };+export type DatabaseBackupDocument = { format: "mailflare-database-backup"; version: 1 | 2; createdAt: string; includedTables?: DatabaseBackupTable[]; tables: Partial<Record<DatabaseBackupTable, DatabaseRecord[]>>; };diff --git a/tests/backup-table-list.test.mjs b/tests/backup-table-list.test.mjsnew file mode 100644index 0000000..59c5104--- /dev/null+++ b/tests/backup-table-list.test.mjs@@ -0,0 +1,105 @@+import assert from "node:assert/strict";+import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";+import { spawnSync } from "node:child_process";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import test, { after } from "node:test";+import { fileURLToPath, pathToFileURL } from "node:url";++import Database from "better-sqlite3";+import { build } from "esbuild";++const root = join(dirname(fileURLToPath(import.meta.url)), "..");++/**+ * The backup constants and the bundled migrations move apart when a migration+ * adds a table, so the test bundles the constants with the esbuild already used+ * by other tests and replays the bundle exactly like `push-devices-migration.test.mjs`.+ */+const outDir = mkdtempSync(join(tmpdir(), "mailflare-backup-table-list-test-"));+after(() => rmSync(outDir, { recursive: true, force: true }));++await build({+ stdin: {+ contents: `export { BACKUP_TABLES, INTERNAL_TABLES, INTERNAL_TABLE_PATTERNS, assertBackupTablesCoverDatabase } from "./src/lib/backups/export.ts";`,+ resolveDir: root,+ sourcefile: "backup-table-list-test-entry.js",+ },+ outfile: join(outDir, "backup-list.mjs"),+ bundle: true,+ platform: "node",+ format: "esm",+ target: "node22",+ tsconfig: join(root, "tsconfig.json"),+ logLevel: "silent",+});++const { BACKUP_TABLES, INTERNAL_TABLES, INTERNAL_TABLE_PATTERNS, assertBackupTablesCoverDatabase } = await import(+ pathToFileURL(join(outDir, "backup-list.mjs")).href+);++await build({+ stdin: {+ contents: `export { BACKUP_TABLE_GROUPS } from "./src/lib/backups/table-groups.ts";`,+ resolveDir: root,+ sourcefile: "backup-table-groups-test-entry.js",+ },+ outfile: join(outDir, "backup-groups.mjs"),+ bundle: true,+ platform: "node",+ format: "esm",+ target: "node22",+ tsconfig: join(root, "tsconfig.json"),+ logLevel: "silent",+});++const { BACKUP_TABLE_GROUPS } = await import(pathToFileURL(join(outDir, "backup-list.mjs")).href.replace("backup-list.mjs", "backup-groups.mjs"));++const bundlePath = join(root, "src/lib/migrations/bundle.json");+if (!existsSync(bundlePath)) spawnSync("node", [join(root, "scripts/generate-migration-bundle.mjs")], { cwd: root });+const { migrations } = JSON.parse(readFileSync(bundlePath, "utf8"));++const db = new Database(":memory:");+db.pragma("foreign_keys = OFF");+for (const migration of migrations) for (const statement of migration.statements) db.exec(statement);+after(() => db.close());++/** A minimal D1Database facade over the migrated in-memory database. */+const d1 = {+ prepare(sql) {+ return { all: async () => ({ results: db.prepare(sql).all() }), first: async () => db.prepare(sql).get() };+ },+};++const isPatternTable = (name) => INTERNAL_TABLE_PATTERNS.some((pattern) => new RegExp(`^${pattern.replaceAll("%", ".*")}$`).test(name));++test("every table in a migrated database is backed up or documented as internal", () => {+ const tables = db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").all().map((row) => row.name);+ const internal = new Set([...INTERNAL_TABLES, ...tables.filter(isPatternTable)]);+ const leftover = tables.filter((name) => !internal.has(name));+ assert.deepEqual(leftover.sort(), [...BACKUP_TABLES].sort());+});++test("the coverage guard passes on a fully migrated database", async () => {+ const covered = await assertBackupTablesCoverDatabase(d1);+ assert.equal(covered.size, BACKUP_TABLES.length);+ for (const table of BACKUP_TABLES) assert.ok(covered.has(table), `${table} is not covered`);+});++test("every backed-up table sits in exactly one group that only holds backed-up tables", () => {+ const assigned = BACKUP_TABLE_GROUPS.flatMap((group) => group.tables);+ const duplicated = BACKUP_TABLES.filter((table) => assigned.filter((item) => item === table).length !== 1);+ const unknown = assigned.filter((table) => !BACKUP_TABLES.includes(table));+ assert.deepEqual([...duplicated, ...unknown], []);+});++test("an unlisted table aborts the backup with a pointing-finger message", async () => {+ const scratch = new Database(":memory:");+ scratch.exec("CREATE TABLE future_table (id TEXT PRIMARY KEY)");+ const scratchD1 = {+ prepare(sql) {+ return { all: async () => ({ results: scratch.prepare(sql).all() }) };+ },+ };+ await assert.rejects(assertBackupTablesCoverDatabase(scratchD1), /future_table not listed in BACKUP_TABLES/);+});