dsh-cloud-backup 0.0.0-stage → 0.1.139
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +28 -0
- package/LICENSE +674 -0
- package/README.md +134 -2
- package/THIRD_PARTY.md +11 -0
- package/client.js +3060 -0
- package/cordis.patch.yml +3 -0
- package/lib/auth/adrive-local.js +17 -0
- package/lib/auth/aliyun.js +600 -0
- package/lib/auth/drive-login-state.js +240 -0
- package/lib/auth/qr-page.js +140 -0
- package/lib/engine/backups.js +341 -0
- package/lib/engine/blob.js +80 -0
- package/lib/engine/collect.js +148 -0
- package/lib/engine/host-info.js +48 -0
- package/lib/engine/host-version.js +139 -0
- package/lib/engine/lock.js +46 -0
- package/lib/engine/manifest.js +77 -0
- package/lib/engine/plugin-install.js +442 -0
- package/lib/engine/plugin-packs.js +328 -0
- package/lib/engine/prune.js +102 -0
- package/lib/engine/restart.js +172 -0
- package/lib/engine/restore.js +361 -0
- package/lib/engine/rotation.js +50 -0
- package/lib/engine/run.js +170 -0
- package/lib/index.js +1017 -0
- package/lib/providers/aliyun.js +1222 -0
- package/lib/qr.js +29 -0
- package/lib/store/config.js +63 -0
- package/lib/store/credentials.js +69 -0
- package/lib/store/paths.js +45 -0
- package/lib/store/secret.js +94 -0
- package/lib/store/state.js +17 -0
- package/lib/util/errors.js +5 -0
- package/lib/util/log.js +107 -0
- package/lib/util/proc.js +104 -0
- package/lib/util/validate.js +42 -0
- package/lib/vendor/qrcode-generator.cjs +2297 -0
- package/package.json +55 -4
package/lib/index.js
ADDED
|
@@ -0,0 +1,1017 @@
|
|
|
1
|
+
// dsh-cloud-backup 宿主侧:授权、备份与维护路由。
|
|
2
|
+
|
|
3
|
+
import fs, { readFileSync } from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
|
|
7
|
+
import { authStatus, startQrSession, pollQrSession, refreshTokens, disconnect, userGet, ensureAppFolder, ensureAccessToken, exchangeCode, openPlatformAuthorizeUrl, exchangeOpenPlatformCode, ALIPAN_OAUTH, CLIENT_ID, appFolderName, AuthError } from "./auth/aliyun.js";
|
|
8
|
+
import { qrPageHtml, oauthAuthorizeUrl } from "./auth/qr-page.js";
|
|
9
|
+
import { adoptLocalClient } from "./auth/adrive-local.js";
|
|
10
|
+
import { importRefreshToken, peekLoginState } from "./auth/drive-login-state.js";
|
|
11
|
+
import { qrSvg } from "./qr.js";
|
|
12
|
+
import { dataDir, storeDir } from "./store/paths.js";
|
|
13
|
+
import { backend } from "./store/secret.js";
|
|
14
|
+
import { loadState, saveState } from "./store/state.js";
|
|
15
|
+
import { loadConfig, saveConfig } from "./store/config.js";
|
|
16
|
+
import { runBackup, auditStore } from "./engine/run.js";
|
|
17
|
+
import { createUploader, listRemoteSnapshots, pullSnapshot, getPullProgress, pausePull, isPullPaused, cleanupRemoteOrphans, gcRemoteSnapshots, pruneRemoteSnapshots, getRemoteManifest, dropManifestCache, invalidateRemoteSnapshotCache } from "./providers/aliyun.js";
|
|
18
|
+
import { pruneLocalSnapshots } from "./engine/prune.js";
|
|
19
|
+
import { listBackups, deleteBackup, pruneCache, cacheStats, uploadBackup } from "./engine/backups.js";
|
|
20
|
+
import { compatInfo } from "./engine/host-version.js";
|
|
21
|
+
import { isStamp, isLocalOrigin, hasCsrfHeader, clampInt } from "./util/validate.js";
|
|
22
|
+
import { logInfo, logWarn, logError, tailLines, logStats, logDir, logPath, checkDownloadConsistency } from "./util/log.js";
|
|
23
|
+
import { loadCredentials, needsRefresh } from "./store/credentials.js";
|
|
24
|
+
import { listRestorable, previewRestore, restoreSnapshot, verifyRestore, snapshotTree, treeFromManifest } from "./engine/restore.js";
|
|
25
|
+
import { installPluginPacks, buildRestorePrompt, localPluginsDir } from "./engine/plugin-install.js";
|
|
26
|
+
import { detectHost, sameHost } from "./engine/host-info.js";
|
|
27
|
+
import { launchSpec, describeLaunch, restartRefusal, servingPort, scheduleRestart } from "./engine/restart.js";
|
|
28
|
+
import { readManifest, manifestPath } from "./engine/manifest.js";
|
|
29
|
+
|
|
30
|
+
// 开放平台 OAuth:state 表 + 回跳地址(用请求 Host 推导,避免端口写死)
|
|
31
|
+
const oauthStates = new Map();
|
|
32
|
+
// 同一时刻只允许一份快照在下载:进度与暂停状态是 provider 级单例,并发会让它们互相覆盖
|
|
33
|
+
let pullInFlight = null;
|
|
34
|
+
// 还原进度:面板在还原期间轮询 /status 读它;取消只置标志,停止点由 restoreSnapshot 在文件之间判定
|
|
35
|
+
let rsProgress = null;
|
|
36
|
+
function oauthCallbackUri(req, cfg) {
|
|
37
|
+
if (cfg && cfg.oauthRedirectUri) return String(cfg.oauthRedirectUri);
|
|
38
|
+
const host = String((req.headers && req.headers.host) || "127.0.0.1");
|
|
39
|
+
return "http://" + host + BASE + "/auth/oauth/callback";
|
|
40
|
+
}
|
|
41
|
+
function oauthStart(req, cfg) {
|
|
42
|
+
const callbackUri = oauthCallbackUri(req, cfg);
|
|
43
|
+
if (!cfg.oauthClientId || !cfg.oauthClientSecret) {
|
|
44
|
+
return {
|
|
45
|
+
ok: false, callbackUri,
|
|
46
|
+
hint: "还没配置开放平台 App:去阿里云盘开放平台创建应用并把回调地址填成 " + callbackUri +
|
|
47
|
+
",再把 App ID / App Secret 填进面板「开放平台 App(可选)」,即可用浏览器一键授权。",
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
for (const [k, v] of oauthStates) { if (Date.now() - v.at > 10 * 60 * 1000) oauthStates.delete(k); }
|
|
51
|
+
const state = "st-" + Date.now().toString(36) + "-" + Math.random().toString(16).slice(2, 10);
|
|
52
|
+
const redirectUri = cfg.oauthRedirectUri ? String(cfg.oauthRedirectUri) : callbackUri;
|
|
53
|
+
oauthStates.set(state, { at: Date.now(), redirectUri });
|
|
54
|
+
return { ok: true, url: openPlatformAuthorizeUrl({ clientId: cfg.oauthClientId, redirectUri, state }), redirectUri, callbackUri };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export const name = "dsh-cloud-backup";
|
|
58
|
+
export const inject = ["webServer"];
|
|
59
|
+
|
|
60
|
+
const BASE = "/api/dsh-cloud-backup";
|
|
61
|
+
const LOGIN_URL = "https://www.alipan.com/"; // 网页版首页(兜底)
|
|
62
|
+
const OAUTH_REDIRECT = "https://www.aliyundrive.com/sign/callback"; // 官方授权页的回调(注册在客户端里)
|
|
63
|
+
const LEGACY_BASE = "/dsh-cloud-backup"; // 旧版路径,保留 status 别名便于排障
|
|
64
|
+
const QR_TTL_SEC = 180;
|
|
65
|
+
const SESSION_GC_MS = 10 * 60 * 1000;
|
|
66
|
+
|
|
67
|
+
/** 进行中的扫码会话(内存态:重启即失效,符合安全直觉) */
|
|
68
|
+
const sessions = new Map();
|
|
69
|
+
|
|
70
|
+
function json(res, status, value) {
|
|
71
|
+
const body = JSON.stringify(value);
|
|
72
|
+
res.writeHead(status, {
|
|
73
|
+
"content-type": "application/json; charset=utf-8",
|
|
74
|
+
"content-length": Buffer.byteLength(body),
|
|
75
|
+
"cache-control": "no-store",
|
|
76
|
+
});
|
|
77
|
+
res.end(body);
|
|
78
|
+
}
|
|
79
|
+
const ok = (res, value = {}) => json(res, 200, { ok: true, ...value });
|
|
80
|
+
const bad = (res, status, message, extra = {}) => json(res, status, { ok: false, error: String(message), ...extra });
|
|
81
|
+
|
|
82
|
+
async function readJson(req, limit = 64 * 1024) {
|
|
83
|
+
const chunks = [];
|
|
84
|
+
let size = 0;
|
|
85
|
+
for await (const chunk of req) {
|
|
86
|
+
size += chunk.length;
|
|
87
|
+
if (size > limit) { req.resume?.(); return undefined; } // 超限也要把流读干,否则连接悬挂
|
|
88
|
+
chunks.push(chunk);
|
|
89
|
+
}
|
|
90
|
+
if (size === 0) return {};
|
|
91
|
+
try { return JSON.parse(Buffer.concat(chunks).toString("utf8")); } catch { return undefined; }
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// 路由前置守卫:统一做方法校验与来源校验
|
|
95
|
+
// 只读路由;其余一律要求 POST。非 GET 请求必须来自本机来源且 content-type 为 application/json
|
|
96
|
+
function readRuntimeOf(storeDir, stamp) {
|
|
97
|
+
try {
|
|
98
|
+
const m = readManifest(manifestPath(storeDir, stamp));
|
|
99
|
+
return (m && m.runtime) || null;
|
|
100
|
+
} catch { return null; }
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function currentHost() {
|
|
104
|
+
return detectHost({ dshHome: process.env.DSH_HOME || "", argv: process.argv, env: process.env, versions: process.versions });
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const GET_PATHS = new Set(["/plugins/prompt","/status", "/backup/status", "/backups", "/restore/snapshots", "/restore/tree", "/auth/qr/page", "/auth/oauth-url", "/auth/oauth/start", "/auth/oauth/callback", "/logs", "/restore/history"]);
|
|
108
|
+
function routeTail(p) {
|
|
109
|
+
for (const prefix of [BASE, LEGACY_BASE]) if (p.indexOf(prefix) === 0) return p.slice(prefix.length);
|
|
110
|
+
return p;
|
|
111
|
+
}
|
|
112
|
+
function guard(method, inner) {
|
|
113
|
+
return async (req, res) => {
|
|
114
|
+
try {
|
|
115
|
+
const m = String(req.method || "GET").toUpperCase();
|
|
116
|
+
if (m === "OPTIONS") return bad(res, 405, "不支持的方法");
|
|
117
|
+
if (method === "GET") {
|
|
118
|
+
if (m !== "GET" && m !== "HEAD") return bad(res, 405, "该接口只接受 GET");
|
|
119
|
+
} else {
|
|
120
|
+
if (m !== "POST") return bad(res, 405, "该接口只接受 POST");
|
|
121
|
+
if (!isLocalOrigin(req.headers && req.headers.origin)) return bad(res, 403, "跨站请求被拒绝");
|
|
122
|
+
const ct = String((req.headers && req.headers["content-type"]) || "");
|
|
123
|
+
if (ct && ct.indexOf("application/json") < 0) return bad(res, 415, "content-type 必须是 application/json");
|
|
124
|
+
// 跨站脚本无法伪造自定义头(带自定义头会先发预检,而预检被上面的 405 拒),因此这一项关掉 CSRF。
|
|
125
|
+
if (!hasCsrfHeader(req.headers)) return bad(res, 403, "缺少 CSRF 标记头(x-dshcb-csrf: 1)");
|
|
126
|
+
}
|
|
127
|
+
return await inner(req, res);
|
|
128
|
+
} catch (error) {
|
|
129
|
+
const status = error instanceof AuthError ? 400 : (error && error.status === 404) ? 404 : 500;
|
|
130
|
+
logError("route.error", { via: "guard", status, message: (error && error.message) || String(error), stack: (error && error.stack) ? String(error.stack).split("\n").slice(0, 4).join(" | ") : undefined });
|
|
131
|
+
bad(res, status, (error && error.message) || String(error));
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** 校验快照 ID(会直接拼路径),不合法直接 400 */
|
|
137
|
+
function badStamp(res, value) {
|
|
138
|
+
if (!isStamp(value)) { bad(res, 400, "非法 stamp(只接受快照 ID,如 20261028-210209)"); return true; }
|
|
139
|
+
return false;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function sweep(now = Date.now()) {
|
|
143
|
+
for (const [id, s] of sessions) if (now - s.createdAt > SESSION_GC_MS) sessions.delete(id);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** 统一包裹:任何异常都转成 JSON,避免宿主只回 500 空体 */
|
|
147
|
+
function handler(fn) {
|
|
148
|
+
return async (req, res) => {
|
|
149
|
+
try { await fn(req, res); }
|
|
150
|
+
catch (error) {
|
|
151
|
+
const status = error instanceof AuthError ? 400 : (error && error.status === 404) ? 404 : 500;
|
|
152
|
+
logError("route.error", { via: "handler", path: String((req && req.url) || ""), status, message: (error && error.message) || String(error), stack: (error && error.stack) ? String(error.stack).split("\n").slice(0, 4).join(" | ") : undefined });
|
|
153
|
+
bad(res, status, (error && error.message) || String(error));
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
let _audit = { at: 0, value: null };
|
|
159
|
+
const AUDIT_TTL_MS = 20 * 1000;
|
|
160
|
+
function safeAudit({ fresh = false } = {}) {
|
|
161
|
+
const now = Date.now();
|
|
162
|
+
if (!fresh && _audit.value && now - _audit.at < AUDIT_TTL_MS) return _audit.value;
|
|
163
|
+
try { _audit = { at: now, value: auditStore() }; } catch (e) { _audit = { at: now, value: { error: String((e && e.message) || e) } }; }
|
|
164
|
+
return _audit.value;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** 调度器运行态:给界面显示「下次自动备份」。进程内变量,宿主重启后重建。 */
|
|
168
|
+
const sched = { nextAt: 0, intervalMin: 0, running: false };
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
*/
|
|
172
|
+
function pluginVersion() {
|
|
173
|
+
try {
|
|
174
|
+
const here = fileURLToPath(new URL("../package.json", import.meta.url));
|
|
175
|
+
return JSON.parse(readFileSync(here, "utf8")).version || "0.1.0";
|
|
176
|
+
} catch {
|
|
177
|
+
return "0.1.0";
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
const VERSION = pluginVersion();
|
|
181
|
+
|
|
182
|
+
function statusPayload() {
|
|
183
|
+
const st = loadState();
|
|
184
|
+
return {
|
|
185
|
+
version: VERSION,
|
|
186
|
+
provider: "aliyun",
|
|
187
|
+
providerLabel: "阿里云盘",
|
|
188
|
+
appFolder: appFolderName(),
|
|
189
|
+
stateDir: dataDir(),
|
|
190
|
+
secretBackend: backend(),
|
|
191
|
+
folder: st.folder || null,
|
|
192
|
+
lastVerifiedAt: st.verified_at || null,
|
|
193
|
+
auth: authStatus(),
|
|
194
|
+
bootId: BOOT_ID,
|
|
195
|
+
compat: compatInfo(),
|
|
196
|
+
backup: { last: st.last_backup || null, lastRestore: st.last_restore || null,
|
|
197
|
+
needsRestart: !!(st.last_restore && st.last_restore.bootId === BOOT_ID && (st.last_restore.restored || 0) > 0),
|
|
198
|
+
audit: safeAudit(), config: loadConfig(), host: currentHost() },
|
|
199
|
+
schedule: {
|
|
200
|
+
enabled: loadConfig().enabled !== false,
|
|
201
|
+
intervalMinutes: Number(loadConfig().intervalMinutes) || 60,
|
|
202
|
+
nextAt: sched.nextAt ? new Date(sched.nextAt).toISOString() : null,
|
|
203
|
+
running: !!sched.running,
|
|
204
|
+
},
|
|
205
|
+
restore: { dshHome: process.env.DSH_HOME || "", defaultTarget: "", progress: rsProgress },
|
|
206
|
+
pull: getPullProgress(),
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// 每次进程启动生成一个标识:面板据此判断“还原之后有没有重启过”
|
|
211
|
+
const BOOT_ID = Date.now().toString(36) + "-" + Math.random().toString(36).slice(2, 8);
|
|
212
|
+
const HISTORY_MAX = 10; // 只留最近 10 条还原记录(够回溯,也不让弹窗无限长)
|
|
213
|
+
|
|
214
|
+
function historyPath() { return path.join(dataDir(), "restore-history.json"); }
|
|
215
|
+
|
|
216
|
+
function readRestoreHistory() {
|
|
217
|
+
try {
|
|
218
|
+
const j = JSON.parse(fs.readFileSync(historyPath(), "utf8"));
|
|
219
|
+
return Array.isArray(j.items) ? j.items : [];
|
|
220
|
+
} catch { return []; }
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function appendRestoreHistory(entry) {
|
|
224
|
+
try {
|
|
225
|
+
const items = [entry].concat(readRestoreHistory()).slice(0, HISTORY_MAX);
|
|
226
|
+
fs.mkdirSync(path.dirname(historyPath()), { recursive: true });
|
|
227
|
+
fs.writeFileSync(historyPath(), JSON.stringify({ v: 1, items }, null, 2));
|
|
228
|
+
return true;
|
|
229
|
+
} catch (e) { logWarn("restore.history.fail", { message: (e && e.message) || String(e) }); return false; }
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function storeDirHint() { return process.env.DSH_CLOUD_BACKUP_STORE || ""; }
|
|
233
|
+
|
|
234
|
+
export function apply(ctx) {
|
|
235
|
+
const logger = ctx.logger ?? console;
|
|
236
|
+
try { logInfo("plugin.start", { pid: process.pid, node: process.version, platform: process.platform + "/" + process.arch, dshHome: process.env.DSH_HOME || "", store: storeDirHint() }); } catch {}
|
|
237
|
+
|
|
238
|
+
// 预热:把凭据解密、state 读取、最新快照清单读进缓存,面板第一次 /status 不必替我们付冷启动的钱
|
|
239
|
+
setTimeout(function () {
|
|
240
|
+
try {
|
|
241
|
+
authStatus();
|
|
242
|
+
loadState();
|
|
243
|
+
const list = listBackups({ storeDir: storeDirHint() });
|
|
244
|
+
const first = (list && list.items && list.items[0]) || null;
|
|
245
|
+
if (first) snapshotTree({ stamp: first.stamp, depth: 1 });
|
|
246
|
+
} catch (e) { /* 预热失败不影响功能 */ }
|
|
247
|
+
}, 200);
|
|
248
|
+
|
|
249
|
+
ctx.inject(["webServer"], (sctx) => {
|
|
250
|
+
sctx.effect(() => {
|
|
251
|
+
const routes = [
|
|
252
|
+
{
|
|
253
|
+
kind: "exact", path: BASE + "/restore/history",
|
|
254
|
+
handler: handler(async (req, res) => ok(res, { items: readRestoreHistory(), bootId: BOOT_ID })),
|
|
255
|
+
},
|
|
256
|
+
{
|
|
257
|
+
kind: "exact", path: BASE + "/logs",
|
|
258
|
+
handler: handler(async (req, res) => {
|
|
259
|
+
const q = String(req.url || "");
|
|
260
|
+
const at = q.indexOf("tail=");
|
|
261
|
+
const n = at >= 0 ? Number(q.slice(at + 5).split("&")[0]) : 300;
|
|
262
|
+
const st = logStats();
|
|
263
|
+
ok(res, { ok: true, path: st.file, dir: st.dir, bytes: st.bytes, rotatedBytes: st.rotatedBytes, lines: tailLines(n) });
|
|
264
|
+
}),
|
|
265
|
+
},
|
|
266
|
+
{
|
|
267
|
+
kind: "exact", path: BASE + "/logs/open",
|
|
268
|
+
handler: handler(async (req, res) => {
|
|
269
|
+
const dir = logDir();
|
|
270
|
+
const cp = await import("node:child_process");
|
|
271
|
+
const cmd = process.platform === "win32" ? ["explorer.exe", [dir]] : process.platform === "darwin" ? ["open", [dir]] : ["xdg-open", [dir]];
|
|
272
|
+
try {
|
|
273
|
+
const child = cp.spawn(cmd[0], cmd[1], { detached: true, stdio: "ignore" });
|
|
274
|
+
child.unref();
|
|
275
|
+
} catch (e) {
|
|
276
|
+
logWarn("logs.open.fail", { message: (e && e.message) || String(e) });
|
|
277
|
+
}
|
|
278
|
+
logInfo("logs.open", { dir });
|
|
279
|
+
ok(res, { ok: true, dir, file: logPath() });
|
|
280
|
+
}),
|
|
281
|
+
},
|
|
282
|
+
{
|
|
283
|
+
kind: "exact", path: BASE + "/status",
|
|
284
|
+
handler: handler(async (req, res) => {
|
|
285
|
+
sweep();
|
|
286
|
+
// 自愈放到后台:读状态不能被网络与 DPAPI 解密拖慢
|
|
287
|
+
try {
|
|
288
|
+
const c = loadCredentials();
|
|
289
|
+
if (c && needsRefresh(c)) ensureAccessToken().catch(() => {});
|
|
290
|
+
} catch {}
|
|
291
|
+
ok(res, statusPayload());
|
|
292
|
+
}),
|
|
293
|
+
},
|
|
294
|
+
{
|
|
295
|
+
kind: "exact", path: BASE + "/auth/qr/start",
|
|
296
|
+
handler: handler(async (req, res) => {
|
|
297
|
+
sweep();
|
|
298
|
+
const body = await readJson(req);
|
|
299
|
+
if (body === undefined) return bad(res, 400, "请求体不是合法 JSON");
|
|
300
|
+
// 每次只保留一个活跃会话,避免多个二维码同时被扫
|
|
301
|
+
for (const [oldId, oldS] of sessions) { if (Date.now() - oldS.createdAt > oldS.expireMs + 30_000) sessions.delete(oldId); }
|
|
302
|
+
while (sessions.size > 4) { const firstKey = sessions.keys().next().value; sessions.delete(firstKey); }
|
|
303
|
+
const session = await startQrSession();
|
|
304
|
+
sessions.set(session.id, session);
|
|
305
|
+
const hostHdr = String((req.headers && (req.headers.host || req.headers.Host)) || "127.0.0.1");
|
|
306
|
+
const absBase = "http://" + hostHdr;
|
|
307
|
+
const pagePath = BASE + "/auth/qr/page?session=" + encodeURIComponent(session.id);
|
|
308
|
+
const svg = qrSvg(session.codeContent, { cellSize: 4, margin: 2, alt: "阿里云盘登录二维码" });
|
|
309
|
+
const dataUrl = "data:image/svg+xml;base64," + Buffer.from(svg, "utf8").toString("base64");
|
|
310
|
+
logger.info?.(`[dsh-cloud-backup] QR session ${session.id} created`);
|
|
311
|
+
ok(res, {
|
|
312
|
+
sessionId: session.id, qr: dataUrl, qrUrl: session.codeContent, loginUrl: LOGIN_URL,
|
|
313
|
+
pageUrl: pagePath, pageUrlAbs: absBase + pagePath,
|
|
314
|
+
oauthUrl: null,
|
|
315
|
+
expiresInSec: QR_TTL_SEC,
|
|
316
|
+
hint: "用阿里云盘 App 扫码确认;也可以用本机浏览器打开登录页确认(浏览器已登录阿里云盘时最快)",
|
|
317
|
+
});
|
|
318
|
+
}),
|
|
319
|
+
},
|
|
320
|
+
{
|
|
321
|
+
kind: "exact", path: BASE + "/auth/qr/poll",
|
|
322
|
+
handler: handler(async (req, res) => {
|
|
323
|
+
const body = await readJson(req);
|
|
324
|
+
if (!body || !body.sessionId) return bad(res, 400, "缺少 sessionId");
|
|
325
|
+
const session = sessions.get(body.sessionId);
|
|
326
|
+
if (!session) return ok(res, { status: "expired", reason: "会话不存在或已失效,请重新生成二维码" });
|
|
327
|
+
const r = await pollQrSession(session);
|
|
328
|
+
const nextPollMs = r.status === "connecting" ? 700 : (r.status === "scanned" ? 800 : 2000);
|
|
329
|
+
// 令牌在 pollQrSession 内只解析一次并落库;这里只“汇报”,而且不再删会话。
|
|
330
|
+
if (r.status === "confirmed") {
|
|
331
|
+
let folder = null;
|
|
332
|
+
try { folder = await ensureAppFolder(); saveState({ folder }); } catch (e) { logger.warn?.(("[dsh-cloud-backup] ensureAppFolder failed: " + ((e && e.message) || e))); }
|
|
333
|
+
return ok(res, { status: "connected", account: r.account, auth: authStatus(), folder, nextPollMs: 0, done: true });
|
|
334
|
+
}
|
|
335
|
+
if (r.status === "failed") {
|
|
336
|
+
return ok(res, { status: "failed", reason: r.reason, diagPath: r.diagPath, bizExtRawPath: r.bizExtRawPath, nextPollMs: 0 });
|
|
337
|
+
}
|
|
338
|
+
ok(res, { status: r.status, raw: r.raw, attempt: r.attempt, diagPath: r.diagPath, nextPollMs });
|
|
339
|
+
}),
|
|
340
|
+
},
|
|
341
|
+
{
|
|
342
|
+
kind: "exact", path: BASE + "/auth/qr/page",
|
|
343
|
+
handler: handler(async (req, res) => {
|
|
344
|
+
const url = new URL(String(req.url || "/"), "http://localhost");
|
|
345
|
+
const id = url.searchParams.get("session") || "";
|
|
346
|
+
const session = sessions.get(id);
|
|
347
|
+
const svg = session ? qrSvg(session.codeContent, { cellSize: 6, margin: 3, alt: "阿里云盘登录二维码" }) : "";
|
|
348
|
+
const dataUrl = session ? "data:image/svg+xml;base64," + Buffer.from(svg, "utf8").toString("base64") : "";
|
|
349
|
+
const html = qrPageHtml({
|
|
350
|
+
sessionId: session ? id : "",
|
|
351
|
+
qr: dataUrl,
|
|
352
|
+
apiBase: BASE,
|
|
353
|
+
expiresInSec: QR_TTL_SEC,
|
|
354
|
+
oauthUrl: oauthAuthorizeUrl(CLIENT_ID, OAUTH_REDIRECT),
|
|
355
|
+
});
|
|
356
|
+
const buf = Buffer.from(html, "utf8");
|
|
357
|
+
res.writeHead(200, {
|
|
358
|
+
"content-type": "text/html; charset=utf-8",
|
|
359
|
+
"content-length": buf.length,
|
|
360
|
+
"cache-control": "no-store",
|
|
361
|
+
});
|
|
362
|
+
res.end(buf);
|
|
363
|
+
}),
|
|
364
|
+
},
|
|
365
|
+
{
|
|
366
|
+
kind: "exact", path: BASE + "/auth/oauth-url",
|
|
367
|
+
handler: handler(async (req, res) => {
|
|
368
|
+
const cfg = loadConfig();
|
|
369
|
+
const start = oauthStart(req, cfg);
|
|
370
|
+
if (!start.ok) return ok(res, { ok: true, needConfig: true, callbackUri: start.callbackUri, hint: start.hint, scope: ALIPAN_OAUTH.scope });
|
|
371
|
+
ok(res, { ok: true, url: start.url, redirectUri: start.redirectUri, scope: ALIPAN_OAUTH.scope });
|
|
372
|
+
}),
|
|
373
|
+
},
|
|
374
|
+
{
|
|
375
|
+
kind: "exact", path: BASE + "/auth/oauth/start",
|
|
376
|
+
handler: handler(async (req, res) => {
|
|
377
|
+
const cfg = loadConfig();
|
|
378
|
+
const start = oauthStart(req, cfg);
|
|
379
|
+
if (!start.ok) return bad(res, 400, start.hint);
|
|
380
|
+
ok(res, { ok: true, url: start.url, redirectUri: start.redirectUri, scope: ALIPAN_OAUTH.scope });
|
|
381
|
+
}),
|
|
382
|
+
},
|
|
383
|
+
{
|
|
384
|
+
kind: "exact", path: BASE + "/auth/oauth/callback",
|
|
385
|
+
handler: handler(async (req, res) => {
|
|
386
|
+
const url = new URL(String(req.url || "/"), "http://localhost");
|
|
387
|
+
const code = url.searchParams.get("code") || "";
|
|
388
|
+
const state = url.searchParams.get("state") || "";
|
|
389
|
+
const err = url.searchParams.get("error") || "";
|
|
390
|
+
const cfg = loadConfig();
|
|
391
|
+
const cbUri = oauthCallbackUri(req, cfg);
|
|
392
|
+
const escHtml = (v) => String(v === undefined || v === null ? "" : v).replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]));
|
|
393
|
+
const page = (titleIn, bodyIn, tone) => {
|
|
394
|
+
const title = escHtml(titleIn);
|
|
395
|
+
const body = escHtml(bodyIn);
|
|
396
|
+
const color = tone === "ok" ? "#0a7d32" : "#b42318";
|
|
397
|
+
res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
|
|
398
|
+
res.end("<!doctype html><html lang=\"zh-CN\"><head><meta charset=\"utf-8\"><title>" + title + "</title>" +
|
|
399
|
+
"<style>body{font:14px/1.7 -apple-system,Segoe UI,Microsoft YaHei,sans-serif;background:#fff;color:#1b1c1e;display:flex;min-height:100vh;align-items:center;justify-content:center;margin:0}" +
|
|
400
|
+
".c{max-width:520px;padding:28px 30px;border:1px solid #e6e7eb;border-radius:14px}.t{font-size:18px;font-weight:600;color:" + color + "}" +
|
|
401
|
+
".b{margin-top:10px;color:#3c4046;white-space:pre-wrap;word-break:break-word}.h{margin-top:14px;color:#6b6f76;font-size:12.5px}</style></head><body>" +
|
|
402
|
+
"<div class=c><div class=t>" + title + "</div><div class=b>" + body + "</div><div class=h>本页由本机 DSH(云盘备份插件)提供,可以关闭。</div></div></body></html>");
|
|
403
|
+
};
|
|
404
|
+
if (err) return page("授权被拒绝", "阿里云盘返回:" + err + "\n可以关掉本页,回到 DSH 面板重试。", "err");
|
|
405
|
+
if (!code) return page("缺少授权码", "回调地址里没有 code。请从「用开放平台 App 授权」重新发起一次。", "err");
|
|
406
|
+
const st = oauthStates.get(state);
|
|
407
|
+
if (!st) return page("授权会话已失效", "state 校验不通过(可能超过 10 分钟,或不是在同一个 DSH 实例里发起)。请重新发起授权。", "err");
|
|
408
|
+
oauthStates.delete(state);
|
|
409
|
+
try {
|
|
410
|
+
const creds = await exchangeOpenPlatformCode({ code, clientId: cfg.oauthClientId, clientSecret: cfg.oauthClientSecret, redirectUri: st.redirectUri || cbUri });
|
|
411
|
+
let folder = null;
|
|
412
|
+
try { folder = await ensureAppFolder(); saveState({ folder }); } catch (e) {}
|
|
413
|
+
saveState({ last_oauth: { at: new Date().toISOString(), ok: true, account: (creds && creds.nick_name) || null } });
|
|
414
|
+
page("登录成功", "已自动完成授权" + (creds && creds.nick_name ? ":" + creds.nick_name : "") + (folder && (folder.name || folder) ? "\n云端目录:" + (folder.name || folder) : "") + "\nDSH 面板会立刻显示「已连接」。", "ok");
|
|
415
|
+
} catch (e) {
|
|
416
|
+
const msg = (e && e.message) || String(e);
|
|
417
|
+
saveState({ last_oauth: { at: new Date().toISOString(), ok: false, error: msg } });
|
|
418
|
+
page("授权失败", msg + "\n\n常见原因:App ID/Secret 不对;回调地址与开放平台后台登记的不一致;该 App 未开通对应 scope。", "err");
|
|
419
|
+
}
|
|
420
|
+
}),
|
|
421
|
+
},
|
|
422
|
+
{
|
|
423
|
+
kind: "exact", path: BASE + "/auth/code",
|
|
424
|
+
handler: handler(async (req, res) => {
|
|
425
|
+
const body = await readJson(req);
|
|
426
|
+
if (!body || !body.code) return bad(res, 400, "缺少 code(从浏览器地址栏 code= 后面那段复制出来)");
|
|
427
|
+
const code = String(body.code).trim();
|
|
428
|
+
if (!/^[A-Za-z0-9._~\-+=]{8,512}$/.test(code)) return bad(res, 400, "code 形态不合法");
|
|
429
|
+
const creds = await exchangeCode(code);
|
|
430
|
+
let folder = null;
|
|
431
|
+
try { folder = await ensureAppFolder(); saveState({ folder }); } catch { /* 不影响授权结果 */ }
|
|
432
|
+
logger.info?.("[dsh-cloud-backup] 授权码登录成功(user_id=" + (creds && creds.user_id) + ")");
|
|
433
|
+
const auth = authStatus();
|
|
434
|
+
ok(res, { account: auth.account || null, auth, folder });
|
|
435
|
+
}),
|
|
436
|
+
},
|
|
437
|
+
{
|
|
438
|
+
kind: "exact", path: BASE + "/auth/refresh",
|
|
439
|
+
handler: handler(async (req, res) => {
|
|
440
|
+
await refreshTokens();
|
|
441
|
+
ok(res, { auth: authStatus() });
|
|
442
|
+
}),
|
|
443
|
+
},
|
|
444
|
+
{
|
|
445
|
+
// 免扫码捷径:读本机已登录的阿里云盘客户端登录态(只读本机文件,用户点一下才跑)
|
|
446
|
+
kind: "exact", path: BASE + "/auth/import-local",
|
|
447
|
+
handler: handler(async (req, res) => {
|
|
448
|
+
const body = await readJson(req);
|
|
449
|
+
if (body === undefined) return bad(res, 400, "请求体不是合法 JSON");
|
|
450
|
+
const r = await adoptLocalClient({ logger, minMtimeMs: Number(body.since) > 0 ? Number(body.since) : 0 });
|
|
451
|
+
if (!r.ok) return bad(res, 400, r.error || "未在本机找到可用的阿里云盘登录态", { found: r.found, tried: r.tried });
|
|
452
|
+
let folder = null;
|
|
453
|
+
try {
|
|
454
|
+
folder = await ensureAppFolder();
|
|
455
|
+
saveState({ folder, verified_at: new Date().toISOString() });
|
|
456
|
+
} catch (e) { logger.warn?.("[dsh-cloud-backup] ensureAppFolder failed after import: " + ((e && e.message) || e)); }
|
|
457
|
+
logger.info?.("[dsh-cloud-backup] imported local client session (tried " + r.tried + ")");
|
|
458
|
+
ok(res, { imported: true, source: r.source, tried: r.tried, account: r.account, folder, auth: authStatus() });
|
|
459
|
+
}),
|
|
460
|
+
},
|
|
461
|
+
|
|
462
|
+
{
|
|
463
|
+
// 等待浏览器登录:只回答「有没有比 since 更新的登录态」,不换令牌、不发网络
|
|
464
|
+
kind: "exact", path: BASE + "/auth/watch-local",
|
|
465
|
+
handler: handler(async (req, res) => {
|
|
466
|
+
const body = (await readJson(req)) || {};
|
|
467
|
+
const since = Number(body.since) > 0 ? Number(body.since) : 0;
|
|
468
|
+
const r = peekLoginState({ minMtimeMs: since });
|
|
469
|
+
ok(res, { since, found: r.found, kind: r.kind, source: r.source, mtimeMs: r.mtimeMs, total: r.total });
|
|
470
|
+
}),
|
|
471
|
+
},
|
|
472
|
+
{
|
|
473
|
+
kind: "exact", path: BASE + "/auth/import-token",
|
|
474
|
+
handler: handler(async (req, res) => {
|
|
475
|
+
const body = await readJson(req);
|
|
476
|
+
if (body === undefined) return bad(res, 400, "请求体不是合法 JSON");
|
|
477
|
+
const rt = body && body.refreshToken;
|
|
478
|
+
const r = await importRefreshToken(rt, { logger, clientId: String((body && body.clientId) || "") });
|
|
479
|
+
if (!r.ok) return bad(res, 400, r.error || "导入失败", { tried: r.tried });
|
|
480
|
+
let folder = null;
|
|
481
|
+
try {
|
|
482
|
+
folder = await ensureAppFolder();
|
|
483
|
+
saveState({ folder, verified_at: new Date().toISOString() });
|
|
484
|
+
} catch (e) { logger.warn?.("[dsh-cloud-backup] ensureAppFolder failed after token import: " + ((e && e.message) || e)); }
|
|
485
|
+
logger.info?.("[dsh-cloud-backup] imported refresh_token from user input");
|
|
486
|
+
ok(res, { imported: true, account: r.account, folder, auth: authStatus() });
|
|
487
|
+
}),
|
|
488
|
+
},
|
|
489
|
+
{
|
|
490
|
+
kind: "exact", path: BASE + "/auth/verify",
|
|
491
|
+
handler: handler(async (req, res) => {
|
|
492
|
+
const at = await userGet(await (await import("./auth/aliyun.js")).ensureAccessToken());
|
|
493
|
+
const folder = await ensureAppFolder();
|
|
494
|
+
saveState({ folder, verified_at: new Date().toISOString() });
|
|
495
|
+
ok(res, { auth: authStatus(), folder, user: { user_id: at.user_id, name: at.name, nick_name: at.nick_name } });
|
|
496
|
+
}),
|
|
497
|
+
},
|
|
498
|
+
{
|
|
499
|
+
kind: "exact", path: BASE + "/auth/logout",
|
|
500
|
+
handler: handler(async (req, res) => {
|
|
501
|
+
const logoutBody = (await readJson(req)) || {};
|
|
502
|
+
if (logoutBody.confirm !== true) return bad(res, 400, "退出登录需要确认(confirm: true)");
|
|
503
|
+
dropManifestCache(); // 换了凭证/断开:旧清单不可信
|
|
504
|
+
disconnect();
|
|
505
|
+
sessions.clear();
|
|
506
|
+
logger.info?.("[dsh-cloud-backup] disconnected");
|
|
507
|
+
ok(res, { auth: authStatus() });
|
|
508
|
+
}),
|
|
509
|
+
},
|
|
510
|
+
{
|
|
511
|
+
kind: "exact", path: BASE + "/backup/status",
|
|
512
|
+
handler: handler(async (req, res) => {
|
|
513
|
+
const cfgOut = { ...loadConfig() };
|
|
514
|
+
if (cfgOut.oauthClientSecret) { cfgOut.hasOauthSecret = true; cfgOut.oauthClientSecret = ""; }
|
|
515
|
+
ok(res, { config: cfgOut, audit: safeAudit(), last: loadState().last_backup || null, lastRestore: loadState().last_restore || null });
|
|
516
|
+
}),
|
|
517
|
+
},
|
|
518
|
+
{
|
|
519
|
+
kind: "exact", path: BASE + "/backup/run",
|
|
520
|
+
handler: handler(async (req, res) => {
|
|
521
|
+
const body = (await readJson(req)) || {};
|
|
522
|
+
const auth = authStatus();
|
|
523
|
+
if (!auth.connected) return bad(res, 400, "未连接云盘,无法备份");
|
|
524
|
+
if (body.confirm !== true) return bad(res, 400, "启动备份需要确认(confirm: true)");
|
|
525
|
+
const uploader = body.upload === false ? null : createUploader({ logger });
|
|
526
|
+
logger.info?.("[dsh-cloud-backup] manual backup start (upload=" + (!!uploader) + ")");
|
|
527
|
+
const result = await runBackup({
|
|
528
|
+
trigger: body.trigger || "manual",
|
|
529
|
+
forceUpload: body.upload === true,
|
|
530
|
+
uploader,
|
|
531
|
+
logger: (m) => logger.info?.("[dsh-cloud-backup] " + m),
|
|
532
|
+
});
|
|
533
|
+
logger.info?.("[dsh-cloud-backup] manual backup done: " + JSON.stringify({ ok: result.ok, files: result.files, new: result.newBlobs, upload: result.upload && result.upload.ok }));
|
|
534
|
+
// 上传成功才顺手清云端孤儿目录(只删没有 manifest 的空壳,有清单的一律不动)
|
|
535
|
+
let orphans = null;
|
|
536
|
+
if (uploader && result.upload && result.upload.ok) {
|
|
537
|
+
try { orphans = await cleanupRemoteOrphans({ logger: (m) => logger.info?.("[dsh-cloud-backup] " + m) }); }
|
|
538
|
+
catch (e) { logger.warn?.("[dsh-cloud-backup] orphan cleanup skipped: " + ((e && e.message) || e)); }
|
|
539
|
+
}
|
|
540
|
+
ok(res, { result, orphans, audit: safeAudit(), last: loadState().last_backup || null });
|
|
541
|
+
}),
|
|
542
|
+
},
|
|
543
|
+
{
|
|
544
|
+
kind: "exact", path: BASE + "/backup/config",
|
|
545
|
+
handler: handler(async (req, res) => {
|
|
546
|
+
const body = await readJson(req);
|
|
547
|
+
if (!body) return bad(res, 400, "请求体不是合法 JSON");
|
|
548
|
+
const next = saveConfig(body);
|
|
549
|
+
ok(res, { config: next });
|
|
550
|
+
}),
|
|
551
|
+
},
|
|
552
|
+
{
|
|
553
|
+
kind: "exact", path: BASE + "/restore/snapshots",
|
|
554
|
+
handler: handler(async (req, res) => {
|
|
555
|
+
const url = new URL(req.url, "http://127.0.0.1");
|
|
556
|
+
let remote = null;
|
|
557
|
+
if (url.searchParams.get("remote") === "1") {
|
|
558
|
+
// fresh=1:跳过云端清单缓存,切换视图/删除后立刻看到最新
|
|
559
|
+
const fresh = url.searchParams.get("fresh") === "1";
|
|
560
|
+
try { remote = await listRemoteSnapshots({ fresh }); } catch (e) { remote = { ok: false, error: String((e && e.message) || e), snapshots: [] }; }
|
|
561
|
+
}
|
|
562
|
+
ok(res, { local: listRestorable({}), remote, dshHome: process.env.DSH_HOME || "" });
|
|
563
|
+
}),
|
|
564
|
+
},
|
|
565
|
+
{
|
|
566
|
+
kind: "exact", path: BASE + "/plugins/prompt",
|
|
567
|
+
handler: handler(async (req, res) => {
|
|
568
|
+
const u = new URL(req.url || "", "http://x");
|
|
569
|
+
const stamp = u.searchParams.get("stamp") || "";
|
|
570
|
+
if (!stamp) return bad(res, 400, "缺少 stamp");
|
|
571
|
+
if (badStamp(res, stamp)) return;
|
|
572
|
+
let man = null;
|
|
573
|
+
const local = snapshotTree({ stamp, depth: 1 });
|
|
574
|
+
if (local && local.ok) man = { plugins: local.plugins || [] };
|
|
575
|
+
else if (authStatus().connected) {
|
|
576
|
+
const got = await getRemoteManifest(stamp);
|
|
577
|
+
man = got && got.manifest ? got.manifest : null;
|
|
578
|
+
}
|
|
579
|
+
if (!man) return bad(res, 400, "拿不到该快照的清单(先同步或下载这份快照)");
|
|
580
|
+
const plugins = (Array.isArray(man.plugins) ? man.plugins : []).map((p) => ({
|
|
581
|
+
name: p.name, version: p.version, state: p.state, spec: p.spec || null,
|
|
582
|
+
source_kind: p.source_kind || null, profiles: p.profiles || [], blob: p.blob || null,
|
|
583
|
+
}));
|
|
584
|
+
const raw = u.searchParams.get("profiles");
|
|
585
|
+
const profiles = raw ? raw.split(",").map((x) => x.trim()).filter(Boolean).slice(0, 10) : [];
|
|
586
|
+
const text = buildRestorePrompt({
|
|
587
|
+
stamp, plugins, profiles,
|
|
588
|
+
fromProfile: (function () { const sd2 = storeDirHint(); const rt = (sd2 && stamp) ? readRuntimeOf(sd2, stamp) : null; return (rt && rt.profile) || null; })(),
|
|
589
|
+
toProfile: currentHost().profile,
|
|
590
|
+
tarballDir: localPluginsDir(process.env.DSH_HOME || ""),
|
|
591
|
+
dshHome: process.env.DSH_HOME || "",
|
|
592
|
+
});
|
|
593
|
+
ok(res, { ok: true, stamp, count: plugins.length, plugins, text });
|
|
594
|
+
}),
|
|
595
|
+
},
|
|
596
|
+
{ kind: "exact", path: BASE + "/restore/tree",
|
|
597
|
+
handler: handler(async (req, res) => {
|
|
598
|
+
const u = new URL(req.url || "", "http://x");
|
|
599
|
+
const depth = clampInt(u.searchParams.get("depth") || 1, 1, 1, 3);
|
|
600
|
+
const stamp = u.searchParams.get("stamp") || "";
|
|
601
|
+
if (!stamp) return bad(res, 400, "缺少 stamp");
|
|
602
|
+
if (badStamp(res, stamp)) return;
|
|
603
|
+
if (u.searchParams.get("remote") === "1") {
|
|
604
|
+
// 只看目录树、不拉数据:manifest 从云端取,不在本地 store 留半份快照
|
|
605
|
+
if (!authStatus().connected) return bad(res, 400, "未连接云盘");
|
|
606
|
+
const { manifest, cached } = await getRemoteManifest(stamp);
|
|
607
|
+
const t = treeFromManifest(manifest, depth);
|
|
608
|
+
if (!t.ok) return bad(res, 502, t.error || "云端清单不可用");
|
|
609
|
+
return ok(res, { ok: true, stamp: t.stamp || stamp, depth, remote: true, cached, top: t.top, plugins: t.plugins || [] });
|
|
610
|
+
}
|
|
611
|
+
const treeLocal = snapshotTree({ stamp, depth });
|
|
612
|
+
if (treeLocal && treeLocal.ok === false) return bad(res, 404, treeLocal.error || "快照不存在");
|
|
613
|
+
ok(res, treeLocal);
|
|
614
|
+
}),
|
|
615
|
+
},
|
|
616
|
+
{
|
|
617
|
+
// 恢复:只算不写的预览
|
|
618
|
+
kind: "exact", path: BASE + "/restore/preview",
|
|
619
|
+
handler: handler(async (req, res) => {
|
|
620
|
+
const body = await readJson(req);
|
|
621
|
+
if (!body || !body.stamp) return bad(res, 400, "缺少 stamp");
|
|
622
|
+
if (badStamp(res, body.stamp)) return;
|
|
623
|
+
const targetRoot = String(body.targetRoot || process.env.DSH_HOME || "");
|
|
624
|
+
if (!targetRoot) return bad(res, 400, "缺少目标目录 targetRoot");
|
|
625
|
+
const p = previewRestore({ stamp: body.stamp, targetRoot, overwrite: !!body.overwrite, flat: !!body.flat });
|
|
626
|
+
ok(res, { preview: p, targetRoot });
|
|
627
|
+
}),
|
|
628
|
+
},
|
|
629
|
+
{
|
|
630
|
+
// 恢复:真正写盘。写 DSH_HOME 属于高危动作,必须带 confirm:true
|
|
631
|
+
kind: "exact", path: BASE + "/restore/run",
|
|
632
|
+
handler: handler(async (req, res) => {
|
|
633
|
+
const body = await readJson(req);
|
|
634
|
+
if (!body || !body.stamp) return bad(res, 400, "缺少 stamp");
|
|
635
|
+
if (badStamp(res, body.stamp)) return;
|
|
636
|
+
const targetRoot = String(body.targetRoot || process.env.DSH_HOME || "");
|
|
637
|
+
if (!targetRoot) return bad(res, 400, "缺少目标目录 targetRoot");
|
|
638
|
+
const dshHome = process.env.DSH_HOME || "";
|
|
639
|
+
// 必须用 path.resolve 归一化后再比较:字符串去尾比较可被 "DSH_HOME\sessions\.." 绕过
|
|
640
|
+
const hitsHome = !!dshHome && path.resolve(targetRoot) === path.resolve(dshHome);
|
|
641
|
+
if (hitsHome && body.confirm !== true) {
|
|
642
|
+
return bad(res, 400, "目标就是当前 DSH_HOME,会覆盖正在使用的会话与配置;请先备份并把 confirm 设为 true 再执行", { needsConfirm: true, targetRoot });
|
|
643
|
+
}
|
|
644
|
+
logger.warn?.("[dsh-cloud-backup] restore start -> " + targetRoot + " (overwrite=" + (!!body.overwrite) + ")");
|
|
645
|
+
const rels = Array.isArray(body.rels) ? body.rels.map((x) => String(x)).filter(Boolean) : null;
|
|
646
|
+
if (rels && (rels.length > 200 || rels.some((x) => x.length > 512))) return bad(res, 400, "rels 过多或过长(≤200 条、单条 ≤512 字符)");
|
|
647
|
+
const wantPlugins = body.plugins === true;
|
|
648
|
+
const allowScripts = body.allowScripts === true;
|
|
649
|
+
const here = currentHost();
|
|
650
|
+
const pluginProfiles = Array.isArray(body.pluginProfiles) && body.pluginProfiles.length
|
|
651
|
+
? body.pluginProfiles.map((x) => String(x)).filter(Boolean).slice(0, 10)
|
|
652
|
+
: (here.profile ? [here.profile] : null);
|
|
653
|
+
rsProgress = { active: true, stamp: body.stamp, done: 0, total: 0, cancelled: false, startedAt: Date.now() };
|
|
654
|
+
const r = restoreSnapshot({
|
|
655
|
+
stamp: body.stamp, targetRoot,
|
|
656
|
+
overwrite: !!body.overwrite, flat: !!body.flat, rels,
|
|
657
|
+
backupOverwritten: body.backupOverwritten !== false,
|
|
658
|
+
logger: (m) => logger.info?.("[dsh-cloud-backup] " + m),
|
|
659
|
+
onStep: (done, total) => { if (rsProgress) { rsProgress.done = done; rsProgress.total = total; } },
|
|
660
|
+
shouldStop: () => !!(rsProgress && rsProgress.cancelled),
|
|
661
|
+
});
|
|
662
|
+
if (rsProgress) { rsProgress.active = false; rsProgress.cancelled = false; }
|
|
663
|
+
logger.warn?.("[dsh-cloud-backup] restore done: " + JSON.stringify({ ok: r.ok, restored: r.restored, skipped: r.skipped,
|
|
664
|
+
skippedSame: r.skippedSame, skippedDiff: r.skippedDiff, failed: r.failed.length, mergedWorkspace: r.mergedWorkspace ? { added: r.mergedWorkspace.added, kept: r.mergedWorkspace.kept, sessionsAdded: r.mergedWorkspace.sessionsAdded } : null }));
|
|
665
|
+
if (r && r.ok === false && !r.restored && /快照不存在|清\s*单损坏/.test(String(r.error || ""))) return bad(res, 404, r.error);
|
|
666
|
+
let pluginResult = null;
|
|
667
|
+
let pluginScope = null;
|
|
668
|
+
if (wantPlugins) {
|
|
669
|
+
try {
|
|
670
|
+
const man = readManifest(manifestPath(storeDir(), body.stamp));
|
|
671
|
+
pluginResult = await installPluginPacks({
|
|
672
|
+
dshHome, storeDir: storeDir(), plugins: (man && man.plugins) || [],
|
|
673
|
+
profiles: pluginProfiles, allowScripts,
|
|
674
|
+
onLog: (ev) => logger.info?.("[dsh-cloud-backup] plugin " + JSON.stringify(ev)),
|
|
675
|
+
});
|
|
676
|
+
const scopeTarget = pluginProfiles || [];
|
|
677
|
+
const scopeAll = [];
|
|
678
|
+
((man && man.plugins) || []).forEach((x) => { ((x && x.profiles) || []).forEach((y) => { if (scopeAll.indexOf(y) < 0) scopeAll.push(y); }); });
|
|
679
|
+
pluginScope = { target: scopeTarget, others: scopeAll.filter((y) => scopeTarget.indexOf(y) < 0) };
|
|
680
|
+
logInfo("plugin.install.summary", {
|
|
681
|
+
installed: pluginResult.installed.length, skipped: pluginResult.skipped.length,
|
|
682
|
+
failed: pluginResult.failed.length, allowScripts: allowScripts ? 1 : 0,
|
|
683
|
+
});
|
|
684
|
+
} catch (e) {
|
|
685
|
+
pluginResult = { ok: false, error: String((e && e.message) || e), installed: [], skipped: [], failed: [] };
|
|
686
|
+
logError("plugin.install.summary", { error: pluginResult.error });
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
// 落盘一次结果:面板/页面刷新后仍能看到“上次还原”发生了什么
|
|
690
|
+
try {
|
|
691
|
+
const fail0 = (r.failed && r.failed[0]) || null;
|
|
692
|
+
const sd = storeDirHint();
|
|
693
|
+
const snapHost = (sd && body.stamp) ? readRuntimeOf(sd, body.stamp) : null;
|
|
694
|
+
const hostInfo = { from: snapHost, to: here, mismatch: !sameHost(snapHost, here) };
|
|
695
|
+
const lrEntry = {
|
|
696
|
+
at: new Date().toISOString(), stamp: body.stamp || null, targetRoot, bootId: BOOT_ID,
|
|
697
|
+
host: hostInfo,
|
|
698
|
+
ok: r.ok !== false, restored: r.restored || 0, skipped: r.skipped || 0,
|
|
699
|
+
skippedSame: r.skippedSame || 0, skippedDiff: r.skippedDiff || 0,
|
|
700
|
+
skippedDiffSample: (r.skippedDiffSample || []).slice(0, 8),
|
|
701
|
+
mergedWorkspace: r.mergedWorkspace || null,
|
|
702
|
+
overwritten: r.overwritten || 0, failed: (r.failed || []).length,
|
|
703
|
+
firstError: fail0 ? String(fail0.rel) + ":" + String(fail0.error) : null,
|
|
704
|
+
plugins: pluginResult ? {
|
|
705
|
+
ok: pluginResult.ok !== false, error: pluginResult.error || null,
|
|
706
|
+
installed: (pluginResult.installed || []).map((x) => ({ name: x.name, profile: x.profile, via: x.via })),
|
|
707
|
+
skipped: (pluginResult.skipped || []).map((x) => ({ name: x.name, reason: x.reason || null })),
|
|
708
|
+
skippedScoped: (pluginResult.skipped || []).filter((x) => x && x.reason === "profile-not-in-scope").length,
|
|
709
|
+
skippedBlob: (pluginResult.skipped || []).filter((x) => x && /blob/i.test(String(x.reason || ""))).length,
|
|
710
|
+
failed: (pluginResult.failed || []).map((x) => ({ name: x.name, profile: x.profile, error: x.error || null, detail: x.detail || null })),
|
|
711
|
+
rollback: pluginResult.rollback || null, allowScripts, scope: pluginScope,
|
|
712
|
+
} : null,
|
|
713
|
+
};
|
|
714
|
+
saveState({ last_restore: lrEntry });
|
|
715
|
+
appendRestoreHistory(lrEntry);
|
|
716
|
+
} catch (e) { logger.warn?.("[dsh-cloud-backup] save last_restore failed: " + ((e && e.message) || e)); }
|
|
717
|
+
if (pluginResult) {
|
|
718
|
+
const skipList = pluginResult.skipped || [];
|
|
719
|
+
const skippedScoped = skipList.filter((x) => x && x.reason === "profile-not-in-scope").length;
|
|
720
|
+
const skippedBlob = skipList.filter((x) => x && /blob/i.test(String(x.reason || ""))).length;
|
|
721
|
+
r.pluginSummary = {
|
|
722
|
+
installed: (pluginResult.installed || []).length,
|
|
723
|
+
skipped: skipList.length,
|
|
724
|
+
skippedScoped,
|
|
725
|
+
skippedBlob,
|
|
726
|
+
failed: (pluginResult.failed || []).length,
|
|
727
|
+
target: (pluginScope && pluginScope.target) || [],
|
|
728
|
+
others: (pluginScope && pluginScope.others) || [],
|
|
729
|
+
error: pluginResult.error || null,
|
|
730
|
+
};
|
|
731
|
+
}
|
|
732
|
+
ok(res, { result: r, plugins: pluginResult, pluginScope });
|
|
733
|
+
}),
|
|
734
|
+
},
|
|
735
|
+
{
|
|
736
|
+
kind: "exact", path: BASE + "/restore/cancel",
|
|
737
|
+
handler: handler(async (req, res) => {
|
|
738
|
+
await readJson(req).catch(() => null);
|
|
739
|
+
if (!rsProgress || !rsProgress.active) return ok(res, { ok: true, cancelled: false, idle: true });
|
|
740
|
+
rsProgress.cancelled = true;
|
|
741
|
+
logger.warn?.("[dsh-cloud-backup] restore cancel requested: " + String(rsProgress.done || 0) + "/" + String(rsProgress.total || 0));
|
|
742
|
+
return ok(res, { ok: true, cancelled: true, done: rsProgress.done || 0, total: rsProgress.total || 0 });
|
|
743
|
+
}),
|
|
744
|
+
},
|
|
745
|
+
{
|
|
746
|
+
kind: "exact", path: BASE + "/restore/pause",
|
|
747
|
+
handler: handler(async (req, res) => {
|
|
748
|
+
await readJson(req).catch(() => null);
|
|
749
|
+
const did = pausePull();
|
|
750
|
+
ok(res, { paused: did || isPullPaused(), pull: getPullProgress() });
|
|
751
|
+
}),
|
|
752
|
+
},
|
|
753
|
+
{
|
|
754
|
+
kind: "exact", path: BASE + "/restore/from-cloud",
|
|
755
|
+
handler: handler(async (req, res) => {
|
|
756
|
+
const body = await readJson(req);
|
|
757
|
+
if (!body || !body.stamp) return bad(res, 400, "缺少 stamp");
|
|
758
|
+
if (badStamp(res, body.stamp)) return;
|
|
759
|
+
if (!authStatus().connected) return bad(res, 400, "未连接云盘");
|
|
760
|
+
// 可选 rels:只下载这些路径(文件或目录前缀)用到的块,避免为几个文件拉整份快照
|
|
761
|
+
const rels = Array.isArray(body.rels) ? body.rels.map((x) => String(x)).filter(Boolean) : null;
|
|
762
|
+
if (rels && (rels.length > 200 || rels.some((r) => r.length > 512))) return bad(res, 400, "rels 过多或过长(≤200 条、单条 ≤512 字符)");
|
|
763
|
+
// 进度与暂停状态是 provider 级单例:同一时刻只允许一个下载(同 stamp 重复点击也会互相污染字节计数)
|
|
764
|
+
if (pullInFlight) return bad(res, 409, "已有下载在进行(" + pullInFlight + "),请等它结束或先暂停");
|
|
765
|
+
// 先做参数校验(404/400 直接返回),校验通过才占锁——否则提前 return 会把锁永久留在外面
|
|
766
|
+
let hashes = null;
|
|
767
|
+
if (rels && rels.length) {
|
|
768
|
+
const got = await getRemoteManifest(body.stamp);
|
|
769
|
+
const man = got && got.manifest;
|
|
770
|
+
if (!man || !Array.isArray(man.files)) return bad(res, 400, "云端清单不可用,无法按路径下载");
|
|
771
|
+
const hit = man.files.filter((f) => rels.some((r) => f.rel === r || f.rel.indexOf(r.replace(/\/+$/, "") + "/") === 0));
|
|
772
|
+
if (!hit.length) return bad(res, 404, "这些路径在快照里不存在");
|
|
773
|
+
hashes = [...new Set(hit.map((f) => f.hash))];
|
|
774
|
+
}
|
|
775
|
+
// 占位与释放必须在同一 try/finally 内,任何异常都要把锁放掉
|
|
776
|
+
pullInFlight = body.stamp;
|
|
777
|
+
let r = null;
|
|
778
|
+
try {
|
|
779
|
+
r = await pullSnapshot({ stamp: body.stamp, hashes, logger: (m) => logger.info?.("[dsh-cloud-backup] " + m) });
|
|
780
|
+
} finally { pullInFlight = null; }
|
|
781
|
+
ok(res, { pull: r, scope: hashes ? { files: hashes.length, rels } : null });
|
|
782
|
+
}),
|
|
783
|
+
},
|
|
784
|
+
{
|
|
785
|
+
// 自重启:默认只回报计划(入口找不找得到、会不会走 shell),confirm:true 才真的替换进程。
|
|
786
|
+
// 计划要先落盘再动手,这样即使新宿主没起来,日志里也能看出它当时打算怎么拉起来。
|
|
787
|
+
kind: "exact", path: BASE + "/restart",
|
|
788
|
+
handler: handler(async (req, res) => {
|
|
789
|
+
const body = (await readJson(req)) || {};
|
|
790
|
+
const spec = launchSpec();
|
|
791
|
+
const plan = describeLaunch(spec);
|
|
792
|
+
const refusal = restartRefusal();
|
|
793
|
+
const port = servingPort(req);
|
|
794
|
+
const base = { plan, port, refusal, host: currentHost() };
|
|
795
|
+
if (body.confirm !== true) return ok(res, Object.assign({ dryRun: true }, base));
|
|
796
|
+
if (refusal) return bad(res, 400, refusal);
|
|
797
|
+
if (!plan || !plan.resolvable) return bad(res, 400, "找不到宿主启动入口,无法自重启(可手动重启 DSH)");
|
|
798
|
+
if (pullInFlight) return bad(res, 409, "下载/还原正在进行(" + pullInFlight + "),等它结束再重启");
|
|
799
|
+
const r = scheduleRestart({ spec, port, logDir: logDir() });
|
|
800
|
+
if (!r.ok) return bad(res, 500, r.error || "自重启失败");
|
|
801
|
+
logInfo("restart.scheduled", { port, file: r.spawn && r.spawn.file, helperPid: r.helperPid, logFile: r.logFile });
|
|
802
|
+
ok(res, Object.assign({ dryRun: false, launch: r }, base));
|
|
803
|
+
}),
|
|
804
|
+
},
|
|
805
|
+
{
|
|
806
|
+
// 恢复:还原后逐文件校验(stamp 走白名单校验)
|
|
807
|
+
kind: "exact", path: BASE + "/restore/verify",
|
|
808
|
+
handler: handler(async (req, res) => {
|
|
809
|
+
const body = await readJson(req);
|
|
810
|
+
if (!body || !body.stamp) return bad(res, 400, "缺少 stamp");
|
|
811
|
+
if (badStamp(res, body.stamp)) return;
|
|
812
|
+
const targetRoot = String(body.targetRoot || process.env.DSH_HOME || "");
|
|
813
|
+
if (!targetRoot) return bad(res, 400, "缺少目标目录 targetRoot");
|
|
814
|
+
ok(res, { verify: verifyRestore({ stamp: body.stamp, targetRoot, flat: !!body.flat }) });
|
|
815
|
+
}),
|
|
816
|
+
},
|
|
817
|
+
{
|
|
818
|
+
// 「备份 = 云端,本地只是缓存」的两个入口
|
|
819
|
+
kind: "exact", path: BASE + "/backups",
|
|
820
|
+
handler: handler(async (req, res) => {
|
|
821
|
+
const url = new URL(String(req.url || "/"), "http://localhost");
|
|
822
|
+
const fresh = url.searchParams.get("fresh") === "1";
|
|
823
|
+
ok(res, await listBackups({ fresh }));
|
|
824
|
+
}),
|
|
825
|
+
},
|
|
826
|
+
{
|
|
827
|
+
kind: "exact", path: BASE + "/backups/delete",
|
|
828
|
+
handler: handler(async (req, res) => {
|
|
829
|
+
const body = (await readJson(req)) || {};
|
|
830
|
+
if (badStamp(res, body.stamp)) return;
|
|
831
|
+
const r = await deleteBackup({
|
|
832
|
+
stamp: body.stamp,
|
|
833
|
+
dryRun: body.dryRun !== false,
|
|
834
|
+
allowLast: body.allowLast === true,
|
|
835
|
+
logger: (m) => logger.info?.("[dsh-cloud-backup] " + m),
|
|
836
|
+
});
|
|
837
|
+
if (!r.ok && r.code === "lastCloudCopy") return bad(res, 409, r.error);
|
|
838
|
+
if (!r.ok && r.code === "notFound") return bad(res, 404, r.error);
|
|
839
|
+
if (!r.ok) return bad(res, 400, r.error || "删除失败");
|
|
840
|
+
if ((r.plan || {}).lastCloudCopy && body.allowLast !== true) {
|
|
841
|
+
return bad(res, 409, "这是云端最后一份备份;确认要删请带 allowLast:true(会清空云端备份)");
|
|
842
|
+
}
|
|
843
|
+
if (!r.dryRun) saveState(Object.assign(loadState() || {}, { last_delete: { at: new Date().toISOString(), stamp: body.stamp } }));
|
|
844
|
+
ok(res, r);
|
|
845
|
+
}),
|
|
846
|
+
},
|
|
847
|
+
{
|
|
848
|
+
kind: "exact", path: BASE + "/backups/upload",
|
|
849
|
+
handler: handler(async (req, res) => {
|
|
850
|
+
const body = (await readJson(req)) || {};
|
|
851
|
+
if (badStamp(res, body.stamp)) return;
|
|
852
|
+
if (!authStatus().connected) return bad(res, 400, "未连接云盘");
|
|
853
|
+
const r = await uploadBackup({ stamp: body.stamp, logger: (m) => logger.info?.("[dsh-cloud-backup] " + m) });
|
|
854
|
+
if (!r.ok) return bad(res, 400, r.error || "上传失败");
|
|
855
|
+
invalidateRemoteSnapshotCache();
|
|
856
|
+
try {
|
|
857
|
+
const st0 = loadState();
|
|
858
|
+
const lb = st0 && st0.last_backup;
|
|
859
|
+
if (lb && lb.snapshot === body.stamp) {
|
|
860
|
+
lb.upload = { ok: true, via: "manual", at: new Date().toISOString() };
|
|
861
|
+
saveState({ last_backup: lb });
|
|
862
|
+
}
|
|
863
|
+
} catch (e) { logger.warn?.("[dsh-cloud-backup] last_backup sync skipped: " + ((e && e.message) || e)); }
|
|
864
|
+
ok(res, r);
|
|
865
|
+
}),
|
|
866
|
+
},
|
|
867
|
+
{
|
|
868
|
+
kind: "exact", path: BASE + "/maintenance/cache",
|
|
869
|
+
handler: handler(async (req, res) => {
|
|
870
|
+
const body = (await readJson(req)) || {};
|
|
871
|
+
if (body.dryRun !== false) return ok(res, { dryRun: true, stats: cacheStats() });
|
|
872
|
+
if (!authStatus().connected) return bad(res, 400, "未连接云盘:无法确认哪些缓存已上传,拒绝清理(避免删掉唯一副本)");
|
|
873
|
+
const cloud = await listRemoteSnapshots({ fresh: true });
|
|
874
|
+
if (!cloud.ok) return bad(res, 400, cloud.error || "读云端快照列表失败");
|
|
875
|
+
const set = new Set((cloud.snapshots || []).filter((x) => x.hasManifest).map((x) => x.stamp));
|
|
876
|
+
if (body.keep !== undefined && body.keep !== null && !Number.isFinite(Number(body.keep))) {
|
|
877
|
+
return bad(res, 400, "keep 必须是数字(收到:" + JSON.stringify(body.keep) + ")");
|
|
878
|
+
}
|
|
879
|
+
const keep = Number.isFinite(Number(body.keep)) ? Math.max(0, Math.floor(Number(body.keep))) : 3;
|
|
880
|
+
ok(res, pruneCache({ keep, cloudStamps: set }));
|
|
881
|
+
}),
|
|
882
|
+
},
|
|
883
|
+
{
|
|
884
|
+
kind: "exact", path: BASE + "/maintenance/cleanup",
|
|
885
|
+
handler: handler(async (req, res) => {
|
|
886
|
+
const body = (await readJson(req)) || {};
|
|
887
|
+
if (!authStatus().connected) return bad(res, 400, "未连接云盘");
|
|
888
|
+
const dryRun = body.dryRun !== false; // 默认只演练,必须显式 dryRun:false 才真删
|
|
889
|
+
const lg = (m) => logger.info?.("[dsh-cloud-backup] " + m);
|
|
890
|
+
const orphans = await cleanupRemoteOrphans({ dryRun, logger: lg });
|
|
891
|
+
let gc = null;
|
|
892
|
+
if (body.gc === true) {
|
|
893
|
+
gc = await gcRemoteSnapshots({ keepRecent: clampInt(body.keepRecent, 8, 1, 999), dryRun, logger: lg });
|
|
894
|
+
}
|
|
895
|
+
ok(res, { dryRun, orphans, gc });
|
|
896
|
+
}),
|
|
897
|
+
},
|
|
898
|
+
{
|
|
899
|
+
// 维护:清理本地旧快照(删前查云端 hasManifest;默认 dryRun 只返回计划)
|
|
900
|
+
kind: "exact", path: BASE + "/maintenance/prune-local",
|
|
901
|
+
handler: handler(async (req, res) => {
|
|
902
|
+
const body = (await readJson(req)) || {};
|
|
903
|
+
// keepRecent 必须是 ≥0 的整数:非数字会让保留份数变 NaN → 清空本地快照(已复现),这里直接拒
|
|
904
|
+
let keepRecent = 5;
|
|
905
|
+
if (body.keepRecent !== undefined) {
|
|
906
|
+
const n = Number(body.keepRecent);
|
|
907
|
+
if (!Number.isFinite(n) || n < 0) return bad(res, 400, "keepRecent 必须是 ≥0 的数字(收到:" + JSON.stringify(body.keepRecent) + ")");
|
|
908
|
+
keepRecent = Math.floor(n);
|
|
909
|
+
}
|
|
910
|
+
// stamps 会直接拼进路径,必须逐个过白名单
|
|
911
|
+
let stamps = null;
|
|
912
|
+
if (Array.isArray(body.stamps)) {
|
|
913
|
+
if (body.stamps.length > 200) return bad(res, 400, "stamps 一次最多 200 条");
|
|
914
|
+
const badOne = body.stamps.filter((s) => !isStamp(s));
|
|
915
|
+
if (badOne.length) return bad(res, 400, "非法 stamp:" + JSON.stringify(badOne.slice(0, 3)));
|
|
916
|
+
stamps = body.stamps.slice();
|
|
917
|
+
}
|
|
918
|
+
const r = await pruneLocalSnapshots({
|
|
919
|
+
keepRecent: keepRecent,
|
|
920
|
+
stamps: stamps,
|
|
921
|
+
dryRun: body.dryRun !== false,
|
|
922
|
+
requireCloud: body.requireCloud !== false,
|
|
923
|
+
reclaim: body.reclaim !== false,
|
|
924
|
+
logger: (m) => logger.info?.("[dsh-cloud-backup] " + m),
|
|
925
|
+
});
|
|
926
|
+
_audit = { at: 0, value: null }; // 快照数变了,体检缓存作废
|
|
927
|
+
ok(res, r);
|
|
928
|
+
}),
|
|
929
|
+
},
|
|
930
|
+
{
|
|
931
|
+
// 维护:删云端旧快照(进阿里云盘回收站,30 天可在云盘 UI 找回)。
|
|
932
|
+
// 默认 dryRun;默认拒删「本地仍有副本」与「云端最后一份」,必须显式放行。
|
|
933
|
+
kind: "exact", path: BASE + "/maintenance/prune-remote",
|
|
934
|
+
handler: handler(async (req, res) => {
|
|
935
|
+
const body = (await readJson(req)) || {};
|
|
936
|
+
if (!authStatus().connected) return bad(res, 400, "未连接云盘");
|
|
937
|
+
let stamps = null;
|
|
938
|
+
if (Array.isArray(body.stamps)) {
|
|
939
|
+
if (body.stamps.length > 200) return bad(res, 400, "stamps 一次最多 200 条");
|
|
940
|
+
const badOne = body.stamps.filter((s) => !isStamp(s));
|
|
941
|
+
if (badOne.length) return bad(res, 400, "非法 stamp:" + JSON.stringify(badOne.slice(0, 3)));
|
|
942
|
+
stamps = body.stamps.slice();
|
|
943
|
+
}
|
|
944
|
+
let keepRecent = null;
|
|
945
|
+
if (body.keepRecent !== undefined) {
|
|
946
|
+
const n = Number(body.keepRecent);
|
|
947
|
+
if (!Number.isFinite(n) || n < 1) return bad(res, 400, "keepRecent 必须是 ≥1 的数字(收到:" + JSON.stringify(body.keepRecent) + ")");
|
|
948
|
+
keepRecent = Math.floor(n);
|
|
949
|
+
}
|
|
950
|
+
if (!stamps && keepRecent === null) return bad(res, 400, "需要 stamps(按份删)或 keepRecent(按保留份数)");
|
|
951
|
+
const r = await pruneRemoteSnapshots({
|
|
952
|
+
stamps: stamps,
|
|
953
|
+
keepRecent: keepRecent,
|
|
954
|
+
dryRun: body.dryRun !== false,
|
|
955
|
+
allowLocalCopy: body.allowLocalCopy === true,
|
|
956
|
+
allowLastCopy: body.allowLastCopy === true,
|
|
957
|
+
logger: (m) => logger.info?.("[dsh-cloud-backup] " + m),
|
|
958
|
+
});
|
|
959
|
+
if (!r.ok) return bad(res, 400, r.error || "云端删除失败");
|
|
960
|
+
ok(res, r);
|
|
961
|
+
}),
|
|
962
|
+
},
|
|
963
|
+
{
|
|
964
|
+
kind: "exact", path: LEGACY_BASE + "/status",
|
|
965
|
+
handler: handler(async (req, res) => { sweep(); ok(res, statusPayload()); }),
|
|
966
|
+
},
|
|
967
|
+
];
|
|
968
|
+
|
|
969
|
+
const disposers = [];
|
|
970
|
+
for (const route of routes) {
|
|
971
|
+
try {
|
|
972
|
+
const method = GET_PATHS.has(routeTail(route.path)) ? "GET" : "POST";
|
|
973
|
+
const dispose = sctx.webServer.register({ ...route, handler: guard(method, route.handler) });
|
|
974
|
+
disposers.push(typeof dispose === "function" ? dispose : () => {});
|
|
975
|
+
} catch (error) {
|
|
976
|
+
logger.warn?.(`[dsh-cloud-backup] route ${route.path} 注册失败: ${(error && error.message) || error}`);
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
logger.info?.(`[dsh-cloud-backup] 已挂载 ${disposers.length}/${routes.length} 条路由,前缀 ${BASE},状态目录 ${dataDir()}`);
|
|
980
|
+
|
|
981
|
+
// 定时备份:进程内定时器(宿主重启即重建)。每分钟检查一次,到点且满足条件才跑。
|
|
982
|
+
const tick = () => {
|
|
983
|
+
try {
|
|
984
|
+
const cfg = loadConfig();
|
|
985
|
+
const every = Math.max(1, Number(cfg.intervalMinutes) || 60) * 60 * 1000;
|
|
986
|
+
const mins = Math.round(every / 60000);
|
|
987
|
+
// 间隔被改过 → 从现在起重新计时(否则要等上一次调度走完才生效)
|
|
988
|
+
if (sched.intervalMin !== mins) {
|
|
989
|
+
if (sched.intervalMin) logger.info?.("[dsh-cloud-backup] schedule interval -> " + mins + " min");
|
|
990
|
+
sched.intervalMin = mins;
|
|
991
|
+
sched.nextAt = Date.now() + every;
|
|
992
|
+
}
|
|
993
|
+
if (!cfg.enabled) return;
|
|
994
|
+
if (!sched.nextAt) sched.nextAt = Date.now() + every;
|
|
995
|
+
if (Date.now() < sched.nextAt) return;
|
|
996
|
+
sched.nextAt = Date.now() + every;
|
|
997
|
+
if (!authStatus().connected) return;
|
|
998
|
+
if (sched.running) return;
|
|
999
|
+
sched.running = true;
|
|
1000
|
+
logger.info?.("[dsh-cloud-backup] scheduled backup start");
|
|
1001
|
+
runBackup({ trigger: "schedule", uploader: createUploader({ logger }), logger: (m) => logger.info?.("[dsh-cloud-backup] " + m) })
|
|
1002
|
+
.then((r) => logger.info?.("[dsh-cloud-backup] scheduled backup done " + JSON.stringify({ ok: r.ok, files: r.files, new: r.newBlobs })))
|
|
1003
|
+
.catch((e) => logger.warn?.("[dsh-cloud-backup] scheduled backup failed: " + ((e && e.message) || e)))
|
|
1004
|
+
.finally(() => { sched.running = false; _audit = { at: 0, value: null }; });
|
|
1005
|
+
} catch (e) { logger.warn?.("[dsh-cloud-backup] scheduler tick failed: " + ((e && e.message) || e)); }
|
|
1006
|
+
};
|
|
1007
|
+
const timer = setInterval(tick, 60 * 1000);
|
|
1008
|
+
try { tick(); } catch {} // 立刻排一次,界面才能显示「下次自动备份」时间
|
|
1009
|
+
// 预热:把 DPAPI 解密(单次约 3 秒)挪到后台,用户点开卡片时命中缓存
|
|
1010
|
+
const warm = setTimeout(() => { try { loadCredentials(); safeAudit(); } catch {} }, 1500);
|
|
1011
|
+
if (warm.unref) warm.unref();
|
|
1012
|
+
if (typeof timer.unref === "function") timer.unref();
|
|
1013
|
+
|
|
1014
|
+
return () => { clearInterval(timer); for (const d of disposers) { try { d(); } catch {} } sessions.clear(); };
|
|
1015
|
+
}, "dsh-cloud-backup: http routes");
|
|
1016
|
+
});
|
|
1017
|
+
}
|