diff --git a/worker/src/index.ts b/worker/src/index.ts index a06c249..f43220c 100644 --- a/worker/src/index.ts +++ b/worker/src/index.ts @@ -10,6 +10,7 @@ import { meRoutes } from "./routes/me"; import { itemRoutes } from "./routes/items"; import { dashboardRoutes } from "./routes/dashboard"; import { adminRoutes } from "./routes/admin"; +import { adminBackupRoutes, meBackupRoutes } from "./routes/backup"; import { notifyRoutes } from "./routes/notify"; import { setupRoutes } from "./routes/setup"; import { handleScheduled } from "./services/scheduler"; @@ -60,6 +61,11 @@ app.use( app.route("/api/auth", authRoutes); app.route("/api/auth/2fa", auth2faRoutes); +// Export/import (backup) routers are registered before the regular me/admin +// routers so their session-only guard runs first (an API-key request must be +// rejected explicitly, not merely fail cookie auth). +app.route("/api/me", meBackupRoutes); +app.route("/api/admin", adminBackupRoutes); app.route("/api/me", meRoutes); app.route("/api/items", itemRoutes); app.route("/api/dashboard", dashboardRoutes); diff --git a/worker/src/lib/backup/CONTRACT.md b/worker/src/lib/backup/CONTRACT.md new file mode 100644 index 0000000..7c243cd --- /dev/null +++ b/worker/src/lib/backup/CONTRACT.md @@ -0,0 +1,154 @@ +# 导出 / 导入后端契约(v1,冻结格式 + 六个接口) + +> 状态:已实现(子单 ONE-359,父单 ONE-358)。本文件是前端子单的唯一对接依据:路由名、请求/响应形状、错误码都以本文为准。 +> 数据格式契约见父单「导出文件格式 / 敏感性与加密 / 导入语义」三节,本文件不重复其规范,只描述 HTTP 表面。 + +## 1. 六个接口 + +| 路由 | 方法 | 鉴权 | 说明 | +|---|---|---|---| +| `/api/me/export` | POST | 登录会话 | 个人档导出(`scope: "user"`) | +| `/api/me/import/preview` | POST | 登录会话 | 个人档导入预检(dry-run,merge 模式) | +| `/api/me/import` | POST | 登录会话 | 个人档导入(merge 模式) | +| `/api/admin/export` | POST | 会话 + admin | 全站导出(`scope: "instance"`) | +| `/api/admin/import/preview` | POST | 会话 + admin | 全站导入预检(restore 或 merge) | +| `/api/admin/import` | POST | 会话 + admin | 全站导入(restore 默认 / merge 可选) | + +**只认 cookie 会话,不认 API Key**:请求带 `Authorization: Bearer enk_...` 时直接返回 `403 { code: "API_KEY_NOT_ALLOWED" }`(即使同时带着有效会话)。未登录 `401`,非管理员访问 admin 路由 `403`。 + +## 2. 上传方式 + +JSON 请求体(现值前端 `web/src/lib/api.ts` 的惯例,全部请求都是 JSON): + +```jsonc +{ + "file": { /* 解析后的导出文件 */ }, // 也可以传原始文件文本:"file": "" + "passphrase": "…", // 加密文件必填;明文文件忽略 + "mode": "restore" // 仅 admin 导入/预检使用,见下 +} +``` + +- 整个请求体上限 **10 MB(10485760 字节)**,超出返回 `413 { code: "PAYLOAD_TOO_LARGE", details: { max_bytes } }`。 +- 前端读 `File.text()` 后既可直接 `JSON.parse` 再传对象,也可把文本原样放进 `file` 字符串,两种都支持。 + +## 3. 导出 + +请求体: + +```jsonc +{ + "encrypted": true, // 默认 true;要明文文件必须显式传 false + "passphrase": "…", // encrypted 时必填,否则 400 PASSPHRASE_REQUIRED + "include_history": false // 默认 false:data.notification_history 为空数组 +} +``` + +响应:**文件内容直接作为响应体**(不是外层包装),头: + +``` +Content-Type: application/json; charset=utf-8 +Content-Disposition: attachment; filename="enotify-user-20261025T153000Z-encrypted.json" +Cache-Control: no-store +``` + +- `encrypted: true` 时响应体是可识别信封 `{format:"enotify-export-encrypted", format_version:1, kdf:{name:"PBKDF2",hash:"SHA-256",iterations:210000,salt}, cipher:{name:"AES-GCM",length:256,iv,tag_length:128}, payload}`;`salt`/`iv`/`payload` 均为 base64。 +- `encrypted: false` 时响应体即明文导出文件(`enotify-export`)。 +- 前端把它当 blob 下载即可(`tagged-` 无需再拼信封)。 + +## 4. 导入预检(dry-run) + +请求体见 §2(`mode` 仅 admin 用;个人档固定 merge)。 + +响应 `200`: + +```jsonc +{ + "ok": true, + "mode": "restore", // "restore" | "merge" + "scope": "instance", // 文件自身声明的 scope + "encrypted": true, // 上传的是否为加密信封 + "format_version": 1, + "app_version": "1.0.4", + "exported_at": "2026-10-25T15:00:00.000Z", + "counts": { "users": 3, "user_2fa": 1, "items": 3, "payment_history": 2, + "notification_configs": 2, "system_settings": 2, "notification_history": 0 }, + "will_write": { /* 同上七个键:本次真正会写入的行数 */ }, + "users": [ { "id": "u1", "email": "a@example.com", "role": "admin" } ], + "can_execute": true, // false 时前端必须禁用「确认导入」 + "blockers": [ { "code": "RESTORE_TARGET_NOT_EMPTY", "message": "…" } ], + "conflicts": { + "target_users": 0, // 目标实例当前用户数(restore 用) + "email_conflicts": [], // 预留:同邮箱冲突清单 + "settings_overwritten": [], // restore:会被文件覆盖的 system_settings 键 + "config_overwritten": false, // merge:是否会整行覆盖当前用户的渠道配置 + "skipped_orphan_payments": 0, // merge:因找不到对应通知而跳过的缴费记录数 + "skipped_foreign_items": 0, // merge:文件中属于其他账号、被忽略的通知数 + "skipped_foreign_payments": 0, + "skipped_history_rows": 0 // merge:不导入的通知历史条数 + }, + "ignored_tables": ["users", "user_2fa", "system_settings", "notification_history"], + "warnings": ["…"] // 展示给用户看的提示(含「API Key 不含在文件里」等) +} +``` + +前端预检页据此展示:每表行数、用户邮箱清单、冲突点(`conflicts` + `blockers`)、`ignored_tables`(merge 时明示被忽略的表)、`warnings`。 + +## 5. 导入执行 + +请求体同 §2。admin 路由 `mode` 缺省为 `restore`;`mode: "merge"` 时把文件里的个人数据合并进**当前登录账号**(个人档路由固定 merge,传其他值返回 `400 MODE_NOT_ALLOWED`)。 + +响应 `200`: + +```jsonc +{ + "ok": true, + "mode": "restore", + "scope": "instance", + "written": { "users": 3, "user_2fa": 1, "items": 3, "payment_history": 2, + "notification_configs": 2, "system_settings": 2, "notification_history": 0 }, + "total_written": 13, + "notices": ["恢复完成:API Key 需重新签发,所有用户需要重新登录"], + "warnings": ["…"] +} +``` + +restore 成功后的 `notices` 必须原样展示(API Key 重新签发 + 所有用户重新登录)。merge 的 `notices` 为空数组,提示都在 `warnings` 里。 + +## 6. 错误码 + +响应体统一 `{ "error": "<可直接展示的中文文案>", "code": "<机器码>", "details"?: {...} }`。 + +| HTTP | code | 场景 | +|---|---|---| +| 400 | `PASSPHRASE_REQUIRED` | 加密导出没给口令 / 加密文件导入没给口令 | +| 400 | `DECRYPT_FAILED` | 口令错误或文件被篡改(**零写入**) | +| 400 | `INVALID_ENVELOPE` | 加密信封字段缺失/参数不受支持 | +| 400 | `INVALID_FORMAT` / `INVALID_FILE` / `INVALID_ROW` | 不是 eNotify 导出文件 / JSON 形状不对 | +| 400 | `UNSUPPORTED_FORMAT_VERSION` | 文件 `format_version` 高于本服务支持(1) | +| 400 | `MODE_NOT_ALLOWED` | 个人档路由收到 restore,或用 user 档文件走 restore | +| 400 | `MERGE_SOURCE_NOT_FOUND` | 文件里没有属于当前账号(邮箱)的数据 | +| 400 | `INVALID_REQUEST` | 请求体不是 JSON / 缺少 `file` | +| 401 | — | 未登录 | +| 403 | `API_KEY_NOT_ALLOWED` | 用 API Key 调这些接口 | +| 403 | — | 非管理员访问 admin 路由 | +| 409 | `RESTORE_TARGET_NOT_EMPTY` | restore 打到非空实例(**不提供覆盖**) | +| 409 | `REFERENCE_MISSING` / `DUPLICATE_KEY` / `MISSING_COLUMN` | 文件行校验失败(预检给 blockers,导入拒绝) | +| 409 | `STALE_PREVIEW` | 预检后数据库变化,需重新预检 | +| 413 | `PAYLOAD_TOO_LARGE` | 请求体超过 10 MB | +| 429 | — | 同一账号每分钟超过 20 次导出/导入调用(`{ error: "Too many requests" }`) | +| 500 | `WRITE_FAILED` | 写入失败,事务已整体回滚(数据没有任何变化) | +| 500 | `RESTORE_COUNT_MISMATCH` | 写后行数断言不符 | + +## 7. 导入原子性与安全要点(前端可依赖的行为) + +- 恢复模式只接受 `scope: "instance"`,且目标 `users` 表必须非空拒绝(预检 `can_execute: false`,执行 `409`)。 +- 单次导入的全部写入是 **一次 `db.batch`(D1 单事务)**:任一行失败整批回滚,不会出现半套数据或悬空外键。 +- 错口令在解密阶段失败,**不会写任何数据**。 +- 合并模式:ID 全部重新生成,`user_id` 改写为当前账号,`payment_history.item_id` 按旧→新映射改写,`notification_configs` 整行覆盖(预检 `conflicts.config_overwritten` 已明示);`users`/`user_2fa`/`system_settings`/`notification_history` 忽略。 +- 审计:导出/导入各写一条 `[audit] backup {...}` 结构化 server log(操作者、scope/mode、是否加密、各表行数),口令永不出现在日志里。 + +## 8. 前端必须写进 UI 的提示(规格「不在导出范围」节) + +- 文件等同主钥匙包,妥善保管,不要经聊天/邮件传输。 +- 不含 API Key(明文不可恢复,恢复后需重新签发)、不含会话/JWT(导入后所有用户需重新登录)、不含 KV 中的运行时状态。 +- 加密导出默认勾选;口令框需说明「口令不会保存,忘记无法恢复文件」。 diff --git a/worker/src/lib/backup/crypto.ts b/worker/src/lib/backup/crypto.ts new file mode 100644 index 0000000..628190e --- /dev/null +++ b/worker/src/lib/backup/crypto.ts @@ -0,0 +1,263 @@ +/** + * Passphrase encryption for export files (parent issue ONE-358 + * "敏感性与加密" section). + * + * Built only from WebCrypto primitives — no hand-rolled cryptography: + * + * key = PBKDF2(passphrase, salt, iterations, SHA-256) → AES-GCM-256 + * salt = 16 random bytes, iv = 12 random bytes + * payload = base64(AES-GCM ciphertext || 128-bit tag) + * + * Envelope (the encrypted file is recognizable without the passphrase): + * + * { + * "format": "enotify-export-encrypted", + * "format_version": 1, + * "kdf": { "name": "PBKDF2", "hash": "SHA-256", "iterations": 210000, + * "salt": "" }, + * "cipher":{ "name": "AES-GCM", "length": 256, "iv": "", + * "tag_length": 128 }, + * "payload": "" + * } + * + * The passphrase itself is never stored, echoed, or logged; a wrong passphrase + * fails inside AES-GCM authentication and surfaces as DECRYPT_FAILED before + * any database access happens (zero writes). + */ +import { BackupError } from "./errors"; +import { BACKUP_ENCRYPTED_FORMAT, BACKUP_FORMAT_VERSION } from "./format"; + +export const PBKDF2_ITERATIONS = 210_000; +export const PBKDF2_HASH = "SHA-256"; +export const SALT_BYTES = 16; +export const IV_BYTES = 12; +export const AES_KEY_LENGTH = 256; +export const TAG_LENGTH = 128; + +// Bounds accepted when reading a foreign envelope. The floor is the spec's +// "迭代次数 ≥ 210,000"; the ceiling keeps a hostile file from pinning a Worker +// in PBKDF2 indefinitely. +const MIN_ACCEPTED_ITERATIONS = 210_000; +const MAX_ACCEPTED_ITERATIONS = 10_000_000; + +export interface ExportKdf { + name: "PBKDF2"; + hash: "SHA-256"; + iterations: number; + salt: string; +} + +export interface ExportCipher { + name: "AES-GCM"; + length: number; + iv: string; + tag_length: number; +} + +export interface EncryptedExportFile { + format: typeof BACKUP_ENCRYPTED_FORMAT; + format_version: number; + kdf: ExportKdf; + cipher: ExportCipher; + payload: string; +} + +function bytesToBase64(bytes: Uint8Array): string { + let binary = ""; + for (let i = 0; i < bytes.length; i++) + binary += String.fromCharCode(bytes[i]); + return btoa(binary); +} + +function base64ToBytes(value: string): Uint8Array { + let binary: string; + try { + binary = atob(value); + } catch { + throw new BackupError( + "INVALID_ENVELOPE", + 400, + "加密信封内的 base64 字段无效", + ); + } + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); + return bytes; +} + +async function deriveKey( + passphrase: string, + salt: Uint8Array, + iterations: number, +): Promise { + const material = await crypto.subtle.importKey( + "raw", + new TextEncoder().encode(passphrase), + "PBKDF2", + false, + ["deriveKey"], + ); + return crypto.subtle.deriveKey( + { + name: "PBKDF2", + salt: salt as BufferSource, + iterations, + hash: PBKDF2_HASH, + }, + material, + { name: "AES-GCM", length: AES_KEY_LENGTH }, + false, + ["encrypt", "decrypt"], + ); +} + +/** Encrypts the serialized plain export file into an envelope. */ +export async function encryptExport( + plain: unknown, + passphrase: string, +): Promise { + if (!passphrase) { + throw new BackupError("PASSPHRASE_REQUIRED", 400, "加密导出必须提供口令"); + } + const salt = crypto.getRandomValues(new Uint8Array(SALT_BYTES)); + const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES)); + const key = await deriveKey(passphrase, salt, PBKDF2_ITERATIONS); + + const plaintext = new TextEncoder().encode(JSON.stringify(plain)); + const ciphertext = await crypto.subtle.encrypt( + { name: "AES-GCM", iv: iv as BufferSource, tagLength: TAG_LENGTH }, + key, + plaintext as BufferSource, + ); + + return { + format: BACKUP_ENCRYPTED_FORMAT, + format_version: BACKUP_FORMAT_VERSION, + kdf: { + name: "PBKDF2", + hash: PBKDF2_HASH, + iterations: PBKDF2_ITERATIONS, + salt: bytesToBase64(salt), + }, + cipher: { + name: "AES-GCM", + length: AES_KEY_LENGTH, + iv: bytesToBase64(iv), + tag_length: TAG_LENGTH, + }, + payload: bytesToBase64(new Uint8Array(ciphertext)), + }; +} + +export function isEncryptedEnvelope( + input: unknown, +): input is EncryptedExportFile { + return ( + typeof input === "object" && + input !== null && + !Array.isArray(input) && + (input as Record).format === BACKUP_ENCRYPTED_FORMAT + ); +} + +/** Validates the envelope shape and returns its parsed KDF/cipher params. */ +function readEnvelope(envelope: unknown): { + salt: Uint8Array; + iv: Uint8Array; + iterations: number; + payload: Uint8Array; + version: number; +} { + const invalid = (message: string): never => { + throw new BackupError("INVALID_ENVELOPE", 400, message); + }; + if (!isEncryptedEnvelope(envelope)) + invalid("文件不是加密的 eNotify 导出信封"); + + const env = envelope as EncryptedExportFile; + + const version = env.format_version; + if (typeof version !== "number" || !Number.isInteger(version) || version < 1) + invalid("加密信封缺少有效的 format_version"); + if (version > BACKUP_FORMAT_VERSION) + throw new BackupError( + "UNSUPPORTED_FORMAT_VERSION", + 400, + `加密信封 format_version 为 ${version},本服务最高支持 ${BACKUP_FORMAT_VERSION}`, + { file_format_version: version, supported: BACKUP_FORMAT_VERSION }, + ); + + const kdf = env.kdf; + if (kdf?.name !== "PBKDF2" || kdf.hash !== PBKDF2_HASH) + invalid("加密信封的 kdf 参数不受支持(需要 PBKDF2 + SHA-256)"); + const iterations = kdf.iterations; + if ( + typeof iterations !== "number" || + !Number.isInteger(iterations) || + iterations < MIN_ACCEPTED_ITERATIONS || + iterations > MAX_ACCEPTED_ITERATIONS + ) + invalid( + `加密信封的 PBKDF2 迭代次数不受支持(需 ${MIN_ACCEPTED_ITERATIONS}–${MAX_ACCEPTED_ITERATIONS})`, + ); + + const cipher = env.cipher; + if (cipher?.name !== "AES-GCM" || cipher.length !== AES_KEY_LENGTH) + invalid("加密信封的 cipher 参数不受支持(需要 AES-GCM-256)"); + + if (typeof kdf.salt !== "string" || typeof env.payload !== "string") + invalid("加密信封缺少 salt 或 payload"); + + const salt = base64ToBytes(kdf.salt); + if (salt.length !== SALT_BYTES) + invalid(`加密信封的 salt 必须是 ${SALT_BYTES} 字节`); + const iv = base64ToBytes(String(cipher.iv)); + if (iv.length !== IV_BYTES) invalid(`加密信封的 iv 必须是 ${IV_BYTES} 字节`); + const payload = base64ToBytes(env.payload); + if (payload.length <= TAG_LENGTH / 8) invalid("加密信封的 payload 长度无效"); + + return { salt, iv, iterations, payload, version }; +} + +/** + * Decrypts an envelope and returns the parsed plain export object. + * + * A wrong passphrase (or a corrupted payload) is indistinguishable by design + * and always reports DECRYPT_FAILED; nothing is written anywhere first. + */ +export async function decryptExport( + envelope: unknown, + passphrase: string, +): Promise { + if (!passphrase) { + throw new BackupError( + "PASSPHRASE_REQUIRED", + 400, + "该文件已加密,请提供口令", + { encrypted: true }, + ); + } + const { salt, iv, iterations, payload } = readEnvelope(envelope); + const key = await deriveKey(passphrase, salt, iterations); + + let plaintext: ArrayBuffer; + try { + plaintext = await crypto.subtle.decrypt( + { name: "AES-GCM", iv: iv as BufferSource, tagLength: TAG_LENGTH }, + key, + payload as BufferSource, + ); + } catch { + throw new BackupError( + "DECRYPT_FAILED", + 400, + "口令错误或文件已损坏,未能解密(未写入任何数据)", + ); + } + + try { + return JSON.parse(new TextDecoder().decode(plaintext)); + } catch { + throw new BackupError("INVALID_FILE", 400, "解密成功但内容不是有效的 JSON"); + } +} diff --git a/worker/src/lib/backup/errors.ts b/worker/src/lib/backup/errors.ts new file mode 100644 index 0000000..398605b --- /dev/null +++ b/worker/src/lib/backup/errors.ts @@ -0,0 +1,49 @@ +/** + * Error type for the export/import ("backup") feature. + * + * Every user-facing failure is expressed as a BackupError carrying a stable + * machine-readable `code` and the HTTP status the route should answer with, so + * the frontend can branch on `code` instead of on message text. Messages are + * deliberately free of secrets: passphrases never appear in errors or logs. + */ +export type BackupErrorCode = + | "INVALID_REQUEST" + | "PAYLOAD_TOO_LARGE" + | "INVALID_FILE" + | "INVALID_FORMAT" + | "UNSUPPORTED_FORMAT_VERSION" + | "INVALID_SCOPE" + | "INVALID_ROW" + | "PASSPHRASE_REQUIRED" + | "PASSPHRASE_NOT_APPLICABLE" + | "INVALID_ENVELOPE" + | "DECRYPT_FAILED" + | "MODE_NOT_ALLOWED" + | "RESTORE_TARGET_NOT_EMPTY" + | "MERGE_SOURCE_NOT_FOUND" + | "MISSING_COLUMN" + | "DUPLICATE_KEY" + | "REFERENCE_MISSING" + | "STALE_PREVIEW" + | "RESTORE_COUNT_MISMATCH" + | "TABLE_MISSING" + | "WRITE_FAILED"; + +export class BackupError extends Error { + readonly code: BackupErrorCode; + readonly status: number; + readonly details?: unknown; + + constructor( + code: BackupErrorCode, + status: number, + message: string, + details?: unknown, + ) { + super(message); + this.name = "BackupError"; + this.code = code; + this.status = status; + this.details = details; + } +} diff --git a/worker/src/lib/backup/export.ts b/worker/src/lib/backup/export.ts new file mode 100644 index 0000000..a4999e1 --- /dev/null +++ b/worker/src/lib/backup/export.ts @@ -0,0 +1,121 @@ +/** + * Export: read the 7 tables under the resolved `{prefix}` and serialize them + * into the frozen v1 file format. + */ +import { BackupError } from "./errors"; +import { + BACKUP_FORMAT, + BACKUP_FORMAT_VERSION, + BACKUP_TABLES, + emptyData, + serializeRow, + type BackupData, + type BackupScope, + type BackupTable, + type PlainExportFile, + TABLE_BY_NAME, + HISTORY_TABLE, +} from "./format"; + +/** Declared globally by `worker/src/env.d.ts`, injected at build time. */ +export function getAppVersion(): string { + try { + return typeof APP_VERSION !== "undefined" && APP_VERSION + ? APP_VERSION + : "0.0.0"; + } catch { + return "0.0.0"; + } +} + +export interface ExportOptions { + scope: BackupScope; + /** Required for `scope: "user"`: whose data to export. */ + userId?: string; + /** Log table is opt-in; default drops it (data.notification_history: []). */ + includeHistory?: boolean; +} + +export interface BuiltExport { + file: PlainExportFile; + counts: Record; +} + +async function selectRows( + db: D1Database, + prefix: string, + table: BackupTable, + userId?: string, +): Promise[]> { + const spec = TABLE_BY_NAME[table]; + const tableName = `${prefix}${table}`; + + if (userId === undefined) { + const result = await db + .prepare(`SELECT * FROM ${tableName} ORDER BY ${spec.orderBy}`) + .all>(); + return result.results ?? []; + } + + const result = await db + .prepare( + `SELECT * FROM ${tableName} WHERE ${spec.userColumn} = ? ORDER BY ${spec.orderBy}`, + ) + .bind(userId) + .all>(); + return result.results ?? []; +} + +/** + * Builds the plain (unencrypted) export file. + * + * `scope: "user"` keeps only the exporting user's own rows plus that one + * `users` row; `system_settings` is always empty for that scope. + * `scope: "instance"` dumps every row of every table. + */ +export async function buildExportFile( + db: D1Database, + prefix: string, + options: ExportOptions, +): Promise { + if (options.scope === "user" && !options.userId) { + throw new BackupError("INVALID_REQUEST", 500, "个人档导出缺少用户标识"); + } + + const data: BackupData = emptyData(); + const counts = {} as Record; + + for (const spec of BACKUP_TABLES) { + const table = spec.name; + + if (table === HISTORY_TABLE && !options.includeHistory) { + counts[table] = 0; + continue; + } + if (options.scope === "user" && table === "system_settings") { + counts[table] = 0; + continue; + } + + const rows = await selectRows( + db, + prefix, + table, + options.scope === "user" ? options.userId : undefined, + ); + data[table] = rows.map((row) => serializeRow(spec, row)); + counts[table] = data[table].length; + } + + return { + file: { + format: BACKUP_FORMAT, + format_version: BACKUP_FORMAT_VERSION, + app_version: getAppVersion(), + exported_at: new Date().toISOString(), + scope: options.scope, + data, + }, + counts, + }; +} diff --git a/worker/src/lib/backup/format.ts b/worker/src/lib/backup/format.ts new file mode 100644 index 0000000..cfbf764 --- /dev/null +++ b/worker/src/lib/backup/format.ts @@ -0,0 +1,338 @@ +/** + * Export/import file format — the frozen v1 contract (parent issue ONE-358 + * "导出文件格式" section). + * + * A plain export is: + * + * { + * "format": "enotify-export", + * "format_version": 1, + * "app_version": "", + * "exported_at": "", + * "scope": "instance | user", + * "data": { users: [], user_2fa: [], items: [], payment_history: [], + * notification_configs: [], system_settings: [], + * notification_history: [] } + * } + * + * Rows are column-name keyed objects. JSON columns are exported as parsed JSON + * values; a column whose stored text is not valid JSON is exported verbatim as + * a string and listed in that row's `_raw` array, and import writes such + * columns back exactly as the string it found (nothing may be lost or + * reshaped). `format_version` is independent of the DB schema version: the + * importer ignores unknown fields and lets the DB apply current column + * defaults for absent ones, but refuses a file whose `format_version` is + * higher than it supports. + */ +import { BackupError } from "./errors"; + +export const BACKUP_FORMAT = "enotify-export"; +export const BACKUP_ENCRYPTED_FORMAT = "enotify-export-encrypted"; +export const BACKUP_FORMAT_VERSION = 1; + +export type BackupScope = "instance" | "user"; + +export type BackupTable = + | "users" + | "user_2fa" + | "items" + | "payment_history" + | "notification_configs" + | "system_settings" + | "notification_history"; + +export interface TableSpec { + name: BackupTable; + /** Columns stored as TEXT that hold JSON; exported as parsed values. */ + jsonColumns: readonly string[]; + /** + * Column that identifies the owning user for `scope: "user"` filtering and + * merge targeting ("id" for users itself, "user_id" elsewhere). + */ + userColumn: string; + /** Deterministic export order. */ + orderBy: string; + /** + * Columns regenerated during merge mode (new primary keys / rewritten + * owner references), so a missing value is not an error for them. + */ + generatedOnMerge: readonly string[]; + /** True when merge replaces the whole row instead of inserting a new one. */ + replaceOnMerge?: boolean; +} + +/** + * Table order is also the restore insert order: parents before children, so + * foreign keys are satisfied without deferring them. + */ +export const BACKUP_TABLES: readonly TableSpec[] = [ + { + name: "users", + jsonColumns: [], + userColumn: "id", + orderBy: "id", + generatedOnMerge: [], + }, + { + name: "user_2fa", + jsonColumns: ["passkey_credentials"], + userColumn: "user_id", + orderBy: "user_id", + generatedOnMerge: [], + }, + { + name: "items", + jsonColumns: ["channels", "notification_hours"], + userColumn: "user_id", + orderBy: "id", + generatedOnMerge: ["id", "user_id"], + }, + { + name: "payment_history", + jsonColumns: [], + userColumn: "user_id", + orderBy: "id", + generatedOnMerge: ["id", "user_id", "item_id"], + }, + { + name: "notification_configs", + jsonColumns: [ + "enabled_channels", + "telegram_config", + "webhook_config", + "wechatbot_config", + "email_config", + "bark_config", + "slack_config", + "feishu_config", + "discord_config", + "notification_hours", + ], + userColumn: "user_id", + orderBy: "user_id", + generatedOnMerge: ["user_id"], + replaceOnMerge: true, + }, + { + name: "system_settings", + jsonColumns: [], + userColumn: "key", + orderBy: "key", + generatedOnMerge: [], + }, + { + name: "notification_history", + jsonColumns: [], + userColumn: "user_id", + orderBy: "id", + generatedOnMerge: [], + }, +]; + +export const TABLE_BY_NAME: Record = Object.fromEntries( + BACKUP_TABLES.map((spec) => [spec.name, spec]), +) as Record; + +export type BackupRow = Record; +export type BackupData = Record; + +export interface PlainExportFile { + format: typeof BACKUP_FORMAT; + format_version: number; + app_version: string; + exported_at: string; + scope: BackupScope; + data: BackupData; +} + +/** Columns that must never be imported from a merge-mode file. */ +export const MERGE_IGNORED_TABLES: readonly BackupTable[] = [ + "users", + "user_2fa", + "system_settings", + "notification_history", +]; + +/** Default-dropped log table: exported only when the caller opts in. */ +export const HISTORY_TABLE: BackupTable = "notification_history"; + +export function emptyData(): BackupData { + return { + users: [], + user_2fa: [], + items: [], + payment_history: [], + notification_configs: [], + system_settings: [], + notification_history: [], + }; +} + +export function countRows(data: BackupData): Record { + const counts = {} as Record; + for (const spec of BACKUP_TABLES) counts[spec.name] = data[spec.name].length; + return counts; +} + +function isPlainObject(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +/** + * Row serializer: DB row → file row. JSON columns become parsed values; a + * value that fails to parse is kept as the original string and flagged in + * `_raw` so importing it back cannot silently reshape the data. + */ +export function serializeRow(spec: TableSpec, row: BackupRow): BackupRow { + const out: BackupRow = {}; + const raw: string[] = []; + + for (const [column, value] of Object.entries(row)) { + if (!spec.jsonColumns.includes(column)) { + out[column] = value === undefined ? null : value; + continue; + } + if (value === null || value === undefined) { + out[column] = null; + continue; + } + if (typeof value === "string") { + try { + out[column] = JSON.parse(value); + } catch { + out[column] = value; + raw.push(column); + } + continue; + } + out[column] = value; + } + + if (raw.length > 0) out._raw = raw; + return out; +} + +/** Columns of a file row flagged as "keep the raw string" by the exporter. */ +export function rawColumnsOf(row: BackupRow): string[] { + const raw = row._raw; + if (!Array.isArray(raw)) return []; + return raw.filter((c): c is string => typeof c === "string"); +} + +/** + * File → DB value for one column. Returns the value to bind into the INSERT. + * + * - JSON columns: marked-raw columns are written back as the original string; + * everything else is JSON.stringify'd (parsed JSON value → text). A string + * value that already parses as JSON is written verbatim. + * - all other columns: written as-is (IDs, timestamps, amounts stay untouched). + */ +export function deserializeValue( + spec: TableSpec, + column: string, + value: unknown, + rawColumns: readonly string[], +): unknown { + if (value === null || value === undefined) return null; + if (!spec.jsonColumns.includes(column)) return value; + if (rawColumns.includes(column)) return value; + if (typeof value === "string") { + try { + JSON.parse(value); + return value; + } catch { + return JSON.stringify(value); + } + } + return JSON.stringify(value); +} + +/** Loosely validates a decrypted/plain file and normalizes absent tables. */ +export function assertPlainExport(input: unknown): PlainExportFile { + if (!isPlainObject(input)) { + throw new BackupError("INVALID_FILE", 400, "导入内容不是有效的 JSON 对象"); + } + + if (input.format === BACKUP_ENCRYPTED_FORMAT) { + throw new BackupError( + "INVALID_FORMAT", + 400, + "文件已加密,请提供口令后重试", + { encrypted: true }, + ); + } + if (input.format !== BACKUP_FORMAT) { + throw new BackupError( + "INVALID_FORMAT", + 400, + `文件格式不是 ${BACKUP_FORMAT},无法导入`, + ); + } + + const version = input.format_version; + if ( + typeof version !== "number" || + !Number.isInteger(version) || + version < 1 + ) { + throw new BackupError( + "INVALID_FORMAT", + 400, + "文件缺少有效的 format_version", + ); + } + if (version > BACKUP_FORMAT_VERSION) { + throw new BackupError( + "UNSUPPORTED_FORMAT_VERSION", + 400, + `文件 format_version 为 ${version},本服务最高支持 ${BACKUP_FORMAT_VERSION},请升级 eNotify 后再导入`, + { file_format_version: version, supported: BACKUP_FORMAT_VERSION }, + ); + } + + const scope = input.scope; + if (scope !== "instance" && scope !== "user") { + throw new BackupError( + "INVALID_SCOPE", + 400, + '文件的 scope 必须是 "instance" 或 "user"', + ); + } + + const rawData = input.data; + if (!isPlainObject(rawData)) { + throw new BackupError("INVALID_FILE", 400, "文件缺少 data 对象"); + } + + const data = emptyData(); + for (const spec of BACKUP_TABLES) { + const tableRows = rawData[spec.name]; + if (tableRows === undefined || tableRows === null) { + data[spec.name] = []; + continue; + } + if (!Array.isArray(tableRows)) { + throw new BackupError("INVALID_ROW", 400, `data.${spec.name} 必须是数组`); + } + data[spec.name] = tableRows.map((row, index) => { + if (!isPlainObject(row)) { + throw new BackupError( + "INVALID_ROW", + 400, + `data.${spec.name}[${index}] 必须是对象(行 = 以列名为键的对象)`, + ); + } + return row; + }); + } + + return { + format: BACKUP_FORMAT, + format_version: version, + app_version: + typeof input.app_version === "string" ? input.app_version : "unknown", + exported_at: typeof input.exported_at === "string" ? input.exported_at : "", + scope, + data, + }; +} diff --git a/worker/src/lib/backup/import.ts b/worker/src/lib/backup/import.ts new file mode 100644 index 0000000..60f9061 --- /dev/null +++ b/worker/src/lib/backup/import.ts @@ -0,0 +1,897 @@ +/** + * Import: dry-run preview, restore (full instance) and merge (personal data + * into the signed-in account). + * + * Atomicity model (parent issue ONE-358 "导入语义"): + * - Every write of an import is built as ONE `db.batch([...])` call. D1 runs a + * batch as a single SQL transaction: if any statement fails, the whole batch + * is rolled back, so a failed import can never leave half the tables written + * or a payment row pointing at a missing item. + * - The batch is only built after a full validation pass (format, row shapes, + * required columns, in-file duplicate keys, in-file reference integrity), so + * avoidable failures are rejected before any write. + * - Row counts are captured before the batch and asserted again afterwards; a + * mismatch (which the transaction rules out) is reported instead of being + * silently accepted. A preview taken against a database that has changed + * since is rejected with STALE_PREVIEW rather than writing against a stale + * plan. + */ +import { generateId } from "../../core/auth"; +import { BackupError, type BackupErrorCode } from "./errors"; +import { + BACKUP_TABLES, + HISTORY_TABLE, + MERGE_IGNORED_TABLES, + TABLE_BY_NAME, + deserializeValue, + rawColumnsOf, + type BackupRow, + type BackupScope, + type BackupTable, + type PlainExportFile, + type TableSpec, +} from "./format"; + +export type ImportMode = "restore" | "merge"; + +export interface ImportActor { + id: string; + email: string; +} + +export interface ImportBlocker { + code: BackupErrorCode; + message: string; +} + +export interface ImportUserSummary { + id: string; + email: string; + role: string; +} + +export interface ImportPreview { + mode: ImportMode; + scope: BackupScope; + encrypted: boolean; + format_version: number; + app_version: string; + exported_at: string; + counts: Record; + will_write: Record; + users: ImportUserSummary[]; + can_execute: boolean; + blockers: ImportBlocker[]; + conflicts: { + target_users: number; + email_conflicts: string[]; + settings_overwritten: string[]; + config_overwritten: boolean; + skipped_orphan_payments: number; + skipped_foreign_items: number; + skipped_foreign_payments: number; + skipped_history_rows: number; + }; + ignored_tables: BackupTable[]; + warnings: string[]; +} + +export interface ImportResult { + ok: true; + mode: ImportMode; + scope: BackupScope; + written: Record; + total_written: number; + notices: string[]; + warnings: string[]; +} + +interface ColumnInfo { + name: string; + notNull: boolean; + hasDefault: boolean; + pk: boolean; +} + +type ColumnsByTable = Record; + +interface BoundRow { + columns: string[]; + values: unknown[]; +} + +interface TablePlan { + table: BackupTable; + spec: TableSpec; + /** INSERT OR REPLACE (config replacement / settings upsert) vs plain INSERT. */ + upsert: boolean; + rows: BoundRow[]; + /** Absolute row count this table must have after a successful write. */ + expectedAfter: number; +} + +interface ImportPlan { + mode: ImportMode; + file: PlainExportFile; + tables: TablePlan[]; + before: Record; + preview: ImportPreview; +} + +const MAX_ROW_MESSAGES = 20; + +// ─── introspection / counts ─────────────────────────────────────────────────── + +async function introspectTable( + db: D1Database, + prefix: string, + table: BackupTable, +): Promise { + const result = await db.prepare(`PRAGMA table_info(${prefix}${table})`).all<{ + name: string; + notnull: number; + dflt_value: unknown; + pk: number; + }>(); + const rows = result.results ?? []; + if (rows.length === 0) { + throw new BackupError( + "TABLE_MISSING", + 500, + `数据表 ${prefix}${table} 不存在,请先完成数据库初始化`, + ); + } + return rows.map((row) => ({ + name: row.name, + notNull: Number(row.notnull) === 1, + hasDefault: row.dflt_value !== null && row.dflt_value !== undefined, + pk: Number(row.pk) > 0, + })); +} + +async function introspectAll( + db: D1Database, + prefix: string, +): Promise { + const out = {} as ColumnsByTable; + for (const spec of BACKUP_TABLES) { + out[spec.name] = await introspectTable(db, prefix, spec.name); + } + return out; +} + +async function countTable( + db: D1Database, + prefix: string, + table: BackupTable, +): Promise { + const row = await db + .prepare(`SELECT COUNT(*) AS n FROM ${prefix}${table}`) + .first<{ n: number }>(); + return Number(row?.n ?? 0); +} + +async function countAll( + db: D1Database, + prefix: string, +): Promise> { + const out = {} as Record; + for (const spec of BACKUP_TABLES) { + out[spec.name] = await countTable(db, prefix, spec.name); + } + return out; +} + +// ─── row binding ────────────────────────────────────────────────────────────── + +function coerceScalar(value: unknown): unknown { + if (typeof value === "boolean") return value ? 1 : 0; + return value; +} + +/** + * Turns a file row into an explicit column/value list for the CURRENT schema: + * unknown columns are dropped, absent columns are left to the DB defaults, + * `_raw`-flagged JSON columns are written back as the original string. + */ +function bindRow( + spec: TableSpec, + row: BackupRow, + columns: ColumnInfo[], + /** Row description used in validation messages. */ + label: string, +): { bound: BoundRow; problems: ImportBlocker[] } { + const rawColumns = rawColumnsOf(row); + const bound: BoundRow = { columns: [], values: [] }; + const problems: ImportBlocker[] = []; + + for (const column of columns) { + if (!(column.name in row)) { + if (column.notNull && !column.hasDefault) { + problems.push({ + code: "MISSING_COLUMN", + message: `${label} 缺少必填列 ${column.name}`, + }); + } + continue; + } + const value = deserializeValue( + spec, + column.name, + row[column.name], + rawColumns, + ); + if (value === null) { + if (column.notNull) { + problems.push({ + code: "INVALID_ROW", + message: `${label} 的 ${column.name} 不能为空`, + }); + continue; + } + bound.columns.push(column.name); + bound.values.push(null); + continue; + } + if (typeof value === "object") { + // Only JSON columns may hold objects/arrays; deserializeValue already + // stringified them, so reaching here means a non-JSON column was given a + // structured value. + problems.push({ + code: "INVALID_ROW", + message: `${label} 的 ${column.name} 必须是标量值`, + }); + continue; + } + bound.columns.push(column.name); + bound.values.push(coerceScalar(value)); + } + + return { bound, problems }; +} + +// ─── validation helpers ─────────────────────────────────────────────────────── + +function collectDuplicates( + rows: BackupRow[], + columns: string[], + label: string, +): ImportBlocker[] { + const blockers: ImportBlocker[] = []; + const seen = new Map(); + for (const row of rows) { + const values = columns.map((c) => String(row[c] ?? "")); + if (values.every((value) => value === "")) continue; + // JSON keeps the composite key unambiguous (no separator collisions). + const key = JSON.stringify(values); + const entry = seen.get(key); + if (entry) entry.count += 1; + else seen.set(key, { display: values.join("/"), count: 1 }); + } + for (const { display, count } of seen.values()) { + if (count > 1) { + blockers.push({ + code: "DUPLICATE_KEY", + message: `${label} 中主键 ${display} 重复出现 ${count} 次`, + }); + } + } + return blockers; +} + +function idsOf(rows: BackupRow[], column: string): Set { + const ids = new Set(); + for (const row of rows) { + const value = row[column]; + if (typeof value === "string" && value !== "") ids.add(value); + } + return ids; +} + +function missingReferences( + rows: BackupRow[], + column: string, + targets: Set, +): number { + let missing = 0; + for (const row of rows) { + const value = row[column]; + if (value === null || value === undefined) continue; + if (typeof value !== "string" || !targets.has(value)) missing += 1; + } + return missing; +} + +function emptyCounts(): Record { + const out = {} as Record; + for (const spec of BACKUP_TABLES) out[spec.name] = 0; + return out; +} + +function fileCounts(file: PlainExportFile): Record { + const out = {} as Record; + for (const spec of BACKUP_TABLES) + out[spec.name] = file.data[spec.name].length; + return out; +} + +function summarizeUsers(file: PlainExportFile): ImportUserSummary[] { + return file.data.users.map((row) => ({ + id: typeof row.id === "string" ? row.id : "", + email: typeof row.email === "string" ? row.email : "", + role: typeof row.role === "string" ? row.role : "", + })); +} + +function newBlocker(code: BackupErrorCode, message: string): ImportBlocker { + return { code, message }; +} + +// ─── restore plan ───────────────────────────────────────────────────────────── + +async function planRestore( + db: D1Database, + prefix: string, + file: PlainExportFile, + encrypted: boolean, +): Promise { + if (file.scope !== "instance") { + throw new BackupError( + "MODE_NOT_ALLOWED", + 400, + '恢复模式只接受 scope 为 "instance" 的全站导出文件;个人档文件请使用合并导入', + ); + } + + const columns = await introspectAll(db, prefix); + const before = await countAll(db, prefix); + const blockers: ImportBlocker[] = []; + const warnings: string[] = []; + + if (before.users > 0) { + blockers.push( + newBlocker( + "RESTORE_TARGET_NOT_EMPTY", + `目标实例的 users 表已有 ${before.users} 个用户。恢复模式只允许在空实例上执行(不提供覆盖选项)`, + ), + ); + } + + // Validate every row of every table before planning writes. + const boundRows = {} as Record; + for (const spec of BACKUP_TABLES) { + const rows = file.data[spec.name]; + const bound: BoundRow[] = []; + for (let i = 0; i < rows.length; i++) { + const { bound: row, problems } = bindRow( + spec, + rows[i], + columns[spec.name], + `data.${spec.name}[${i}]`, + ); + for (const problem of problems) { + if (blockers.length < MAX_ROW_MESSAGES) blockers.push(problem); + } + bound.push(row); + } + boundRows[spec.name] = bound; + } + + // In-file key duplicates would make the batch fail; surface them up front. + for (const spec of BACKUP_TABLES) { + const pkColumns = columns[spec.name].filter((c) => c.pk).map((c) => c.name); + const keyColumns = pkColumns.length > 0 ? pkColumns : [spec.userColumn]; + for (const blocker of collectDuplicates( + file.data[spec.name], + keyColumns, + `data.${spec.name}`, + )) { + if (blockers.length < MAX_ROW_MESSAGES) blockers.push(blocker); + } + } + const duplicateEmails = new Set(); + const seenEmails = new Set(); + for (const user of file.data.users) { + const email = + typeof user.email === "string" ? user.email.trim().toLowerCase() : ""; + if (!email) continue; + if (seenEmails.has(email)) duplicateEmails.add(email); + seenEmails.add(email); + } + for (const email of duplicateEmails) { + blockers.push( + newBlocker("DUPLICATE_KEY", `data.users 中邮箱 ${email} 重复出现`), + ); + } + + // Restore targets an empty instance, so every reference must resolve inside + // the file — no dangling pointers may be created. + const userIds = idsOf(file.data.users, "id"); + const itemIds = idsOf(file.data.items, "id"); + const referenceChecks: { + table: BackupTable; + column: string; + targets: Set; + label: string; + }[] = [ + { + table: "user_2fa", + column: "user_id", + targets: userIds, + label: "users.id", + }, + { table: "items", column: "user_id", targets: userIds, label: "users.id" }, + { + table: "payment_history", + column: "item_id", + targets: itemIds, + label: "items.id", + }, + { + table: "payment_history", + column: "user_id", + targets: userIds, + label: "users.id", + }, + { + table: "notification_configs", + column: "user_id", + targets: userIds, + label: "users.id", + }, + { + table: "notification_history", + column: "item_id", + targets: itemIds, + label: "items.id", + }, + { + table: "notification_history", + column: "user_id", + targets: userIds, + label: "users.id", + }, + ]; + for (const check of referenceChecks) { + const missing = missingReferences( + file.data[check.table], + check.column, + check.targets, + ); + if (missing > 0) { + blockers.push( + newBlocker( + "REFERENCE_MISSING", + `data.${check.table} 中有 ${missing} 行的 ${check.column} 找不到对应的 ${check.label}`, + ), + ); + } + } + + // system_settings are upserted: existing keys (installed defaults) are + // overwritten by the file's values instead of aborting the whole restore. + const existingSettings = new Set(); + if (file.data.system_settings.length > 0) { + const result = await db + .prepare(`SELECT key FROM ${prefix}system_settings`) + .all<{ key: string }>(); + for (const row of result.results ?? []) existingSettings.add(row.key); + } + const settingsOverwritten = file.data.system_settings + .map((row) => (typeof row.key === "string" ? row.key : "")) + .filter((key) => key && existingSettings.has(key)); + + if (file.data[HISTORY_TABLE].length === 0) { + warnings.push( + "该文件不含通知历史(导出时未勾选「包含通知历史」),恢复后历史记录为空", + ); + } + warnings.push( + "API Key 不包含在导出文件中(服务端只保存其哈希),恢复后需要重新签发", + ); + + const tables: TablePlan[] = []; + const willWrite = emptyCounts(); + for (const spec of BACKUP_TABLES) { + const rows = boundRows[spec.name]; + const upsert = spec.name === "system_settings"; + let expectedAfter = before[spec.name] + rows.length; + if (upsert) { + const replaced = file.data.system_settings.filter( + (row) => typeof row.key === "string" && existingSettings.has(row.key), + ).length; + expectedAfter = before[spec.name] + rows.length - replaced; + } + willWrite[spec.name] = rows.length; + tables.push({ table: spec.name, spec, upsert, rows, expectedAfter }); + } + + const preview: ImportPreview = { + mode: "restore", + scope: file.scope, + encrypted, + format_version: file.format_version, + app_version: file.app_version, + exported_at: file.exported_at, + counts: fileCounts(file), + will_write: willWrite, + users: summarizeUsers(file), + can_execute: blockers.length === 0, + blockers, + conflicts: { + target_users: before.users, + email_conflicts: [], + settings_overwritten: settingsOverwritten, + config_overwritten: false, + skipped_orphan_payments: 0, + skipped_foreign_items: 0, + skipped_foreign_payments: 0, + skipped_history_rows: 0, + }, + ignored_tables: [], + warnings, + }; + + return { mode: "restore", file, tables, before, preview }; +} + +// ─── merge plan ─────────────────────────────────────────────────────────────── + +async function planMerge( + db: D1Database, + prefix: string, + file: PlainExportFile, + actor: ImportActor, + encrypted: boolean, +): Promise { + const columns = await introspectAll(db, prefix); + const before = await countAll(db, prefix); + const blockers: ImportBlocker[] = []; + const warnings: string[] = []; + const actorEmail = actor.email.trim().toLowerCase(); + + const sourceUser = file.data.users.find( + (row) => + typeof row.email === "string" && + row.email.trim().toLowerCase() === actorEmail, + ); + if (!sourceUser || typeof sourceUser.id !== "string" || !sourceUser.id) { + throw new BackupError( + "MERGE_SOURCE_NOT_FOUND", + 400, + `文件中没有属于当前账号(${actor.email})的数据,无法合并导入`, + ); + } + const sourceUserId = sourceUser.id; + + const itemRows = file.data.items.filter((row) => + typeof row.user_id === "string" ? row.user_id === sourceUserId : false, + ); + const paymentRows = file.data.payment_history.filter((row) => + typeof row.user_id === "string" ? row.user_id === sourceUserId : false, + ); + const configRows = file.data.notification_configs.filter((row) => + typeof row.user_id === "string" ? row.user_id === sourceUserId : false, + ); + + const skippedForeignItems = file.data.items.length - itemRows.length; + const skippedForeignPayments = + file.data.payment_history.length - paymentRows.length; + const skippedHistoryRows = file.data[HISTORY_TABLE].length; + + // items: new ids, owner rewritten. + const idMap = new Map(); + const itemBound: BoundRow[] = []; + for (let i = 0; i < itemRows.length; i++) { + const row = itemRows[i]; + const newId = generateId(); + if (typeof row.id === "string" && row.id) idMap.set(row.id, newId); + const { bound, problems } = bindRow( + TABLE_BY_NAME.items, + { ...row, id: newId, user_id: actor.id }, + columns.items, + `data.items[${i}]`, + ); + for (const p of problems) { + if (blockers.length < MAX_ROW_MESSAGES) blockers.push(p); + } + itemBound.push(bound); + } + + // payment_history: new ids, item_id remapped through idMap. + const paymentBound: BoundRow[] = []; + let skippedOrphanPayments = 0; + for (let i = 0; i < paymentRows.length; i++) { + const row = paymentRows[i]; + const oldItemId = typeof row.item_id === "string" ? row.item_id : ""; + const newItemId = oldItemId ? idMap.get(oldItemId) : undefined; + if (!newItemId) { + skippedOrphanPayments += 1; + continue; + } + const { bound, problems } = bindRow( + TABLE_BY_NAME.payment_history, + { ...row, id: generateId(), item_id: newItemId, user_id: actor.id }, + columns.payment_history, + `data.payment_history[${i}]`, + ); + for (const p of problems) { + if (blockers.length < MAX_ROW_MESSAGES) blockers.push(p); + } + paymentBound.push(bound); + } + + // notification_configs: the whole row replaces the importer's config. + const configBound: BoundRow[] = []; + if (configRows.length > 0) { + const { bound, problems } = bindRow( + TABLE_BY_NAME.notification_configs, + { ...configRows[0], user_id: actor.id }, + columns.notification_configs, + "data.notification_configs[0]", + ); + for (const p of problems) { + if (blockers.length < MAX_ROW_MESSAGES) blockers.push(p); + } + configBound.push(bound); + } + + const existingConfig = await db + .prepare( + `SELECT 1 AS present FROM ${prefix}notification_configs WHERE user_id = ?`, + ) + .bind(actor.id) + .first<{ present: number }>(); + const configOverwritten = Boolean(existingConfig); + + if (configBound.length === 0) { + warnings.push("文件中没有你的渠道配置,当前渠道配置将保持不变"); + } else if (configOverwritten) { + warnings.push("文件中的渠道配置将整行覆盖你当前的渠道配置"); + } + if (skippedOrphanPayments > 0) { + warnings.push( + `有 ${skippedOrphanPayments} 条缴费记录引用了文件中不存在的通知,已跳过`, + ); + } + if (skippedHistoryRows > 0) { + warnings.push( + `合并模式不导入通知历史,已跳过 ${skippedHistoryRows} 条历史记录`, + ); + } + if (skippedForeignItems > 0 || skippedForeignPayments > 0) { + warnings.push( + `已忽略文件中属于其他账号的数据(通知 ${skippedForeignItems} 条、缴费 ${skippedForeignPayments} 条)`, + ); + } + warnings.push( + "合并模式忽略 users / user_2fa / system_settings / notification_history,账号与系统设置保持不变", + ); + warnings.push( + "API Key 不包含在导出文件中(服务端只保存其哈希),如来源实例不同需重新签发", + ); + + const tables: TablePlan[] = [ + { + table: "items", + spec: TABLE_BY_NAME.items, + upsert: false, + rows: itemBound, + expectedAfter: before.items + itemBound.length, + }, + { + table: "payment_history", + spec: TABLE_BY_NAME.payment_history, + upsert: false, + rows: paymentBound, + expectedAfter: before.payment_history + paymentBound.length, + }, + { + table: "notification_configs", + spec: TABLE_BY_NAME.notification_configs, + upsert: true, + rows: configBound, + expectedAfter: + configBound.length > 0 + ? before.notification_configs + (configOverwritten ? 0 : 1) + : before.notification_configs, + }, + ]; + + const willWrite = emptyCounts(); + for (const plan of tables) willWrite[plan.table] = plan.rows.length; + + const preview: ImportPreview = { + mode: "merge", + scope: file.scope, + encrypted, + format_version: file.format_version, + app_version: file.app_version, + exported_at: file.exported_at, + counts: fileCounts(file), + will_write: willWrite, + users: summarizeUsers(file), + can_execute: blockers.length === 0, + blockers, + conflicts: { + target_users: before.users, + email_conflicts: [], + settings_overwritten: [], + config_overwritten: configOverwritten, + skipped_orphan_payments: skippedOrphanPayments, + skipped_foreign_items: skippedForeignItems, + skipped_foreign_payments: skippedForeignPayments, + skipped_history_rows: skippedHistoryRows, + }, + ignored_tables: [...MERGE_IGNORED_TABLES], + warnings, + }; + + return { mode: "merge", file, tables, before, preview }; +} + +// ─── public API ─────────────────────────────────────────────────────────────── + +export interface ImportOptions { + mode: ImportMode; + actor: ImportActor; + /** True when the uploaded file was an encrypted envelope. */ + encrypted?: boolean; +} + +/** Dry run: validates the file and reports what would be written. */ +export async function previewImport( + db: D1Database, + prefix: string, + file: PlainExportFile, + options: ImportOptions, +): Promise { + const plan = + options.mode === "restore" + ? await planRestore(db, prefix, file, Boolean(options.encrypted)) + : await planMerge( + db, + prefix, + file, + options.actor, + Boolean(options.encrypted), + ); + return plan.preview; +} + +function buildInsert( + db: D1Database, + prefix: string, + table: BackupTable, + row: BoundRow, + upsert: boolean, +): D1PreparedStatement { + const verb = upsert ? "INSERT OR REPLACE INTO" : "INSERT INTO"; + const columnList = row.columns.join(", "); + const placeholders = row.columns.map(() => "?").join(", "); + return db + .prepare( + `${verb} ${prefix}${table} (${columnList}) VALUES (${placeholders})`, + ) + .bind(...row.values); +} + +/** + * Guards the write path against a database that moved between planning and + * writing: any per-table row-count difference aborts with STALE_PREVIEW. + */ +export function assertCountsUnchanged( + before: Record, + current: Record, +): void { + for (const spec of BACKUP_TABLES) { + if (current[spec.name] !== before[spec.name]) { + throw new BackupError( + "STALE_PREVIEW", + 409, + "数据库在上次预检后已发生变化,请重新预检后再导入", + { + table: spec.name, + expected: before[spec.name], + actual: current[spec.name], + }, + ); + } + } +} + +/** + * Executes an import: plans afresh (a preview payload is never trusted as the + * write plan), refuses on blockers, writes everything in one atomic batch and + * verifies the resulting row counts. + */ +export async function executeImport( + db: D1Database, + prefix: string, + file: PlainExportFile, + options: ImportOptions, +): Promise { + const plan = + options.mode === "restore" + ? await planRestore(db, prefix, file, Boolean(options.encrypted)) + : await planMerge( + db, + prefix, + file, + options.actor, + Boolean(options.encrypted), + ); + + if (plan.preview.blockers.length > 0) { + const first = plan.preview.blockers[0]; + throw new BackupError( + first.code, + options.mode === "restore" ? 409 : 400, + first.message, + { blockers: plan.preview.blockers }, + ); + } + + // Refuse to write against a database that changed since planning. + assertCountsUnchanged(plan.before, await countAll(db, prefix)); + + const statements: D1PreparedStatement[] = []; + for (const tablePlan of plan.tables) { + for (const row of tablePlan.rows) { + if (row.columns.length === 0) continue; + statements.push( + buildInsert(db, prefix, tablePlan.table, row, tablePlan.upsert), + ); + } + } + + if (statements.length > 0) { + try { + // One batch = one SQL transaction in D1: all or nothing. + await db.batch(statements); + } catch (err) { + throw new BackupError( + "WRITE_FAILED", + 500, + "写入失败,事务已整体回滚,数据库未发生任何变化", + { reason: err instanceof Error ? err.message : String(err) }, + ); + } + } + + // Post-write assertion: every table must hold exactly the expected count. + for (const tablePlan of plan.tables) { + const actual = await countTable(db, prefix, tablePlan.table); + if (actual !== tablePlan.expectedAfter) { + throw new BackupError( + "RESTORE_COUNT_MISMATCH", + 500, + `写入后 ${tablePlan.table} 的行数为 ${actual},与预期的 ${tablePlan.expectedAfter} 不一致`, + { table: tablePlan.table, expected: tablePlan.expectedAfter, actual }, + ); + } + } + + const written = emptyCounts(); + for (const tablePlan of plan.tables) + written[tablePlan.table] = tablePlan.rows.length; + const totalWritten = Object.values(written).reduce((a, b) => a + b, 0); + + const notices: string[] = []; + if (plan.mode === "restore") { + notices.push("恢复完成:API Key 需重新签发,所有用户需要重新登录"); + if (written.users > 0) { + notices.push(`已恢复 ${written.users} 个用户及其数据`); + } + } + + return { + ok: true, + mode: plan.mode, + scope: plan.file.scope, + written, + total_written: totalWritten, + notices, + warnings: plan.preview.warnings, + }; +} diff --git a/worker/src/routes/backup.ts b/worker/src/routes/backup.ts new file mode 100644 index 0000000..9f12d47 --- /dev/null +++ b/worker/src/routes/backup.ts @@ -0,0 +1,413 @@ +/** + * Export / import ("backup") endpoints. + * + * me POST /api/me/export + * POST /api/me/import/preview + * POST /api/me/import + * admin POST /api/admin/export + * POST /api/admin/import/preview + * POST /api/admin/import + * + * Authentication is cookie session only. An API key (Authorization: Bearer + * enk_...) is explicitly rejected: an export file is a master key bundle, so + * these endpoints intentionally do not accept long-lived programmatic + * credentials. Admin routes additionally require the admin role. + * + * Uploads are JSON request bodies (the web client already posts JSON through + * `web/src/lib/api.ts`); the file itself may be sent either as a parsed object + * (`{ file: {...} }`) or as the raw file text (`{ file: "" }`), and + * the whole request body is capped at 10 MB. + */ +import { Hono } from "hono"; +import type { Context, Next } from "hono"; +import type { ContentfulStatusCode } from "hono/utils/http-status"; +import { API_KEY_PREFIX } from "../core/apiKey"; +import { findUserById } from "../db/queries/users"; +import { authMiddleware, getEffectiveUserId } from "../middleware/auth"; +import { adminMiddleware } from "../middleware/admin"; +import { rateLimit } from "../middleware/ratelimit"; +import { getTablePrefix, type HonoEnv } from "../types"; +import { BackupError } from "../lib/backup/errors"; +import { buildExportFile } from "../lib/backup/export"; +import { + decryptExport, + encryptExport, + isEncryptedEnvelope, +} from "../lib/backup/crypto"; +import { assertPlainExport, type PlainExportFile } from "../lib/backup/format"; +import { + executeImport, + previewImport, + type ImportMode, + type ImportResult, +} from "../lib/backup/import"; + +/** Hard cap for an uploaded import body (parent spec suggests 10 MB). */ +export const MAX_UPLOAD_BYTES = 10 * 1024 * 1024; + +type BackupContext = Context; + +// ─── helpers ────────────────────────────────────────────────────────────────── + +function isPlainObject(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function tooLarge(): BackupError { + return new BackupError( + "PAYLOAD_TOO_LARGE", + 413, + `上传内容超过上限 ${MAX_UPLOAD_BYTES} 字节(10MB)`, + { max_bytes: MAX_UPLOAD_BYTES }, + ); +} + +/** Reads the request body once, enforcing the size cap before parsing. */ +async function readJsonBody( + c: BackupContext, +): Promise> { + const declared = Number(c.req.header("content-length") ?? "0"); + if (Number.isFinite(declared) && declared > MAX_UPLOAD_BYTES) + throw tooLarge(); + + const text = await c.req.text(); + if (new TextEncoder().encode(text).length > MAX_UPLOAD_BYTES) + throw tooLarge(); + if (!text.trim()) return {}; + + let parsed: unknown; + try { + parsed = JSON.parse(text); + } catch { + throw new BackupError("INVALID_REQUEST", 400, "请求体必须是 JSON"); + } + if (!isPlainObject(parsed)) { + throw new BackupError("INVALID_REQUEST", 400, "请求体必须是 JSON 对象"); + } + return parsed; +} + +interface ImportPayload { + /** Parsed export object or the raw file text. */ + file: unknown; + passphrase: string; +} + +function readImportPayload(body: Record): ImportPayload { + const passphrase = typeof body.passphrase === "string" ? body.passphrase : ""; + + let file = body.file; + if (typeof file === "string") { + if (new TextEncoder().encode(file).length > MAX_UPLOAD_BYTES) + throw tooLarge(); + try { + file = JSON.parse(file); + } catch { + throw new BackupError("INVALID_FILE", 400, "上传的文件不是有效的 JSON"); + } + } + if (file === undefined || file === null) { + throw new BackupError( + "INVALID_REQUEST", + 400, + "缺少 file 字段(导入文件内容)", + ); + } + return { file, passphrase }; +} + +/** Decrypts if needed and validates the frozen v1 format contract. */ +async function resolveImportFile( + payload: ImportPayload, +): Promise<{ plain: PlainExportFile; encrypted: boolean }> { + const encrypted = isEncryptedEnvelope(payload.file); + const decoded = encrypted + ? await decryptExport(payload.file, payload.passphrase) + : payload.file; + return { plain: assertPlainExport(decoded), encrypted }; +} + +/** + * Audit sink: exports and imports each emit one structured `[audit]` line with + * the operator, scope/mode, whether the file was encrypted and the per-table + * row counts. Passphrases never reach this function. + * (The current schema has no audit table; this follows the existing `[audit]` + * console convention used for admin impersonation.) + */ +function writeAudit(event: Record): void { + console.log(`[audit] backup ${JSON.stringify(event)}`); +} + +async function loadActor( + db: D1Database, + prefix: string, + userId: string, +): Promise<{ id: string; email: string }> { + const user = await findUserById(db, prefix, userId); + if (!user) throw new BackupError("INVALID_REQUEST", 401, "Unauthorized"); + return { id: user.id, email: user.email }; +} + +/** + * Merge needs the operator's real account row (its id and email drive the + * rewrite). Restore runs against an instance whose `users` table is empty by + * definition, so the operator is identified by the signed session alone — + * looking their row up would always fail on a fresh instance. + */ +async function resolveActor( + c: BackupContext, + mode: ImportMode, +): Promise<{ id: string; email: string }> { + const userId = getEffectiveUserId(c); + if (mode === "merge") { + return loadActor(c.env.DB, getTablePrefix(c.env), userId); + } + return { id: userId, email: "" }; +} + +function timestampForFilename(): string { + return new Date().toISOString().replace(/[-:]/g, "").replace(/\..+$/, "Z"); +} + +/** + * These endpoints never accept API-key auth: a backup file is a master key + * bundle, so it must be produced/consumed with an interactive session. + */ +async function rejectApiKeyAuth( + c: BackupContext, + next: Next, +): Promise { + const bearer = c.req.header("Authorization")?.match(/^Bearer\s+(\S+)$/i)?.[1]; + if (bearer?.startsWith(API_KEY_PREFIX)) { + return c.json( + { + error: "导出/导入接口不接受 API Key,请使用浏览器会话登录后再操作", + code: "API_KEY_NOT_ALLOWED", + }, + 403, + ); + } + await next(); + return undefined; +} + +function errorResponse(c: BackupContext, err: unknown): Response { + if (err instanceof BackupError) { + return c.json( + { + error: err.message, + code: err.code, + ...(err.details === undefined ? {} : { details: err.details }), + }, + err.status as ContentfulStatusCode, + ); + } + console.error("Backup endpoint failed:", err); + return c.json({ error: "Internal server error" }, 500); +} + +function jsonHandler(handler: (c: BackupContext) => Promise) { + return async (c: BackupContext): Promise => { + try { + return await handler(c); + } catch (err) { + return errorResponse(c, err); + } + }; +} + +// ─── shared handlers ────────────────────────────────────────────────────────── + +async function exportHandler( + c: BackupContext, + scope: "instance" | "user", +): Promise { + const body = await readJsonBody(c); + const encrypted = body.encrypted !== false; // encrypted by default + const passphrase = typeof body.passphrase === "string" ? body.passphrase : ""; + const includeHistory = body.include_history === true; + + if (encrypted && !passphrase) { + throw new BackupError( + "PASSPHRASE_REQUIRED", + 400, + "加密导出必须提供口令;若要导出明文文件,请显式传 encrypted: false", + ); + } + + const prefix = getTablePrefix(c.env); + const userId = getEffectiveUserId(c); + const { file, counts } = await buildExportFile(c.env.DB, prefix, { + scope, + userId: scope === "user" ? userId : undefined, + includeHistory, + }); + const payload = encrypted ? await encryptExport(file, passphrase) : file; + + writeAudit({ + action: "export", + scope, + operator: c.get("userId"), + impersonating: c.get("impersonating") ?? null, + encrypted, + include_history: includeHistory, + rows: counts, + at: new Date().toISOString(), + }); + + const filename = `enotify-${scope}-${timestampForFilename()}-${ + encrypted ? "encrypted" : "plain" + }.json`; + + return new Response(JSON.stringify(payload, null, 2), { + status: 200, + headers: { + "Content-Type": "application/json; charset=utf-8", + "Content-Disposition": `attachment; filename="${filename}"`, + "Cache-Control": "no-store", + Pragma: "no-cache", + }, + }); +} + +async function previewHandler( + c: BackupContext, + resolveMode: (body: Record) => ImportMode, +): Promise { + const body = await readJsonBody(c); + const mode = resolveMode(body); + const payload = readImportPayload(body); + const { plain, encrypted } = await resolveImportFile(payload); + + const prefix = getTablePrefix(c.env); + const actor = await resolveActor(c, mode); + const preview = await previewImport(c.env.DB, prefix, plain, { + mode, + actor, + encrypted, + }); + return c.json({ ok: true, ...preview }); +} + +async function importHandler( + c: BackupContext, + fixedMode: ImportMode | undefined, +): Promise { + const body = await readJsonBody(c); + const requestedMode = body.mode; + + let mode: ImportMode; + if (fixedMode) { + if (requestedMode !== undefined && requestedMode !== fixedMode) { + throw new BackupError( + "MODE_NOT_ALLOWED", + 400, + `个人档导入只支持 mode: "${fixedMode}"`, + ); + } + mode = fixedMode; + } else if (requestedMode === undefined) { + mode = "restore"; + } else if (requestedMode === "restore" || requestedMode === "merge") { + mode = requestedMode; + } else { + throw new BackupError( + "INVALID_REQUEST", + 400, + 'mode 必须是 "restore" 或 "merge"', + ); + } + + const payload = readImportPayload(body); + const { plain, encrypted } = await resolveImportFile(payload); + + const prefix = getTablePrefix(c.env); + const actor = await resolveActor(c, mode); + + const result: ImportResult = await executeImport(c.env.DB, prefix, plain, { + mode, + actor, + encrypted, + }); + + writeAudit({ + action: "import", + mode, + scope: plain.scope, + operator: actor.id, + encrypted, + written: result.written, + at: new Date().toISOString(), + }); + + return c.json(result); +} + +// ─── routers ────────────────────────────────────────────────────────────────── + +/** + * Cheap abuse guard for the two expensive operations (PBKDF2 on the exported + * file, and bulk writes on import). Keyed by user, per endpoint group. + */ +const backupLimiter = rateLimit({ + max: 20, + window: 60, + keyPrefix: "backup", + keyFn: (c) => c.get("userId") ?? "", +}); + +export const meBackupRoutes = new Hono(); +meBackupRoutes.use("*", rejectApiKeyAuth); +meBackupRoutes.use("*", authMiddleware); +meBackupRoutes.use("*", backupLimiter); + +meBackupRoutes.post( + "/export", + jsonHandler((c) => exportHandler(c, "user")), +); + +meBackupRoutes.post( + "/import/preview", + jsonHandler((c) => previewHandler(c, () => "merge")), +); + +meBackupRoutes.post( + "/import", + jsonHandler((c) => importHandler(c, "merge")), +); + +export const adminBackupRoutes = new Hono(); +adminBackupRoutes.use("*", rejectApiKeyAuth); +adminBackupRoutes.use("*", authMiddleware); +adminBackupRoutes.use("*", adminMiddleware); +adminBackupRoutes.use("*", backupLimiter); + +adminBackupRoutes.post( + "/export", + jsonHandler((c) => exportHandler(c, "instance")), +); + +adminBackupRoutes.post( + "/import/preview", + jsonHandler((c) => previewHandler(c, adminPreviewMode)), +); + +adminBackupRoutes.post( + "/import", + jsonHandler((c) => importHandler(c, undefined)), +); + +/** + * Admin preview defaults to restore mode; an explicit `mode: "merge"` selects + * merge (into the signed-in admin account) instead. + */ +function adminPreviewMode(body: Record): ImportMode { + const mode = body.mode; + if (mode === undefined) return "restore"; + if (mode === "restore" || mode === "merge") return mode; + throw new BackupError( + "INVALID_REQUEST", + 400, + 'mode 必须是 "restore" 或 "merge"', + ); +} diff --git a/worker/test/backup-auth.test.ts b/worker/test/backup-auth.test.ts new file mode 100644 index 0000000..7e8138b --- /dev/null +++ b/worker/test/backup-auth.test.ts @@ -0,0 +1,154 @@ +import { describe, expect, it } from "vitest"; +import { + ADMIN, + BOB, + SqliteD1, + callWorker, + jsonPost, + makeBackupEnv, + seedInstance, +} from "./support/backup"; +import { cookieHeader, makeToken, seedSession } from "./helpers"; + +async function userCookie(env: any, userId = BOB.id, sid = "sess-bob") { + const token = await makeToken("user", { sub: userId, sid }); + await seedSession(env, userId, sid); + return cookieHeader(token); +} + +async function adminCookie(env: any) { + const token = await makeToken("admin", { sub: ADMIN.id, sid: "sess-admin" }); + await seedSession(env, ADMIN.id, "sess-admin"); + return cookieHeader(token); +} + +const ME_PATHS = ["/api/me/export", "/api/me/import/preview", "/api/me/import"]; +const ADMIN_PATHS = [ + "/api/admin/export", + "/api/admin/import/preview", + "/api/admin/import", +]; + +function seededEnv() { + const db = new SqliteD1(); + seedInstance(db); + return { db, env: makeBackupEnv(db) }; +} + +describe("session requirements", () => { + it.each([...ME_PATHS, ...ADMIN_PATHS])( + "rejects an unauthenticated request to %s with 401", + async (path) => { + const { env } = seededEnv(); + const res = await callWorker(env, path, jsonPost({})); + expect(res.status).toBe(401); + }, + ); + + it.each(ADMIN_PATHS)( + "rejects a non-admin session on %s with 403", + async (path) => { + const { env } = seededEnv(); + const res = await callWorker( + env, + path, + jsonPost({}, await userCookie(env)), + ); + expect(res.status).toBe(403); + }, + ); + + it("rejects an API key even when a valid session cookie is present", async () => { + const { env } = seededEnv(); + const cookie = await adminCookie(env); + const headers = { ...cookie, Authorization: "Bearer enk_live_key_123" }; + + const me = await callWorker(env, "/api/me/export", jsonPost({}, headers)); + expect(me.status).toBe(403); + expect(me.body.code).toBe("API_KEY_NOT_ALLOWED"); + + const admin = await callWorker( + env, + "/api/admin/export", + jsonPost({}, headers), + ); + expect(admin.status).toBe(403); + expect(admin.body.code).toBe("API_KEY_NOT_ALLOWED"); + }); + + it("rejects an API-key bearer on the import endpoints too", async () => { + const { env } = seededEnv(); + const res = await callWorker( + env, + "/api/admin/import", + jsonPost( + { file: {} }, + { + ...(await adminCookie(env)), + Authorization: "Bearer enk_another_key", + }, + ), + ); + expect(res.status).toBe(403); + expect(res.body.code).toBe("API_KEY_NOT_ALLOWED"); + }); +}); + +describe("request hardening", () => { + it("rejects an upload larger than 10 MB with 413", async () => { + const { env } = seededEnv(); + const huge = "x".repeat(10 * 1024 * 1024 + 16); + const res = await callWorker( + env, + "/api/admin/import", + jsonPost({ file: huge }, await adminCookie(env)), + ); + expect(res.status).toBe(413); + expect(res.body.code).toBe("PAYLOAD_TOO_LARGE"); + expect(res.body.details.max_bytes).toBe(10 * 1024 * 1024); + }); + + it("rejects a non-JSON request body with 400", async () => { + const { env } = seededEnv(); + const res = await callWorker(env, "/api/me/import", { + method: "POST", + headers: { + "Content-Type": "application/json", + ...(await userCookie(env)), + }, + body: "not json", + }); + expect(res.status).toBe(400); + expect(res.body.code).toBe("INVALID_REQUEST"); + }); + + it("rejects a request without a file field", async () => { + const { env } = seededEnv(); + const res = await callWorker( + env, + "/api/me/import/preview", + jsonPost({ passphrase: "pw" }, await userCookie(env)), + ); + expect(res.status).toBe(400); + expect(res.body.code).toBe("INVALID_REQUEST"); + expect(res.body.error).toContain("file"); + }); + + it("accepts the file as raw JSON text as well as a parsed object", async () => { + const { db, env } = seededEnv(); + const exported = await callWorker( + env, + "/api/admin/export", + jsonPost({ encrypted: false }, await adminCookie(env)), + ); + + const asText = await callWorker( + env, + "/api/admin/import/preview", + jsonPost({ file: JSON.stringify(exported.body) }, await adminCookie(env)), + ); + expect(asText.status).toBe(200); + expect(asText.body.can_execute).toBe(false); // non-empty target + expect(db.count("users")).toBe(3); + }); +}); diff --git a/worker/test/backup-crypto.test.ts b/worker/test/backup-crypto.test.ts new file mode 100644 index 0000000..b3254f4 --- /dev/null +++ b/worker/test/backup-crypto.test.ts @@ -0,0 +1,245 @@ +import { describe, expect, it } from "vitest"; +import { + ADMIN, + BOB, + SqliteD1, + callWorker, + jsonPost, + makeBackupEnv, + seedInstance, +} from "./support/backup"; +import { cookieHeader, makeToken, seedSession } from "./helpers"; +import { + PBKDF2_ITERATIONS, + decryptExport, + encryptExport, +} from "../src/lib/backup/crypto"; + +async function userCookie(env: any, userId = BOB.id, sid = "sess-bob") { + const token = await makeToken("user", { sub: userId, sid }); + await seedSession(env, userId, sid); + return cookieHeader(token); +} + +async function adminCookie(env: any) { + const token = await makeToken("admin", { sub: ADMIN.id, sid: "sess-admin" }); + await seedSession(env, ADMIN.id, "sess-admin"); + return cookieHeader(token); +} + +const PLAIN = { + format: "enotify-export", + format_version: 1, + app_version: "1.0.4", + exported_at: "2026-10-25T15:00:00.000Z", + scope: "user", + data: { + users: [{ id: "u1", email: "a@example.com" }], + items: [], + user_2fa: [], + payment_history: [], + notification_configs: [], + system_settings: [], + notification_history: [], + }, +}; + +function base64Bytes(value: string): Uint8Array { + const binary = atob(value); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); + return bytes; +} + +describe("encryption envelope", () => { + it("carries every field the contract requires", async () => { + const envelope = await encryptExport(PLAIN, "correct horse"); + const raw = envelope as any; + + expect(raw.format).toBe("enotify-export-encrypted"); + expect(raw.format_version).toBe(1); + expect(raw.kdf.name).toBe("PBKDF2"); + expect(raw.kdf.hash).toBe("SHA-256"); + expect(raw.kdf.iterations).toBeGreaterThanOrEqual(210_000); + expect(raw.kdf.iterations).toBe(PBKDF2_ITERATIONS); + expect(base64Bytes(raw.kdf.salt)).toHaveLength(16); + expect(raw.cipher.name).toBe("AES-GCM"); + expect(raw.cipher.length).toBe(256); + expect(base64Bytes(raw.cipher.iv)).toHaveLength(12); + expect(raw.cipher.tag_length).toBe(128); + expect(typeof raw.payload).toBe("string"); + expect(base64Bytes(raw.payload).length).toBeGreaterThan(16); + }); + + it("uses a fresh salt and IV for every export", async () => { + const a = await encryptExport(PLAIN, "same-passphrase"); + const b = await encryptExport(PLAIN, "same-passphrase"); + expect(a.kdf.salt).not.toBe(b.kdf.salt); + expect(a.cipher.iv).not.toBe(b.cipher.iv); + expect(a.payload).not.toBe(b.payload); + }); + + it("round-trips to exactly the plaintext payload", async () => { + const envelope = await encryptExport(PLAIN, "pässphrase-ü"); + await expect(decryptExport(envelope, "pässphrase-ü")).resolves.toEqual( + PLAIN, + ); + }); + + it("does not store the passphrase anywhere in the envelope", async () => { + const passphrase = "unique-passphrase-marker-1234"; + const envelope = await encryptExport(PLAIN, passphrase); + expect(JSON.stringify(envelope)).not.toContain(passphrase); + }); + + it("rejects an envelope with too few PBKDF2 iterations", async () => { + const envelope = await encryptExport(PLAIN, "pw"); + const weakened = { + ...envelope, + kdf: { ...envelope.kdf, iterations: 1_000 }, + }; + await expect(decryptExport(weakened, "pw")).rejects.toMatchObject({ + code: "INVALID_ENVELOPE", + }); + }); + + it("rejects an envelope with a non-SHA-256 KDF", async () => { + const envelope = await encryptExport(PLAIN, "pw"); + const swapped = { + ...envelope, + kdf: { ...envelope.kdf, hash: "SHA-1" as any }, + }; + await expect(decryptExport(swapped, "pw")).rejects.toMatchObject({ + code: "INVALID_ENVELOPE", + }); + }); +}); + +describe("encrypted export / import endpoints", () => { + it("defaults to encryption and refuses to encrypt without a passphrase", async () => { + const db = new SqliteD1(); + seedInstance(db); + const env = makeBackupEnv(db); + + const noPassphrase = await callWorker( + env, + "/api/me/export", + jsonPost({}, await userCookie(env)), + ); + expect(noPassphrase.status).toBe(400); + expect(noPassphrase.body.code).toBe("PASSPHRASE_REQUIRED"); + + const encrypted = await callWorker( + env, + "/api/me/export", + jsonPost({ passphrase: "pw-123456" }, await userCookie(env)), + ); + expect(encrypted.status).toBe(200); + expect(encrypted.body.format).toBe("enotify-export-encrypted"); + expect(encrypted.headers.get("content-disposition")).toContain("encrypted"); + }); + + it("reports a clear error and writes nothing when the passphrase is wrong", async () => { + const source = new SqliteD1(); + seedInstance(source); + const sourceEnv = makeBackupEnv(source); + const exported = await callWorker( + sourceEnv, + "/api/me/export", + jsonPost({ passphrase: "right-passphrase" }, await userCookie(sourceEnv)), + ); + + const target = new SqliteD1(); + seedInstance(target); + const before = JSON.stringify( + target.select("SELECT * FROM items ORDER BY id"), + ); + const targetEnv = makeBackupEnv(target); + + const res = await callWorker( + targetEnv, + "/api/me/import", + jsonPost( + { file: exported.body, passphrase: "wrong-passphrase" }, + await userCookie(targetEnv), + ), + ); + + expect(res.status).toBe(400); + expect(res.body.code).toBe("DECRYPT_FAILED"); + expect(res.body.error).toContain("口令"); + // Zero writes: the database is byte-for-byte unchanged. + expect( + JSON.stringify(target.select("SELECT * FROM items ORDER BY id")), + ).toBe(before); + expect(target.count("payment_history")).toBe(2); + }); + + it("requires a passphrase to import an encrypted file", async () => { + const db = new SqliteD1(); + seedInstance(db); + const env = makeBackupEnv(db); + + const exported = await callWorker( + env, + "/api/me/export", + jsonPost({ passphrase: "pw" }, await userCookie(env)), + ); + const res = await callWorker( + env, + "/api/me/import", + jsonPost({ file: exported.body }, await userCookie(env)), + ); + + expect(res.status).toBe(400); + expect(res.body.code).toBe("PASSPHRASE_REQUIRED"); + expect(res.body.details).toEqual({ encrypted: true }); + }); + + it("rejects a tampered payload as a decryption failure", async () => { + const db = new SqliteD1(); + seedInstance(db); + const env = makeBackupEnv(db); + + const exported = await callWorker( + env, + "/api/admin/export", + jsonPost({ passphrase: "pw" }, await adminCookie(env)), + ); + const tampered = { + ...exported.body, + payload: btoa("not the real payload"), + }; + + const res = await callWorker( + env, + "/api/admin/import", + jsonPost( + { mode: "restore", file: tampered, passphrase: "pw" }, + await adminCookie(env), + ), + ); + expect(res.status).toBe(400); + expect(res.body.code).toBe("DECRYPT_FAILED"); + }); + + it("reports an encrypted file as such when no passphrase was supplied for preview", async () => { + const db = new SqliteD1(); + seedInstance(db); + const env = makeBackupEnv(db); + + const exported = await callWorker( + env, + "/api/me/export", + jsonPost({ passphrase: "pw" }, await userCookie(env)), + ); + const res = await callWorker( + env, + "/api/me/import/preview", + jsonPost({ file: exported.body }, await userCookie(env)), + ); + expect(res.status).toBe(400); + expect(res.body.code).toBe("PASSPHRASE_REQUIRED"); + expect(res.body.details.encrypted).toBe(true); + }); +}); diff --git a/worker/test/backup-format.test.ts b/worker/test/backup-format.test.ts new file mode 100644 index 0000000..6eccd31 --- /dev/null +++ b/worker/test/backup-format.test.ts @@ -0,0 +1,407 @@ +import { describe, expect, it, vi } from "vitest"; +import { + ADMIN, + BOB, + SqliteD1, + callWorker, + jsonPost, + makeBackupEnv, + seedInstance, +} from "./support/backup"; +import { cookieHeader, makeToken, seedSession } from "./helpers"; + +async function userCookie(env: any, userId = BOB.id, sid = "sess-bob") { + const token = await makeToken("user", { sub: userId, sid }); + await seedSession(env, userId, sid); + return cookieHeader(token); +} + +async function adminCookie(env: any) { + const token = await makeToken("admin", { sub: ADMIN.id, sid: "sess-admin" }); + await seedSession(env, ADMIN.id, "sess-admin"); + return cookieHeader(token); +} + +const EMPTY_DATA_KEYS = [ + "users", + "user_2fa", + "items", + "payment_history", + "notification_configs", + "system_settings", + "notification_history", +]; + +describe("export file format", () => { + it("writes the frozen v1 header and all seven data keys", async () => { + const db = new SqliteD1(); + seedInstance(db); + const env = makeBackupEnv(db); + + const res = await callWorker( + env, + "/api/me/export", + jsonPost({ encrypted: false }, await userCookie(env)), + ); + + expect(res.status).toBe(200); + expect(res.body.format).toBe("enotify-export"); + expect(res.body.format_version).toBe(1); + expect(typeof res.body.app_version).toBe("string"); + expect(Number.isNaN(Date.parse(res.body.exported_at))).toBe(false); + expect(res.body.scope).toBe("user"); + expect(Object.keys(res.body.data).sort()).toEqual( + [...EMPTY_DATA_KEYS].sort(), + ); + }); + + it("sets download headers and forbids caching", async () => { + const db = new SqliteD1(); + seedInstance(db); + const env = makeBackupEnv(db); + + const res = await callWorker( + env, + "/api/me/export", + jsonPost({ encrypted: false }, await userCookie(env)), + ); + + expect(res.headers.get("content-disposition")).toMatch( + /^attachment; filename="enotify-user-.*-plain\.json"$/, + ); + expect(res.headers.get("cache-control")).toBe("no-store"); + }); + + it("keeps scope=user to the exporting user's own rows", async () => { + const db = new SqliteD1(); + seedInstance(db); + const env = makeBackupEnv(db); + + const res = await callWorker( + env, + "/api/me/export", + jsonPost({ encrypted: false }, await userCookie(env)), + ); + const data = res.body.data; + + expect(data.users).toHaveLength(1); + expect(data.users[0].email).toBe(BOB.email); + expect(data.user_2fa.map((r: any) => r.user_id)).toEqual([BOB.id]); + expect(data.items.map((r: any) => r.id).sort()).toEqual([ + "item-bob-1", + "item-bob-broken", + ]); + expect(data.payment_history.map((r: any) => r.id)).toEqual(["pay-bob-1"]); + expect(data.notification_configs.map((r: any) => r.user_id)).toEqual([ + BOB.id, + ]); + expect(data.system_settings).toEqual([]); + expect(data.notification_history).toEqual([]); + }); + + it("includes notification_history only when the option is on", async () => { + const db = new SqliteD1(); + seedInstance(db); + const env = makeBackupEnv(db); + const cookie = await userCookie(env); + + const without = await callWorker( + env, + "/api/me/export", + jsonPost({ encrypted: false }, cookie), + ); + expect(without.body.data.notification_history).toEqual([]); + + const withHistory = await callWorker( + env, + "/api/me/export", + jsonPost({ encrypted: false, include_history: true }, cookie), + ); + expect(withHistory.body.data.notification_history).toHaveLength(1); + expect(withHistory.body.data.notification_history[0].id).toBe("hist-1"); + }); + + it("exports JSON columns as parsed values and keeps scalars as-is", async () => { + const db = new SqliteD1(); + seedInstance(db); + const env = makeBackupEnv(db); + + const res = await callWorker( + env, + "/api/me/export", + jsonPost({ encrypted: false }, await userCookie(env)), + ); + const item = res.body.data.items.find((r: any) => r.id === "item-bob-1"); + const config = res.body.data.notification_configs[0]; + const twofa = res.body.data.user_2fa[0]; + + expect(item.channels).toEqual(["telegram", "email"]); + expect(item.notification_hours).toEqual([9, 21]); + expect(item.amount).toBe(12.5); + expect(item.calendar_mode).toBe("lunar"); + expect(item.lunar_expiry_date).toBe("2026-09-15"); + expect(item._raw).toBeUndefined(); + + expect(config.enabled_channels).toEqual(["telegram", "email"]); + expect(config.telegram_config).toEqual({ + bot_token: "123:abc", + chat_id: "-100", + }); + expect(config.notification_hours).toEqual([8, 20]); + // default_channel is a plain string column, not JSON. + expect(config.default_channel).toBe("telegram"); + + expect(twofa.passkey_credentials).toEqual([ + { + id: "cred-1", + publicKey: "pk-base64", + counter: 3, + transports: ["internal"], + }, + ]); + // TOTP secret is exported verbatim (no transformation). + expect(twofa.totp_secret).toBe("JBSWY3DPEHPK3PXP"); + }); + + it("flags unparsable JSON columns with _raw and keeps the original string", async () => { + const db = new SqliteD1(); + seedInstance(db); + const env = makeBackupEnv(db); + + const res = await callWorker( + env, + "/api/me/export", + jsonPost({ encrypted: false }, await userCookie(env)), + ); + const broken = res.body.data.items.find( + (r: any) => r.id === "item-bob-broken", + ); + + expect(broken.channels).toBe('{"broken": '); + expect(broken._raw).toEqual(["channels"]); + }); + + it("records an audit line for a personal export without leaking the passphrase", async () => { + const db = new SqliteD1(); + seedInstance(db); + const env = makeBackupEnv(db); + const spy = vi.spyOn(console, "log").mockImplementation(() => {}); + + try { + const res = await callWorker( + env, + "/api/me/export", + jsonPost( + { encrypted: true, passphrase: "correct horse battery staple" }, + await userCookie(env), + ), + ); + expect(res.status).toBe(200); + + const auditLines = spy.mock.calls + .map((args) => String(args[0])) + .filter((line) => line.startsWith("[audit] backup ")); + expect(auditLines).toHaveLength(1); + + const event = JSON.parse(auditLines[0].replace("[audit] backup ", "")); + expect(event.action).toBe("export"); + expect(event.scope).toBe("user"); + expect(event.operator).toBe(BOB.id); + expect(event.encrypted).toBe(true); + expect(event.rows.items).toBe(2); + expect(event.rows.users).toBe(1); + expect(auditLines[0]).not.toContain("correct horse battery staple"); + } finally { + spy.mockRestore(); + } + }); +}); + +describe("export → import round trip", () => { + it("restores an instance file with no loss (JSON columns, _raw, 2FA, lunar, default_channel)", async () => { + const source = new SqliteD1(); + seedInstance(source); + const sourceEnv = makeBackupEnv(source); + + const exported = await callWorker( + sourceEnv, + "/api/admin/export", + jsonPost( + { encrypted: false, include_history: true }, + await adminCookie(sourceEnv), + ), + ); + expect(exported.status).toBe(200); + expect(exported.body.scope).toBe("instance"); + expect(exported.body.data.users).toHaveLength(3); + + const target = new SqliteD1(); + const targetEnv = makeBackupEnv(target); + const imported = await callWorker( + targetEnv, + "/api/admin/import", + jsonPost( + { mode: "restore", file: exported.body }, + await adminCookie(targetEnv), + ), + ); + expect(imported.status).toBe(200); + expect(imported.body.written).toEqual({ + users: 3, + user_2fa: 1, + items: 3, + payment_history: 2, + notification_configs: 2, + system_settings: 2, + notification_history: 1, + }); + + const reExported = await callWorker( + targetEnv, + "/api/admin/export", + jsonPost( + { encrypted: false, include_history: true }, + await adminCookie(targetEnv), + ), + ); + + // Whole-file equality: every ID, timestamp, amount, JSON column and the + // _raw fallback row survive the trip unchanged. + expect(reExported.body.data).toEqual(exported.body.data); + + const broken = target.select( + "SELECT channels FROM items WHERE id = ?", + "item-bob-broken", + ); + expect(broken[0].channels).toBe('{"broken": '); + }); + + it("round-trips through the encrypted envelope", async () => { + const source = new SqliteD1(); + seedInstance(source); + const sourceEnv = makeBackupEnv(source); + + const exported = await callWorker( + sourceEnv, + "/api/me/export", + jsonPost( + { passphrase: "s3cret-passphrase", include_history: true }, + await userCookie(sourceEnv), + ), + ); + expect(exported.body.format).toBe("enotify-export-encrypted"); + + // A different instance holding an account with the same email: merge + // targets the signed-in account, not the file's (already gone) id. + const target = new SqliteD1(); + target.insert("users", { + id: "u-bob-2", + email: BOB.email, + password_hash: "hash", + role: "user", + created_at: "2026-10-25T10:00:00.000Z", + updated_at: "2026-10-25T10:00:00.000Z", + }); + const targetEnv = makeBackupEnv(target); + const token = await makeToken("user", { sub: "u-bob-2", sid: "sess-bob2" }); + await seedSession(targetEnv, "u-bob-2", "sess-bob2"); + + const imported = await callWorker( + targetEnv, + "/api/me/import", + jsonPost( + { file: exported.body, passphrase: "s3cret-passphrase" }, + cookieHeader(token), + ), + ); + expect(imported.status).toBe(200); + expect(imported.body.written.items).toBe(2); + expect(imported.body.written.payment_history).toBe(1); + }); +}); + +describe("schema-evolution tolerance", () => { + it("ignores unknown fields and applies current column defaults for missing ones", async () => { + const source = new SqliteD1(); + seedInstance(source); + const sourceEnv = makeBackupEnv(source); + + const exported = await callWorker( + sourceEnv, + "/api/admin/export", + jsonPost({ encrypted: false }, await adminCookie(sourceEnv)), + ); + + const item = exported.body.data.items.find( + (r: any) => r.id === "item-bob-1", + ); + item.unknown_future_column = "ignored"; + delete item.currency; + delete item.auto_renew; + delete item.reminder_value; + + const target = new SqliteD1(); + const targetEnv = makeBackupEnv(target); + const imported = await callWorker( + targetEnv, + "/api/admin/import", + jsonPost( + { mode: "restore", file: exported.body }, + await adminCookie(targetEnv), + ), + ); + expect(imported.status).toBe(200); + + const row = target.select( + "SELECT * FROM items WHERE id = ?", + "item-bob-1", + )[0]; + expect(row.currency).toBe("CNY"); // schema default + expect(row.auto_renew).toBe(1); // schema default + expect(row.reminder_value).toBe(7); // schema default + expect("unknown_future_column" in row).toBe(false); + }); + + it("rejects files whose format_version is newer than supported", async () => { + const db = new SqliteD1(); + seedInstance(db); + const env = makeBackupEnv(db); + + const res = await callWorker( + env, + "/api/admin/import", + jsonPost( + { + mode: "restore", + file: { + format: "enotify-export", + format_version: 2, + app_version: "9.9.9", + exported_at: new Date().toISOString(), + scope: "instance", + data: {}, + }, + }, + await adminCookie(env), + ), + ); + + expect(res.status).toBe(400); + expect(res.body.code).toBe("UNSUPPORTED_FORMAT_VERSION"); + expect(res.body.error).toContain("format_version"); + }); + + it("rejects a file that is neither a plain nor an encrypted enotify export", async () => { + const db = new SqliteD1(); + seedInstance(db); + const env = makeBackupEnv(db); + + const res = await callWorker( + env, + "/api/admin/import/preview", + jsonPost({ file: { hello: "world" } }, await adminCookie(env)), + ); + expect(res.status).toBe(400); + expect(res.body.code).toBe("INVALID_FORMAT"); + }); +}); diff --git a/worker/test/backup-merge.test.ts b/worker/test/backup-merge.test.ts new file mode 100644 index 0000000..f4b3205 --- /dev/null +++ b/worker/test/backup-merge.test.ts @@ -0,0 +1,381 @@ +import { describe, expect, it } from "vitest"; +import { + ADMIN, + BOB, + SqliteD1, + callWorker, + jsonPost, + makeBackupEnv, + seedInstance, +} from "./support/backup"; +import { cookieHeader, makeToken, seedSession } from "./helpers"; + +const NEW_USER_ID = "u-bob-new"; +const OTHER_USER_ID = "u-other"; + +function insertUser( + db: SqliteD1, + id: string, + email: string, + role = "user", +): void { + db.insert("users", { + id, + email, + password_hash: "$argon2id$hash", + role, + is_active: 1, + email_verified: 1, + base_currency: "CNY", + timezone: "UTC", + language: "zh", + theme: "system", + created_at: "2026-10-20T00:00:00.000Z", + updated_at: "2026-10-20T00:00:00.000Z", + }); +} + +/** Target instance: one account with the same email as the file's owner. */ +function makeTarget(): SqliteD1 { + const db = new SqliteD1(); + insertUser(db, NEW_USER_ID, BOB.email); + insertUser(db, OTHER_USER_ID, "other@example.com"); + db.insert("items", { + id: "other-item", + user_id: OTHER_USER_ID, + name: "Other user item", + expiry_date: "2027-01-01", + created_at: "2026-10-20T00:00:00.000Z", + updated_at: "2026-10-20T00:00:00.000Z", + }); + db.insert("notification_configs", { + user_id: NEW_USER_ID, + enabled_channels: JSON.stringify(["bark"]), + default_channel: "bark", + bark_config: JSON.stringify({ device_key: "old" }), + updated_at: "2026-10-20T00:00:00.000Z", + }); + return db; +} + +async function sessionFor(env: any, sub: string, sid: string, role = "user") { + const token = await makeToken(role as "user" | "admin", { sub, sid }); + await seedSession(env, sub, sid); + return cookieHeader(token); +} + +async function exportInstanceFile(options: { includeHistory?: boolean } = {}) { + const source = new SqliteD1(); + seedInstance(source); + const env = makeBackupEnv(source); + const res = await callWorker( + env, + "/api/admin/export", + jsonPost( + { encrypted: false, include_history: options.includeHistory ?? false }, + await sessionFor(env, ADMIN.id, "sess-admin", "admin"), + ), + ); + expect(res.status).toBe(200); + return res.body; +} + +describe("merge mode preview", () => { + it("reports what will be written, what is ignored and that config is replaced", async () => { + const file = await exportInstanceFile(); + const target = makeTarget(); + const env = makeBackupEnv(target); + const cookie = await sessionFor(env, NEW_USER_ID, "sess-new"); + + const preview = await callWorker( + env, + "/api/me/import/preview", + jsonPost({ file }, cookie), + ); + + expect(preview.status).toBe(200); + expect(preview.body.mode).toBe("merge"); + expect(preview.body.counts.items).toBe(3); + expect(preview.body.will_write).toEqual({ + users: 0, + user_2fa: 0, + items: 2, + payment_history: 1, + notification_configs: 1, + system_settings: 0, + notification_history: 0, + }); + expect(preview.body.ignored_tables).toEqual([ + "users", + "user_2fa", + "system_settings", + "notification_history", + ]); + expect(preview.body.conflicts.config_overwritten).toBe(true); + expect(preview.body.conflicts.skipped_foreign_items).toBe(1); + expect(preview.body.conflicts.skipped_foreign_payments).toBe(1); + expect(preview.body.can_execute).toBe(true); + + // A preview never writes. + expect(target.count("items")).toBe(1); + expect(target.count("payment_history")).toBe(0); + }); + + it("refuses a file that has no data for the importing account", async () => { + const file = await exportInstanceFile(); + const target = new SqliteD1(); + insertUser(target, "u-stranger", "stranger@example.com"); + const env = makeBackupEnv(target); + const cookie = await sessionFor(env, "u-stranger", "sess-stranger"); + + const res = await callWorker( + env, + "/api/me/import", + jsonPost({ file }, cookie), + ); + + expect(res.status).toBe(400); + expect(res.body.code).toBe("MERGE_SOURCE_NOT_FOUND"); + expect(res.body.error).toContain("stranger@example.com"); + expect(target.count("items")).toBe(0); + }); +}); + +describe("merge mode execution", () => { + it("regenerates every id, rewrites owners and payment references", async () => { + const file = await exportInstanceFile({ includeHistory: true }); + const target = makeTarget(); + const env = makeBackupEnv(target); + const cookie = await sessionFor(env, NEW_USER_ID, "sess-new"); + + const res = await callWorker( + env, + "/api/me/import", + jsonPost({ file }, cookie), + ); + + expect(res.status).toBe(200); + expect(res.body.written).toEqual({ + users: 0, + user_2fa: 0, + items: 2, + payment_history: 1, + notification_configs: 1, + system_settings: 0, + notification_history: 0, + }); + expect(res.body.notices).toEqual([]); // restore-only notices stay out of merge + + const importedItems = target.select( + "SELECT * FROM items WHERE user_id = ? ORDER BY name", + NEW_USER_ID, + ); + expect(importedItems).toHaveLength(2); + const fileItemIds = file.data.items + .filter((row: any) => row.user_id === BOB.id) + .map((row: any) => row.id); + for (const item of importedItems) { + expect(fileItemIds).not.toContain(item.id); + expect(item.user_id).toBe(NEW_USER_ID); + } + + // Scalar payload survives the copy. + const vps = importedItems.find((item) => item.name === "VPS"); + expect(vps.amount).toBe(12.5); + expect(vps.currency).toBe("USD"); + expect(vps.calendar_mode).toBe("lunar"); + expect(vps.lunar_expiry_date).toBe("2026-09-15"); + expect(JSON.parse(vps.channels)).toEqual(["telegram", "email"]); + expect(JSON.parse(vps.notification_hours)).toEqual([9, 21]); + + // payment_history points at the NEW item id and keeps its own new id. + const payments = target.select( + "SELECT * FROM payment_history WHERE user_id = ?", + NEW_USER_ID, + ); + expect(payments).toHaveLength(1); + expect(payments[0].id).not.toBe("pay-bob-1"); + expect(payments[0].item_id).toBe(vps.id); + expect(payments[0].amount).toBe(12.5); + + // Another account's data is untouched and nothing from other users in the + // file leaked in. + expect(target.count("items")).toBe(3); + const otherItems = target.select( + "SELECT * FROM items WHERE user_id = ?", + OTHER_USER_ID, + ); + expect(otherItems).toHaveLength(1); + expect(otherItems[0].id).toBe("other-item"); + expect( + target.select("SELECT * FROM items WHERE user_id = ?", ADMIN.id), + ).toHaveLength(0); + }); + + it("replaces the whole channel config of the importing account", async () => { + const file = await exportInstanceFile(); + const target = makeTarget(); + const env = makeBackupEnv(target); + const cookie = await sessionFor(env, NEW_USER_ID, "sess-new"); + + await callWorker(env, "/api/me/import", jsonPost({ file }, cookie)); + + const config = target.select( + "SELECT * FROM notification_configs WHERE user_id = ?", + NEW_USER_ID, + ); + expect(config).toHaveLength(1); + expect(config[0].default_channel).toBe("telegram"); + expect(JSON.parse(config[0].enabled_channels)).toEqual([ + "telegram", + "email", + ]); + expect(JSON.parse(config[0].telegram_config)).toEqual({ + bot_token: "123:abc", + chat_id: "-100", + }); + // The old bark config is gone (whole-row replacement), not merged. + expect(JSON.parse(config[0].bark_config)).toEqual({}); + }); + + it("leaves users, 2FA and system settings alone", async () => { + const file = await exportInstanceFile(); + const target = makeTarget(); + const env = makeBackupEnv(target); + const cookie = await sessionFor(env, NEW_USER_ID, "sess-new"); + + await callWorker(env, "/api/me/import", jsonPost({ file }, cookie)); + + expect(target.count("users")).toBe(2); + expect(target.count("user_2fa")).toBe(0); + expect(target.count("system_settings")).toBe(0); + expect(target.count("notification_history")).toBe(0); + // No stray account was created from the file. + expect( + target.select("SELECT * FROM users WHERE email = ?", ADMIN.email), + ).toHaveLength(0); + }); + + it("skips payment rows whose item is missing from the file", async () => { + const file = await exportInstanceFile(); + const trimmed = structuredClone(file); + trimmed.data.items = trimmed.data.items.filter( + (row: any) => row.id !== "item-bob-1", + ); + const trimmedVpsGone = trimmed.data.items; + expect(trimmedVpsGone.some((row: any) => row.id === "item-bob-1")).toBe( + false, + ); + + const target = makeTarget(); + const env = makeBackupEnv(target); + const cookie = await sessionFor(env, NEW_USER_ID, "sess-new"); + + const res = await callWorker( + env, + "/api/me/import", + jsonPost({ file: trimmed }, cookie), + ); + + expect(res.status).toBe(200); + expect(res.body.written.items).toBe(1); + expect(res.body.written.payment_history).toBe(0); + expect(res.body.warnings.join(" ")).toContain("已跳过"); + expect(target.count("payment_history")).toBe(0); + }); + + it("does not import notification history in merge mode", async () => { + const file = await exportInstanceFile({ includeHistory: true }); + expect(file.data.notification_history).toHaveLength(1); + + const target = makeTarget(); + const env = makeBackupEnv(target); + const cookie = await sessionFor(env, NEW_USER_ID, "sess-new"); + const res = await callWorker( + env, + "/api/me/import", + jsonPost({ file }, cookie), + ); + + expect(res.status).toBe(200); + expect(res.body.written.notification_history).toBe(0); + expect(target.count("notification_history")).toBe(0); + expect(res.body.warnings.join(" ")).toContain("不导入通知历史"); + }); + + it("lets an admin merge into their own account through the admin endpoint", async () => { + const file = await exportInstanceFile(); + const target = new SqliteD1(); + insertUser(target, "u-admin-new", ADMIN.email, "admin"); + const env = makeBackupEnv(target); + const cookie = await sessionFor( + env, + "u-admin-new", + "sess-admin-new", + "admin", + ); + + const preview = await callWorker( + env, + "/api/admin/import/preview", + jsonPost({ mode: "merge", file }, cookie), + ); + expect(preview.body.mode).toBe("merge"); + expect(preview.body.will_write.items).toBe(1); + + const res = await callWorker( + env, + "/api/admin/import", + jsonPost({ mode: "merge", file }, cookie), + ); + expect(res.status).toBe(200); + expect(res.body.mode).toBe("merge"); + const items = target.select( + "SELECT * FROM items WHERE user_id = ?", + "u-admin-new", + ); + expect(items).toHaveLength(1); + expect(items[0].name).toBe("Domain"); + }); + + it("writes nothing when a merge batch fails", async () => { + const file = await exportInstanceFile(); + const target = makeTarget(); + const before = target.count("items"); + target.failWhen = (sql) => + /^\s*INSERT/i.test(sql) && sql.includes("payment_history"); + const env = makeBackupEnv(target); + const cookie = await sessionFor(env, NEW_USER_ID, "sess-new"); + + const res = await callWorker( + env, + "/api/me/import", + jsonPost({ file }, cookie), + ); + + expect(res.status).toBe(500); + expect(res.body.code).toBe("WRITE_FAILED"); + expect(target.count("items")).toBe(before); + expect(target.count("payment_history")).toBe(0); + const config = target.select( + "SELECT * FROM notification_configs WHERE user_id = ?", + NEW_USER_ID, + ); + expect(config[0].default_channel).toBe("bark"); + }); + + it("rejects a mode that the personal endpoint does not support", async () => { + const file = await exportInstanceFile(); + const target = makeTarget(); + const env = makeBackupEnv(target); + const cookie = await sessionFor(env, NEW_USER_ID, "sess-new"); + + const res = await callWorker( + env, + "/api/me/import", + jsonPost({ file, mode: "restore" }, cookie), + ); + expect(res.status).toBe(400); + expect(res.body.code).toBe("MODE_NOT_ALLOWED"); + }); +}); diff --git a/worker/test/backup-restore.test.ts b/worker/test/backup-restore.test.ts new file mode 100644 index 0000000..257a3fe --- /dev/null +++ b/worker/test/backup-restore.test.ts @@ -0,0 +1,392 @@ +import { describe, expect, it } from "vitest"; +import { + ADMIN, + BOB, + SqliteD1, + callWorker, + jsonPost, + makeBackupEnv, + seedInstance, +} from "./support/backup"; +import { cookieHeader, makeToken, seedSession } from "./helpers"; +import { assertCountsUnchanged } from "../src/lib/backup/import"; +import { emptyData } from "../src/lib/backup/format"; + +async function userCookie(env: any, userId = BOB.id, sid = "sess-bob") { + const token = await makeToken("user", { sub: userId, sid }); + await seedSession(env, userId, sid); + return cookieHeader(token); +} + +async function adminCookie(env: any) { + const token = await makeToken("admin", { sub: ADMIN.id, sid: "sess-admin" }); + await seedSession(env, ADMIN.id, "sess-admin"); + return cookieHeader(token); +} + +/** Exports the seeded source instance as a plain, history-included file. */ +async function exportInstanceFile() { + const source = new SqliteD1(); + seedInstance(source); + const env = makeBackupEnv(source); + const res = await callWorker( + env, + "/api/admin/export", + jsonPost( + { encrypted: false, include_history: true }, + await adminCookie(env), + ), + ); + expect(res.status).toBe(200); + return { file: res.body, source }; +} + +const EMPTY_COUNTS = { + users: 0, + user_2fa: 0, + items: 0, + payment_history: 0, + notification_configs: 0, + system_settings: 0, + notification_history: 0, +}; + +describe("restore mode preconditions", () => { + it("refuses a non-empty target instance (preview blocks, import 409)", async () => { + const { file } = await exportInstanceFile(); + + const target = new SqliteD1(); + seedInstance(target); + const env = makeBackupEnv(target); + const cookie = await adminCookie(env); + + const preview = await callWorker( + env, + "/api/admin/import/preview", + jsonPost({ mode: "restore", file }, cookie), + ); + expect(preview.status).toBe(200); + expect(preview.body.can_execute).toBe(false); + expect(preview.body.conflicts.target_users).toBe(3); + expect(preview.body.blockers[0].code).toBe("RESTORE_TARGET_NOT_EMPTY"); + + const imported = await callWorker( + env, + "/api/admin/import", + jsonPost({ mode: "restore", file }, cookie), + ); + expect(imported.status).toBe(409); + expect(imported.body.code).toBe("RESTORE_TARGET_NOT_EMPTY"); + expect(target.count("users")).toBe(3); + expect(target.count("items")).toBe(3); + }); + + it("refuses a user-scope file in restore mode", async () => { + const source = new SqliteD1(); + seedInstance(source); + const sourceEnv = makeBackupEnv(source); + const userFile = await callWorker( + sourceEnv, + "/api/me/export", + jsonPost({ encrypted: false }, await userCookie(sourceEnv)), + ); + + const target = new SqliteD1(); + const env = makeBackupEnv(target); + const res = await callWorker( + env, + "/api/admin/import", + jsonPost( + { mode: "restore", file: userFile.body }, + await adminCookie(env), + ), + ); + + expect(res.status).toBe(400); + expect(res.body.code).toBe("MODE_NOT_ALLOWED"); + expect(target.count("users")).toBe(0); + }); + + it("blocks a file with a dangling reference or a duplicated primary key", async () => { + const { file } = await exportInstanceFile(); + + const dangling = structuredClone(file); + dangling.data.payment_history[0].item_id = "item-does-not-exist"; + const target = new SqliteD1(); + const env = makeBackupEnv(target); + const cookie = await adminCookie(env); + + const preview = await callWorker( + env, + "/api/admin/import/preview", + jsonPost({ mode: "restore", file: dangling }, cookie), + ); + expect(preview.body.can_execute).toBe(false); + expect( + preview.body.blockers.some((b: any) => b.code === "REFERENCE_MISSING"), + ).toBe(true); + + const imported = await callWorker( + env, + "/api/admin/import", + jsonPost({ mode: "restore", file: dangling }, cookie), + ); + expect(imported.status).toBe(409); + expect(imported.body.code).toBe("REFERENCE_MISSING"); + expect(target.count("payment_history")).toBe(0); + }); + + it("blocks a row that misses a required column", async () => { + const { file } = await exportInstanceFile(); + const broken = structuredClone(file); + delete broken.data.items[0].name; + + const env = makeBackupEnv(new SqliteD1()); + const preview = await callWorker( + env, + "/api/admin/import/preview", + jsonPost({ mode: "restore", file: broken }, await adminCookie(env)), + ); + + expect(preview.body.can_execute).toBe(false); + expect( + preview.body.blockers.some((b: any) => b.code === "MISSING_COLUMN"), + ).toBe(true); + }); + + it("flags a newer format_version before touching the database", async () => { + const { file } = await exportInstanceFile(); + const newer = { ...file, format_version: 2 }; + + const env = makeBackupEnv(new SqliteD1()); + const res = await callWorker( + env, + "/api/admin/import", + jsonPost({ mode: "restore", file: newer }, await adminCookie(env)), + ); + + expect(res.status).toBe(400); + expect(res.body.code).toBe("UNSUPPORTED_FORMAT_VERSION"); + }); +}); + +describe("restore mode execution", () => { + it("restores every table into an empty instance with matching rows", async () => { + const { file, source } = await exportInstanceFile(); + const target = new SqliteD1(); + const env = makeBackupEnv(target); + + const res = await callWorker( + env, + "/api/admin/import", + jsonPost({ mode: "restore", file }, await adminCookie(env)), + ); + + expect(res.status).toBe(200); + expect(res.body.ok).toBe(true); + expect(res.body.mode).toBe("restore"); + + // Row counts per table match the source instance exactly. + for (const table of Object.keys(EMPTY_COUNTS)) { + expect(target.count(table)).toBe(source.count(table)); + } + + // Spot checks: a channel config and one item are byte-identical. + const sourceConfig = source.select( + "SELECT * FROM notification_configs WHERE user_id = ?", + BOB.id, + ); + const targetConfig = target.select( + "SELECT * FROM notification_configs WHERE user_id = ?", + BOB.id, + ); + expect(targetConfig).toEqual(sourceConfig); + expect( + JSON.parse(String((targetConfig[0] as any).telegram_config)), + ).toEqual({ + bot_token: "123:abc", + chat_id: "-100", + }); + + const sourceItem = source.select( + "SELECT * FROM items WHERE id = ?", + "item-bob-1", + ); + const targetItem = target.select( + "SELECT * FROM items WHERE id = ?", + "item-bob-1", + ); + expect(targetItem).toEqual(sourceItem); + + // Restore-specific guidance is surfaced to the operator. + expect(res.body.notices.join(" ")).toContain("API Key"); + expect(res.body.notices.join(" ")).toContain("重新登录"); + }); + + it("reports the planned rows in preview and the actual rows after import", async () => { + const { file } = await exportInstanceFile(); + const target = new SqliteD1(); + const env = makeBackupEnv(target); + const cookie = await adminCookie(env); + + const preview = await callWorker( + env, + "/api/admin/import/preview", + jsonPost({ mode: "restore", file }, cookie), + ); + expect(preview.status).toBe(200); + expect(preview.body.can_execute).toBe(true); + expect(preview.body.counts).toEqual({ + users: 3, + user_2fa: 1, + items: 3, + payment_history: 2, + notification_configs: 2, + system_settings: 2, + notification_history: 1, + }); + expect(preview.body.users.map((u: any) => u.email).sort()).toEqual([ + "admin@example.com", + "bob@example.com", + "carol@example.com", + ]); + // A preview must not write anything. + expect(target.count("users")).toBe(0); + + const imported = await callWorker( + env, + "/api/admin/import", + jsonPost({ mode: "restore", file }, cookie), + ); + expect(imported.body.written).toEqual(preview.body.will_write); + }); + + it("overwrites installed system settings defaults instead of aborting", async () => { + const { file } = await exportInstanceFile(); + const target = new SqliteD1(); + // A freshly initialized instance already holds default settings keys. + target.insert("system_settings", { + key: "app_name", + value: "default app", + updated_at: "2026-10-25T09:00:00.000Z", + }); + const env = makeBackupEnv(target); + const cookie = await adminCookie(env); + + const preview = await callWorker( + env, + "/api/admin/import/preview", + jsonPost({ mode: "restore", file }, cookie), + ); + expect(preview.body.can_execute).toBe(true); + expect(preview.body.conflicts.settings_overwritten).toEqual(["app_name"]); + + const res = await callWorker( + env, + "/api/admin/import", + jsonPost({ mode: "restore", file }, cookie), + ); + expect(res.status).toBe(200); + expect( + target.select( + "SELECT value FROM system_settings WHERE key = ?", + "app_name", + )[0].value, + ).toBe("eNotify"); + }); + + it("leaves no partial data when a write fails mid-batch", async () => { + const { file } = await exportInstanceFile(); + const target = new SqliteD1(); + // Fail only the payment_history INSERT so the batch aborts after users, + // user_2fa, items and configs were already written inside the transaction. + target.failWhen = (sql) => + /^\s*INSERT/i.test(sql) && sql.includes("payment_history"); + const env = makeBackupEnv(target); + + const res = await callWorker( + env, + "/api/admin/import", + jsonPost({ mode: "restore", file }, await adminCookie(env)), + ); + + expect(res.status).toBe(500); + expect(res.body.code).toBe("WRITE_FAILED"); + // Exactly one batch was attempted, and the transaction rolled back: users, + // items and configs that were written earlier in the batch are gone too. + expect(target.batchCalls).toBe(1); + for (const table of Object.keys(EMPTY_COUNTS)) { + expect(target.count(table)).toBe(0); + } + }); + + it("restores into a prefixed schema ({prefix} resolution)", async () => { + const { file } = await exportInstanceFile(); + const target = new SqliteD1({ prefix: "eNotify_" }); + const env = makeBackupEnv(target, { TABLE_PREFIX: "eNotify" }); + + const res = await callWorker( + env, + "/api/admin/import", + jsonPost({ mode: "restore", file }, await adminCookie(env)), + ); + + expect(res.status).toBe(200); + expect( + target.select<{ n: number }>("SELECT COUNT(*) AS n FROM eNotify_items")[0] + .n, + ).toBe(3); + // The unprefixed table names must not exist in this database. + const unprefixed = target.select<{ name: string }>( + "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'items'", + ); + expect(unprefixed).toEqual([]); + }); +}); + +describe("staleness guard", () => { + it("rejects a write when a table changed since planning", () => { + const before = { ...EMPTY_COUNTS }; + const current = { ...EMPTY_COUNTS, users: 1 }; + expect(() => assertCountsUnchanged(before, current)).toThrowError( + /发生变化/, + ); + try { + assertCountsUnchanged(before, current); + } catch (err: any) { + expect(err.code).toBe("STALE_PREVIEW"); + expect(err.status).toBe(409); + expect(err.details).toEqual({ table: "users", expected: 0, actual: 1 }); + } + expect(() => + assertCountsUnchanged(before, { ...EMPTY_COUNTS }), + ).not.toThrow(); + }); +}); + +describe("file shape tolerance", () => { + it("accepts a file whose notification_history key is missing", async () => { + const db = new SqliteD1(); + seedInstance(db); + const env = makeBackupEnv(db); + const data = emptyData(); + const file = { + format: "enotify-export", + format_version: 1, + app_version: "test", + exported_at: new Date().toISOString(), + scope: "user", + data: { ...data, users: [] }, + }; + delete (file.data as any).notification_history; + + const res = await callWorker( + env, + "/api/me/import/preview", + jsonPost({ file }, await userCookie(env)), + ); + // Structurally valid: it fails later on missing merge source, not on shape. + expect(res.status).toBe(400); + expect(res.body.code).toBe("MERGE_SOURCE_NOT_FOUND"); + }); +}); diff --git a/worker/test/support/backup.ts b/worker/test/support/backup.ts new file mode 100644 index 0000000..f99cbc1 --- /dev/null +++ b/worker/test/support/backup.ts @@ -0,0 +1,459 @@ +/** + * Test support for the export/import ("backup") endpoints. + * + * D1 is SQLite, so these tests run the production SQL against a real in-memory + * SQLite database (`node:sqlite`, built into Node 22+/24) initialized from the + * repository's own `worker/src/db/schema.sql`. That keeps the assertions about + * defaults, constraints, foreign keys and batch atomicity honest instead of + * testing a hand-written mock. + */ +// @ts-expect-error node:sqlite ships with Node but is not in the Workers type set. +import { DatabaseSync } from "node:sqlite"; +import { readFileSync } from "node:fs"; +import worker from "../../src/index"; +import { MockKV, TEST_JWT_SECRET, TEST_SETUP_SECRET } from "../helpers"; +import type { Env } from "../../src/types"; + +const SCHEMA_TEMPLATE = readFileSync( + new URL("../../src/db/schema.sql", import.meta.url), + "utf8", +); + +export type Row = Record; + +class SqliteStatement { + args: unknown[] = []; + + constructor( + private readonly db: SqliteD1, + readonly sql: string, + ) {} + + bind(...args: unknown[]): this { + // D1 rejects undefined/boolean bindings; mirror that by normalizing only + // what the code under test is allowed to bind. + this.args = args.map((arg) => (arg === undefined ? null : arg)); + return this; + } + + async first(): Promise { + const rows = this.db.execStatement(this.sql, this.args) as T[]; + return rows.length > 0 ? rows[0] : null; + } + + async all(): Promise<{ results: T[] }> { + return { results: this.db.execStatement(this.sql, this.args) as T[] }; + } + + async run(): Promise<{ success: true }> { + this.db.execStatement(this.sql, this.args); + return { success: true }; + } +} + +export class SqliteD1 { + readonly raw: DatabaseSync; + /** Optional failure injection: return true to make that statement throw. */ + failWhen: ((sql: string) => boolean) | null = null; + batchCalls = 0; + + constructor(options: { prefix?: string; schema?: boolean } = {}) { + this.raw = new DatabaseSync(":memory:"); + this.raw.exec("PRAGMA foreign_keys = ON"); + if (options.schema !== false) { + const prefix = options.prefix ?? ""; + this.raw.exec(SCHEMA_TEMPLATE.replace(/\{prefix\}/g, prefix)); + } + } + + prepare(sql: string): SqliteStatement { + return new SqliteStatement(this, sql); + } + + /** + * Mirrors D1: a batch runs as a single transaction, so one failing statement + * rolls the whole batch back. + */ + async batch(statements: SqliteStatement[]): Promise { + this.batchCalls += 1; + this.raw.exec("BEGIN"); + const results: unknown[] = []; + try { + for (const statement of statements) { + results.push(await statement.run()); + } + this.raw.exec("COMMIT"); + return results; + } catch (err) { + this.raw.exec("ROLLBACK"); + throw err; + } + } + + execStatement(sql: string, args: unknown[]): unknown[] { + if (this.failWhen?.(sql)) { + throw new Error(`injected failure for statement: ${sql.slice(0, 60)}`); + } + const prepared = this.raw.prepare(sql); + if (/^\s*(select|pragma|with)\b/i.test(sql)) { + return prepared.all(...(args as never[])) as unknown[]; + } + prepared.run(...(args as never[])); + return []; + } + + // ── direct helpers for fixtures and assertions ──────────────────────────── + + insert(table: string, row: Row): void { + const columns = Object.keys(row); + const sql = `INSERT INTO ${table} (${columns.join(", ")}) VALUES (${columns + .map(() => "?") + .join(", ")})`; + this.execStatement( + sql, + columns.map((column) => row[column] ?? null), + ); + } + + select(sql: string, ...args: unknown[]): T[] { + return this.execStatement(sql, args) as T[]; + } + + count(table: string): number { + const rows = this.select<{ n: number }>( + `SELECT COUNT(*) AS n FROM ${table}`, + ); + return Number(rows[0]?.n ?? 0); + } +} + +export interface BackupTestEnv extends Record { + DB: SqliteD1; + KV: MockKV; +} + +export function makeBackupEnv( + db: SqliteD1, + overrides: Record = {}, +): BackupTestEnv { + return { + DB: db, + KV: new MockKV(), + JWT_SECRET: TEST_JWT_SECRET, + SETUP_SECRET: TEST_SETUP_SECRET, + TABLE_PREFIX: "", + ASSETS: {}, + ...overrides, + }; +} + +const executionCtx = { + waitUntil: () => {}, + passThroughOnException: () => {}, +} as unknown as ExecutionContext; + +export interface BackupResponse { + status: number; + body: any; + headers: Headers; + text: string; +} + +/** Calls the real worker app (index.ts) so routing/middleware are covered. */ +export async function callWorker( + env: BackupTestEnv, + path: string, + init: RequestInit = {}, +): Promise { + const res = await worker.fetch( + new Request(`https://enotify.test${path}`, init), + env as unknown as Env, + executionCtx, + ); + const text = await res.text(); + let body: any = null; + try { + body = text ? JSON.parse(text) : null; + } catch { + body = text; + } + return { status: res.status, body, headers: res.headers, text }; +} + +export function jsonPost( + body: unknown, + headers: Record = {}, +): RequestInit { + return { + method: "POST", + headers: { "Content-Type": "application/json", ...headers }, + body: JSON.stringify(body), + }; +} + +// ─── fixture: a fully populated source instance ─────────────────────────────── + +export const BOB = { + id: "u-bob", + email: "bob@example.com", +}; + +export const ADMIN = { + id: "u-admin", + email: "admin@example.com", +}; + +export const CAROL = { + id: "u-carol", + email: "carol@example.com", +}; + +/** + * Seeds one admin, two regular users, and rows in all seven tables — including + * a row whose `channels` JSON is deliberately malformed to exercise `_raw`. + */ +export function seedInstance(db: SqliteD1): void { + const now = "2026-10-25T10:00:00.000Z"; + + db.insert("users", { + id: ADMIN.id, + email: ADMIN.email, + password_hash: "$argon2id$admin-hash", + role: "admin", + is_active: 1, + email_verified: 1, + base_currency: "USD", + timezone: "Asia/Shanghai", + language: "en", + theme: "dark", + created_at: now, + updated_at: now, + }); + db.insert("users", { + id: BOB.id, + email: BOB.email, + password_hash: "$argon2id$bob-hash", + role: "user", + is_active: 1, + email_verified: 0, + base_currency: "CNY", + timezone: "UTC", + language: "zh", + theme: "system", + created_at: now, + updated_at: now, + }); + db.insert("users", { + id: CAROL.id, + email: CAROL.email, + password_hash: "$argon2id$carol-hash", + role: "user", + is_active: 1, + email_verified: 1, + base_currency: "CNY", + timezone: "UTC", + language: "zh", + theme: "system", + created_at: now, + updated_at: now, + }); + + db.insert("user_2fa", { + user_id: BOB.id, + totp_secret: "JBSWY3DPEHPK3PXP", + totp_enabled: 1, + passkey_credentials: JSON.stringify([ + { + id: "cred-1", + publicKey: "pk-base64", + counter: 3, + transports: ["internal"], + }, + ]), + passkey_enabled: 1, + email_otp_enabled: 0, + preferred_method: "totp", + updated_at: now, + }); + + db.insert("items", { + id: "item-bob-1", + user_id: BOB.id, + name: "VPS", + item_mode: "cycle", + category: "server", + start_date: "2026-01-01", + expiry_date: "2026-11-01", + period_value: 1, + period_unit: "month", + reminder_unit: "day", + reminder_value: 7, + notes: "note-1", + amount: 12.5, + currency: "USD", + last_payment_date: "2026-10-01", + is_active: 1, + auto_renew: 1, + calendar_mode: "lunar", + lunar_expiry_date: "2026-09-15", + channels: JSON.stringify(["telegram", "email"]), + notification_hours: JSON.stringify([9, 21]), + item_kind: "subscription", + created_at: now, + updated_at: now, + }); + db.insert("items", { + id: "item-bob-broken", + user_id: BOB.id, + name: "Broken JSON", + item_mode: "reset", + category: "", + start_date: null, + expiry_date: "2026-12-31", + period_value: 2, + period_unit: "week", + reminder_unit: "hour", + reminder_value: 3, + notes: "", + amount: null, + currency: "CNY", + last_payment_date: null, + is_active: 0, + auto_renew: 0, + calendar_mode: "solar", + lunar_expiry_date: null, + // Deliberately invalid JSON: must survive via the `_raw` marker. + channels: '{"broken": ', + notification_hours: "[]", + item_kind: "regular", + created_at: now, + updated_at: now, + }); + db.insert("items", { + id: "item-admin-1", + user_id: ADMIN.id, + name: "Domain", + item_mode: "cycle", + category: "", + start_date: null, + expiry_date: "2027-01-01", + period_value: 1, + period_unit: "year", + reminder_unit: "day", + reminder_value: 14, + notes: "", + amount: 88, + currency: "CNY", + last_payment_date: null, + is_active: 1, + auto_renew: 1, + calendar_mode: "both", + lunar_expiry_date: "2026-11-20", + channels: JSON.stringify([]), + notification_hours: JSON.stringify([]), + item_kind: "regular", + created_at: now, + updated_at: now, + }); + + db.insert("payment_history", { + id: "pay-bob-1", + item_id: "item-bob-1", + user_id: BOB.id, + date: "2026-10-01", + amount: 12.5, + currency: "USD", + type: "auto", + note: "october", + period_start: "2026-10-01", + period_end: "2026-11-01", + created_at: now, + }); + db.insert("payment_history", { + id: "pay-admin-1", + item_id: "item-admin-1", + user_id: ADMIN.id, + date: "2026-10-02", + amount: 88, + currency: "CNY", + type: "manual", + note: "", + period_start: null, + period_end: null, + created_at: now, + }); + + db.insert("notification_configs", { + user_id: BOB.id, + enabled_channels: JSON.stringify(["telegram", "email"]), + default_channel: "telegram", + telegram_config: JSON.stringify({ + bot_token: "123:abc", + chat_id: "-100", + }), + webhook_config: "{}", + wechatbot_config: "{}", + email_config: JSON.stringify({ to: "bob@example.com", smtp_host: "smtp" }), + bark_config: "{}", + slack_config: "{}", + feishu_config: "{}", + discord_config: "{}", + notification_hours: JSON.stringify([8, 20]), + updated_at: now, + }); + db.insert("notification_configs", { + user_id: ADMIN.id, + enabled_channels: JSON.stringify(["email"]), + default_channel: "email", + telegram_config: "{}", + webhook_config: "{}", + wechatbot_config: "{}", + email_config: "{}", + bark_config: "{}", + slack_config: "{}", + feishu_config: "{}", + discord_config: "{}", + notification_hours: JSON.stringify([]), + updated_at: now, + }); + + db.insert("system_settings", { + key: "app_name", + value: "eNotify", + updated_at: now, + }); + db.insert("system_settings", { + key: "smtp_config", + value: JSON.stringify({ host: "smtp.example.com", password: "s3cret" }), + updated_at: now, + }); + + db.insert("notification_history", { + id: "hist-1", + user_id: BOB.id, + item_id: "item-bob-1", + channel: "telegram", + title: "VPS expiring", + body: "body", + success: 1, + error: null, + created_at: now, + }); +} + +/** Every row of every table, for whole-database equality assertions. */ +export function dumpTables(db: SqliteD1): Record { + const out: Record = {}; + for (const table of [ + "users", + "user_2fa", + "items", + "payment_history", + "notification_configs", + "system_settings", + "notification_history", + ]) { + out[table] = db.select(`SELECT * FROM ${table} ORDER BY rowid`); + } + return out; +}