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/lib/qr.js ADDED
@@ -0,0 +1,29 @@
1
+ // lib/qr.js —— 二维码封装(自包含,无外部依赖)
2
+
3
+ import { createRequire } from "node:module";
4
+
5
+ const require = createRequire(import.meta.url);
6
+ const qrcodeFactory = require("./vendor/qrcode-generator.cjs");
7
+
8
+ /** 纠错等级:L/M/Q/H。M 在容错与尺寸间平衡,阿里云盘登录二维码用 M 已足够。 */
9
+ export const DEFAULT_ECC = "M";
10
+
11
+ /** 生成矩阵:{ count, isDark(row, col) },便于测试与自定义渲染。 */
12
+ export function qrMatrix(text, { ecc = DEFAULT_ECC, typeNumber = 0 } = {}) {
13
+ const qr = qrcodeFactory(typeNumber, ecc);
14
+ qr.addData(String(text));
15
+ qr.make();
16
+ const count = qr.getModuleCount();
17
+ return { count, isDark: (row, col) => qr.isDark(row, col) };
18
+ }
19
+
20
+ /** 生成独立 SVG(无外部引用、无 CSS 依赖),可直接嵌入 <img src="data:...">。 */
21
+ export function qrSvg(text, { ecc = DEFAULT_ECC, cellSize = 4, margin = 2, alt = "二维码" } = {}) {
22
+ const qr = qrcodeFactory(0, ecc);
23
+ qr.addData(String(text));
24
+ qr.make();
25
+ return qr.createSvgTag({ cellSize, margin, alt: { text: alt } });
26
+ }
27
+
28
+ /** data:URL 形式(默认 base64,避免中文/特殊字符转义问题)。 */
29
+ export default qrSvg;
@@ -0,0 +1,63 @@
1
+
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { dataDir, writeFileAtomic } from "./paths.js";
5
+
6
+ export const DEFAULT_CONFIG = {
7
+ enabled: true,
8
+ autoUpload: true,
9
+ intervalMinutes: 60,
10
+ workspace: "all", // "all" | 具体工作区目录名(sessions/ 下那一层)
11
+ remoteFolder: "dsh-cloud-backup",
12
+ recentKeep: 24,
13
+ retryFailed: 3,
14
+ dailyKeep: 7,
15
+ weeklyKeep: 4,
16
+ monthlyKeep: 6,
17
+ maxFileBytes: 64 * 1024 * 1024,
18
+ maxTotalBytes: 3 * 1024 * 1024 * 1024,
19
+ skipPlugins: false, // true = 只备份会话与 storages
20
+ packPlugins: true, // true = 备份时把本地/社区插件打成 tarball 一起上云
21
+ maxPluginPackMB: 20, // 单个插件包上限(MB),超过则只记 spec
22
+ maxPluginPacks: 20, // 单次备份最多打包多少个插件
23
+ sidebarEntry: true, // true = 在侧栏底部显示「云盘备份」入口(设置里的入口始终保留)
24
+ // 开放平台 App(可选):填了才能用“浏览器 OAuth 一键授权”;留空则只用扫码/免扫码
25
+ oauthClientId: "",
26
+ oauthClientSecret: "",
27
+ oauthRedirectUri: "", // 留空 = 自动用 http://<你在访问的 Host>/api/dsh-cloud-backup/auth/oauth/callback
28
+ };
29
+
30
+ export function configPath() { return path.join(dataDir(), "config.json"); }
31
+
32
+ export function loadConfig() {
33
+ let raw = {};
34
+ try { if (fs.existsSync(configPath())) raw = JSON.parse(fs.readFileSync(configPath(), "utf8")) || {}; } catch { raw = {}; }
35
+ const cfg = { ...DEFAULT_CONFIG };
36
+ for (const k of Object.keys(DEFAULT_CONFIG)) {
37
+ if (k in raw && raw[k] !== null && raw[k] !== undefined) cfg[k] = raw[k];
38
+ }
39
+ return cfg;
40
+ }
41
+
42
+ export function saveConfig(patch = {}) {
43
+ // 只接受白名单键 + 类型与范围归一化,避免任意键值落盘
44
+ const clean = {};
45
+ const inRange = (v, min, max) => (Number.isFinite(Number(v)) ? Math.min(max, Math.max(min, Math.floor(Number(v)))) : undefined);
46
+ const BOUNDS = {
47
+ intervalMinutes: [5, 7 * 24 * 60], recentKeep: [0, 999], dailyKeep: [0, 999], weeklyKeep: [0, 999], monthlyKeep: [0, 999],
48
+ retryFailed: [0, 20],
49
+ maxFileBytes: [1024, 8 * 1024 * 1024 * 1024], maxTotalBytes: [1024 * 1024, 512 * 1024 * 1024 * 1024],
50
+ maxPluginPackMB: [1, 200], maxPluginPacks: [0, 100],
51
+ };
52
+ for (const k of Object.keys(DEFAULT_CONFIG)) {
53
+ if (!(k in patch) || patch[k] === null || patch[k] === undefined) continue;
54
+ const v = patch[k];
55
+ const dv = DEFAULT_CONFIG[k];
56
+ if (typeof dv === "boolean") clean[k] = v === true || v === "true";
57
+ else if (typeof dv === "number") { const b = BOUNDS[k] || [0, Number.MAX_SAFE_INTEGER]; const n = inRange(v, b[0], b[1]); if (n === undefined) continue; clean[k] = n; }
58
+ else clean[k] = String(v).slice(0, 200);
59
+ }
60
+ const next = { ...loadConfig(), ...clean };
61
+ writeFileAtomic(configPath(), JSON.stringify(next, null, 2));
62
+ return next;
63
+ }
@@ -0,0 +1,69 @@
1
+ // lib/store/credentials.js —— 凭据持久化(密文 + 明文元信息分离)
2
+
3
+ import fs from "node:fs";
4
+ import { credentialsPath, writeFileAtomic } from "./paths.js";
5
+ import { protect, unprotect, isProtected } from "./secret.js";
6
+
7
+ /** 文件结构:{\"v\":1,\"provider\":\"aliyun\",\"meta\":{非机密展示信息},\"secret\":\"<加密后的 token 块>\"} */
8
+ const V = 1;
9
+
10
+ // DPAPI 解密一次约 3 秒(要起 PowerShell);按文件 mtime+size 缓存,命中即返回。
11
+ let _cache = null; // { key, file, value }
12
+
13
+ function stampKey(file) {
14
+ try { const st = fs.statSync(file); return st.mtimeMs + ":" + st.size; } catch { return null; }
15
+ }
16
+
17
+ /** 读取凭据;不存在或损坏返回 null(损坏时另存 .bad-<ts> 便于排查,不静默丢弃) */
18
+ export function loadCredentials() {
19
+ const file = credentialsPath();
20
+ const key = stampKey(file);
21
+ if (!key) { _cache = null; return null; }
22
+ if (_cache && _cache.file === file && _cache.key === key) return _cache.value;
23
+ let raw;
24
+ try { raw = JSON.parse(fs.readFileSync(file, "utf8")); }
25
+ catch (e) {
26
+ try { fs.renameSync(file, `${file}.bad-${Date.now()}`); } catch {}
27
+ return null;
28
+ }
29
+ if (!raw || raw.v !== V) return null;
30
+ try {
31
+ const secret = raw.secret && isProtected(raw.secret) ? JSON.parse(unprotect(raw.secret)) : {};
32
+ const value = { ...raw.meta, ...secret, provider: raw.provider, _savedAt: raw.savedAt };
33
+ _cache = { file, key, value };
34
+ return value;
35
+ } catch (e) {
36
+ return null; // 换机/换用户后 DPAPI 解不开,等同未连接
37
+ }
38
+ }
39
+
40
+ /** 保存凭据:token 等机密进 secret 块(加密),其余明文便于 UI 未解密时展示 */
41
+ export function saveCredentials(c) {
42
+ const { provider = "aliyun", _savedAt, ...rest } = c || {};
43
+ // 机密键:一律进加密块;其余(账号展示名、过期时间、计数器…)明文存放,便于未解密时渲染 UI。
44
+ // 注意必须用"非机密即明文"的写法,不能用白名单——白名单会静默丢字段(updated_at/refreshed_count 曾因此丢失)。
45
+ const SECRET_KEYS = ["access_token", "refresh_token", "id_token", "token_type", "device_id"];
46
+ const secret = {}, meta = {};
47
+ for (const [k, v] of Object.entries(rest)) (SECRET_KEYS.includes(k) ? secret : meta)[k] = v;
48
+ const body = {
49
+ v: V, provider, savedAt: new Date().toISOString(),
50
+ meta,
51
+ secret: protect(JSON.stringify(secret)),
52
+ };
53
+ writeFileAtomic(credentialsPath(), JSON.stringify(body, null, 2));
54
+ _cache = null;
55
+ return body;
56
+ }
57
+
58
+ export function clearCredentials() {
59
+ const file = credentialsPath();
60
+ try { if (fs.existsSync(file)) fs.unlinkSync(file); } catch {}
61
+ _cache = null;
62
+ return true;
63
+ }
64
+
65
+ /** 是否"看起来已过期"(提前 skewMs 视为需要刷新) */
66
+ export function needsRefresh(creds, skewMs = 600_000) {
67
+ if (!creds || !creds.expires_at) return true;
68
+ return Number(creds.expires_at) - Date.now() <= skewMs;
69
+ }
@@ -0,0 +1,45 @@
1
+ // lib/store/paths.js —— 运行时目录推导(不依赖宿主 API,纯 Node)
2
+
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+
6
+ /** DSH 主目录:DSH_HOME > 启用了 profiles 的 cwd 推导 > ~/.dsh */
7
+ export function dshHome() {
8
+ const env = process.env.DSH_HOME;
9
+ if (env && env.trim()) return path.resolve(env.trim());
10
+ const cwd = process.cwd();
11
+ if (path.basename(cwd).toLowerCase() === ".dsh" || cwd.includes(`${path.sep}profiles${path.sep}`)) return cwd;
12
+ return path.join(os.homedir(), ".dsh");
13
+ }
14
+
15
+ /** 本插件的数据目录:%DSH_HOME%/cloud-backup */
16
+ export function dataDir() {
17
+ const override = process.env.DSH_CLOUD_BACKUP_HOME;
18
+ if (override && override.trim()) return path.resolve(override.trim());
19
+ return path.join(dshHome(), "cloud-backup");
20
+ }
21
+
22
+ export function credentialsPath() { return path.join(dataDir(), "credentials.json"); }
23
+
24
+ /** 备份库目录:%DSH_HOME%/cloud-backup/store(与凭据/配置分开,便于整体搬迁或删除) */
25
+ export function storeDir() {
26
+ const override = process.env.DSH_CLOUD_BACKUP_STORE;
27
+ if (override && override.trim()) return path.resolve(override.trim());
28
+ return path.join(dataDir(), "store");
29
+ }
30
+ export function statePath() { return path.join(dataDir(), "state.json"); }
31
+ export function keyPath() { return path.join(dataDir(), ".key"); }
32
+
33
+ /** 原子写:同目录 .tmp-<pid>-<rand> 落盘后 rename,避免半截文件。 */
34
+ export function writeFileAtomic(file, text) {
35
+ const dir = path.dirname(file);
36
+ const tmp = path.join(dir, `.tmp-${process.pid}-${Math.random().toString(16).slice(2, 8)}`);
37
+ fsWriteFile(tmp, text);
38
+ try { fs.renameSync(tmp, file); } catch (e) { try { fs.unlinkSync(tmp); } catch {} throw e; }
39
+ }
40
+ import fs from "node:fs";
41
+ function fsWriteFile(file, text) {
42
+ const dir = path.dirname(file);
43
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
44
+ fs.writeFileSync(file, text, { encoding: "utf8", mode: 0o600 });
45
+ }
@@ -0,0 +1,94 @@
1
+ // lib/store/secret.js —— 凭据加密(Windows DPAPI 优先,非 Windows 退化为本机密钥 AES-256-GCM)
2
+
3
+ import crypto from "node:crypto";
4
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+ import { spawnSync } from "node:child_process";
7
+ import { keyPath } from "./paths.js";
8
+
9
+ const DPAPI_PREFIX = "dpapi:v1:";
10
+ const AES_PREFIX = "aesgcm:v1:";
11
+
12
+ /** 是否为 dpapi:v1 密文 */
13
+ export function isProtected(text) {
14
+ return typeof text === "string" && (text.startsWith(DPAPI_PREFIX) || text.startsWith(AES_PREFIX));
15
+ }
16
+
17
+ function dpapiSupported() {
18
+ return process.platform === "win32" && process.env.DSH_CLOUD_BACKUP_DISABLE_DPAPI !== "1";
19
+ }
20
+
21
+ // DPAPI:经 powershell.exe 调用,base64 进出避免编码问题。
22
+ // 待处理的数据走 stdin:命令行参数对本机其它进程可读(任务管理器 / WMI / EDR),
23
+ // 把明文 base64 拼进 -Command 等于把凭据暴露在进程命令行里。
24
+ function psRun(script, stdinText) {
25
+ const r = spawnSync("powershell.exe", ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", script], {
26
+ encoding: "utf8", windowsHide: true, timeout: 20000, input: stdinText === undefined ? undefined : String(stdinText),
27
+ });
28
+ if (r.error) throw new Error("powershell 启动失败: " + r.error.message);
29
+ if (r.status !== 0) throw new Error("powershell 退出码 " + r.status + ": " + String(r.stderr || "").trim().slice(0, 300));
30
+ return String(r.stdout || "").trim();
31
+ }
32
+
33
+ function dpapi(mode, b64) {
34
+ const asm = "Add-Type -AssemblyName System.Security;";
35
+ const read = "$s=[Console]::In.ReadToEnd().Trim(); $b=[Convert]::FromBase64String($s);";
36
+ const body = mode === "protect"
37
+ ? "$o=[System.Security.Cryptography.ProtectedData]::Protect($b,$null,'CurrentUser'); [Convert]::ToBase64String($o)"
38
+ : "$o=[System.Security.Cryptography.ProtectedData]::Unprotect($b,$null,'CurrentUser'); [Convert]::ToBase64String($o)";
39
+ const out = psRun(asm + " " + read + " " + body, b64);
40
+ if (!/^[A-Za-z0-9+/=]+$/.test(out)) throw new Error("DPAPI 返回非 base64: " + out.slice(0, 120));
41
+ return out;
42
+ }
43
+
44
+ // 兜底:AES-256-GCM
45
+ function aesKey() {
46
+ const file = keyPath();
47
+ if (fs.existsSync(file)) {
48
+ const raw = fs.readFileSync(file, "utf8").trim();
49
+ const key = Buffer.from(raw, "base64");
50
+ if (key.length === 32) return key;
51
+ }
52
+ const key = crypto.randomBytes(32);
53
+ const dir = path.dirname(file); // 用 dirname 取目录:手写 lastIndexOf("\\") 在 POSIX 上会切出 "…/.ke" 这类垃圾目录
54
+ fs.mkdirSync(dir, { recursive: true });
55
+ fs.writeFileSync(file, key.toString("base64") + "\n", { encoding: "utf8", mode: 0o600 });
56
+ return key;
57
+ }
58
+
59
+ function aesEncrypt(text) {
60
+ const iv = crypto.randomBytes(12);
61
+ const c = crypto.createCipheriv("aes-256-gcm", aesKey(), iv);
62
+ const ct = Buffer.concat([c.update(Buffer.from(text, "utf8")), c.final()]);
63
+ return AES_PREFIX + [iv.toString("base64"), ct.toString("base64"), c.getAuthTag().toString("base64")].join(":");
64
+ }
65
+
66
+ function aesDecrypt(payload) {
67
+ const [ivB64, ctB64, tagB64] = payload.split(":");
68
+ const d = crypto.createDecipheriv("aes-256-gcm", aesKey(), Buffer.from(ivB64, "base64"));
69
+ d.setAuthTag(Buffer.from(tagB64, "base64"));
70
+ return Buffer.concat([d.update(Buffer.from(ctB64, "base64")), d.final()]).toString("utf8");
71
+ }
72
+
73
+ export function backend() { return dpapiSupported() ? "dpapi" : "aesgcm"; }
74
+
75
+ /** 加密字符串 → 带前缀的密文(可安全写文件) */
76
+ export function protect(text) {
77
+ const s = String(text);
78
+ if (dpapiSupported()) {
79
+ try { return DPAPI_PREFIX + dpapi("protect", Buffer.from(s, "utf8").toString("base64")); }
80
+ catch (e) { if (process.env.DSH_CLOUD_BACKUP_STRICT_DPAPI === "1") throw e; /* 退化为 AES */ }
81
+ }
82
+ return aesEncrypt(s);
83
+ }
84
+
85
+ /** 解密(自动识别前缀;明文原样返回,便于迁移旧文件) */
86
+ export function unprotect(token) {
87
+ const s = String(token);
88
+ if (s.startsWith(DPAPI_PREFIX)) {
89
+ const b64 = dpapi("unprotect", s.slice(DPAPI_PREFIX.length));
90
+ return Buffer.from(b64, "base64").toString("utf8");
91
+ }
92
+ if (s.startsWith(AES_PREFIX)) return aesDecrypt(s.slice(AES_PREFIX.length));
93
+ return s;
94
+ }
@@ -0,0 +1,17 @@
1
+
2
+ import fs from "node:fs";
3
+ import { statePath, writeFileAtomic } from "./paths.js";
4
+
5
+ export function loadState() {
6
+ try {
7
+ if (!fs.existsSync(statePath())) return {};
8
+ const s = JSON.parse(fs.readFileSync(statePath(), "utf8"));
9
+ return s && typeof s === "object" ? s : {};
10
+ } catch { return {}; }
11
+ }
12
+
13
+ export function saveState(patch) {
14
+ const next = { ...loadState(), ...patch, updated_at: new Date().toISOString() };
15
+ writeFileAtomic(statePath(), JSON.stringify(next, null, 2));
16
+ return next;
17
+ }
@@ -0,0 +1,5 @@
1
+ // 资源缺失(快照、清单、路径)与内部故障分开报:前者 404,后者 500。
2
+ // 用 status 字段而不是只靠 instanceof:宿主可能把插件模块加载成两份,类对象不相等。
3
+ export class NotFoundError extends Error {
4
+ constructor(message) { super(message); this.name = "NotFoundError"; this.status = 404; }
5
+ }
@@ -0,0 +1,107 @@
1
+ // 结构化运行日志:单文件追加 + 2 MB 轮转 + 内存尾缓冲,供「打开日志」与 GET /logs 读取。
2
+
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import { storeDir } from "../store/paths.js";
6
+
7
+ const MAX_BYTES = 2 * 1024 * 1024;
8
+ const TAIL_KEEP = 400;
9
+ const tail = [];
10
+
11
+ export function logDir() {
12
+ return path.join(storeDir(), "logs");
13
+ }
14
+
15
+ export function logPath() {
16
+ return path.join(logDir(), "cloud-backup.log");
17
+ }
18
+
19
+ function rotateIfNeeded() {
20
+ try {
21
+ const st = fs.statSync(logPath());
22
+ if (st.size <= MAX_BYTES) return;
23
+ const old = logPath() + ".1";
24
+ try { fs.unlinkSync(old); } catch {}
25
+ fs.renameSync(logPath(), old);
26
+ } catch {}
27
+ }
28
+
29
+ // 敏感值兜底:日志会经 /logs 与「打开日志」外露,任何令牌形态的值都要在落盘前抹掉。
30
+ const SECRET_KEY = /(token|secret|password|passwd|authorization|cookie|signature|accesskey)/i;
31
+ const SECRET_PATTERNS = [
32
+ /((?:access_token|refresh_token|token|signature|Signature|OSSAccessKeyId|security-token|x-oss-signature|sig)=)[^&\s"',]+/g,
33
+ /(Bearer\s+)[A-Za-z0-9._\-]{8,}/g,
34
+ /((?:access_token|refresh_token|token|password)["']?\s*:\s*["'])[^"']+/g,
35
+ ];
36
+
37
+ export function redact(text) {
38
+ let s = String(text === null || text === undefined ? "" : text);
39
+ for (const re of SECRET_PATTERNS) s = s.replace(re, "$1***");
40
+ return s;
41
+ }
42
+
43
+ function fmt(v) {
44
+ if (v === null || v === undefined) return "-";
45
+ if (typeof v === "number" || typeof v === "boolean") return String(v);
46
+ if (v instanceof Error) return JSON.stringify({ message: v.message, code: v.code || undefined });
47
+ const s = typeof v === "string" ? v : JSON.stringify(v);
48
+ return /[\s"=]/.test(s) ? JSON.stringify(s) : s;
49
+ }
50
+
51
+ export function logEvent(level, event, fields) {
52
+ const at = new Date().toISOString();
53
+ let line = at + " " + String(level || "info").toUpperCase().padEnd(5) + " " + event;
54
+ if (fields && typeof fields === "object") {
55
+ for (const k of Object.keys(fields)) {
56
+ if (fields[k] === undefined) continue;
57
+ line += " " + k + "=" + (SECRET_KEY.test(k) ? "***" : redact(fmt(fields[k])));
58
+ }
59
+ }
60
+ tail.push(line);
61
+ if (tail.length > TAIL_KEEP) tail.length = TAIL_KEEP;
62
+ try {
63
+ fs.mkdirSync(logDir(), { recursive: true });
64
+ rotateIfNeeded();
65
+ fs.appendFileSync(logPath(), line + "\n", "utf8");
66
+ } catch {}
67
+ return line;
68
+ }
69
+
70
+ export function logInfo(event, fields) { return logEvent("info", event, fields); }
71
+ export function logWarn(event, fields) { return logEvent("warn", event, fields); }
72
+ export function logError(event, fields) { return logEvent("error", event, fields); }
73
+
74
+ export function tailLines(n) {
75
+ const want = Math.max(1, Math.min(2000, Number(n) || 200));
76
+ try {
77
+ const txt = fs.readFileSync(logPath(), "utf8");
78
+ return txt.split(/\r?\n/).filter(Boolean).slice(-want);
79
+ } catch (e) {
80
+ return tail.slice(-want);
81
+ }
82
+ }
83
+
84
+ export function logStats() {
85
+ let bytes = 0;
86
+ let rotatedBytes = 0;
87
+ try { bytes = fs.statSync(logPath()).size; } catch {}
88
+ try { rotatedBytes = fs.statSync(logPath() + ".1").size; } catch {}
89
+ return { dir: logDir(), file: logPath(), bytes, rotatedBytes };
90
+ }
91
+
92
+ // 下载完成度自检:块数与字节数两条线必须自洽,偏差写日志供排查
93
+ export function checkDownloadConsistency(p) {
94
+ const issues = [];
95
+ const total = Number(p && p.total) || 0;
96
+ const done = Number(p && p.done) || 0;
97
+ const needBytes = Number(p && p.needBytes) || 0;
98
+ const bytes = Number(p && p.bytes) || 0;
99
+ if (done > total) issues.push("done exceeds total");
100
+ if (needBytes > 0 && bytes > needBytes * 1.02) issues.push("bytes exceed needBytes by >2%");
101
+ if (total > 0 && done === total && needBytes > 0 && bytes < needBytes * 0.98) issues.push("done complete but bytes short by >2%");
102
+ // 块大小差异可达上千倍(小会话文件 vs 大二进制),块百分比与字节百分比天然不同步,不作告警
103
+ const pctByBlocks = total > 0 ? Math.round((done / total) * 100) : 0;
104
+ const pctByBytes = needBytes > 0 ? Math.round((bytes / needBytes) * 100) : pctByBlocks;
105
+ if (issues.length) logWarn("pull.consistency", { total, done, needBytes, bytes, issues: issues.join("; ") });
106
+ return { ok: issues.length === 0, issues, pctByBlocks, pctByBytes };
107
+ }
@@ -0,0 +1,104 @@
1
+ // 子进程一律 spawn + 参数数组:不把用户可控字符串拼进命令行,避免注入。
2
+ // Windows 下 .cmd/.bat 不能用 shell:false 直spawn(EINVAL),只能经 cmd.exe 转发并逐参数转义。
3
+ import { spawn } from "node:child_process";
4
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+
7
+ const MAX_OUT_BYTES = 8 * 1024 * 1024;
8
+
9
+ /** 把「可执行名」解析成磁盘上真实存在的文件(补 .cmd/.exe/.bat,再沿 PATH 找)。 */
10
+ export function resolveExe(cmd) {
11
+ const c = String(cmd || "").trim();
12
+ if (!c) return null;
13
+ const direct = [c, c + ".cmd", c + ".exe", c + ".bat"];
14
+ for (const p of direct) {
15
+ try { if (fs.existsSync(p)) return p; } catch { /* 忽略不可读候选 */ }
16
+ }
17
+ const seg = c.split(path.sep).pop() || c;
18
+ if (seg) {
19
+ // 带扩展名的可执行优先:PATH 里常有同名的无扩展脚本(nvm 的 npm),
20
+ // 它无法被 spawn 直接执行,必须先找 .cmd/.exe/.bat。
21
+ const exts = [".cmd", ".exe", ".bat", ""];
22
+ for (const ext of exts) {
23
+ for (const dir of String(process.env.PATH || "").split(path.delimiter)) {
24
+ if (!dir) continue;
25
+ const full = path.join(dir, seg + ext);
26
+ try { if (fs.existsSync(full)) return full; } catch { /* 忽略不可读候选 */ }
27
+ }
28
+ }
29
+ }
30
+ return c;
31
+ }
32
+
33
+ /** cmd.exe 安全引号:整体包双引号,内部双引号翻倍、% 翻倍。 */
34
+ function cmdQuote(arg) {
35
+ const s = String(arg);
36
+ if (s === "") return '""';
37
+ // 只翻倍双引号,避免参数被引号截断。cmd.exe 对未定义变量(%VAR%)与单 % 号原样保留,
38
+ // 翻倍 % 反而会把所有 % 写成 %%,破坏取值。已定义环境变量会被 cmd.exe 展开,
39
+ // 属其固有行为,命令行层面无法完全规避。
40
+ return '"' + s.replace(/"/g, '""') + '"';
41
+ }
42
+
43
+ function isShim(file) {
44
+ return process.platform === "win32" && /\.(cmd|bat)$/i.test(String(file || ""));
45
+ }
46
+
47
+ // 参数以数组传入;返回 { ok, code, killed, timedOut, stdout, stderr, error }
48
+ export function runCmd(file, args, { cwd, timeoutMs, env } = {}) {
49
+ return new Promise((resolve) => {
50
+ const resolved = resolveExe(file);
51
+ const list = (Array.isArray(args) ? args : []).map((a) => String(a));
52
+ const shim = isShim(resolved);
53
+ // .cmd/.bat 必须经 cmd.exe 转发(shell:false 直接 spawn 会 EINVAL)。
54
+ // /S 会剥掉命令串最外层一对引号,所以整条命令行再包一层引号;
55
+ // 内层每个参数各自加引号(内部 " 翻倍、% 翻倍),不会被解释成命令分隔符。
56
+ const argv = shim
57
+ ? [process.env.ComSpec || "cmd.exe", "/d", "/s", "/c", '"' + [cmdQuote(resolved), ...list.map(cmdQuote)].join(" ") + '"']
58
+ : [resolved, ...list];
59
+
60
+ const out = { ok: false, code: 1, killed: false, timedOut: false, stdout: "", stderr: "", error: null };
61
+ const chunks = { stdout: "", stderr: "" };
62
+ let done = false;
63
+ const finish = (extra) => {
64
+ if (done) return;
65
+ done = true;
66
+ Object.assign(out, extra);
67
+ out.stdout = chunks.stdout;
68
+ out.stderr = chunks.stderr;
69
+ resolve(out);
70
+ };
71
+
72
+ let child = null;
73
+ try {
74
+ child = spawn(argv[0], argv.slice(1), {
75
+ cwd,
76
+ timeout: timeoutMs,
77
+ windowsHide: true,
78
+ shell: false,
79
+ env,
80
+ windowsVerbatimArguments: shim,
81
+ });
82
+ } catch (e) {
83
+ finish({ error: String((e && e.message) || e) });
84
+ return;
85
+ }
86
+ if (child.error) {
87
+ finish({ error: String((child.error && child.error.message) || child.error) });
88
+ return;
89
+ }
90
+ if (child.stdout) child.stdout.on("data", (d) => { if (chunks.stdout.length < MAX_OUT_BYTES) chunks.stdout += String(d); });
91
+ if (child.stderr) child.stderr.on("data", (d) => { if (chunks.stderr.length < MAX_OUT_BYTES) chunks.stderr += String(d); });
92
+ child.on("error", (e) => { finish({ error: String((e && e.message) || e) }); });
93
+ child.on("close", (code, signal) => {
94
+ const killed = !!signal;
95
+ finish({
96
+ ok: code === 0,
97
+ code: typeof code === "number" ? code : 1,
98
+ killed,
99
+ timedOut: !!(killed && timeoutMs),
100
+ error: code === 0 ? null : (killed ? "命令被终止(" + String(signal || "signal") + ")" : "退出码 " + String(code)),
101
+ });
102
+ });
103
+ });
104
+ }
@@ -0,0 +1,42 @@
1
+ // lib/util/validate.js —— 入参白名单校验(stamp/hash 未校验即拼路径 → 路径穿越)
2
+
3
+ /** 合法快照 ID:主格式 YYYYMMDD-HHMMSS,或受限的字母数字变体(≤64,不含路径分隔符与 ..) */
4
+ export const STAMP_RE = /^(?:\d{8}-\d{6}|[A-Za-z0-9][A-Za-z0-9._-]{0,63})$/;
5
+ /** 合法 blob 键:sha256 十六进制 */
6
+ export const HASH_RE = /^[0-9a-f]{64}$/;
7
+
8
+ export function isStamp(v) {
9
+ return typeof v === "string" && STAMP_RE.test(v) && v.indexOf("..") < 0;
10
+ }
11
+
12
+ export function isHash(v) {
13
+ return typeof v === "string" && HASH_RE.test(v);
14
+ }
15
+
16
+ /** 校验通过返回原值;不通过抛错(错误文案可直接给用户看) */
17
+ export function assertHash(v, what = "hash") {
18
+ if (!isHash(v)) throw new Error(`非法 ${what}(必须是 64 位十六进制):${String(v).slice(0, 64)}`);
19
+ return v;
20
+ }
21
+
22
+ /** 是否本机来源:缺失(Node/脚本调用,浏览器跨站请求必带 Origin)、127.0.0.1、localhost、[::1]。
23
+ * "null" 不放行:沙箱 iframe、file:// 与被重定向的跨站请求都会带它,等同跨站。 */
24
+ export function isLocalOrigin(origin) {
25
+ if (!origin) return true;
26
+ const s = String(origin).trim().toLowerCase();
27
+ if (s === "null") return false;
28
+ return /^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/.test(s);
29
+ }
30
+
31
+ /** 非 GET 请求必须带的标记头。跨站脚本加自定义头会触发预检,而预检被 405 拒,等同关闭 CSRF。 */
32
+ export const CSRF_HEADER = "x-dshcb-csrf";
33
+ export function hasCsrfHeader(headers) {
34
+ return String((headers && headers[CSRF_HEADER]) || "").trim() === "1";
35
+ }
36
+
37
+ /** 夹取整数:非有限数一律回落 fallback,再夹到 [min,max] */
38
+ export function clampInt(v, fallback, min, max) {
39
+ const n = Number(v);
40
+ if (!Number.isFinite(n)) return fallback;
41
+ return Math.min(max, Math.max(min, Math.floor(n)));
42
+ }