diff --git a/README.md b/README.md index 3ec01695..4ff8a6dc 100644 --- a/README.md +++ b/README.md @@ -182,16 +182,50 @@ Cloudflare Dashboard → **Workers & Pages → KV** → 打开 `SUBSCRIPTIONS_KV 表单里可用 **季度 / 半年 / 一年** 快捷(本质是 3 个月 / 6 个月 / 1 年)。 公历可勾选 **「每月最后一天」**(适合「每月月末提醒」;农历下不用这个)。 -### 备份与迁移 +### 数据备份与恢复 -在 **系统配置** 最下方: +**系统配置** 底部的「数据备份与恢复」分成两个目的地,各自拥有独立的备份范围与加密密码: -1. **导出备份** → 下载 JSON(默认可不含密钥) -2. 换账号 / 重装后 **导入** - - **合并**:按订阅 ID 覆盖同名,保留其它 - - **覆盖**:先清空再整包导入(危险,先导出当前数据) +| 目的地 | 范围 | 自动备份 | 保留份数 | 加密 | +| --- | --- | --- | --- | --- | +| 云端备份(WebDAV / S3) | 数据 / 数据 + 设置 | 支持(每天 / 每周) | 1–60 份 | 独立密码,留空 = 不加密 | +| 本地备份(下载 JSON) | 数据 / 数据 + 设置 | 无(仅手动) | 无 | 独立密码,留空 = 不加密 | -升级大版本或迁移 CF 账号前,**先导出一份**。 +- **数据** = 订阅 + 提醒规则 + 分类。 +- **设置** = 系统配置页的全部配置,但不含 WebDAV / S3 凭证与备份计划,避免恢复别的实例备份时改掉当前备份通道。 +- **包含密钥**:仅在「数据 + 设置」下可选;勾选前必须先设置对应的加密密码,否则拒绝备份。`JWT_SECRET` 与加密密码永不进备份。 +- 密码只存服务端,接口只返回「是否已配置」,表单留空表示不修改,点「清空」才会真的清掉。导出/恢复时按备份文件里记录的 `scope` / `includeSecrets` 决定写什么。 +- 恢复统一在「03 恢复」:来源可选本地文件或云端备份,模式为 **合并**(按 ID 覆盖同名订阅,其余保留)或 **覆盖**(清空现有订阅后整包导入)。加密备份需先通过密码校验。 + +### 云端备份(WebDAV / S3) + +存储目标配置在云端备份卡内: + +| 项 | 说明 | +| --- | --- | +| 存储类型 | `WebDAV` 或 `S3 兼容对象存储`(AWS S3 / Cloudflare R2 / MinIO / 阿里云 OSS 等) | +| WebDAV | 服务器地址、用户名、**密码**、远程目录(不存在会自动 `MKCOL` 创建) | +| S3 | Endpoint(只填域名,不带桶名/路径)、桶名称(**不能带 `/`**,子目录写到对象前缀)、Region(R2 填 `auto`,AWS 填真实 region)、Access Key ID、**Secret Access Key**、对象前缀、路径寻址开关 | +| 频率 | 关闭 / 每天 / 每周,配合「执行小时(0–23,按系统时区)」与「每周几」 | +| 保留份数 | 超出后自动删除最旧的备份(1–60) | + +- 密码 / Secret Key 只存服务端,接口只返回「是否已配置」,表单留空表示**不修改**,点「清空」才会真的清掉。 +- 「立即备份到云端」与「测试连接」使用表单里当前填写的连接与备份配置(未保存也能先试)。 +- 定时备份复用每小时整点的 Cron,只在「时区 + 小时 + 周期」都匹配时才真正上传,同一天只跑一次。 + +文件名固定为 `substracker-backup-YYYYMMDD-HHmmss.json`,恢复时只接受该前缀的文件,避免误读同目录下其它对象。 + +**关于加密**:设置加密密码后,上传/下载的仍是同名 `.json`,但内容是一个加密信封: + +```json +{"format":"substracker-backup-encrypted","version":1,"cipher":"AES-256-GCM", + "kdf":{"name":"PBKDF2-SHA256","iterations":100000,"salt":"..."},"iv":"...","data":"..."} +``` + +- 明文不落盘、不上传;对象列表、保留份数清理等逻辑完全不变。 +- 恢复时优先用请求里传的密码,否则用服务器保存的加密密码;两者都没有会直接提示「该备份已加密,请先填写备份密码」。 +- **密码丢失 = 备份永久无法恢复**;换密码后旧备份需要用旧密码才能解开,请自行保存历史密码。 +- 加密密码同样是只存服务端的敏感字段,接口只返回是否已配置。 --- diff --git a/src/api/handlers/backup-cloud.js b/src/api/handlers/backup-cloud.js new file mode 100644 index 00000000..4189e945 --- /dev/null +++ b/src/api/handlers/backup-cloud.js @@ -0,0 +1,141 @@ +// @ts-check +/** + * 云端备份 API(WebDAV / S3) + * + * 路径(相对 /api): + * - GET /backup/cloud/status 配置汇总 + 上次运行结果 + * - POST /backup/cloud/test 连接测试(可携带未保存的表单值) + * - POST /backup/cloud/run 立即备份 + * - GET /backup/cloud/files 远端备份列表 + * - POST /backup/cloud/restore 从远端备份恢复 + */ +import { + getCloudBackupStatus, + listCloudBackups, + restoreFromCloudBackup, + runCloudBackup, + testCloudBackupTarget +} from '../../services/backup/cloud.js'; + +function json(data, status = 200) { + return new Response(JSON.stringify(data), { + status, + headers: { 'Content-Type': 'application/json' } + }); +} + +/** + * 从前端请求体里取出覆盖项 + * 兼容两种写法:{ overrides: {...} } 或直接平铺的配置字段 + * @param {Request} request + */ +async function readOverrides(request) { + try { + const body = await request.json(); + if (body && typeof body === 'object' && body.overrides && typeof body.overrides === 'object') { + return body.overrides; + } + return body && typeof body === 'object' ? body : {}; + } catch { + return {}; + } +} + +function errorStatus(error) { + return error && error.status ? error.status : 500; +} + +function errorMessage(error) { + return error && error.message ? error.message : String(error); +} + +/** + * @param {Request} request + * @param {{ SUBSCRIPTIONS_KV: KVNamespace }} env + * @param {string} path 形如 /backup/cloud/status + */ +export async function handleCloudBackupRoutes(request, env, path) { + const method = request.method; + + if (path === '/backup/cloud/status' && method === 'GET') { + try { + const status = await getCloudBackupStatus(env); + return json({ success: true, data: status }); + } catch (error) { + return json({ success: false, message: errorMessage(error) }, errorStatus(error)); + } + } + + if (path === '/backup/cloud/test' && method === 'POST') { + try { + const overrides = await readOverrides(request); + const result = await testCloudBackupTarget(env, overrides); + return json({ success: true, message: result.message, provider: result.provider }); + } catch (error) { + console.error('[backup] 连接测试失败:', errorMessage(error)); + return json({ success: false, message: errorMessage(error) }, errorStatus(error)); + } + } + + if (path === '/backup/cloud/run' && method === 'POST') { + try { + const overrides = await readOverrides(request); + const result = await runCloudBackup(env, { trigger: 'manual', overrides }); + return json({ + success: true, + message: `备份成功(${result.providerLabel})`, + data: result + }); + } catch (error) { + console.error('[backup] 手动备份失败:', errorMessage(error)); + return json({ success: false, message: errorMessage(error) }, errorStatus(error)); + } + } + + if (path === '/backup/cloud/files' && method === 'GET') { + try { + const files = await listCloudBackups(env); + return json({ success: true, data: files }); + } catch (error) { + console.error('[backup] 获取备份列表失败:', errorMessage(error)); + return json({ success: false, message: errorMessage(error), data: [] }, errorStatus(error)); + } + } + + if (path === '/backup/cloud/restore' && method === 'POST') { + try { + /** @type {any} */ + let body = {}; + try { + body = await request.json(); + } catch { + body = {}; + } + + const result = await restoreFromCloudBackup(env, { + file: body.file, + mode: body.mode === 'replace' ? 'replace' : 'merge', + includeSecrets: body.includeSecrets === true, + password: typeof body.password === 'string' ? body.password : '' + }); + + return json({ + success: true, + message: `恢复完成(模式: ${result.mode === 'replace' ? '覆盖' : '合并'})`, + stats: { + subscriptions: result.subscriptions, + reminderRules: result.reminderRules, + categories: result.categories, + configRestored: result.configRestored, + secretsApplied: result.secretsApplied + }, + file: result.file + }); + } catch (error) { + console.error('[backup] 云端恢复失败:', errorMessage(error)); + return json({ success: false, message: errorMessage(error) }, errorStatus(error)); + } + } + + return null; +} diff --git a/src/api/handlers/backup.js b/src/api/handlers/backup.js index c17cae4a..db2d6f07 100644 --- a/src/api/handlers/backup.js +++ b/src/api/handlers/backup.js @@ -1,28 +1,16 @@ // @ts-check /** - * 配置与数据备份 / 恢复 + * 配置与数据备份 / 恢复(HTTP 层,对应「本地备份」) * - * GET /api/backup?includeSecrets=0|1 - * POST /api/restore body: { backup, mode: 'merge'|'replace', includeSecrets?: boolean } + * GET /api/backup?scope=data|settings&includeSecrets=0|1 + * POST /api/restore body: { backup, mode: 'merge'|'replace', password?: string } * - * 设计约束: - * - 默认导出不含密钥/密码,避免备份文件泄露 - * - JWT_SECRET 永不导出、导入时也不覆盖(避免会话被意外作废;换环境请重新登录) - * - 订阅 + reminder_rules 一并导出,保证多规则提醒可无损迁移 + * 载荷的构建与落库在 services/backup/payload.js,云端备份(WebDAV / S3)复用同一份载荷。 + * 本地备份密码取 LOCAL_BACKUP_ENCRYPT_PASSWORD:有密码即加密导出,留空即明文。 */ -import { getConfig, setConfig } from '../../data/config.js'; -import * as subRepo from '../../data/subscriptions.repo.js'; -import * as remindersRepo from '../../data/reminders.repo.js'; -import { getCategories } from '../../data/categories.js'; -import { putKVJson } from '../../data/kv.js'; -import { SECRET_FIELDS } from './config.js'; -import { VERSION } from './extras.js'; - -const BACKUP_FORMAT = 'substracker-backup'; -const BACKUP_VERSION = 1; - -/** 永不导出/覆盖的字段 */ -const NEVER_EXPORT_FIELDS = ['JWT_SECRET', 'ADMIN_PASSWORD']; +import { getConfig } from '../../data/config.js'; +import { applyBackupPayload, buildBackupPayload } from '../../services/backup/payload.js'; +import { decryptBackupText, encryptBackupText, isEncryptedBackup } from '../../services/backup/crypto.js'; /** * @param {any} data @@ -35,26 +23,16 @@ function json(data, status = 200) { }); } -/** - * @param {any} config - * @param {boolean} includeSecrets - */ -function buildExportConfig(config, includeSecrets) { - /** @type {Record} */ - const out = { ...config }; - delete out.JWT_SECRET; - - if (!includeSecrets) { - delete out.ADMIN_PASSWORD; - for (const key of SECRET_FIELDS) { - if (key in out) out[key] = ''; - } - } else { - // 即使含密钥,也不导出 JWT_SECRET - delete out.JWT_SECRET; - } +function pad2(value) { + return String(value).padStart(2, '0'); +} - return out; +/** substracker-backup-YYYYMMDD-HHmmss.json */ +function localFileName(now = new Date()) { + const stamp = + `${now.getUTCFullYear()}${pad2(now.getUTCMonth() + 1)}${pad2(now.getUTCDate())}` + + `-${pad2(now.getUTCHours())}${pad2(now.getUTCMinutes())}${pad2(now.getUTCSeconds())}`; + return `substracker-backup-${stamp}.json`; } /** @@ -66,50 +44,32 @@ function buildExportConfig(config, includeSecrets) { export async function handleExportBackup(request, env) { try { const url = new URL(request.url); + const scope = url.searchParams.get('scope') === 'data' ? 'data' : 'settings'; const includeSecrets = url.searchParams.get('includeSecrets') === '1' || url.searchParams.get('includeSecrets') === 'true'; const config = await getConfig(env); - const categories = await getCategories(env); - const subscriptions = await subRepo.listAll(env); + const password = + typeof config.LOCAL_BACKUP_ENCRYPT_PASSWORD === 'string' ? config.LOCAL_BACKUP_ENCRYPT_PASSWORD : ''; - /** @type {Record} */ - const reminderRules = {}; - for (const sub of subscriptions) { - if (!sub || !sub.id) continue; - let rules = await remindersRepo.listForSubscription(env, sub.id); - if (rules.length === 0) { - rules = [remindersRepo.legacyFieldToRule(sub)]; - } - reminderRules[sub.id] = rules; + if (includeSecrets && !password) { + return json({ success: false, message: '导出含密钥的备份前,请先设置本地备份加密密码' }, 400); } - // 导出体不附带运行时附加字段 - const cleanSubs = subscriptions.map((sub) => { - const { reminderRules: _rr, reminderRulesSummary: _rs, ...rest } = sub || {}; - return rest; - }); - - const backup = { - format: BACKUP_FORMAT, - version: BACKUP_VERSION, - appVersion: VERSION, - exportedAt: new Date().toISOString(), - includeSecrets, - config: buildExportConfig(config, includeSecrets), - categories, - subscriptions: cleanSubs, - reminderRules - }; + const backup = await buildBackupPayload(env, { scope, includeSecrets }); + let body = JSON.stringify(backup, null, 2); + if (password) { + body = await encryptBackupText(body, password); + } - return new Response(JSON.stringify(backup, null, 2), { + return new Response(body, { status: 200, headers: { 'Content-Type': 'application/json; charset=utf-8', - 'Content-Disposition': `attachment; filename="substracker-backup-${new Date() - .toISOString() - .slice(0, 10)}.json"` + 'Content-Disposition': `attachment; filename="${localFileName()}"`, + 'X-Backup-Encrypted': password ? '1' : '0', + 'X-Backup-Scope': backup.scope } }); } catch (error) { @@ -121,89 +81,6 @@ export async function handleExportBackup(request, env) { } } -/** - * 校验备份结构 - * @param {any} raw - * @returns {{ ok: true, backup: any } | { ok: false, message: string }} - */ -/** - * @param {any} sub - * @param {number} index - * @returns {string|null} 错误信息 - */ -function validateSubscriptionEntry(sub, index) { - if (!sub || typeof sub !== 'object') { - return `subscriptions[${index}] 不是对象`; - } - if (typeof sub.id !== 'string' || !sub.id.trim()) { - return `subscriptions[${index}] 缺少有效 id`; - } - if (typeof sub.name !== 'string' || !sub.name.trim()) { - return `subscriptions[${index}] 缺少 name`; - } - if (!sub.expiryDate || Number.isNaN(new Date(sub.expiryDate).getTime())) { - return `subscriptions[${index}] 缺少有效 expiryDate`; - } - return null; -} - -function validateBackup(raw) { - if (!raw || typeof raw !== 'object') { - return { ok: false, message: '备份内容不是有效 JSON 对象' }; - } - if (raw.format && raw.format !== BACKUP_FORMAT) { - return { ok: false, message: `不支持的备份格式: ${raw.format}` }; - } - if (raw.version != null && Number(raw.version) > BACKUP_VERSION) { - return { ok: false, message: `备份版本过高 (${raw.version}),请升级应用后再导入` }; - } - if (!Array.isArray(raw.subscriptions)) { - return { ok: false, message: '备份缺少 subscriptions 数组' }; - } - for (let i = 0; i < raw.subscriptions.length; i++) { - const err = validateSubscriptionEntry(raw.subscriptions[i], i); - if (err) return { ok: false, message: err }; - } - if (raw.reminderRules != null && typeof raw.reminderRules !== 'object') { - return { ok: false, message: 'reminderRules 必须是对象' }; - } - return { ok: true, backup: raw }; -} - -/** - * 合并配置:默认不覆盖密钥空值;includeSecrets 时才写入非空密钥 - * - * @param {any} current - * @param {any} incoming - * @param {boolean} includeSecrets - */ -function mergeConfig(current, incoming, includeSecrets) { - if (!incoming || typeof incoming !== 'object') return current; - - /** @type {Record} */ - const next = { ...current }; - - for (const [key, value] of Object.entries(incoming)) { - if (NEVER_EXPORT_FIELDS.includes(key) || key === 'JWT_SECRET') continue; - - if (SECRET_FIELDS.includes(key) || key === 'ADMIN_PASSWORD') { - if (!includeSecrets) continue; - if (typeof value === 'string' && value.trim() !== '') { - next[key] = value; - } - continue; - } - - if (value !== undefined) { - next[key] = value; - } - } - - // 始终保留现有 JWT - next.JWT_SECRET = current.JWT_SECRET; - return next; -} - /** * POST /api/restore * @@ -219,101 +96,44 @@ export async function handleImportBackup(request, env) { return json({ success: false, message: '请求体不是合法 JSON' }, 400); } - // 兼容:body 直接是备份,或 { backup, mode, includeSecrets } - const rawBackup = body && body.backup ? body.backup : body; + // 兼容:body 直接是备份,或 { backup, mode, password } + let rawBackup = body && body.backup ? body.backup : body; const mode = body && body.mode === 'replace' ? 'replace' : 'merge'; - const includeSecrets = !!(body && body.includeSecrets); - - const validated = validateBackup(rawBackup); - if (!validated.ok) { - return json({ success: false, message: /** @type {any} */ (validated).message }, 400); - } - const backup = /** @type {any} */ (validated).backup; - - // 先写订阅/规则,再写配置:避免配置已改但数据半残 - const incomingSubs = backup.subscriptions.filter((s) => s && typeof s.id === 'string' && s.id); - if (mode === 'replace' && incomingSubs.length === 0) { - return json( - { success: false, message: '覆盖模式拒绝空订阅列表(请确认备份完整或改用合并模式)' }, - 400 - ); - } - - const rulesMap = - backup.reminderRules && typeof backup.reminderRules === 'object' ? backup.reminderRules : {}; - - let importedSubs = 0; - let importedRules = 0; - - if (mode === 'replace') { - const existing = await subRepo.listAll(env); - for (const sub of existing) { - if (sub && sub.id) { - await remindersRepo.clearForSubscription(env, sub.id); - } + const requestPassword = body && typeof body.password === 'string' ? body.password : ''; + + if (isEncryptedBackup(rawBackup)) { + const config = await getConfig(env); + const password = + requestPassword || + (typeof config.LOCAL_BACKUP_ENCRYPT_PASSWORD === 'string' + ? config.LOCAL_BACKUP_ENCRYPT_PASSWORD + : ''); + if (!password) { + return json({ success: false, message: '该备份已加密,请输入解密密码' }, 400); } - await subRepo.replaceAll(env, incomingSubs); - importedSubs = incomingSubs.length; - } else { - for (const sub of incomingSubs) { - await subRepo.save(env, sub); - importedSubs++; + const plaintext = await decryptBackupText(rawBackup, password); + try { + rawBackup = JSON.parse(plaintext); + } catch { + return json({ success: false, message: '解密后的备份内容不是合法 JSON' }, 400); } } - for (const sub of incomingSubs) { - let rules = Array.isArray(rulesMap[sub.id]) ? rulesMap[sub.id] : null; - if (!rules && Array.isArray(sub.reminderRules)) rules = sub.reminderRules; - if (rules && rules.length > 0) { - const normalized = rules.map((r) => remindersRepo.normalizeRule(r)); - await remindersRepo.replaceForSubscription(env, sub.id, normalized); - importedRules += normalized.length; - try { - const { syncLegacyReminderFields } = await import('../../data/subscriptions.js'); - await syncLegacyReminderFields(env, sub.id, normalized); - } catch { - /* ignore */ - } - } - } - - // 分类 - if (Array.isArray(backup.categories)) { - const cats = backup.categories - .filter((c) => typeof c === 'string' && c.trim()) - .map((c) => c.trim()); - if (mode === 'replace') { - await putKVJson(env, 'categories', [...new Set(cats)].sort()); - } else { - const existing = await getCategories(env); - const set = new Set([...existing, ...cats]); - await putKVJson(env, 'categories', [...set].sort()); - } - } - - // 配置放最后 - const currentConfig = await getConfig(env); - if (backup.config && typeof backup.config === 'object') { - const merged = mergeConfig(currentConfig, backup.config, includeSecrets); - await setConfig(env, merged); - } + const stats = await applyBackupPayload(env, rawBackup, { mode }); return json({ success: true, message: `恢复完成(模式: ${mode === 'replace' ? '覆盖' : '合并'})`, - stats: { - subscriptions: importedSubs, - reminderRules: importedRules, - categories: Array.isArray(backup.categories) ? backup.categories.length : 0, - configRestored: !!backup.config, - secretsApplied: includeSecrets - } + stats }); } catch (error) { console.error('[backup] 导入失败:', error); + // @ts-ignore + const status = error && error.status ? error.status : 500; + const message = error && error.message ? error.message : String(error); return json( - { success: false, message: '导入失败: ' + (error && error.message ? error.message : String(error)) }, - 500 + { success: false, message: status === 400 ? message : '导入失败: ' + message }, + status ); } } diff --git a/src/api/handlers/config.js b/src/api/handlers/config.js index 3a0055e5..9e6a3ee8 100644 --- a/src/api/handlers/config.js +++ b/src/api/handlers/config.js @@ -1,27 +1,62 @@ import { getConfig, setConfig } from '../../data/config.js'; +import { SECRET_FIELDS } from '../../data/secret-fields.js'; import { generateRandomSecret, sanitizeNotificationHours } from '../utils.js'; -// 这些字段可能包含 token/密钥,绝不下发到浏览器 -const SECRET_FIELDS = [ - 'TG_BOT_TOKEN', - 'NOTIFYX_API_KEY', - 'WEBHOOK_URL', - 'WEBHOOK_HEADERS', - 'WECHATBOT_WEBHOOK', - 'RESEND_API_KEY', - 'BARK_DEVICE_KEY', - 'THIRD_PARTY_API_TOKEN', - 'GOTIFY_APP_TOKEN', - 'SERVERCHAN_SENDKEY', - 'PUSHPLUS_TOKEN', - 'NTFY_TOKEN', - 'WPUSH_APIKEY' -]; - function isConfiguredSecret(value) { return typeof value === 'string' && value.trim().length > 0; } +/** + * 读取字符串字段(缺省时回退旧值) + * @param {any} incoming + * @param {string} key + * @param {string} [fallback] + */ +function pickString(incoming, key, fallback = '') { + if (!incoming || !(key in incoming) || incoming[key] == null) return fallback; + return String(incoming[key]).trim(); +} + +/** + * 读取布尔字段(缺省时回退旧值) + * @param {any} incoming + * @param {string} key + * @param {boolean} [fallback] + */ +function pickBoolean(incoming, key, fallback = false) { + if (!incoming || !(key in incoming) || incoming[key] == null) return fallback === true; + const value = incoming[key]; + return value === true || value === 'true' || value === '1'; +} + +/** + * 读取整数并收敛到区间 + * @param {any} incoming + * @param {string} key + * @param {number} fallback + * @param {number} min + * @param {number} max + */ +function pickInt(incoming, key, fallback, min, max) { + const value = Number(incoming && key in incoming ? incoming[key] : fallback); + if (!Number.isFinite(value)) return fallback; + return Math.min(max, Math.max(min, Math.floor(value))); +} + +/** + * 云端备份目录/前缀:去掉首尾斜杠,拒绝 .. + * @param {any} value + * @param {string} fallback + */ +function sanitizeBackupPath(value, fallback) { + const raw = String(value == null ? fallback : value) + .trim() + .replace(/\\/g, '/') + .replace(/^\/+|\/+$/g, ''); + if (!raw || raw.split('/').some((part) => part === '..')) return fallback; + return raw; +} + function buildSafeConfig(config) { const { JWT_SECRET, ADMIN_PASSWORD, ...safeConfig } = config; const response = { ...safeConfig }; @@ -132,6 +167,73 @@ async function handleUpdateConfig(request, env) { THIRD_PARTY_API_TOKEN: mergeSecretField(config, newConfig, 'THIRD_PARTY_API_TOKEN', clearSecretFields), + // ── 云端备份(WebDAV / S3)── + BACKUP_ENABLED: pickBoolean(newConfig, 'BACKUP_ENABLED', config.BACKUP_ENABLED), + BACKUP_PROVIDER: + newConfig.BACKUP_PROVIDER === 's3' || newConfig.BACKUP_PROVIDER === 'webdav' + ? newConfig.BACKUP_PROVIDER + : config.BACKUP_PROVIDER || 'webdav', + BACKUP_SCHEDULE: + newConfig.BACKUP_SCHEDULE === 'off' || + newConfig.BACKUP_SCHEDULE === 'daily' || + newConfig.BACKUP_SCHEDULE === 'weekly' + ? newConfig.BACKUP_SCHEDULE + : config.BACKUP_SCHEDULE || 'off', + BACKUP_HOUR: pickInt(newConfig, 'BACKUP_HOUR', config.BACKUP_HOUR ?? 3, 0, 23), + BACKUP_WEEKLY_DAY: pickInt(newConfig, 'BACKUP_WEEKLY_DAY', config.BACKUP_WEEKLY_DAY ?? 1, 1, 7), + BACKUP_RETENTION: pickInt(newConfig, 'BACKUP_RETENTION', config.BACKUP_RETENTION ?? 7, 1, 60), + CLOUD_BACKUP_SCOPE: + newConfig.CLOUD_BACKUP_SCOPE === 'data' || newConfig.CLOUD_BACKUP_SCOPE === 'settings' + ? newConfig.CLOUD_BACKUP_SCOPE + : config.CLOUD_BACKUP_SCOPE || 'settings', + CLOUD_BACKUP_INCLUDE_SECRETS: pickBoolean( + newConfig, + 'CLOUD_BACKUP_INCLUDE_SECRETS', + config.CLOUD_BACKUP_INCLUDE_SECRETS + ), + CLOUD_BACKUP_ENCRYPT_PASSWORD: mergeSecretField( + config, + newConfig, + 'CLOUD_BACKUP_ENCRYPT_PASSWORD', + clearSecretFields + ), + LOCAL_BACKUP_SCOPE: + newConfig.LOCAL_BACKUP_SCOPE === 'data' || newConfig.LOCAL_BACKUP_SCOPE === 'settings' + ? newConfig.LOCAL_BACKUP_SCOPE + : config.LOCAL_BACKUP_SCOPE || 'data', + LOCAL_BACKUP_INCLUDE_SECRETS: pickBoolean( + newConfig, + 'LOCAL_BACKUP_INCLUDE_SECRETS', + config.LOCAL_BACKUP_INCLUDE_SECRETS + ), + LOCAL_BACKUP_ENCRYPT_PASSWORD: mergeSecretField( + config, + newConfig, + 'LOCAL_BACKUP_ENCRYPT_PASSWORD', + clearSecretFields + ), + WEBDAV_URL: pickString(newConfig, 'WEBDAV_URL', config.WEBDAV_URL || ''), + WEBDAV_USERNAME: pickString(newConfig, 'WEBDAV_USERNAME', config.WEBDAV_USERNAME || ''), + WEBDAV_PASSWORD: mergeSecretField(config, newConfig, 'WEBDAV_PASSWORD', clearSecretFields), + WEBDAV_PATH: sanitizeBackupPath( + newConfig.WEBDAV_PATH != null ? newConfig.WEBDAV_PATH : config.WEBDAV_PATH, + 'SubsTracker' + ), + S3_ENDPOINT: pickString(newConfig, 'S3_ENDPOINT', config.S3_ENDPOINT || ''), + S3_REGION: pickString(newConfig, 'S3_REGION', config.S3_REGION || 'auto') || 'auto', + S3_BUCKET: pickString(newConfig, 'S3_BUCKET', config.S3_BUCKET || ''), + S3_ACCESS_KEY_ID: pickString(newConfig, 'S3_ACCESS_KEY_ID', config.S3_ACCESS_KEY_ID || ''), + S3_SECRET_ACCESS_KEY: mergeSecretField(config, newConfig, 'S3_SECRET_ACCESS_KEY', clearSecretFields), + S3_PREFIX: sanitizeBackupPath( + newConfig.S3_PREFIX != null ? newConfig.S3_PREFIX : config.S3_PREFIX, + 'SubsTracker' + ), + S3_FORCE_PATH_STYLE: pickBoolean( + newConfig, + 'S3_FORCE_PATH_STYLE', + config.S3_FORCE_PATH_STYLE !== false + ), + DEBUG_LOGS: newConfig.DEBUG_LOGS === true, PAYMENT_HISTORY_LIMIT: Number.isFinite(Number(newConfig.PAYMENT_HISTORY_LIMIT)) ? Math.min(1000, Math.max(10, Math.floor(Number(newConfig.PAYMENT_HISTORY_LIMIT)))) diff --git a/src/api/handlers/extras.js b/src/api/handlers/extras.js index 77abfd4d..836dd6ab 100644 --- a/src/api/handlers/extras.js +++ b/src/api/handlers/extras.js @@ -22,9 +22,9 @@ import * as notifyLogsRepo from '../../data/notification-logs.repo.js'; import * as schedLogsRepo from '../../data/scheduler-logs.repo.js'; import { getCategories, addCategory } from '../../data/categories.js'; import { getNextFireTime } from '../../services/notify/reminder-engine.js'; +import { VERSION } from '../../core/version.js'; -export const VERSION = '3.0.0'; - +export { VERSION }; /** 标准 JSON 响应 */ function json(data, status = 200) { return new Response(JSON.stringify(data), { diff --git a/src/api/router.js b/src/api/router.js index 1ef58f42..d5805755 100644 --- a/src/api/router.js +++ b/src/api/router.js @@ -50,6 +50,11 @@ async function handleApiRequest(request, env) { } // 备份 / 恢复 + if (path.startsWith('/backup/cloud/')) { + const { handleCloudBackupRoutes } = await import('./handlers/backup-cloud.js'); + const cloudResponse = await handleCloudBackupRoutes(request, env, path); + if (cloudResponse) return cloudResponse; + } if (path === '/backup' && method === 'GET') { const { handleExportBackup } = await import('./handlers/backup.js'); return handleExportBackup(request, env); diff --git a/src/core/version.js b/src/core/version.js new file mode 100644 index 00000000..1a39fb5c --- /dev/null +++ b/src/core/version.js @@ -0,0 +1,5 @@ +// @ts-check +/** + * 应用版本号(单一来源,避免各模块各自维护) + */ +export const VERSION = '3.0.0'; diff --git a/src/data/config.js b/src/data/config.js index 3a6c7e3a..eac51b9a 100644 --- a/src/data/config.js +++ b/src/data/config.js @@ -41,7 +41,34 @@ const DEFAULT_CONFIG = { NTFY_TOKEN: '', WPUSH_APIKEY: '', WPUSH_CHANNEL: '', - WPUSH_TOPIC_CODE: '' + WPUSH_TOPIC_CODE: '', + + // 云端备份(WebDAV / S3) + BACKUP_ENABLED: false, + BACKUP_PROVIDER: 'webdav', + BACKUP_SCHEDULE: 'off', + BACKUP_HOUR: 3, + BACKUP_WEEKLY_DAY: 1, + BACKUP_RETENTION: 7, + CLOUD_BACKUP_SCOPE: 'settings', + CLOUD_BACKUP_INCLUDE_SECRETS: false, + CLOUD_BACKUP_ENCRYPT_PASSWORD: '', + WEBDAV_URL: '', + WEBDAV_USERNAME: '', + WEBDAV_PASSWORD: '', + WEBDAV_PATH: 'SubsTracker', + S3_ENDPOINT: '', + S3_REGION: 'auto', + S3_BUCKET: '', + S3_ACCESS_KEY_ID: '', + S3_SECRET_ACCESS_KEY: '', + S3_PREFIX: 'SubsTracker', + S3_FORCE_PATH_STYLE: true, + + // 本地备份(手动下载) + LOCAL_BACKUP_SCOPE: 'data', + LOCAL_BACKUP_INCLUDE_SECRETS: false, + LOCAL_BACKUP_ENCRYPT_PASSWORD: '' }; async function getConfig(env) { @@ -51,14 +78,36 @@ async function getConfig(env) { } const data = await env.SUBSCRIPTIONS_KV.get('config'); console.log('[配置] 从KV读取配置:', data ? '成功' : '空配置'); - const config = data ? JSON.parse(data) : {}; + let config = data ? JSON.parse(data) : {}; + + // 兼容旧版全局备份加密 / 包含密钥配置,迁移到云端独立配置后删除旧键 + let migrated = false; + if ('BACKUP_INCLUDE_SECRETS' in config) { + if (!('CLOUD_BACKUP_INCLUDE_SECRETS' in config)) { + config.CLOUD_BACKUP_INCLUDE_SECRETS = config.BACKUP_INCLUDE_SECRETS === true; + } + delete config.BACKUP_INCLUDE_SECRETS; + migrated = true; + } + if ('BACKUP_ENCRYPT' in config || 'BACKUP_ENCRYPT_PASSWORD' in config) { + if (!('CLOUD_BACKUP_ENCRYPT_PASSWORD' in config) && typeof config.BACKUP_ENCRYPT_PASSWORD === 'string') { + config.CLOUD_BACKUP_ENCRYPT_PASSWORD = config.BACKUP_ENCRYPT_PASSWORD; + } + delete config.BACKUP_ENCRYPT; + delete config.BACKUP_ENCRYPT_PASSWORD; + migrated = true; + } let jwtSecret = config.JWT_SECRET; + let jwtChanged = false; if (!jwtSecret) { console.log('[配置] 生成新的JWT密钥'); jwtSecret = crypto.randomUUID(); - const updatedConfig = { ...config, JWT_SECRET: jwtSecret }; - await env.SUBSCRIPTIONS_KV.put('config', JSON.stringify(updatedConfig)); + jwtChanged = true; + } + + if (migrated || jwtChanged) { + await env.SUBSCRIPTIONS_KV.put('config', JSON.stringify({ ...config, JWT_SECRET: jwtSecret })); } return { diff --git a/src/data/secret-fields.js b/src/data/secret-fields.js new file mode 100644 index 00000000..8ab85416 --- /dev/null +++ b/src/data/secret-fields.js @@ -0,0 +1,31 @@ +// @ts-check +/** + * 含密钥/凭证的配置字段。 + * + * 约定: + * - 这些字段永远不会下发到浏览器(只返回空字符串 + `${KEY}_CONFIGURED` 标记) + * - 备份导出默认清空,只有显式 includeSecrets 才写入 + */ +const SECRET_FIELDS = [ + 'TG_BOT_TOKEN', + 'NOTIFYX_API_KEY', + 'WEBHOOK_URL', + 'WEBHOOK_HEADERS', + 'WECHATBOT_WEBHOOK', + 'RESEND_API_KEY', + 'BARK_DEVICE_KEY', + 'THIRD_PARTY_API_TOKEN', + 'GOTIFY_APP_TOKEN', + 'SERVERCHAN_SENDKEY', + 'PUSHPLUS_TOKEN', + 'NTFY_TOKEN', + 'WPUSH_APIKEY', + // 云端备份凭证 + 'WEBDAV_PASSWORD', + 'S3_SECRET_ACCESS_KEY', + // 备份文件加密口令(云端 / 本地各自独立) + 'CLOUD_BACKUP_ENCRYPT_PASSWORD', + 'LOCAL_BACKUP_ENCRYPT_PASSWORD' +]; + +export { SECRET_FIELDS }; diff --git a/src/index.js b/src/index.js index 6fea93ce..89fd2109 100644 --- a/src/index.js +++ b/src/index.js @@ -10,6 +10,7 @@ import app from './app.js'; import { ensureMigrations } from './data/migrate.js'; import { checkExpiringSubscriptions } from './services/scheduler.js'; +import { maybeRunScheduledBackup } from './services/backup/cloud.js'; export default { fetch: app.fetch, @@ -36,5 +37,15 @@ export default { new Date().toISOString() ); await checkExpiringSubscriptions(env); + + // 云端备份(WebDAV / S3):到点才真正上传,其余小时直接返回 + try { + const backupResult = /** @type {any} */ (await maybeRunScheduledBackup(env)); + if (backupResult && backupResult.ran) { + console.log('[backup] 定时备份成功:', backupResult.provider, backupResult.file); + } + } catch (err) { + console.error('[backup] 定时备份异常:', err); + } } }; diff --git a/src/services/backup/cloud.js b/src/services/backup/cloud.js new file mode 100644 index 00000000..1edc5d3c --- /dev/null +++ b/src/services/backup/cloud.js @@ -0,0 +1,456 @@ +// @ts-check +/** + * 云端备份编排:WebDAV / S3 + * + * 能力: + * - 立即备份(复用 /api/backup 的导出载荷) + * - 连接测试(可用未保存的表单值覆盖已保存配置) + * - 列出远端备份 / 从远端恢复 + * - 保留份数(超出后删除最旧的) + * - 定时备份(每小时 Cron 触发,按配置的时区 + 小时 + 周期判断) + */ +import { getConfig } from '../../data/config.js'; +import { getKVJson, putKVJson } from '../../data/kv.js'; +import { getNowInTimezone } from '../../core/time.js'; +import { buildBackupPayload, applyBackupPayload } from './payload.js'; +import { + decryptBackupText, + encryptBackupText, + isEncryptedBackup +} from './crypto.js'; +import * as webdav from './webdav.js'; +import * as s3 from './s3.js'; + +export const CLOUD_BACKUP_STATE_KEY = 'cloud_backup_state'; +export const CLOUD_BACKUP_FILE_PREFIX = 'substracker-backup-'; + +/** 云端备份相关配置字段(用于测试时合并未保存的表单值) */ +export const CLOUD_BACKUP_FIELDS = [ + 'BACKUP_ENABLED', + 'BACKUP_PROVIDER', + 'BACKUP_SCHEDULE', + 'BACKUP_HOUR', + 'BACKUP_WEEKLY_DAY', + 'BACKUP_RETENTION', + 'CLOUD_BACKUP_SCOPE', + 'CLOUD_BACKUP_INCLUDE_SECRETS', + 'CLOUD_BACKUP_ENCRYPT_PASSWORD', + 'WEBDAV_URL', + 'WEBDAV_USERNAME', + 'WEBDAV_PASSWORD', + 'WEBDAV_PATH', + 'S3_ENDPOINT', + 'S3_REGION', + 'S3_BUCKET', + 'S3_ACCESS_KEY_ID', + 'S3_SECRET_ACCESS_KEY', + 'S3_PREFIX', + 'S3_FORCE_PATH_STYLE' +]; + +/** + * @param {string} message + * @param {number} [status] + */ +function backupError(message, status = 500) { + const error = new Error(message); + // @ts-ignore + error.status = status; + return error; +} + +function pad2(value) { + return String(value).padStart(2, '0'); +} + +/** @param {any} config */ +export function providerOf(config) { + return config && config.BACKUP_PROVIDER === 's3' ? 's3' : 'webdav'; +} + +/** + * 用请求里的值覆盖已保存配置(空字符串视为“不修改”,便于密钥留空) + * @param {any} config + * @param {any} overrides + */ +export function mergeCloudBackupOverrides(config, overrides) { + if (!overrides || typeof overrides !== 'object') return { ...config }; + /** @type {any} */ + const next = { ...config }; + for (const key of CLOUD_BACKUP_FIELDS) { + if (!(key in overrides)) continue; + const value = overrides[key]; + if (value == null) continue; + if (typeof value === 'string' && !value.trim()) continue; + next[key] = value; + } + return next; +} + +/** @param {any} config */ +function webdavConfigFrom(config) { + return { + url: config.WEBDAV_URL, + username: config.WEBDAV_USERNAME, + password: config.WEBDAV_PASSWORD, + remotePath: config.WEBDAV_PATH || 'SubsTracker' + }; +} + +/** @param {any} config */ +function s3ConfigFrom(config) { + return { + endpoint: config.S3_ENDPOINT, + bucket: config.S3_BUCKET, + region: config.S3_REGION || 'auto', + accessKeyId: config.S3_ACCESS_KEY_ID, + secretAccessKey: config.S3_SECRET_ACCESS_KEY, + prefix: config.S3_PREFIX || 'SubsTracker', + forcePathStyle: config.S3_FORCE_PATH_STYLE !== false + }; +} + +/** + * 备份文件名:substracker-backup-YYYYMMDD-HHmmss.json(按配置时区) + * @param {any} config + * @param {Date} [now] + */ +export function buildBackupFileName(config, now = new Date()) { + const { parts } = getNowInTimezone(config.TIMEZONE || 'Asia/Shanghai', now); + const stamp = `${parts.year}${pad2(parts.month)}${pad2(parts.day)}-${pad2(parts.hour)}${pad2(parts.minute)}${pad2(parts.second)}`; + return `${CLOUD_BACKUP_FILE_PREFIX}${stamp}.json`; +} + +/** + * 读取当前备份状态(上次运行结果 / 定时去重日期) + * @param {{ SUBSCRIPTIONS_KV: KVNamespace }} env + */ +export async function getCloudBackupState(env) { + return getKVJson(env, CLOUD_BACKUP_STATE_KEY, {}); +} + +/** + * @param {{ SUBSCRIPTIONS_KV: KVNamespace }} env + * @param {Record} patch + */ +async function saveCloudBackupState(env, patch) { + const current = await getCloudBackupState(env); + await putKVJson(env, CLOUD_BACKUP_STATE_KEY, { ...current, ...patch }); +} + +/** + * 列出远端备份(只保留本项目的备份文件) + * @param {{ SUBSCRIPTIONS_KV: KVNamespace }} env + * @param {{ overrides?: any, config?: any }} [options] + */ +export async function listCloudBackups(env, options = {}) { + // 允许直接传入已合并的配置:定时/覆盖项备份时列表必须与上传使用同一个后端 + const config = options.config || mergeCloudBackupOverrides(await getConfig(env), options.overrides); + const provider = providerOf(config); + + /** @type {Array<{ name: string, path: string, size: number|null, modifiedAt: string|null }>} */ + let items; + + if (provider === 's3') { + const client = s3.normalizeS3Config(s3ConfigFrom(config)); + const objects = await s3.listObjects(client); + items = objects.map((item) => ({ + name: item.name, + path: item.key, + size: item.size, + modifiedAt: item.modifiedAt + })); + } else { + const client = webdav.normalizeWebdavConfig(webdavConfigFrom(config)); + const files = await webdav.listFiles(client); + items = files.map((item) => ({ + name: item.name, + path: item.url, + size: item.size, + modifiedAt: item.modifiedAt + })); + } + + return items + .filter((item) => item.name.startsWith(CLOUD_BACKUP_FILE_PREFIX) && item.name.endsWith('.json')) + .sort((a, b) => (a.name < b.name ? 1 : a.name > b.name ? -1 : 0)); +} + +/** + * 保留最近 N 份,删除多余的 + * @param {{ SUBSCRIPTIONS_KV: KVNamespace }} env + * @param {any} config + * @param {'webdav'|'s3'} provider + */ +async function pruneCloudBackups(env, config, provider) { + const keep = Math.max(1, Math.min(60, Number(config.BACKUP_RETENTION) || 7)); + const items = await listCloudBackups(env, { config }); + if (items.length <= keep) return 0; + + const stale = items.slice(keep); + let removed = 0; + + if (provider === 's3') { + const client = s3.normalizeS3Config(s3ConfigFrom(config)); + for (const item of stale) { + await s3.deleteObject(client, item.path); + removed++; + } + } else { + const client = webdav.normalizeWebdavConfig(webdavConfigFrom(config)); + for (const item of stale) { + await webdav.deleteFile(client, item.path); + removed++; + } + } + + return removed; +} + +/** + * 立即执行一次云端备份 + * @param {{ SUBSCRIPTIONS_KV: KVNamespace }} env + * @param {{ trigger?: string, overrides?: any, now?: Date }} [options] + */ +export async function runCloudBackup(env, options = {}) { + const config = mergeCloudBackupOverrides(await getConfig(env), options.overrides); + const provider = providerOf(config); + const scope = config.CLOUD_BACKUP_SCOPE === 'data' ? 'data' : 'settings'; + const includeSecrets = scope === 'settings' && config.CLOUD_BACKUP_INCLUDE_SECRETS === true; + const password = + typeof config.CLOUD_BACKUP_ENCRYPT_PASSWORD === 'string' ? config.CLOUD_BACKUP_ENCRYPT_PASSWORD : ''; + const encrypt = password.length > 0; + const trigger = options.trigger || 'manual'; + const now = options.now instanceof Date ? options.now : new Date(); + + try { + if (includeSecrets && !encrypt) { + throw backupError('备份包含密钥时请先设置云端备份密码(留空即明文上传)', 400); + } + const payload = await buildBackupPayload(env, { scope, includeSecrets, now }); + const fileName = buildBackupFileName(config, now); + let body = JSON.stringify(payload, null, 2); + + if (encrypt) { + body = await encryptBackupText(body, password); + } + + let file; + if (provider === 's3') { + const client = s3.normalizeS3Config(s3ConfigFrom(config)); + file = await s3.putObject(client, fileName, body); + } else { + const client = webdav.normalizeWebdavConfig(webdavConfigFrom(config)); + file = await webdav.putFile(client, fileName, body); + } + + const pruned = await pruneCloudBackups(env, config, provider).catch((error) => { + console.error('[backup] 清理旧备份失败:', error && error.message ? error.message : error); + return 0; + }); + + await saveCloudBackupState(env, { + lastRunAt: payload.exportedAt, + lastStatus: 'success', + lastMessage: encrypt ? '备份成功(已加密)' : '备份成功', + lastFile: fileName, + lastSize: body.length, + lastProvider: provider, + lastTrigger: trigger + }); + + return { + provider, + providerLabel: provider === 's3' ? 'S3' : 'WebDAV', + file: fileName, + remotePath: file, + size: body.length, + at: payload.exportedAt, + trigger, + scope, + includeSecrets, + encrypted: encrypt, + pruned + }; + } catch (error) { + await saveCloudBackupState(env, { + lastRunAt: new Date().toISOString(), + lastStatus: 'failed', + lastMessage: error && error.message ? error.message : String(error), + lastProvider: provider, + lastTrigger: trigger + }); + throw error; + } +} + +/** + * 连接测试 + * @param {{ SUBSCRIPTIONS_KV: KVNamespace }} env + * @param {any} [overrides] + */ +export async function testCloudBackupTarget(env, overrides) { + const config = mergeCloudBackupOverrides(await getConfig(env), overrides); + const provider = providerOf(config); + + if (provider === 's3') { + const client = s3.normalizeS3Config(s3ConfigFrom(config)); + const message = await s3.testConnection(client); + return { provider, message }; + } + + const client = webdav.normalizeWebdavConfig(webdavConfigFrom(config)); + const message = await webdav.testConnection(client); + return { provider, message }; +} + +/** + * 从远端备份恢复 + * @param {{ SUBSCRIPTIONS_KV: KVNamespace }} env + * @param {{ file: string, mode?: 'merge'|'replace', includeSecrets?: boolean, password?: string }} options + */ +export async function restoreFromCloudBackup(env, options) { + const file = String(options.file || '').trim(); + if (!file) throw backupError('请选择要恢复的备份文件', 400); + + const config = await getConfig(env); + const provider = providerOf(config); + const items = await listCloudBackups(env); + const target = items.find((item) => item.name === file || item.path === file); + if (!target) throw backupError('远端找不到该备份文件(可能已被清理)', 404); + + let text; + if (provider === 's3') { + const client = s3.normalizeS3Config(s3ConfigFrom(config)); + text = await s3.getObject(client, target.path); + } else { + const client = webdav.normalizeWebdavConfig(webdavConfigFrom(config)); + text = await webdav.getFile(client, target.path); + } + + let backup; + try { + backup = JSON.parse(text); + } catch { + throw backupError('备份文件不是合法 JSON', 400); + } + + let encrypted = false; + if (isEncryptedBackup(backup)) { + encrypted = true; + const password = + String(options.password || '') || + (typeof config.CLOUD_BACKUP_ENCRYPT_PASSWORD === 'string' ? config.CLOUD_BACKUP_ENCRYPT_PASSWORD : ''); + if (!password) throw backupError('该备份已加密,请输入云端备份密码', 400); + const plaintext = await decryptBackupText(backup, password); + try { + backup = JSON.parse(plaintext); + } catch { + throw backupError('解密后的备份内容不是合法 JSON', 400); + } + } + + const stats = await applyBackupPayload(env, backup, { mode: options.mode }); + + return { file: target.name, encrypted, ...stats }; +} + +/** + * 汇总云端备份配置与状态(给前端展示,密钥只返回“是否已配置”) + * @param {{ SUBSCRIPTIONS_KV: KVNamespace }} env + */ +export async function getCloudBackupStatus(env) { + const config = await getConfig(env); + const state = await getCloudBackupState(env); + + return { + enabled: config.BACKUP_ENABLED === true, + provider: providerOf(config), + schedule: config.BACKUP_SCHEDULE || 'off', + hour: Number(config.BACKUP_HOUR) || 0, + weeklyDay: Number(config.BACKUP_WEEKLY_DAY) || 1, + retention: Number(config.BACKUP_RETENTION) || 7, + scope: config.CLOUD_BACKUP_SCOPE === 'data' ? 'data' : 'settings', + includeSecrets: config.CLOUD_BACKUP_SCOPE !== 'data' && config.CLOUD_BACKUP_INCLUDE_SECRETS === true, + encryptPasswordConfigured: + typeof config.CLOUD_BACKUP_ENCRYPT_PASSWORD === 'string' && + config.CLOUD_BACKUP_ENCRYPT_PASSWORD.length > 0, + local: { + scope: config.LOCAL_BACKUP_SCOPE === 'settings' ? 'settings' : 'data', + includeSecrets: config.LOCAL_BACKUP_SCOPE === 'settings' && config.LOCAL_BACKUP_INCLUDE_SECRETS === true, + encryptPasswordConfigured: + typeof config.LOCAL_BACKUP_ENCRYPT_PASSWORD === 'string' && + config.LOCAL_BACKUP_ENCRYPT_PASSWORD.length > 0 + }, + webdav: { + url: config.WEBDAV_URL || '', + username: config.WEBDAV_USERNAME || '', + path: config.WEBDAV_PATH || 'SubsTracker', + passwordConfigured: typeof config.WEBDAV_PASSWORD === 'string' && config.WEBDAV_PASSWORD.length > 0 + }, + s3: { + endpoint: config.S3_ENDPOINT || '', + bucket: config.S3_BUCKET || '', + region: config.S3_REGION || 'auto', + accessKeyId: config.S3_ACCESS_KEY_ID || '', + prefix: config.S3_PREFIX || 'SubsTracker', + forcePathStyle: config.S3_FORCE_PATH_STYLE !== false, + secretConfigured: + typeof config.S3_SECRET_ACCESS_KEY === 'string' && config.S3_SECRET_ACCESS_KEY.length > 0 + }, + lastRun: { + at: state.lastRunAt || null, + status: state.lastStatus || null, + message: state.lastMessage || '', + file: state.lastFile || '', + size: state.lastSize || null, + provider: state.lastProvider || null, + trigger: state.lastTrigger || null + } + }; +} + +/** + * 定时备份入口(由 scheduled handler 每小时调用一次) + * @param {{ SUBSCRIPTIONS_KV: KVNamespace }} env + * @param {Date} [now] + */ +export async function maybeRunScheduledBackup(env, now = new Date()) { + const config = await getConfig(env); + + if (config.BACKUP_ENABLED !== true) return { ran: false, reason: 'disabled' }; + + const schedule = config.BACKUP_SCHEDULE || 'off'; + if (schedule !== 'daily' && schedule !== 'weekly') return { ran: false, reason: 'schedule-off' }; + + const timezone = config.TIMEZONE || 'Asia/Shanghai'; + const { parts, hourString } = getNowInTimezone(timezone, now); + const targetHour = pad2(Math.max(0, Math.min(23, Number(config.BACKUP_HOUR) || 0))); + if (hourString !== targetHour) return { ran: false, reason: 'hour-mismatch' }; + + if (schedule === 'weekly') { + const utcDay = new Date(Date.UTC(parts.year, parts.month - 1, parts.day)).getUTCDay(); + const isoDay = utcDay === 0 ? 7 : utcDay; + const targetDay = Math.max(1, Math.min(7, Number(config.BACKUP_WEEKLY_DAY) || 1)); + if (isoDay !== targetDay) return { ran: false, reason: 'weekday-mismatch' }; + } + + const dateKey = `${parts.year}-${pad2(parts.month)}-${pad2(parts.day)}`; + const state = await getCloudBackupState(env); + if (state.lastScheduleDate === dateKey) return { ran: false, reason: 'already-ran-today' }; + + // 先记日期再执行:避免同一小时被重复触发时重复上传 + await saveCloudBackupState(env, { lastScheduleDate: dateKey, lastScheduleAt: now.toISOString() }); + + try { + const result = await runCloudBackup(env, { trigger: 'schedule', now }); + return { ran: true, ...result }; + } catch (error) { + console.error('[backup] 定时备份失败:', error && error.message ? error.message : error); + return { + ran: false, + reason: 'error', + message: error && error.message ? error.message : String(error) + }; + } +} diff --git a/src/services/backup/crypto.js b/src/services/backup/crypto.js new file mode 100644 index 00000000..1373d6a0 --- /dev/null +++ b/src/services/backup/crypto.js @@ -0,0 +1,160 @@ +// @ts-check +/** + * 备份文件加密(AES-256-GCM + PBKDF2-SHA256) + * + * 设计要点: + * - 只对备份 JSON 加密,不改文件名,云端列表/保留份数逻辑不受影响 + * - 口令不落盘、不导出;加盐 + 随机 IV,每次加密结果都不同 + * - GCM 自带完整性校验:密码错误或文件被改都会解密失败 + * - 实现方式参考 NodeWarden 的 backup-settings-crypto(WebCrypto AES-GCM 信封) + */ + +export const ENCRYPTED_BACKUP_FORMAT = 'substracker-backup-encrypted'; +export const ENCRYPTED_BACKUP_VERSION = 1; +export const DEFAULT_PBKDF2_ITERATIONS = 100000; +const PBKDF2_MIN_ITERATIONS = 10000; +const PBKDF2_MAX_ITERATIONS = 1000000; +const SALT_BYTES = 16; +const IV_BYTES = 12; +const KEY_BITS = 256; + +/** + * @param {string} message + * @param {number} [status] + */ +function cryptoError(message, status = 400) { + const error = new Error(message); + // @ts-ignore + error.status = status; + return error; +} + +/** @param {Uint8Array} bytes */ +function bytesToBase64(bytes) { + let binary = ''; + for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]); + return btoa(binary); +} + +/** @param {string} value */ +function base64ToBytes(value) { + const normalized = String(value || '').trim(); + if (!normalized) return new Uint8Array(0); + let binary; + try { + binary = atob(normalized); + } catch { + throw cryptoError('加密备份内容损坏:base64 解析失败', 400); + } + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); + return bytes; +} + +/** + * @param {string} password + * @param {Uint8Array} salt + * @param {number} iterations + */ +async function deriveKey(password, salt, iterations) { + const material = await crypto.subtle.importKey( + 'raw', + new TextEncoder().encode(password), + 'PBKDF2', + false, + ['deriveKey'] + ); + return crypto.subtle.deriveKey( + { name: 'PBKDF2', hash: 'SHA-256', salt, iterations }, + material, + { name: 'AES-GCM', length: KEY_BITS }, + false, + ['encrypt', 'decrypt'] + ); +} + +/** @param {any} value */ +function normalizeIterations(value) { + const parsed = Number(value); + if (!Number.isFinite(parsed)) return DEFAULT_PBKDF2_ITERATIONS; + return Math.max(PBKDF2_MIN_ITERATIONS, Math.min(PBKDF2_MAX_ITERATIONS, Math.floor(parsed))); +} + +/** + * 加密一段 JSON 文本,返回可直接上传的信封 JSON 字符串 + * @param {string} plaintext + * @param {string} password + * @param {{ iterations?: number }} [options] + */ +export async function encryptBackupText(plaintext, password, options = {}) { + const secret = String(password || ''); + if (!secret) throw cryptoError('请先配置备份加密密码', 400); + + const iterations = normalizeIterations(options.iterations); + const salt = crypto.getRandomValues(new Uint8Array(SALT_BYTES)); + const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES)); + const key = await deriveKey(secret, salt, iterations); + + let ciphertext; + try { + ciphertext = new Uint8Array( + await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, new TextEncoder().encode(plaintext)) + ); + } catch { + throw cryptoError('备份加密失败', 500); + } + + return JSON.stringify({ + format: ENCRYPTED_BACKUP_FORMAT, + version: ENCRYPTED_BACKUP_VERSION, + cipher: 'AES-256-GCM', + kdf: { + name: 'PBKDF2-SHA256', + iterations, + salt: bytesToBase64(salt) + }, + iv: bytesToBase64(iv), + data: bytesToBase64(ciphertext) + }); +} + +/** + * @param {any} value + * @returns {boolean} + */ +export function isEncryptedBackup(value) { + return !!value && typeof value === 'object' && value.format === ENCRYPTED_BACKUP_FORMAT; +} + +/** + * 解密信封,返回原始 JSON 文本 + * @param {any} envelope + * @param {string} password + */ +export async function decryptBackupText(envelope, password) { + if (!isEncryptedBackup(envelope)) { + throw cryptoError('不是加密备份文件', 400); + } + if (Number(envelope.version) > ENCRYPTED_BACKUP_VERSION) { + throw cryptoError(`加密备份版本过高 (${envelope.version}),请升级应用后再恢复`, 400); + } + + const secret = String(password || ''); + if (!secret) throw cryptoError('该备份已加密,请先填写备份密码', 400); + + const kdf = envelope.kdf || {}; + const salt = base64ToBytes(kdf.salt); + const iv = base64ToBytes(envelope.iv); + const data = base64ToBytes(envelope.data); + if (!salt.length || iv.length !== IV_BYTES || !data.length) { + throw cryptoError('加密备份内容不完整', 400); + } + + const key = await deriveKey(secret, salt, normalizeIterations(kdf.iterations)); + try { + const plaintext = await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, key, data); + return new TextDecoder().decode(plaintext); + } catch { + throw cryptoError('解密失败:备份密码不对,或文件已损坏', 400); + } +} diff --git a/src/services/backup/payload.js b/src/services/backup/payload.js new file mode 100644 index 00000000..0658f9ae --- /dev/null +++ b/src/services/backup/payload.js @@ -0,0 +1,337 @@ +// @ts-check +/** + * 备份载荷的构建与落库(与 HTTP 层解耦) + * + * 供两条路径复用: + * - GET /api/backup(本地下载) + * - 云端备份(WebDAV / S3)上传 + * + * 设计约束: + * - 默认导出不含密钥/密码,避免备份文件泄露 + * - JWT_SECRET 永不导出、导入时也不覆盖(避免会话被意外作废) + * - 订阅 + reminder_rules 一并导出,保证多规则提醒可无损迁移 + */ +import { getConfig, setConfig } from '../../data/config.js'; +import * as subRepo from '../../data/subscriptions.repo.js'; +import * as remindersRepo from '../../data/reminders.repo.js'; +import { getCategories } from '../../data/categories.js'; +import { putKVJson } from '../../data/kv.js'; +import { SECRET_FIELDS } from '../../data/secret-fields.js'; +import { VERSION } from '../../core/version.js'; + +export const BACKUP_FORMAT = 'substracker-backup'; +export const BACKUP_VERSION = 1; + +export const BACKUP_SCOPES = ['data', 'settings']; + +/** 永不导出/覆盖的字段 */ +export const NEVER_EXPORT_FIELDS = ['JWT_SECRET', 'ADMIN_PASSWORD']; + +/** + * 「设置」范围不参与备份的配置:云存储凭证、备份计划与备份自身配置。 + * 避免恢复别的实例的备份时把当前备份通道/计划改掉。 + */ +export const SETTINGS_EXCLUDED_FIELDS = [ + 'WEBDAV_URL', + 'WEBDAV_USERNAME', + 'WEBDAV_PASSWORD', + 'WEBDAV_PATH', + 'S3_ENDPOINT', + 'S3_REGION', + 'S3_BUCKET', + 'S3_ACCESS_KEY_ID', + 'S3_SECRET_ACCESS_KEY', + 'S3_PREFIX', + 'S3_FORCE_PATH_STYLE', + 'BACKUP_ENABLED', + 'BACKUP_PROVIDER', + 'BACKUP_SCHEDULE', + 'BACKUP_HOUR', + 'BACKUP_WEEKLY_DAY', + 'BACKUP_RETENTION', + 'CLOUD_BACKUP_SCOPE', + 'CLOUD_BACKUP_INCLUDE_SECRETS', + 'CLOUD_BACKUP_ENCRYPT_PASSWORD', + 'LOCAL_BACKUP_SCOPE', + 'LOCAL_BACKUP_INCLUDE_SECRETS', + 'LOCAL_BACKUP_ENCRYPT_PASSWORD' +]; + +/** + * @param {unknown} value + * @returns {'data'|'settings'} + */ +export function normalizeScope(value) { + return value === 'data' ? 'data' : 'settings'; +} + +/** + * 构造可导出的配置副本 + * + * @param {any} config + * @param {'data'|'settings'} scope + * @param {boolean} includeSecrets + */ +export function buildExportConfig(config, scope, includeSecrets) { + if (normalizeScope(scope) === 'data') return undefined; + + /** @type {Record} */ + const out = {}; + for (const [key, value] of Object.entries(config || {})) { + if (key === 'JWT_SECRET' || SETTINGS_EXCLUDED_FIELDS.includes(key)) continue; + out[key] = value; + } + + if (!includeSecrets) { + delete out.ADMIN_PASSWORD; + for (const key of SECRET_FIELDS) { + if (key in out) out[key] = ''; + } + } + + return out; +} + +/** + * 构建完整备份对象 + * + * @param {{ SUBSCRIPTIONS_KV: KVNamespace }} env + * @param {{ scope?: 'data'|'settings', includeSecrets?: boolean, now?: Date }} [options] + */ +export async function buildBackupPayload(env, options = {}) { + const scope = normalizeScope(options.scope); + const includeSecrets = scope === 'settings' && options.includeSecrets === true; + const exportedAt = (options.now instanceof Date ? options.now : new Date()).toISOString(); + + const config = await getConfig(env); + const categories = await getCategories(env); + const subscriptions = await subRepo.listAll(env); + + /** @type {Record} */ + const reminderRules = {}; + for (const sub of subscriptions) { + if (!sub || !sub.id) continue; + let rules = await remindersRepo.listForSubscription(env, sub.id); + if (rules.length === 0) { + rules = [remindersRepo.legacyFieldToRule(sub)]; + } + reminderRules[sub.id] = rules; + } + + // 导出体不附带运行时附加字段 + const cleanSubs = subscriptions.map((sub) => { + const { reminderRules: _rr, reminderRulesSummary: _rs, ...rest } = sub || {}; + return rest; + }); + + /** @type {Record} */ + const payload = { + format: BACKUP_FORMAT, + version: BACKUP_VERSION, + appVersion: VERSION, + exportedAt, + scope, + includeSecrets, + categories, + subscriptions: cleanSubs, + reminderRules + }; + + if (scope === 'settings') { + payload.config = buildExportConfig(config, scope, includeSecrets); + } + + return payload; +} + +/** + * @param {any} sub + * @param {number} index + * @returns {string|null} 错误信息 + */ +function validateSubscriptionEntry(sub, index) { + if (!sub || typeof sub !== 'object') { + return `subscriptions[${index}] 不是对象`; + } + if (typeof sub.id !== 'string' || !sub.id.trim()) { + return `subscriptions[${index}] 缺少有效 id`; + } + if (typeof sub.name !== 'string' || !sub.name.trim()) { + return `subscriptions[${index}] 缺少 name`; + } + if (!sub.expiryDate || Number.isNaN(new Date(sub.expiryDate).getTime())) { + return `subscriptions[${index}] 缺少有效 expiryDate`; + } + return null; +} + +/** + * 校验备份结构 + * @param {any} raw + * @returns {{ ok: true, backup: any } | { ok: false, message: string }} + */ +export function validateBackup(raw) { + if (!raw || typeof raw !== 'object') { + return { ok: false, message: '备份内容不是有效 JSON 对象' }; + } + if (raw.format && raw.format !== BACKUP_FORMAT) { + return { ok: false, message: `不支持的备份格式: ${raw.format}` }; + } + if (raw.version != null && Number(raw.version) > BACKUP_VERSION) { + return { ok: false, message: `备份版本过高 (${raw.version}),请升级应用后再导入` }; + } + if (!Array.isArray(raw.subscriptions)) { + return { ok: false, message: '备份缺少 subscriptions 数组' }; + } + for (let i = 0; i < raw.subscriptions.length; i++) { + const err = validateSubscriptionEntry(raw.subscriptions[i], i); + if (err) return { ok: false, message: err }; + } + if (raw.reminderRules != null && typeof raw.reminderRules !== 'object') { + return { ok: false, message: 'reminderRules 必须是对象' }; + } + return { ok: true, backup: raw }; +} + +/** + * 合并配置:默认不覆盖密钥空值;includeSecrets 时才写入非空密钥 + * + * @param {any} current + * @param {any} incoming + * @param {boolean} includeSecrets + */ +function mergeConfig(current, incoming, includeSecrets) { + if (!incoming || typeof incoming !== 'object') return current; + + /** @type {Record} */ + const next = { ...current }; + + for (const [key, value] of Object.entries(incoming)) { + if (NEVER_EXPORT_FIELDS.includes(key) || key === 'JWT_SECRET') continue; + if (SETTINGS_EXCLUDED_FIELDS.includes(key)) continue; + + if (SECRET_FIELDS.includes(key) || key === 'ADMIN_PASSWORD') { + if (!includeSecrets) continue; + if (typeof value === 'string' && value.trim() !== '') { + next[key] = value; + } + continue; + } + + if (value !== undefined) { + next[key] = value; + } + } + + // 始终保留现有 JWT + next.JWT_SECRET = current.JWT_SECRET; + return next; +} + +/** + * 备份恢复失败时抛出的可读错误 + * @param {string} message + * @param {number} [status] + */ +function backupError(message, status = 400) { + const error = new Error(message); + // @ts-ignore + error.status = status; + return error; +} + +/** + * 把备份内容写回 KV(订阅 / 提醒规则 / 分类 / 配置) + * + * @param {{ SUBSCRIPTIONS_KV: KVNamespace }} env + * @param {any} rawBackup + * @param {{ mode?: 'merge'|'replace' }} [options] + */ +export async function applyBackupPayload(env, rawBackup, options = {}) { + const mode = options.mode === 'replace' ? 'replace' : 'merge'; + + const validated = validateBackup(rawBackup); + if (!validated.ok) { + throw backupError(/** @type {any} */ (validated).message, 400); + } + const backup = /** @type {any} */ (validated).backup; + + // 范围与是否含密钥以备份文件自身记录为准,避免请求侧越权覆盖 + const scope = backup.scope === 'data' ? 'data' : 'settings'; + const includeSecrets = scope === 'settings' && backup.includeSecrets === true; + + // 先写订阅/规则,再写配置:避免配置已改但数据半残 + const incomingSubs = backup.subscriptions.filter((s) => s && typeof s.id === 'string' && s.id); + if (mode === 'replace' && incomingSubs.length === 0) { + throw backupError('覆盖模式拒绝空订阅列表(请确认备份完整或改用合并模式)', 400); + } + + const rulesMap = + backup.reminderRules && typeof backup.reminderRules === 'object' ? backup.reminderRules : {}; + + let importedSubs = 0; + let importedRules = 0; + + if (mode === 'replace') { + const existing = await subRepo.listAll(env); + for (const sub of existing) { + if (sub && sub.id) { + await remindersRepo.clearForSubscription(env, sub.id); + } + } + await subRepo.replaceAll(env, incomingSubs); + importedSubs = incomingSubs.length; + } else { + for (const sub of incomingSubs) { + await subRepo.save(env, sub); + importedSubs++; + } + } + + for (const sub of incomingSubs) { + let rules = Array.isArray(rulesMap[sub.id]) ? rulesMap[sub.id] : null; + if (!rules && Array.isArray(sub.reminderRules)) rules = sub.reminderRules; + if (rules && rules.length > 0) { + const normalized = rules.map((r) => remindersRepo.normalizeRule(r)); + await remindersRepo.replaceForSubscription(env, sub.id, normalized); + importedRules += normalized.length; + try { + const { syncLegacyReminderFields } = await import('../../data/subscriptions.js'); + await syncLegacyReminderFields(env, sub.id, normalized); + } catch { + /* ignore */ + } + } + } + + // 分类 + if (Array.isArray(backup.categories)) { + const cats = backup.categories + .filter((c) => typeof c === 'string' && c.trim()) + .map((c) => c.trim()); + if (mode === 'replace') { + await putKVJson(env, 'categories', [...new Set(cats)].sort()); + } else { + const existing = await getCategories(env); + const set = new Set([...existing, ...cats]); + await putKVJson(env, 'categories', [...set].sort()); + } + } + + // 配置放最后;「数据」范围不写设置 + if (scope === 'settings' && backup.config && typeof backup.config === 'object') { + const currentConfig = await getConfig(env); + const merged = mergeConfig(currentConfig, backup.config, includeSecrets); + await setConfig(env, merged); + } + + return { + mode, + subscriptions: importedSubs, + reminderRules: importedRules, + categories: Array.isArray(backup.categories) ? backup.categories.length : 0, + configRestored: scope === 'settings' && !!backup.config, + secretsApplied: includeSecrets, + scope + }; +} diff --git a/src/services/backup/s3.js b/src/services/backup/s3.js new file mode 100644 index 00000000..9bcd19d0 --- /dev/null +++ b/src/services/backup/s3.js @@ -0,0 +1,349 @@ +// @ts-check +/** + * S3 兼容对象存储客户端(AWS SigV4) + * + * 使用 WebCrypto 完成签名,可直接运行在 Cloudflare Workers 上。 + * 兼容:AWS S3 / Cloudflare R2 / MinIO / 阿里云 OSS(S3 兼容)等。 + * SigV4 实现参考 NodeWarden 的 backup-uploader。 + */ + +/** + * @param {string} message + * @param {number} [status] + */ +function s3Error(message, status = 500) { + const error = new Error(message); + // @ts-ignore + error.status = status; + return error; +} + +/** + * 校验并规范化 S3 配置 + * @param {{ endpoint?: string, bucket?: string, region?: string, accessKeyId?: string, secretAccessKey?: string, prefix?: string, forcePathStyle?: boolean }} raw + */ +export function normalizeS3Config(raw = {}) { + const endpoint = String(raw.endpoint || '').trim().replace(/\/+$/g, ''); + if (!endpoint) throw s3Error('请填写 S3 Endpoint', 400); + + let parsed; + try { + parsed = new URL(endpoint); + } catch { + throw s3Error('S3 Endpoint 不是合法 URL', 400); + } + if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') { + throw s3Error('S3 Endpoint 必须以 http:// 或 https:// 开头', 400); + } + + const bucket = String(raw.bucket || '').trim(); + if (!bucket) throw s3Error('请填写 S3 桶名称', 400); + if (bucket.includes('/') || bucket.includes('\\')) { + throw s3Error('桶名称不能包含 / 或 \\,子目录请填到「对象前缀」', 400); + } + + const accessKeyId = String(raw.accessKeyId || '').trim(); + if (!accessKeyId) throw s3Error('请填写 S3 Access Key ID', 400); + + const secretAccessKey = String(raw.secretAccessKey || ''); + if (!secretAccessKey) throw s3Error('请填写 S3 Secret Access Key', 400); + + const prefix = String(raw.prefix || 'SubsTracker') + .trim() + .replace(/^\/+|\/+$/g, ''); + if (prefix.split('/').some((part) => part === '..')) { + throw s3Error('S3 路径前缀不能包含 ..', 400); + } + + return { + endpoint: parsed.toString().replace(/\/+$/g, ''), + bucket, + region: String(raw.region || 'auto').trim() || 'auto', + accessKeyId, + secretAccessKey, + prefix, + forcePathStyle: raw.forcePathStyle !== false + }; +} + +function encodeRfc3986(value) { + return encodeURIComponent(value).replace(/[!'()*]/g, (char) => + `%${char.charCodeAt(0).toString(16).toUpperCase()}` + ); +} + +function encodeKeyPath(key) { + return String(key || '') + .split('/') + .filter(Boolean) + .map(encodeRfc3986) + .join('/'); +} + +async function sha256Hex(value) { + const bytes = typeof value === 'string' ? new TextEncoder().encode(value) : value; + const digest = await crypto.subtle.digest('SHA-256', bytes); + return Array.from(new Uint8Array(digest)) + .map((byte) => byte.toString(16).padStart(2, '0')) + .join(''); +} + +async function hmacSha256Raw(keyBytes, message) { + const key = await crypto.subtle.importKey( + 'raw', + keyBytes, + { name: 'HMAC', hash: 'SHA-256' }, + false, + ['sign'] + ); + const signature = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(message)); + return new Uint8Array(signature); +} + +function canonicalQueryString(searchParams) { + return Array.from(searchParams.entries()) + .sort(([aKey, aValue], [bKey, bValue]) => (aKey === bKey ? (aValue < bValue ? -1 : 1) : aKey < bKey ? -1 : 1)) + .map(([key, value]) => `${encodeRfc3986(key)}=${encodeRfc3986(value)}`) + .join('&'); +} + +/** + * @param {string} method + * @param {URL} url + * @param {Record} headers 参与签名的小写头 + * @param {string} payloadHashHex + * @param {ReturnType} config + */ +async function buildAuthorization(method, url, headers, payloadHashHex, config) { + const amzDate = headers['x-amz-date']; + const shortDate = amzDate.slice(0, 8); + + const headerEntries = Object.entries(headers) + .map(([name, value]) => [name.toLowerCase(), value] ) + .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)); + const canonicalHeaders = headerEntries + .map(([name, value]) => `${name}:${String(value).trim().replace(/\s+/g, ' ')}`) + .join('\n'); + const signedHeaders = headerEntries.map(([name]) => name).join(';'); + + const canonicalRequest = [ + method.toUpperCase(), + url.pathname || '/', + canonicalQueryString(url.searchParams), + `${canonicalHeaders}\n`, + signedHeaders, + payloadHashHex + ].join('\n'); + + const credentialScope = `${shortDate}/${config.region}/s3/aws4_request`; + const stringToSign = [ + 'AWS4-HMAC-SHA256', + amzDate, + credentialScope, + await sha256Hex(canonicalRequest) + ].join('\n'); + + const kDate = await hmacSha256Raw(new TextEncoder().encode(`AWS4${config.secretAccessKey}`), shortDate); + const kRegion = await hmacSha256Raw(kDate, config.region); + const kService = await hmacSha256Raw(kRegion, 's3'); + const kSigning = await hmacSha256Raw(kService, 'aws4_request'); + const signatureBytes = await hmacSha256Raw(kSigning, stringToSign); + const signature = Array.from(signatureBytes) + .map((byte) => byte.toString(16).padStart(2, '0')) + .join(''); + + return `AWS4-HMAC-SHA256 Credential=${config.accessKeyId}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signature}`; +} + +/** @param {ReturnType} config */ +function bucketBaseUrl(config) { + if (!config.forcePathStyle) { + const url = new URL(config.endpoint); + if (!url.hostname.startsWith(`${config.bucket}.`)) { + url.hostname = `${config.bucket}.${url.hostname}`; + } + return url; + } + return new URL(`${config.endpoint}/${encodeRfc3986(config.bucket)}`); +} + +/** @param {ReturnType} config */ +function objectKey(config, fileName) { + return config.prefix ? `${config.prefix}/${fileName}` : fileName; +} + +/** @param {ReturnType} config */ +function objectUrl(config, key) { + return new URL(`${bucketBaseUrl(config).toString().replace(/\/+$/g, '')}/${encodeKeyPath(key)}`); +} + +/** + * 发送一个已签名请求 + * @param {ReturnType} config + * @param {'GET'|'PUT'|'DELETE'|'HEAD'} method + * @param {URL} url + * @param {string} [body] + * @param {string} [contentType] + */ +async function signedRequest(config, method, url, body, contentType) { + const payload = body == null ? '' : body; + const payloadHashHex = await sha256Hex(payload); + const amzDate = new Date().toISOString().replace(/[-:]|\.\d{3}/g, ''); + + /** @type {Record} */ + const signedHeaders = { + host: url.host, + 'x-amz-content-sha256': payloadHashHex, + 'x-amz-date': amzDate + }; + if (method === 'PUT') signedHeaders['content-type'] = contentType || 'application/octet-stream'; + + const authorization = await buildAuthorization(method, url, signedHeaders, payloadHashHex, config); + + /** @type {HeadersInit} */ + const headers = { + Authorization: authorization, + 'x-amz-content-sha256': payloadHashHex, + 'x-amz-date': amzDate + }; + if (method === 'PUT') headers['Content-Type'] = signedHeaders['content-type']; + + /** @type {RequestInit} */ + const options = { method, headers }; + if (method === 'PUT') options.body = payload; + try { + if (typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function') { + options.signal = AbortSignal.timeout(30000); + } + } catch { + /* ignore */ + } + + return fetch(url.toString(), options); +} + +/** + * 上传对象 + * @param {ReturnType} config + * @param {string} fileName + * @param {string} body + */ +export async function putObject(config, fileName, body, contentType = 'application/json; charset=utf-8') { + if (!fileName || fileName.includes('/') || fileName.includes('\\')) { + throw s3Error('非法的备份文件名', 400); + } + const key = objectKey(config, fileName); + const response = await signedRequest(config, 'PUT', objectUrl(config, key), body, contentType); + if (![200, 201, 204].includes(response.status)) { + throw await describeFailure('S3 上传失败', response); + } + return key; +} + +function decodeXml(value) { + return String(value || '') + .replace(/&/gi, '&') + .replace(/</gi, '<') + .replace(/>/gi, '>') + .replace(/"/gi, '"') + .replace(/'/g, "'"); +} + +/** + * 把 S3 错误响应体里的 Code / Message 抽出来,便于定位 403 是权限还是签名 + * @param {string} action + * @param {Response} response + */ +async function describeFailure(action, response) { + let detail = ''; + try { + const text = await response.text(); + const code = text.match(/<(?:[^\s:>]+:)?Code\b[^>]*>([\s\S]*?)<\/(?:[^\s:>]+:)?Code>/i); + const message = text.match(/<(?:[^\s:>]+:)?Message\b[^>]*>([\s\S]*?)<\/(?:[^\s:>]+:)?Message>/i); + if (code) { + detail = decodeXml(code[1].trim()) + (message ? `: ${decodeXml(message[1].trim())}` : ''); + } else if (text) { + detail = text.replace(/<[^>]*>/g, ' ').trim().slice(0, 120); + } + } catch { + /* 响应体读不出来就只报状态码 */ + } + return s3Error(`${action}: HTTP ${response.status}${detail ? `(${detail})` : ''}`, 502); +} + +/** + * 列出前缀下的对象 + * @param {ReturnType} config + */ +export async function listObjects(config) { + const items = []; + let continuationToken = ''; + + do { + const url = bucketBaseUrl(config); + url.searchParams.set('list-type', '2'); + if (config.prefix) url.searchParams.set('prefix', `${config.prefix}/`); + url.searchParams.set('max-keys', '1000'); + if (continuationToken) url.searchParams.set('continuation-token', continuationToken); + + const response = await signedRequest(config, 'GET', url); + if (!response.ok) { + throw await describeFailure('列出 S3 备份失败', response); + } + + const xml = await response.text(); + const contents = xml.match(/<(?:[^\s:>]+:)?Contents\b[^>]*>[\s\S]*?<\/(?:[^\s:>]+:)?Contents>/gi) || []; + for (const block of contents) { + const keyMatch = block.match(/<(?:[^\s:>]+:)?Key\b[^>]*>([\s\S]*?)<\/(?:[^\s:>]+:)?Key>/i); + if (!keyMatch) continue; + const key = decodeXml(keyMatch[1]); + const sizeMatch = block.match(/<(?:[^\s:>]+:)?Size\b[^>]*>([\s\S]*?)<\/(?:[^\s:>]+:)?Size>/i); + const modifiedMatch = block.match(/<(?:[^\s:>]+:)?LastModified\b[^>]*>([\s\S]*?)<\/(?:[^\s:>]+:)?LastModified>/i); + items.push({ + key, + name: key.split('/').filter(Boolean).pop() || key, + size: sizeMatch ? Number(sizeMatch[1]) : null, + modifiedAt: modifiedMatch ? decodeXml(modifiedMatch[1]) : null + }); + } + + const tokenMatch = xml.match(/<(?:[^\s:>]+:)?NextContinuationToken\b[^>]*>([\s\S]*?)<\/(?:[^\s:>]+:)?NextContinuationToken>/i); + continuationToken = tokenMatch ? decodeXml(tokenMatch[1]) : ''; + } while (continuationToken); + + return items; +} + +/** + * 下载对象 + * @param {ReturnType} config + * @param {string} key + */ +export async function getObject(config, key) { + const response = await signedRequest(config, 'GET', objectUrl(config, key)); + if (!response.ok) { + throw await describeFailure('读取 S3 备份失败', response); + } + return response.text(); +} + +/** + * 删除对象 + * @param {ReturnType} config + * @param {string} key + */ +export async function deleteObject(config, key) { + const response = await signedRequest(config, 'DELETE', objectUrl(config, key)); + if (![200, 204, 404].includes(response.status)) { + throw await describeFailure('删除 S3 备份失败', response); + } +} + +/** + * 连通性测试:列一次对象 + * @param {ReturnType} config + */ +export async function testConnection(config) { + await listObjects(config); + return 'S3 连接成功'; +} diff --git a/src/services/backup/webdav.js b/src/services/backup/webdav.js new file mode 100644 index 00000000..5ee5b42c --- /dev/null +++ b/src/services/backup/webdav.js @@ -0,0 +1,271 @@ +// @ts-check +/** + * WebDAV 客户端(Cloudflare Workers 环境) + * + * 只做备份需要的最小集合:建目录 / 上传 / 列表 / 下载 / 删除 / 连通性测试。 + * 实现参考 MiSub 的 webdav-backup-handler:Basic Auth + MKCOL + PROPFIND。 + */ + +const PROPFIND_BODY = ` + + + + + + +`; + +/** + * @param {string} message + * @param {number} [status] + */ +function webdavError(message, status = 500) { + const error = new Error(message); + // @ts-ignore + error.status = status; + return error; +} + +/** UTF-8 → Base64(Workers 里 btoa 只接受 latin1) */ +function base64Utf8(value) { + const bytes = new TextEncoder().encode(value); + let binary = ''; + for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]); + return btoa(binary); +} + +function buildAuthHeader(username, password) { + return `Basic ${base64Utf8(`${username || ''}:${password || ''}`)}`; +} + +/** + * 校验并规范化 WebDAV 配置 + * @param {{ url?: string, username?: string, password?: string, remotePath?: string }} raw + */ +export function normalizeWebdavConfig(raw = {}) { + const url = String(raw.url || '').trim(); + if (!url) throw webdavError('请填写 WebDAV 服务器地址', 400); + + let parsed; + try { + parsed = new URL(url); + } catch { + throw webdavError('WebDAV 地址不是合法 URL', 400); + } + if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') { + throw webdavError('WebDAV 地址必须以 http:// 或 https:// 开头', 400); + } + + const username = String(raw.username || '').trim(); + if (!username) throw webdavError('请填写 WebDAV 用户名', 400); + const password = String(raw.password || ''); + if (!password) throw webdavError('请填写 WebDAV 密码', 400); + + const remotePath = String(raw.remotePath || 'SubsTracker') + .trim() + .replace(/\\/g, '/') + .replace(/^\/+|\/+$/g, ''); + if (remotePath.split('/').some((part) => part === '..')) { + throw webdavError('WebDAV 远程目录不能包含 ..', 400); + } + + return { + baseUrl: parsed.toString().replace(/\/+$/g, ''), + username, + password, + remotePath + }; +} + +/** @param {ReturnType} config */ +function authHeaderOf(config) { + return buildAuthHeader(config.username, config.password); +} + +/** + * 拼接远端 URL(逐段编码,保留 baseUrl 自带的路径) + * @param {string} baseUrl + * @param {string} relativePath + */ +function buildUrl(baseUrl, relativePath) { + const segments = String(relativePath || '') + .split('/') + .filter(Boolean) + .map((part) => encodeURIComponent(part)); + return segments.length ? `${baseUrl}/${segments.join('/')}` : baseUrl; +} + +function fetchOptions(config, init = {}) { + const headers = new Headers(init.headers || {}); + headers.set('Authorization', authHeaderOf(config)); + /** @type {RequestInit} */ + const options = { ...init, headers }; + try { + if (typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function') { + options.signal = AbortSignal.timeout(20000); + } + } catch { + /* ignore */ + } + return options; +} + +/** + * 逐级创建远程目录(405 = 已存在) + * @param {ReturnType} config + */ +export async function ensureDirectory(config) { + const segments = config.remotePath.split('/').filter(Boolean); + let current = ''; + for (const segment of segments) { + current = current ? `${current}/${segment}` : segment; + const response = await fetch(buildUrl(config.baseUrl, current), fetchOptions(config, { method: 'MKCOL' })); + if (![200, 201, 204, 405].includes(response.status)) { + throw webdavError(`创建 WebDAV 目录失败: HTTP ${response.status}`, 502); + } + } +} + +/** + * 上传一个文件(自动建目录) + * @param {ReturnType} config + * @param {string} fileName + * @param {string} body + * @param {string} [contentType] + */ +export async function putFile(config, fileName, body, contentType = 'application/json; charset=utf-8') { + if (!fileName || fileName.includes('/') || fileName.includes('\\')) { + throw webdavError('非法的备份文件名', 400); + } + await ensureDirectory(config); + + const response = await fetch( + buildUrl(config.baseUrl, config.remotePath ? `${config.remotePath}/${fileName}` : fileName), + fetchOptions(config, { + method: 'PUT', + headers: { 'Content-Type': contentType }, + body + }) + ); + + if (![200, 201, 204].includes(response.status)) { + throw webdavError(`WebDAV 上传失败: HTTP ${response.status}`, 502); + } + + return buildUrl(config.baseUrl, config.remotePath ? `${config.remotePath}/${fileName}` : fileName); +} + +function decodeXml(value) { + return String(value || '') + .replace(/&/gi, '&') + .replace(/</gi, '<') + .replace(/>/gi, '>') + .replace(/"/gi, '"') + .replace(/'/g, "'"); +} + +/** + * 解析 PROPFIND 响应里的文件条目 + * @param {string} xml + * @param {string} baseUrl + */ +function parseEntries(xml, baseUrl) { + const endpoint = new URL(baseUrl); + const endpointPath = endpoint.pathname.replace(/\/+$/, ''); + const items = []; + + const responseBlocks = xml.match(/<(?:[^\s:>]+:)?response\b[^>]*>[\s\S]*?<\/(?:[^\s:>]+:)?response>/gi) || []; + for (const block of responseBlocks) { + const hrefMatch = block.match(/<(?:[^\s:>]+:)?href\b[^>]*>([\s\S]*?)<\/(?:[^\s:>]+:)?href>/i); + if (!hrefMatch) continue; + const href = decodeXml(hrefMatch[1].trim()); + + let target; + try { + target = new URL(href, `${endpoint.origin}/`); + } catch { + continue; + } + // 不允许把其它站点的地址当成可凭据访问的对象 + if (target.origin !== endpoint.origin) continue; + if (href.endsWith('/')) continue; + + const isInBase = endpointPath + ? target.pathname === endpointPath || target.pathname.startsWith(`${endpointPath}/`) + : true; + if (!isInBase) continue; + + const name = decodeURIComponent(target.pathname.split('/').filter(Boolean).pop() || ''); + const sizeMatch = block.match(/<(?:[^\s:>]+:)?getcontentlength\b[^>]*>([\s\S]*?)<\/(?:[^\s:>]+:)?getcontentlength>/i); + const modifiedMatch = block.match(/<(?:[^\s:>]+:)?getlastmodified\b[^>]*>([\s\S]*?)<\/(?:[^\s:>]+:)?getlastmodified>/i); + const resourceTypeMatch = block.match(/<(?:[^\s:>]+:)?resourcetype\b[^>]*>([\s\S]*?)<\/(?:[^\s:]+:)?resourcetype>/i); + + items.push({ + name, + url: `${target.origin}${target.pathname}`, + isDirectory: !!(resourceTypeMatch && /collection/i.test(resourceTypeMatch[1])), + size: sizeMatch ? Number(sizeMatch[1]) : null, + modifiedAt: modifiedMatch ? decodeXml(modifiedMatch[1].trim()) : null + }); + } + + return items; +} + +/** + * 列出远程目录下的文件 + * @param {ReturnType} config + */ +export async function listFiles(config) { + const path = config.remotePath || '/'; + const response = await fetch( + buildUrl(config.baseUrl, path), + fetchOptions(config, { + method: 'PROPFIND', + headers: { Depth: '1', 'Content-Type': 'application/xml; charset=utf-8' }, + body: PROPFIND_BODY + }) + ); + + if (!response.ok) { + throw webdavError(`列出 WebDAV 备份失败: HTTP ${response.status}`, 502); + } + + const xml = await response.text(); + return parseEntries(xml, config.baseUrl).filter((item) => !item.isDirectory); +} + +/** + * 下载一个远端文件 + * @param {ReturnType} config + * @param {string} url + */ +export async function getFile(config, url) { + const response = await fetch(url, fetchOptions(config, { method: 'GET' })); + if (!response.ok) { + throw webdavError(`读取 WebDAV 备份失败: HTTP ${response.status}`, 502); + } + return response.text(); +} + +/** + * 删除远端文件 + * @param {ReturnType} config + * @param {string} url + */ +export async function deleteFile(config, url) { + const response = await fetch(url, fetchOptions(config, { method: 'DELETE' })); + if (![200, 202, 204, 404].includes(response.status)) { + throw webdavError(`删除 WebDAV 备份失败: HTTP ${response.status}`, 502); + } +} + +/** + * 连通性测试:建目录 + 列目录 + * @param {ReturnType} config + */ +export async function testConnection(config) { + await ensureDirectory(config); + await listFiles(config); + return 'WebDAV 连接成功'; +} diff --git a/src/views/configPage.html b/src/views/configPage.html index 783ae93c..c28e6450 100644 --- a/src/views/configPage.html +++ b/src/views/configPage.html @@ -718,59 +718,338 @@

WPUSH 配置

-
- -
- + +
+
+

+ 数据备份与恢复 +

+
+ 尚未执行 + +
+
+

+ 两个目的地各管各的:云端负责定时上传与保留份数,本地负责临时导出。备份范围、加密、是否含密钥都跟着目的地走,恢复时按文件里记录的范围写回。改动需点「保存配置」落库;立即备份可直接用当前填入值试跑。 +

+ + +
+
+ 01 +

云端备份

+
+

WebDAV / S3 自动上传。范围、目标、自动备份、保留份数都在这张卡里,不再和本地导出共用。

- -
-

- 数据备份与恢复 -

-

- 导出系统配置、订阅列表与提醒规则,便于换账号部署或升级迁移。 - 默认导出不含 Bot Token / API Key 等密钥;需要时可勾选「包含敏感配置」。 -

- -
-
-

导出备份

- -

勾选后请妥善保管 JSON 文件,勿上传公开仓库。

- +
+
+
+ 云端备份 +
+ 自动备份未启用 +
+ +
+
+ +
+
备份内容
+
+ +
+ + +
+ +
+

数据 = 订阅 / 规则 / 分类;设置 = 系统配置页(不含 WebDAV/S3 与备份计划);勾「含密钥」需先设加密密码。

+
+ + +
+
存储目标
+ +
+ + +
+ +
+
+
+ + +
+
+ + +

不存在会自动创建(MKCOL)

+
+
+ + +
+
+ +
+ + +
+
+
+
+ + +
+ + +
+
备份加密
+
+ +
+ + +
+

AES-256-GCM · PBKDF2-SHA256 派生密钥;密码只存服务器,不写进备份文件。

+
+
+
+ + +
+
+
+ 自动备份 + +
+
+ + +
+
+
+ + +
+
+ + +
+
+
+ +
+ + 份 +
+

超出自动删除最旧的

+
+
+ +
+
操作
+ + +

立即备份使用当前填入的连接与备份配置(未保存也可试跑)。

+
+
+
+
-
-

导入恢复

- -
- - - + +
+
+ 02 +

本地备份

+ 手动 · 无定时 +
+

只做手动导出:没有自动备份、没有保留份数,也不占用云端存储。范围独立配置,可以只导数据或带设置。

+ +
+
+
+
备份内容
+
+ +
+ + +
+ +
+

本地文件更容易被转发或误传,勾「包含密钥」时需先设置加密密码。

+
+ +
+
文件
+
substracker-backup-{datetime}.json
+

JSON 格式;下载后由浏览器保存,无法自动清理历史文件,所以不提供保留份数。

+
+ +
+
备份加密
+
+ +
+ + +
+

AES-256-GCM,留空 = 不加密。

+
+
+
+ +
+ + 导出后请妥善保存,含密钥时必须加密。 +
+
+
+ + +
+
+ 03 +

恢复

+
+

两个来源:本地文件、云端备份。文件内记录了备份范围,恢复时据此决定是否写设置、是否写密钥。

+ +
+
+
+ 从备份恢复 +
+
+ + +
+
+ +
+
+ +
未选择文件。加密备份需在下方填写解密密码。
+
+ + + +
+ + +
+ +
+ + +
+

合并:按 ID 覆盖同名订阅,其余保留。

+ +
+ + 加密备份先验证密码;范围不含设置时不动配置,不含密钥时不覆盖 Token。 +
+
-
-
+ +
+ +
+
@@ -841,6 +1120,10 @@

{ + btn.addEventListener('click', () => { + input.value = btn.getAttribute('data-scope-value'); + initScope(group); + }); + }); + } + + function guardKeySwitch(inputId, secretKey, message) { + const el = document.getElementById(inputId); + if (!el) return; + el.addEventListener('change', () => { + const configured = !!(window.SECRET_CONFIGURED && window.SECRET_CONFIGURED[secretKey]); + if (el.checked && !configured) { + el.checked = false; + showToast(message, 'warning', 4500); + } + }); + } + guardKeySwitch('cloudIncludeSecrets', 'CLOUD_BACKUP_ENCRYPT_PASSWORD', '包含密钥前,请先设置云端备份的加密密码'); + guardKeySwitch('localIncludeSecrets', 'LOCAL_BACKUP_ENCRYPT_PASSWORD', '包含密钥前,请先设置本地备份的加密密码'); + + initScope('cloudBackupScope'); + initScope('localBackupScope'); + + // 存储目标(WebDAV / S3) + const provider = document.getElementById('backupProvider'); + const webdavBox = document.getElementById('webdavConfig'); + const s3Box = document.getElementById('s3Config'); + function applyVisibility() { + if (!provider) return; + const isS3 = provider.value === 's3'; + if (webdavBox) webdavBox.classList.toggle('hidden', isS3); + if (s3Box) s3Box.classList.toggle('hidden', !isS3); + paintButtons('[data-provider-value]', 'data-provider-value', isS3 ? 's3' : 'webdav', 'bg-indigo-600 text-white hover:bg-indigo-700', 'bg-white text-gray-600 hover:bg-gray-50'); + } + window.__applyCloudBackupVisibility = applyVisibility; + document.querySelectorAll('[data-provider-value]').forEach((btn) => { + btn.addEventListener('click', () => { + if (provider) provider.value = btn.getAttribute('data-provider-value'); + applyVisibility(); + }); + }); + applyVisibility(); + + // 自动备份摘要 + 每周几可用状态 + const autoSwitch = document.getElementById('backupEnabled'); + const scheduleEl = document.getElementById('backupSchedule'); + const weeklyDayEl = document.getElementById('backupWeeklyDay'); + const autoSummary = document.getElementById('cloudAutoSummary'); + function refreshAutoSummary() { + if (scheduleEl) weeklyDayEl && (weeklyDayEl.disabled = scheduleEl.value !== 'weekly'); + if (!autoSummary) return; + if (!autoSwitch || !autoSwitch.checked || !scheduleEl || scheduleEl.value === 'off') { + autoSummary.textContent = '自动备份未启用'; + autoSummary.className = 'text-xs text-gray-500'; + return; + } + const hour = (document.getElementById('backupHour') && document.getElementById('backupHour').value) || '3'; + const retention = (document.getElementById('backupRetention') && document.getElementById('backupRetention').value) || '7'; + autoSummary.textContent = + (scheduleEl.value === 'weekly' ? '每周 · ' : '每天 · ') + '0' + String(hour).slice(-2) + ':00 · 保留 ' + retention + ' 份'; + autoSummary.className = 'text-xs text-green-600'; + } + [autoSwitch, scheduleEl, document.getElementById('backupHour'), document.getElementById('backupRetention')].forEach((el) => { + if (el) el.addEventListener('change', refreshAutoSummary); + }); + if (autoSwitch) autoSwitch.addEventListener('change', refreshAutoSummary); + refreshAutoSummary(); + window.__refreshBackupUi = function () { + initScope('cloudBackupScope'); + initScope('localBackupScope'); + applyVisibility(); + refreshAutoSummary(); + }; + + // 恢复来源 tabs + 模式说明 + const MODE_HINT = { + merge: '合并:按 ID 覆盖同名订阅,其余保留。', + replace: '覆盖:清空现有订阅后整包导入,适合换号迁移。' + }; + function paintRestorePane(src) { + document.querySelectorAll('[data-restore-pane]').forEach((btn) => { + const on = btn.getAttribute('data-restore-pane') === src; + ['bg-indigo-600', 'text-white', 'hover:bg-indigo-700'].forEach((cls) => btn.classList.toggle(cls, on)); + ['bg-white', 'text-gray-600', 'hover:bg-gray-50'].forEach((cls) => btn.classList.toggle(cls, !on)); + }); + const filePane = document.getElementById('restorePaneFile'); + const cloudPane = document.getElementById('restorePaneCloud'); + if (filePane) filePane.classList.toggle('hidden', src !== 'file'); + if (cloudPane) cloudPane.classList.toggle('hidden', src !== 'cloud'); + window.__restoreSource = src; + } + document.querySelectorAll('[data-restore-pane]').forEach((btn) => { + btn.addEventListener('click', () => paintRestorePane(btn.getAttribute('data-restore-pane'))); + }); + paintRestorePane('file'); + + document.querySelectorAll('input[name="restoreMode"]').forEach((radio) => { + radio.addEventListener('change', () => { + const hint = document.getElementById('restoreModeHint'); + if (hint) hint.textContent = MODE_HINT[radio.value] || MODE_HINT.merge; + }); + }); + + const saveBtn = document.getElementById('backupSaveBtn'); + if (saveBtn) { + saveBtn.addEventListener('click', () => { + const form = document.getElementById('configForm'); + if (form) form.requestSubmit(); + }); + } + })(); + + // ─────────────────────────────────────────────────────── + // 本地备份:下载 / 选择文件 / 恢复 // ─────────────────────────────────────────────────────── (function () { const exportBtn = document.getElementById('exportBackupBtn'); const importBtn = document.getElementById('importBackupBtn'); + const fileInput = document.getElementById('importBackupFile'); + const fileInfo = document.getElementById('restoreFileInfo'); if (!exportBtn || !importBtn) return; + function readMode() { + const el = document.querySelector('input[name="restoreMode"]:checked'); + return el && el.value === 'replace' ? 'replace' : 'merge'; + } + exportBtn.addEventListener('click', async () => { - const includeSecrets = document.getElementById('exportIncludeSecrets').checked; - if (includeSecrets && !confirm('将导出包含 Token / 密钥的完整备份,请确认文件会安全保存。继续?')) { + const scope = document.getElementById('localBackupScope').value === 'settings' ? 'settings' : 'data'; + const includeSecrets = + scope === 'settings' && document.getElementById('localIncludeSecrets').checked === true; + if (includeSecrets && !confirm('备份将包含 Token / 密码等密钥(加密后下载),请确认文件会安全保存。继续?')) { return; } const original = exportBtn.innerHTML; exportBtn.disabled = true; exportBtn.innerHTML = '导出中...'; try { - const url = '/api/backup?includeSecrets=' + (includeSecrets ? '1' : '0'); + const url = '/api/backup?scope=' + scope + '&includeSecrets=' + (includeSecrets ? '1' : '0'); const res = await apiFetch(url); if (!res.ok) { const err = await res.json().catch(() => ({})); throw new Error(err.message || ('HTTP ' + res.status)); } const blob = await res.blob(); + const disposition = res.headers.get('Content-Disposition') || ''; + const match = disposition.match(/filename="([^"]+)"/); + const fileName = + (match && match[1]) || + 'substracker-backup-' + new Date().toISOString().replace(/[-:]/g, '').slice(0, 15) + '.json'; const a = document.createElement('a'); const objectUrl = URL.createObjectURL(blob); a.href = objectUrl; - a.download = 'substracker-backup-' + new Date().toISOString().slice(0, 10) + '.json'; + a.download = fileName; document.body.appendChild(a); a.click(); a.remove(); @@ -1772,39 +2280,69 @@

({})); if (!res.ok || !result.success) { @@ -1817,12 +2355,7 @@

({})); + const last = (payload.data || {}).lastRun || {}; + const el = document.getElementById('cloudBackupLastRun'); + if (!el) return; + if (!last.at) { + el.textContent = '尚未执行'; + el.className = 'text-xs text-gray-500'; + return; + } + const timeText = new Date(last.at).toLocaleString(); + if (last.status === 'success') { + el.textContent = '上次成功:' + timeText + (last.size ? ' · ' + formatBytes(last.size) : ''); + el.className = 'text-xs text-green-600'; + } else { + el.textContent = '上次失败:' + timeText + (last.message ? '(' + last.message + ')' : ''); + el.className = 'text-xs text-red-600'; + } + } catch (_) { + /* ignore */ + } + } + window.__refreshCloudBackupStatus = refreshStatus; + refreshStatus(); + + function renderFiles(files) { + if (!listBox) return; + if (!files || !files.length) { + listBox.innerHTML = '远端还没有备份文件。'; + return; + } + const rows = files + .map( + (file) => + '' + + '' + escapeHtml(file.name) + '' + + '' + formatBytes(file.size) + '' + + '' + + (file.modifiedAt ? escapeHtml(new Date(file.modifiedAt).toLocaleString()) : '-') + + '' + + '' + + '' + + '' + + '' + ) + .join(''); + + listBox.innerHTML = + '
' + + '' + + '' + + '' + rows + '
文件名大小时间操作
'; + } + + async function refreshFiles(options) { + const silent = !!(options && options.silent); + try { + const res = await apiFetch('/api/backup/cloud/files'); + const payload = await res.json().catch(() => ({})); + if (!res.ok || !payload.success) { + throw new Error(payload.message || ('HTTP ' + res.status)); + } + renderFiles(payload.data || []); + } catch (error) { + if (error && error.message === 'AUTH_EXPIRED') return; + if (!silent) showToast('读取备份列表失败: ' + (error.message || error), 'error', 6000); + if (listBox) listBox.innerHTML = '无法读取远端备份列表。'; + } + } + + const testBtn = document.getElementById('cloudTestBtn'); + if (testBtn) { + testBtn.addEventListener('click', async () => { + const original = testBtn.innerHTML; + testBtn.disabled = true; + testBtn.innerHTML = '测试中...'; + try { + const res = await apiFetch('/api/backup/cloud/test', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ overrides: collectOverrides() }) + }); + const result = await res.json().catch(() => ({})); + if (!res.ok || !result.success) throw new Error(result.message || ('HTTP ' + res.status)); + showToast(result.message || '连接成功', 'success'); + refreshStatus(); + } catch (error) { + if (error && error.message === 'AUTH_EXPIRED') return; + showToast('连接失败: ' + (error.message || error), 'error', 6000); + } finally { + testBtn.disabled = false; + testBtn.innerHTML = original; + } + }); + } + + const runBtn = document.getElementById('cloudRunBtn'); + if (runBtn) { + runBtn.addEventListener('click', async () => { + if (document.getElementById('cloudIncludeSecrets').checked) { + if (!confirm('备份将包含 Token / 密码等密钥,确认继续?')) return; + } + const original = runBtn.innerHTML; + runBtn.disabled = true; + runBtn.innerHTML = '备份中...'; + try { + const res = await apiFetch('/api/backup/cloud/run', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ overrides: collectOverrides() }) + }); + const result = await res.json().catch(() => ({})); + if (!res.ok || !result.success) throw new Error(result.message || ('HTTP ' + res.status)); + const data = result.data || {}; + showToast('备份成功: ' + (data.file || '') + '(' + formatBytes(data.size) + ')', 'success', 6000); + refreshStatus(); + refreshFiles({ silent: true }); + } catch (error) { + if (error && error.message === 'AUTH_EXPIRED') return; + showToast('备份失败: ' + (error.message || error), 'error', 8000); + refreshStatus(); + } finally { + runBtn.disabled = false; + runBtn.innerHTML = original; + } + }); + } + + const filesBtn = document.getElementById('cloudFilesBtn'); + if (filesBtn) { + filesBtn.addEventListener('click', async () => { + const original = filesBtn.innerHTML; + filesBtn.disabled = true; + filesBtn.innerHTML = '加载中...'; + try { + await refreshFiles(); + } finally { + filesBtn.disabled = false; + filesBtn.innerHTML = original; + } + }); + } + + if (listBox) { + listBox.addEventListener('click', async (event) => { + const button = event.target.closest('[data-restore]'); + if (!button) return; + const file = button.getAttribute('data-restore'); + const modeEl = document.querySelector('input[name="restoreMode"]:checked'); + const mode = modeEl && modeEl.value === 'replace' ? 'replace' : 'merge'; + + if (mode === 'replace' && !confirm('覆盖恢复会删除当前全部订阅后再导入,且不可撤销。确定继续?')) return; + if (!confirm('确认从远端备份恢复?建议先手动备份一份当前数据。')) return; + + const passwordInput = document.getElementById('restorePassword'); + const password = passwordInput ? passwordInput.value : ''; + if (!password && !confirm('未填写密码,仅当备份未加密时才能恢复。继续?')) return; + + const original = button.innerHTML; + button.disabled = true; + button.innerHTML = '恢复中...'; + try { + const res = await apiFetch('/api/backup/cloud/restore', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ file, mode, password }) + }); + const result = await res.json().catch(() => ({})); + if (!res.ok || !result.success) throw new Error(result.message || ('HTTP ' + res.status)); + const stats = result.stats || {}; + showToast( + '恢复成功:订阅 ' + (stats.subscriptions || 0) + ' 条,规则 ' + (stats.reminderRules || 0) + ' 条', + 'success', + 5000 + ); + setTimeout(function () { location.reload(); }, 800); + } catch (error) { + if (error && error.message === 'AUTH_EXPIRED') return; + showToast('恢复失败: ' + (error.message || error), 'error', 6000); + } finally { + button.disabled = false; + button.innerHTML = original; + } + }); + } + })(); + diff --git a/tests/api/backup-cloud-routes.test.js b/tests/api/backup-cloud-routes.test.js new file mode 100644 index 00000000..4519d8f3 --- /dev/null +++ b/tests/api/backup-cloud-routes.test.js @@ -0,0 +1,234 @@ +// @ts-check +/** + * 云端备份路由测试 + * + * 覆盖: + * - 鉴权 + * - 状态接口不下发密码/密钥 + * - 配置保存后 *_CONFIGURED 标记 + * - 测试连接 / 立即备份 / 文件列表 / 恢复 + */ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +// @ts-ignore +import { env } from 'cloudflare:test'; + +import app from '../../src/app.js'; + +const WEBDAV_BASE = 'https://dav.example.com/dav'; + +async function clearKv() { + const list = await env.SUBSCRIPTIONS_KV.list(); + await Promise.all(list.keys.map((key) => env.SUBSCRIPTIONS_KV.delete(key.name))); +} + +async function loginCookie() { + await env.SUBSCRIPTIONS_KV.put( + 'config', + JSON.stringify({ + ADMIN_USERNAME: 'admin', + ADMIN_PASSWORD: 'password', + JWT_SECRET: 'test-jwt-secret', + TIMEZONE: 'Asia/Shanghai', + WEBDAV_URL: WEBDAV_BASE, + WEBDAV_USERNAME: 'davuser', + WEBDAV_PASSWORD: 'super-secret-password', + WEBDAV_PATH: 'SubsTracker', + BACKUP_PROVIDER: 'webdav', + BACKUP_RETENTION: 5 + }) + ); + const res = await app.request( + '/api/login', + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ username: 'admin', password: 'password' }) + }, + env + ); + return res.headers.get('Set-Cookie')?.split(';')[0] || ''; +} + +function installFetchMock() { + const calls = []; + const mock = vi.fn(async (url, init = {}) => { + const method = String(init.method || 'GET').toUpperCase(); + calls.push({ url: String(url), method }); + if (method === 'MKCOL') return new Response('', { status: 201 }); + if (method === 'PUT') return new Response('', { status: 201 }); + if (method === 'PROPFIND') { + return new Response( + '' + + '/dav/SubsTracker/substracker-backup-20261203-030000.json' + + '321' + + 'Thu, 03 Dec 2026 03:00:00 GMT' + + '', + { status: 207 } + ); + } + if (method === 'DELETE') return new Response('', { status: 204 }); + return new Response('', { status: 200 }); + }); + vi.stubGlobal('fetch', mock); + return { calls }; +} + +beforeEach(clearKv); +afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +describe('云端备份路由', () => { + it('未登录 → 401', async () => { + const res = await app.request('/api/backup/cloud/status', {}, env); + expect(res.status).toBe(401); + }); + + it('状态接口不下发密码,只给已配置标记', async () => { + const cookie = await loginCookie(); + const res = await app.request('/api/backup/cloud/status', { headers: { Cookie: cookie } }, env); + expect(res.status).toBe(200); + + const text = await res.text(); + expect(text).not.toContain('super-secret-password'); + + const payload = JSON.parse(text); + expect(payload.success).toBe(true); + expect(payload.data.provider).toBe('webdav'); + expect(payload.data.webdav.passwordConfigured).toBe(true); + expect(payload.data.webdav.username).toBe('davuser'); + expect(payload.data.s3.secretConfigured).toBe(false); + }); + + it('保存配置时新字段生效,GET 配置不回显密钥', async () => { + const cookie = await loginCookie(); + const save = await app.request( + '/api/config', + { + method: 'POST', + headers: { 'Content-Type': 'application/json', Cookie: cookie }, + body: JSON.stringify({ + ADMIN_USERNAME: 'admin', + BACKUP_ENABLED: true, + BACKUP_PROVIDER: 's3', + BACKUP_SCHEDULE: 'daily', + BACKUP_HOUR: 4, + BACKUP_WEEKLY_DAY: 2, + BACKUP_RETENTION: 10, + S3_ENDPOINT: 'https://acc.r2.cloudflarestorage.com', + S3_BUCKET: 'backup', + S3_REGION: 'auto', + S3_ACCESS_KEY_ID: 'AKIDEXAMPLE', + S3_SECRET_ACCESS_KEY: 'new-secret-key', + S3_PREFIX: 'SubsTracker', + S3_FORCE_PATH_STYLE: true, + WEBDAV_PASSWORD: '' + }) + }, + env + ); + expect(save.status).toBe(200); + + const res = await app.request('/api/config', { headers: { Cookie: cookie } }, env); + const config = await res.json(); + + expect(config.BACKUP_PROVIDER).toBe('s3'); + expect(config.BACKUP_SCHEDULE).toBe('daily'); + expect(config.BACKUP_HOUR).toBe(4); + expect(config.BACKUP_RETENTION).toBe(10); + expect(config.S3_SECRET_ACCESS_KEY).toBe(''); + expect(config.S3_SECRET_ACCESS_KEY_CONFIGURED).toBe(true); + // 原有 WebDAV 密码留空 → 保留 + expect(config.WEBDAV_PASSWORD_CONFIGURED).toBe(true); + }); + + it('测试连接:配置缺失 → 400 并给出可读提示', async () => { + const cookie = await loginCookie(); + installFetchMock(); + const res = await app.request( + '/api/backup/cloud/test', + { + method: 'POST', + headers: { 'Content-Type': 'application/json', Cookie: cookie }, + body: JSON.stringify({ overrides: { WEBDAV_URL: '', WEBDAV_PASSWORD: '' } }) + }, + env + ); + // 空值被忽略 → 回落到已保存配置,所以这里应成功 + expect(res.status).toBe(200); + + await clearKv(); + const cookie2 = await loginCookie(); + await env.SUBSCRIPTIONS_KV.put( + 'config', + JSON.stringify({ + ADMIN_USERNAME: 'admin', + ADMIN_PASSWORD: 'password', + JWT_SECRET: 'test-jwt-secret' + }) + ); + const res2 = await app.request( + '/api/backup/cloud/test', + { method: 'POST', headers: { 'Content-Type': 'application/json', Cookie: cookie2 }, body: '{}' }, + env + ); + expect(res2.status).toBe(400); + const body = await res2.json(); + expect(body.message).toMatch(/WebDAV/); + }); + + it('立即备份返回文件名,并写入状态', async () => { + const cookie = await loginCookie(); + const { calls } = installFetchMock(); + + const res = await app.request( + '/api/backup/cloud/run', + { method: 'POST', headers: { 'Content-Type': 'application/json', Cookie: cookie }, body: '{}' }, + env + ); + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.success).toBe(true); + expect(body.data.file).toMatch(/^substracker-backup-\d{8}-\d{6}\.json$/); + expect(calls.some((call) => call.method === 'PUT')).toBe(true); + + const status = await app.request('/api/backup/cloud/status', { headers: { Cookie: cookie } }, env); + const statusBody = await status.json(); + expect(statusBody.data.lastRun.status).toBe('success'); + }); + + it('备份列表返回远端文件名', async () => { + const cookie = await loginCookie(); + installFetchMock(); + const res = await app.request('/api/backup/cloud/files', { headers: { Cookie: cookie } }, env); + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.success).toBe(true); + expect(body.data[0].name).toBe('substracker-backup-20261203-030000.json'); + expect(body.data[0].size).toBe(321); + }); + + it('恢复接口:缺 file → 400;文件不存在 → 404', async () => { + const cookie = await loginCookie(); + installFetchMock(); + + const missing = await app.request( + '/api/backup/cloud/restore', + { method: 'POST', headers: { 'Content-Type': 'application/json', Cookie: cookie }, body: '{}' }, + env + ); + expect(missing.status).toBe(400); + + const notFound = await app.request( + '/api/backup/cloud/restore', + { + method: 'POST', + headers: { 'Content-Type': 'application/json', Cookie: cookie }, + body: JSON.stringify({ file: 'substracker-backup-20250101-000000.json' }) + }, + env + ); + expect(notFound.status).toBe(404); + }); +}); diff --git a/tests/api/backup-routes.test.js b/tests/api/backup-routes.test.js index d1ea6446..703c1781 100644 --- a/tests/api/backup-routes.test.js +++ b/tests/api/backup-routes.test.js @@ -17,7 +17,7 @@ async function clearKv() { await Promise.all(list.keys.map((k) => env.SUBSCRIPTIONS_KV.delete(k.name))); } -async function loginCookie() { +async function loginCookie(extra = {}) { await env.SUBSCRIPTIONS_KV.put( 'config', JSON.stringify({ @@ -26,7 +26,8 @@ async function loginCookie() { JWT_SECRET: 'test-jwt-secret', TG_BOT_TOKEN: 'secret-token-value', TG_CHAT_ID: '12345', - TIMEZONE: 'Asia/Shanghai' + TIMEZONE: 'Asia/Shanghai', + ...extra }) ); const res = await app.request( @@ -79,14 +80,28 @@ describe('GET /api/backup', () => { expect(backup.categories).toContain('视频'); }); - it('includeSecrets=1 时导出 Token', async () => { + it('includeSecrets=1 且未设本地密码 → 400', async () => { const cookie = await loginCookie(); const res = await app.request('/api/backup?includeSecrets=1', { headers: { Cookie: cookie } }, env); + expect(res.status).toBe(400); + const body = await res.json(); + expect(body.message).toMatch(/本地备份加密密码/); + }); + + it('includeSecrets=1 且设了本地密码 → 导出加密信封', async () => { + const cookie = await loginCookie({ LOCAL_BACKUP_ENCRYPT_PASSWORD: 'local-pass-123' }); + const res = await app.request('/api/backup?includeSecrets=1', { headers: { Cookie: cookie } }, env); expect(res.status).toBe(200); - const backup = await res.json(); + const envelope = await res.json(); + expect(envelope.format).toBe('substracker-backup-encrypted'); + + const { decryptBackupText } = await import('../../src/services/backup/crypto.js'); + const plain = await decryptBackupText(envelope, 'local-pass-123'); + const backup = JSON.parse(plain); expect(backup.includeSecrets).toBe(true); expect(backup.config.TG_BOT_TOKEN).toBe('secret-token-value'); expect(backup.config.JWT_SECRET).toBeUndefined(); + expect(backup.config.WEBDAV_PASSWORD).toBeUndefined(); }); }); @@ -144,6 +159,34 @@ describe('POST /api/restore', () => { expect(cfg.JWT_SECRET).toBe('test-jwt-secret'); }); + it('数据范围不写配置,即使备份里带了 config', async () => { + const cookie = await loginCookie(); + const backup = { + format: 'substracker-backup', + version: 1, + scope: 'data', + includeSecrets: true, + config: { TIMEZONE: 'Asia/Tokyo', TG_BOT_TOKEN: 'leaked-token' }, + subscriptions: [ + { id: 'd1', name: 'DataOnly', expiryDate: '2026-11-01T00:00:00.000Z', isActive: true } + ], + reminderRules: {} + }; + const res = await app.request( + '/api/restore', + { + method: 'POST', + headers: { 'Content-Type': 'application/json', Cookie: cookie }, + body: JSON.stringify({ backup, mode: 'merge' }) + }, + env + ); + expect(res.status).toBe(200); + const cfg = await getConfig(env); + expect(cfg.TIMEZONE).toBe('Asia/Shanghai'); + expect(cfg.TG_BOT_TOKEN).toBe('secret-token-value'); + }); + it('覆盖模式删除旧订阅', async () => { const cookie = await loginCookie(); await subRepo.save(env, { diff --git a/tests/services/backup-crypto.test.js b/tests/services/backup-crypto.test.js new file mode 100644 index 00000000..177147ea --- /dev/null +++ b/tests/services/backup-crypto.test.js @@ -0,0 +1,86 @@ +import { describe, expect, it } from 'vitest'; +import { + ENCRYPTED_BACKUP_FORMAT, + decryptBackupText, + encryptBackupText, + isEncryptedBackup +} from '../../src/services/backup/crypto.js'; + +const SAMPLE = JSON.stringify({ + format: 'substracker-backup', + version: 1, + subscriptions: [{ id: 'sub-1', name: '测试订阅', expiryDate: '2027-01-01' }], + config: { TG_BOT_TOKEN: 'should-not-leak' } +}); + +const options = { iterations: 10000 }; + +describe('备份文件加密', () => { + it('加密后是可识别的信封,且不含明文', async () => { + const text = await encryptBackupText(SAMPLE, 'pass-123456', options); + const envelope = JSON.parse(text); + + expect(envelope.format).toBe(ENCRYPTED_BACKUP_FORMAT); + expect(envelope.version).toBe(1); + expect(envelope.cipher).toBe('AES-256-GCM'); + expect(envelope.kdf.name).toBe('PBKDF2-SHA256'); + expect(envelope.kdf.iterations).toBe(10000); + expect(envelope.kdf.salt).toBeTruthy(); + expect(envelope.iv).toBeTruthy(); + expect(envelope.data).toBeTruthy(); + + // 密文里不应出现任何明文片段 + expect(text).not.toContain('测试订阅'); + expect(text).not.toContain('should-not-leak'); + expect(isEncryptedBackup(envelope)).toBe(true); + }); + + it('同一明文两次加密结果不同(随机盐 + IV)', async () => { + const a = await encryptBackupText(SAMPLE, 'pass-123456', options); + const b = await encryptBackupText(SAMPLE, 'pass-123456', options); + expect(a).not.toBe(b); + expect(JSON.parse(a).kdf.salt).not.toBe(JSON.parse(b).kdf.salt); + }); + + it('正确密码可以还原原文', async () => { + const text = await encryptBackupText(SAMPLE, 'pass-123456', options); + const plaintext = await decryptBackupText(JSON.parse(text), 'pass-123456'); + expect(plaintext).toBe(SAMPLE); + }); + + it('密码错误时报 400 而不是崩溃', async () => { + const text = await encryptBackupText(SAMPLE, 'pass-123456', options); + await expect(decryptBackupText(JSON.parse(text), 'wrong-pass')).rejects.toMatchObject({ + status: 400 + }); + await expect(decryptBackupText(JSON.parse(text), 'wrong-pass')).rejects.toThrow(/解密失败/); + }); + + it('密文被篡改时校验失败', async () => { + const text = await encryptBackupText(SAMPLE, 'pass-123456', options); + const envelope = JSON.parse(text); + const dataBytes = Uint8Array.from(atob(envelope.data), (char) => char.charCodeAt(0)); + dataBytes[0] ^= 0xff; + envelope.data = btoa(String.fromCharCode(...dataBytes)); + + await expect(decryptBackupText(envelope, 'pass-123456')).rejects.toThrow(/解密失败/); + }); + + it('未设置密码、结构异常、版本过高都给出明确错误', async () => { + await expect(encryptBackupText(SAMPLE, '')).rejects.toThrow(/加密密码/); + + const text = await encryptBackupText(SAMPLE, 'pass-123456', options); + const envelope = JSON.parse(text); + + await expect(decryptBackupText(envelope, '')).rejects.toThrow(/已加密/); + await expect(decryptBackupText({ ...envelope, data: '' }, 'pass-123456')).rejects.toThrow(/不完整/); + await expect(decryptBackupText({ ...envelope, version: 9 }, 'pass-123456')).rejects.toThrow(/版本过高/); + await expect(decryptBackupText({ format: 'other' }, 'pass-123456')).rejects.toThrow(/不是加密备份/); + }); + + it('isEncryptedBackup 只认本项目信封', () => { + expect(isEncryptedBackup({ format: ENCRYPTED_BACKUP_FORMAT })).toBe(true); + expect(isEncryptedBackup({ format: 'substracker-backup' })).toBe(false); + expect(isEncryptedBackup(null)).toBe(false); + }); +}); diff --git a/tests/services/cloud-backup.test.js b/tests/services/cloud-backup.test.js new file mode 100644 index 00000000..253455a5 --- /dev/null +++ b/tests/services/cloud-backup.test.js @@ -0,0 +1,609 @@ +// @ts-check +/** + * 云端备份(WebDAV / S3)测试 + * + * 用 vi.stubGlobal 模拟 fetch,直接覆盖协议细节: + * - WebDAV:MKCOL / PUT / PROPFIND / DELETE 的路径与 Basic Auth + * - S3:path-style 地址、SigV4 头部、payload hash + * - 编排:载荷脱敏、保留份数、定时判断、远端恢复 + */ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +// @ts-ignore +import { env } from 'cloudflare:test'; + +import * as subRepo from '../../src/data/subscriptions.repo.js'; +import { putKVJson } from '../../src/data/kv.js'; +import * as webdav from '../../src/services/backup/webdav.js'; +import * as s3 from '../../src/services/backup/s3.js'; +import { + listCloudBackups, + maybeRunScheduledBackup, + restoreFromCloudBackup, + runCloudBackup, + testCloudBackupTarget +} from '../../src/services/backup/cloud.js'; + +const WEBDAV_BASE = 'https://dav.example.com/dav'; + +function webdavConfig(overrides = {}) { + return webdav.normalizeWebdavConfig({ + url: WEBDAV_BASE, + username: 'davuser', + password: 'davpass', + remotePath: 'SubsTracker', + ...overrides + }); +} + +function s3Config(overrides = {}) { + return s3.normalizeS3Config({ + endpoint: 'https://acc.r2.cloudflarestorage.com', + bucket: 'backup', + region: 'auto', + accessKeyId: 'AKIDEXAMPLE', + secretAccessKey: 'SECRETEXAMPLE', + prefix: 'SubsTracker', + forcePathStyle: true, + ...overrides + }); +} + +function propfindXml(files) { + const responses = files + .map( + (file) => + '' + + encodeURI(file.href) + + '' + + file.size + + '' + + file.modified + + '' + ) + .join(''); + return ( + '' + + responses + + '' + ); +} + +/** 默认 mock:按 method 返回成功,并记录所有请求 */ +function installFetchMock(handlers = {}) { + const calls = []; + const mock = vi.fn(async (url, init = {}) => { + const method = String(init.method || 'GET').toUpperCase(); + const headers = new Headers(init.headers || {}); + calls.push({ url: String(url), method, headers, body: init.body }); + + if (handlers[method]) return handlers[method]({ url: String(url), headers, body: init.body, calls }); + if (method === 'MKCOL') return new Response('', { status: 201 }); + if (method === 'PUT') return new Response('', { status: 201 }); + if (method === 'PROPFIND') return new Response(propfindXml([]), { status: 207 }); + if (method === 'DELETE') return new Response('', { status: 204 }); + if (method === 'GET') return new Response('{}', { status: 200 }); + return new Response('', { status: 200 }); + }); + vi.stubGlobal('fetch', mock); + return { mock, calls }; +} + +async function seedConfig(overrides = {}) { + await putKVJson(env, 'config', { + ADMIN_USERNAME: 'admin', + ADMIN_PASSWORD: 'password', + JWT_SECRET: 'test-jwt-secret', + TIMEZONE: 'Asia/Shanghai', + TG_BOT_TOKEN: 'super-secret-token', + WEBDAV_URL: WEBDAV_BASE, + WEBDAV_USERNAME: 'davuser', + WEBDAV_PASSWORD: 'davpass', + WEBDAV_PATH: 'SubsTracker', + S3_ENDPOINT: 'https://acc.r2.cloudflarestorage.com', + S3_BUCKET: 'backup', + S3_REGION: 'auto', + S3_ACCESS_KEY_ID: 'AKIDEXAMPLE', + S3_SECRET_ACCESS_KEY: 'SECRETEXAMPLE', + S3_PREFIX: 'SubsTracker', + S3_FORCE_PATH_STYLE: true, + BACKUP_PROVIDER: 'webdav', + BACKUP_RETENTION: 2, + ...overrides + }); +} + +async function clearKv() { + const list = await env.SUBSCRIPTIONS_KV.list(); + await Promise.all(list.keys.map((key) => env.SUBSCRIPTIONS_KV.delete(key.name))); +} + +beforeEach(async () => { + await clearKv(); +}); + +afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +describe('WebDAV 客户端', () => { + it('缺地址/密码时给出明确的 400 错误', () => { + expect(() => webdav.normalizeWebdavConfig({ url: '', username: 'u', password: 'p' })).toThrow( + /WebDAV 服务器地址/ + ); + expect(() => + webdav.normalizeWebdavConfig({ url: WEBDAV_BASE, username: 'u', password: '' }) + ).toThrow(/WebDAV 密码/); + expect(() => + webdav.normalizeWebdavConfig({ url: 'ftp://x.example.com', username: 'u', password: 'p' }) + ).toThrow(/http/); + }); + + it('上传前逐级 MKCOL,PUT 带 Basic Auth 且路径正确', async () => { + const { calls } = installFetchMock({ + PROPFIND: () => new Response(propfindXml([]), { status: 207 }) + }); + const config = webdavConfig({ remotePath: 'Backups/SubsTracker' }); + const url = await webdav.putFile(config, 'substracker-backup-20261203-030000.json', '{"a":1}'); + + const mkcols = calls.filter((call) => call.method === 'MKCOL'); + expect(mkcols.map((call) => new URL(call.url).pathname)).toEqual([ + '/dav/Backups', + '/dav/Backups/SubsTracker' + ]); + + const put = calls.find((call) => call.method === 'PUT'); + expect(new URL(put.url).pathname).toBe('/dav/Backups/SubsTracker/substracker-backup-20261203-030000.json'); + expect(put.headers.get('Authorization')).toBe('Basic ' + btoa('davuser:davpass')); + expect(put.headers.get('Content-Type')).toContain('application/json'); + expect(url).toBe( + WEBDAV_BASE + '/Backups/SubsTracker/substracker-backup-20261203-030000.json' + ); + }); + + it('PROPFIND 解析:忽略目录与跨站 href,保留文件大小', async () => { + installFetchMock({ + PROPFIND: () => + new Response( + propfindXml([ + { href: '/dav/SubsTracker/', size: 0, modified: 'Mon, 01 Dec 2026 00:00:00 GMT' }, + { + href: '/dav/SubsTracker/substracker-backup-20261201-030000.json', + size: 2048, + modified: 'Mon, 01 Dec 2026 03:00:00 GMT' + }, + { href: 'https://evil.example.com/steal.json', size: 1, modified: 'x' } + ]), + { status: 207 } + ) + }); + + const files = await webdav.listFiles(webdavConfig()); + expect(files).toHaveLength(1); + expect(files[0].name).toBe('substracker-backup-20261201-030000.json'); + expect(files[0].size).toBe(2048); + expect(files[0].url).toContain('/dav/SubsTracker/substracker-backup-20261201-030000.json'); + }); +}); + +describe('S3 客户端', () => { + it('校验必填项', () => { + expect(() => s3.normalizeS3Config({ endpoint: '', bucket: 'b' })).toThrow(/Endpoint/); + expect(() => s3.normalizeS3Config({ endpoint: 'https://e.com', bucket: '' })).toThrow(/桶名称/); + expect(() => + s3.normalizeS3Config({ endpoint: 'https://e.com', bucket: 'bucket/sub/dir' }) + ).toThrow(/桶名称不能包含/); + expect(() => + s3.normalizeS3Config({ endpoint: 'https://e.com', bucket: 'b', accessKeyId: 'a', secretAccessKey: '' }) + ).toThrow(/Secret/); + }); + + it('path-style PUT:URL 落在 bucket/prefix 下,带 SigV4 头且 payload hash 正确', async () => { + const { calls } = installFetchMock(); + const body = '{"hello":"s3"}'; + await s3.putObject(s3Config(), 'substracker-backup-20261203-030000.json', body); + + const put = calls.find((call) => call.method === 'PUT'); + const target = new URL(put.url); + expect(target.pathname).toBe('/backup/SubsTracker/substracker-backup-20261203-030000.json'); + + const auth = put.headers.get('Authorization') || ''; + expect(auth).toMatch(/^AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE\/\d{8}\/auto\/s3\/aws4_request, SignedHeaders=content-type;host;x-amz-content-sha256;x-amz-date, Signature=[0-9a-f]{64}$/); + + const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(body)); + const expectedHash = Array.from(new Uint8Array(digest)) + .map((byte) => byte.toString(16).padStart(2, '0')) + .join(''); + expect(put.headers.get('x-amz-content-sha256')).toBe(expectedHash); + expect(put.headers.get('x-amz-date')).toMatch(/^\d{8}T\d{6}Z$/); + }); + + it('virtual-hosted 寻址把 bucket 放进域名', async () => { + const { calls } = installFetchMock(); + await s3.putObject( + s3Config({ endpoint: 'https://s3.example.com', forcePathStyle: false }), + 'a.json', + '{}' + ); + const put = calls.find((call) => call.method === 'PUT'); + const target = new URL(put.url); + expect(target.hostname).toBe('backup.s3.example.com'); + expect(target.pathname).toBe('/SubsTracker/a.json'); + }); +}); + +describe('runCloudBackup', () => { + it('WebDAV:默认脱敏 Token,上传到远端并记录状态', async () => { + await seedConfig({ BACKUP_PROVIDER: 'webdav', BACKUP_RETENTION: 2 }); + await subRepo.save(env, { + id: 's1', + name: 'Netflix', + expiryDate: '2026-08-01T00:00:00.000Z', + isActive: true + }); + + const { calls } = installFetchMock({ + PROPFIND: () => + new Response( + propfindXml([{ href: '/dav/SubsTracker/substracker-backup-20261201-030000.json', size: 10, modified: 'x' }]), + { status: 207 } + ) + }); + + const result = await runCloudBackup(env, { trigger: 'manual' }); + expect(result.provider).toBe('webdav'); + expect(result.file).toMatch(/^substracker-backup-\d{8}-\d{6}\.json$/); + expect(result.size).toBeGreaterThan(0); + + const put = calls.find((call) => call.method === 'PUT'); + const payload = JSON.parse(put.body); + expect(payload.format).toBe('substracker-backup'); + expect(payload.subscriptions).toHaveLength(1); + expect(payload.includeSecrets).toBe(false); + expect(payload.config.TG_BOT_TOKEN).toBe(''); + // 云端凭证属于「设置」排除项,不进备份 + expect(payload.config.WEBDAV_PASSWORD).toBeUndefined(); + expect(payload.config.WEBDAV_URL).toBeUndefined(); + expect(payload.config.BACKUP_RETENTION).toBeUndefined(); + + const state = await env.SUBSCRIPTIONS_KV.get('cloud_backup_state', 'json'); + expect(state.lastStatus).toBe('success'); + expect(state.lastFile).toBe(result.file); + expect(state.lastProvider).toBe('webdav'); + }); + + it('WebDAV:设置加密密码并开启 includeSecrets 时写入 Token', async () => { + await seedConfig({ + BACKUP_PROVIDER: 'webdav', + CLOUD_BACKUP_SCOPE: 'settings', + CLOUD_BACKUP_INCLUDE_SECRETS: true, + CLOUD_BACKUP_ENCRYPT_PASSWORD: 'backup-pass-123' + }); + let uploaded = ''; + const { calls } = installFetchMock({ + PUT: ({ body }) => { + uploaded = String(body); + return new Response('', { status: 201 }); + } + }); + const result = await runCloudBackup(env, { trigger: 'manual' }); + expect(result.encrypted).toBe(true); + expect(uploaded).not.toContain('super-secret-token'); + const envelope = JSON.parse(uploaded); + expect(envelope.format).toBe('substracker-backup-encrypted'); + expect(calls.some((call) => call.method === 'PUT')).toBe(true); + }); + + it('数据范围:不导出 config', async () => { + await seedConfig({ BACKUP_PROVIDER: 'webdav', CLOUD_BACKUP_SCOPE: 'data' }); + await subRepo.save(env, { + id: 's1', + name: 'Netflix', + expiryDate: '2026-08-01T00:00:00.000Z', + isActive: true + }); + const { calls } = installFetchMock(); + await runCloudBackup(env, { trigger: 'manual' }); + const put = calls.find((call) => call.method === 'PUT'); + const payload = JSON.parse(put.body); + expect(payload.scope).toBe('data'); + expect(payload.config).toBeUndefined(); + expect(payload.subscriptions).toHaveLength(1); + }); + + it('超出保留份数时删除最旧备份(S3)', async () => { + await seedConfig({ BACKUP_PROVIDER: 's3', BACKUP_RETENTION: 2 }); + + const listXml = + '' + + [ + ['substracker-backup-20261201-030000.json', 3], + ['substracker-backup-20261202-030000.json', 2], + ['substracker-backup-20261203-030000.json', 1] + ] + .map(([key, size]) => `${key}${size}2026-12-03T03:00:00.000Z`) + .join('') + + ''; + + const { calls } = installFetchMock({ + GET: ({ url }) => + new URL(url).searchParams.get('list-type') === '2' + ? new Response(listXml, { status: 200 }) + : new Response('{}', { status: 200 }) + }); + + const result = await runCloudBackup(env, { trigger: 'manual' }); + expect(result.pruned).toBe(1); + + const deleted = calls.filter((call) => call.method === 'DELETE'); + expect(deleted).toHaveLength(1); + expect(new URL(deleted[0].url).pathname).toContain( + 'substracker-backup-20261201-030000.json' + ); + // 新文件写入的不是被删的那个 + expect(result.file).not.toBe('substracker-backup-20261201-030000.json'); + }); + + it('用未保存的 S3 覆盖项备份时,保留份数也作用在 S3 而不是已保存的 WebDAV', async () => { + await seedConfig({ BACKUP_PROVIDER: 'webdav', BACKUP_RETENTION: 2 }); + + const listXml = + '' + + [ + 'substracker-backup-20261201-030000.json', + 'substracker-backup-20261202-030000.json', + 'substracker-backup-20261203-030000.json' + ] + .map((key) => `${key}102026-12-03T03:00:00.000Z`) + .join('') + + ''; + + const { calls } = installFetchMock({ + GET: ({ url }) => + new URL(url).searchParams.get('list-type') === '2' + ? new Response(listXml, { status: 200 }) + : new Response('{}', { status: 200 }) + }); + + const result = await runCloudBackup(env, { + trigger: 'manual', + overrides: { BACKUP_PROVIDER: 's3' } + }); + + expect(result.provider).toBe('s3'); + expect(result.pruned).toBe(1); + + const deleted = calls.filter((call) => call.method === 'DELETE'); + expect(deleted).toHaveLength(1); + expect(new URL(deleted[0].url).pathname).toContain('substracker-backup-20261201-030000.json'); + // 不应该去列已保存的 WebDAV + expect(calls.some((call) => call.method === 'PROPFIND')).toBe(false); + }); + + it('配置缺失时抛错并记录失败状态', async () => { + await seedConfig({ BACKUP_PROVIDER: 'webdav', WEBDAV_PASSWORD: '', WEBDAV_URL: '' }); + installFetchMock(); + await expect(runCloudBackup(env, { trigger: 'manual' })).rejects.toThrow(/WebDAV 服务器地址/); + const state = await env.SUBSCRIPTIONS_KV.get('cloud_backup_state', 'json'); + expect(state.lastStatus).toBe('failed'); + expect(state.lastMessage).toMatch(/WebDAV/); + }); +}); + +describe('连接测试', () => { + it('WebDAV:建目录 + 列目录即成功', async () => { + await seedConfig({ BACKUP_PROVIDER: 'webdav' }); + installFetchMock({ PROPFIND: () => new Response(propfindXml([]), { status: 207 }) }); + const result = await testCloudBackupTarget(env); + expect(result.provider).toBe('webdav'); + expect(result.message).toContain('WebDAV'); + }); + + it('S3:列对象失败时透出错误', async () => { + await seedConfig({ BACKUP_PROVIDER: 's3' }); + installFetchMock({ + GET: ({ url }) => + new URL(url).searchParams.get('list-type') === '2' + ? new Response('denied', { status: 403 }) + : new Response('{}', { status: 200 }) + }); + await expect(testCloudBackupTarget(env)).rejects.toThrow(/S3 备份失败|HTTP 403/); + }); +}); + +describe('定时备份', () => { + it('未启用时跳过', async () => { + await seedConfig({ BACKUP_ENABLED: false }); + expect((await maybeRunScheduledBackup(env)).reason).toBe('disabled'); + }); + + it('小时不匹配时跳过', async () => { + await seedConfig({ BACKUP_ENABLED: true, BACKUP_SCHEDULE: 'daily', BACKUP_HOUR: 3 }); + const result = await maybeRunScheduledBackup(env, new Date('2026-12-03T12:00:00.000Z')); + expect(result.ran).toBe(false); + expect(result.reason).toBe('hour-mismatch'); + }); + + it('到点执行一次,同一天第二次跳过', async () => { + await seedConfig({ BACKUP_ENABLED: true, BACKUP_SCHEDULE: 'daily', BACKUP_HOUR: 3 }); + installFetchMock(); + + // 2026-12-03T19:00:00Z = 北京时间 12-04 03:00 + const now = new Date('2026-12-03T19:00:00.000Z'); + const first = await maybeRunScheduledBackup(env, now); + expect(first.ran).toBe(true); + expect(first.file).toMatch(/^substracker-backup-20261204-030000\.json$/); + + const second = await maybeRunScheduledBackup(env, new Date('2026-12-03T19:10:00.000Z')); + expect(second.ran).toBe(false); + expect(second.reason).toBe('already-ran-today'); + }); + + it('每周模式只在指定星期执行', async () => { + await seedConfig({ + BACKUP_ENABLED: true, + BACKUP_SCHEDULE: 'weekly', + BACKUP_HOUR: 3, + BACKUP_WEEKLY_DAY: 5 + }); + installFetchMock(); + // 2026-12-03T19:00Z = 北京时间 12-04(周五) + const friday = await maybeRunScheduledBackup(env, new Date('2026-12-03T19:00:00.000Z')); + expect(friday.ran).toBe(true); + + await clearKv(); + await seedConfig({ + BACKUP_ENABLED: true, + BACKUP_SCHEDULE: 'weekly', + BACKUP_HOUR: 3, + BACKUP_WEEKLY_DAY: 1 + }); + installFetchMock(); + const notMonday = await maybeRunScheduledBackup(env, new Date('2026-12-03T19:00:00.000Z')); + expect(notMonday.reason).toBe('weekday-mismatch'); + }); +}); + +describe('加密备份(AES-256-GCM)', () => { + it('没设密码时不加密,直接上传明文', async () => { + await seedConfig({ CLOUD_BACKUP_ENCRYPT_PASSWORD: '' }); + const { calls } = installFetchMock(); + const result = await runCloudBackup(env, { trigger: 'manual' }); + expect(result.encrypted).toBe(false); + const put = calls.find((call) => call.method === 'PUT'); + expect(JSON.parse(put.body).format).toBe('substracker-backup'); + }); + + it('包含密钥但没设密码 → 拒绝执行', async () => { + await seedConfig({ CLOUD_BACKUP_SCOPE: 'settings', CLOUD_BACKUP_INCLUDE_SECRETS: true }); + installFetchMock(); + await expect(runCloudBackup(env, { trigger: 'manual' })).rejects.toThrow(/密码/); + }); + + it('上传内容是加密信封,且恢复时用保存的密码解密', async () => { + await seedConfig({ + BACKUP_PROVIDER: 'webdav', + CLOUD_BACKUP_ENCRYPT_PASSWORD: 'backup-pass-123', + BACKUP_RETENTION: 2 + }); + + let uploaded = ''; + const fileName = 'substracker-backup-20261203-110000.json'; + const href = `${WEBDAV_BASE}/SubsTracker/${fileName}`; + installFetchMock({ + PUT: ({ body }) => { + uploaded = String(body); + return new Response('', { status: 201 }); + }, + PROPFIND: () => + new Response(propfindXml([{ href, size: uploaded.length, modified: 'Wed, 03 Dec 2026 03:00:00 GMT' }]), { + status: 207 + }), + GET: () => new Response(uploaded, { status: 200 }) + }); + + const result = await runCloudBackup(env, { + trigger: 'manual', + now: new Date('2026-12-03T03:00:00.000Z') + }); + expect(result.encrypted).toBe(true); + expect(result.file).toBe(fileName); + + const envelope = JSON.parse(uploaded); + expect(envelope.format).toBe('substracker-backup-encrypted'); + expect(uploaded).not.toContain('super-secret-token'); + + const restored = await restoreFromCloudBackup(env, { file: fileName, mode: 'merge' }); + expect(restored.encrypted).toBe(true); + }); + + it('密码不对时恢复失败并提示密码问题', async () => { + await seedConfig({ CLOUD_BACKUP_ENCRYPT_PASSWORD: 'backup-pass-123' }); + const { encryptBackupText } = await import('../../src/services/backup/crypto.js'); + const envelope = await encryptBackupText('{"format":"substracker-backup","subscriptions":[]}', 'right-pass'); + + const fileName = 'substracker-backup-20261203-110000.json'; + const href = `${WEBDAV_BASE}/SubsTracker/${fileName}`; + installFetchMock({ + PROPFIND: () => new Response(propfindXml([{ href, size: 10, modified: 'Wed, 03 Dec 2026 03:00:00 GMT' }]), { status: 207 }), + GET: () => new Response(envelope, { status: 200 }) + }); + + await expect( + restoreFromCloudBackup(env, { file: fileName, mode: 'merge', password: 'wrong-pass' }) + ).rejects.toThrow(/解密失败/); + }); +}); + +describe('listCloudBackups / restoreFromCloudBackup', () => { + it('列表只保留本项目前缀并按时间倒序', async () => { + await seedConfig({ BACKUP_PROVIDER: 'webdav' }); + installFetchMock({ + PROPFIND: () => + new Response( + propfindXml([ + { href: '/dav/SubsTracker/substracker-backup-20261201-030000.json', size: 1, modified: 'a' }, + { href: '/dav/SubsTracker/substracker-backup-20261203-030000.json', size: 3, modified: 'c' }, + { href: '/dav/SubsTracker/other-file.json', size: 2, modified: 'b' } + ]), + { status: 207 } + ) + }); + + const files = await listCloudBackups(env); + expect(files.map((file) => file.name)).toEqual([ + 'substracker-backup-20261203-030000.json', + 'substracker-backup-20261201-030000.json' + ]); + }); + + it('恢复时找不到文件 → 404', async () => { + await seedConfig({ BACKUP_PROVIDER: 'webdav' }); + installFetchMock(); + await expect(restoreFromCloudBackup(env, { file: 'substracker-backup-20250101-000000.json' })).rejects.toThrow( + /找不到/ + ); + }); + + it('从远端备份恢复订阅', async () => { + await seedConfig({ BACKUP_PROVIDER: 'webdav' }); + const backupPayload = { + format: 'substracker-backup', + version: 1, + exportedAt: '2026-12-03T00:00:00.000Z', + config: { TG_CHAT_ID: '999' }, + categories: ['视频'], + subscriptions: [ + { + id: 'remote-1', + name: 'RemoteSub', + expiryDate: '2026-12-31T00:00:00.000Z', + isActive: true + } + ], + reminderRules: {} + }; + + installFetchMock({ + PROPFIND: () => + new Response( + propfindXml([ + { href: '/dav/SubsTracker/substracker-backup-20261203-030000.json', size: 99, modified: 'c' } + ]), + { status: 207 } + ), + GET: () => new Response(JSON.stringify(backupPayload), { status: 200 }) + }); + + const result = await restoreFromCloudBackup(env, { + file: 'substracker-backup-20261203-030000.json', + mode: 'merge' + }); + + expect(result.file).toBe('substracker-backup-20261203-030000.json'); + expect(result.subscriptions).toBe(1); + + const subs = await subRepo.listAll(env); + expect(subs.map((sub) => sub.id)).toContain('remote-1'); + }); +}); diff --git a/tests/views/config-page-cloud-backup.test.js b/tests/views/config-page-cloud-backup.test.js new file mode 100644 index 00000000..7e255ca0 --- /dev/null +++ b/tests/views/config-page-cloud-backup.test.js @@ -0,0 +1,61 @@ +// @ts-check +import { describe, expect, it } from 'vitest'; +import configPage from '../../src/views/configPage.html'; + +describe('config page backup UI', () => { + it('包含云端 / 本地两个目的地与各自的备份范围', () => { + expect(configPage).toContain('id="backupEnabled"'); + expect(configPage).toContain('id="backupProvider"'); + expect(configPage).toContain('id="backupSchedule"'); + expect(configPage).toContain('id="backupHour"'); + expect(configPage).toContain('id="backupWeeklyDay"'); + expect(configPage).toContain('id="backupRetention"'); + expect(configPage).toContain('id="cloudBackupScope"'); + expect(configPage).toContain('id="cloudIncludeSecrets"'); + expect(configPage).toContain('id="localBackupScope"'); + expect(configPage).toContain('id="localIncludeSecrets"'); + expect(configPage).toContain('id="webdavUrl"'); + expect(configPage).toContain('id="webdavPassword"'); + expect(configPage).toContain('id="s3Endpoint"'); + expect(configPage).toContain('id="s3SecretAccessKey"'); + expect(configPage).toContain('id="s3PathStyle"'); + }); + + it('包含测试 / 立即备份 / 列表 / 恢复操作区', () => { + expect(configPage).toContain('id="cloudTestBtn"'); + expect(configPage).toContain('id="cloudRunBtn"'); + expect(configPage).toContain('id="cloudFilesBtn"'); + expect(configPage).toContain('id="cloudBackupList"'); + expect(configPage).toContain('data-restore='); + expect(configPage).toContain('id="restoreModeHint"'); + }); + + it('密码输入接入脱敏状态与清空按钮(云端 / 本地独立)', () => { + expect(configPage).toContain('WEBDAV_PASSWORDStatus'); + expect(configPage).toContain('S3_SECRET_ACCESS_KEYStatus'); + expect(configPage).toContain('CLOUD_BACKUP_ENCRYPT_PASSWORDStatus'); + expect(configPage).toContain('LOCAL_BACKUP_ENCRYPT_PASSWORDStatus'); + expect(configPage).toMatch(/wireSecretInput\('webdavPassword', 'WEBDAV_PASSWORD'\)/); + expect(configPage).toMatch(/wireClearSecretButton\('clearWebdavPassword'/); + expect(configPage).toMatch(/wireClearSecretButton\('clearS3SecretAccessKey'/); + expect(configPage).toMatch(/wireClearSecretButton\('clearCloudBackupEncryptPassword'/); + expect(configPage).toMatch(/wireClearSecretButton\('clearLocalBackupEncryptPassword'/); + }); + + it('不再使用全局备份加密开关', () => { + expect(configPage).not.toContain('id="backupEncrypt"'); + expect(configPage).not.toContain('id="backupEncryptPassword"'); + expect(configPage).toContain('CLOUD_BACKUP_ENCRYPT_PASSWORD'); + expect(configPage).toContain('LOCAL_BACKUP_ENCRYPT_PASSWORD'); + expect(configPage).toContain('只填桶名,不能带 /'); + expect(configPage).toContain('路径寻址'); + }); + + it('调用云端备份接口并按存储类型切换表单', () => { + expect(configPage).toContain('/api/backup/cloud/test'); + expect(configPage).toContain('/api/backup/cloud/run'); + expect(configPage).toContain('/api/backup/cloud/files'); + expect(configPage).toContain('/api/backup/cloud/restore'); + expect(configPage).toMatch(/__applyCloudBackupVisibility/); + }); +});