fe-deploy-kit 0.0.0-stage → 1.0.0

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.
@@ -0,0 +1,321 @@
1
+ /**
2
+ * 安全守卫:所有"能被写坏东西"的输入,都必须先过这里。
3
+ *
4
+ * 设计目标(对应需求里的"只操作该项目的文件夹"):
5
+ * 1. 远程路径只接受绝对 POSIX 路径,拒绝 .. / 反斜杠 / 控制字符 / 多余斜杠;
6
+ * 2. 远程根目录不能是 /、/www、/www/wwwroot 这类"公共容器",防止误伤别的项目;
7
+ * 3. 目标目录必须严格位于远程根目录内部(不能相等,否则备份和暂存会落进网站根目录);
8
+ * 4. 配置项做白名单校验,拼错的键直接报错,避免"以为生效了其实没生效"。
9
+ */
10
+ import { createHash } from 'node:crypto';
11
+
12
+ export class GuardError extends Error {
13
+ constructor(message) {
14
+ super(message);
15
+ this.name = 'GuardError';
16
+ }
17
+ }
18
+
19
+ export class ConfigError extends GuardError {
20
+ constructor(message) {
21
+ super(message);
22
+ this.name = 'ConfigError';
23
+ }
24
+ }
25
+
26
+ // eslint-disable-next-line no-control-regex -- 这里就是要识别控制字符
27
+ const CONTROL_CHARS = /[\u0000-\u001f\u007f]/;
28
+
29
+ /** 这些远程根目录太"大",一旦在上面做备份/切换会波及别的项目,直接拒绝。 */
30
+ export const BLOCKED_REMOTE_ROOTS = new Set([
31
+ '/',
32
+ '/bin',
33
+ '/boot',
34
+ '/data',
35
+ '/dev',
36
+ '/etc',
37
+ '/home',
38
+ '/lib',
39
+ '/lib64',
40
+ '/media',
41
+ '/mnt',
42
+ '/opt',
43
+ '/proc',
44
+ '/root',
45
+ '/run',
46
+ '/sbin',
47
+ '/srv',
48
+ '/sys',
49
+ '/tmp',
50
+ '/usr',
51
+ '/var',
52
+ '/var/www',
53
+ '/var/www/html',
54
+ '/www',
55
+ '/www/wwwroot'
56
+ ]);
57
+
58
+ /** 目录名本身是"公共容器"的,也拒绝(例如 /srv/wwwroot、/data/public_html)。 */
59
+ export const BLOCKED_REMOTE_ROOT_BASENAMES = new Set(['wwwroot', 'public_html', 'www']);
60
+
61
+ export function pathSegments(value) {
62
+ if (value === '/') return [];
63
+ return value.split('/').slice(1);
64
+ }
65
+
66
+ /**
67
+ * 规范化一个远程绝对路径。不做"猜测式修复",只接受干净的输入。
68
+ * @param {unknown} raw
69
+ * @param {string} label 出错时给人看的名字
70
+ */
71
+ export function normalizeRemotePath(raw, label = '远程路径') {
72
+ if (typeof raw !== 'string' || raw.trim() === '') {
73
+ throw new GuardError(`${label}不能为空`);
74
+ }
75
+ if (CONTROL_CHARS.test(raw)) {
76
+ throw new GuardError(`${label}包含控制字符:${JSON.stringify(raw)}`);
77
+ }
78
+ const value = raw.trim();
79
+ if (value.includes('\\')) {
80
+ throw new GuardError(`${label}必须使用 / 作为分隔符:${value}`);
81
+ }
82
+ if (!value.startsWith('/')) {
83
+ throw new GuardError(`${label}必须是绝对路径(以 / 开头):${value}`);
84
+ }
85
+ if (value === '/') return '/';
86
+ if (value.startsWith('//')) {
87
+ throw new GuardError(`${label}不能以 // 开头:${value}`);
88
+ }
89
+ const segments = value.split('/').slice(1);
90
+ if (segments.some(segment => segment === '')) {
91
+ throw new GuardError(`${label}包含多余的斜杠:${value}`);
92
+ }
93
+ if (segments.some(segment => segment === '.' || segment === '..')) {
94
+ throw new GuardError(`${label}不能包含 . 或 .. 路径段:${value}`);
95
+ }
96
+ return `/${segments.join('/')}`;
97
+ }
98
+
99
+ /**
100
+ * 校验"允许我动手的范围"的根目录。
101
+ * 它必须是项目自己的目录,不能是服务器公共目录。
102
+ */
103
+ export function assertRemoteRoot(raw) {
104
+ const root = normalizeRemotePath(raw, 'remoteRoot');
105
+ const lower = root.toLowerCase();
106
+ if (BLOCKED_REMOTE_ROOTS.has(lower)) {
107
+ throw new GuardError(
108
+ `remoteRoot 不能是公共目录 ${root},否则可能碰到服务器上别的项目。请填写这个前端项目自己的父目录,例如 /www/wwwroot/shop.scylg.cn`
109
+ );
110
+ }
111
+ const segments = pathSegments(root);
112
+ if (segments.length < 2) {
113
+ throw new GuardError(`remoteRoot 层级太浅(${root}),请填写到项目目录,例如 /www/wwwroot/shop.scylg.cn`);
114
+ }
115
+ if (BLOCKED_REMOTE_ROOT_BASENAMES.has(segments[segments.length - 1].toLowerCase())) {
116
+ throw new GuardError(`remoteRoot 不能是公共目录 ${root},请再往下指一层到这个项目,例如 ${root}/<项目名>`);
117
+ }
118
+ return root;
119
+ }
120
+
121
+ /**
122
+ * 校验产物目录:必须严格在 remoteRoot 内部。
123
+ * 严格内部(不能相等)是为了保证 .deploy 暂存/备份目录不会被放进网站根目录,
124
+ * 避免通过 URL 直接下载到旧版本的源码。
125
+ */
126
+ export function assertRemotePath(raw, remoteRoot) {
127
+ const root = assertRemoteRoot(remoteRoot);
128
+ const target = normalizeRemotePath(raw, 'remotePath');
129
+ if (target === root) {
130
+ throw new GuardError(
131
+ `remotePath 不能等于 remoteRoot:备份和暂存目录会因为位于网站根目录而对外可访问。` +
132
+ `请把 remoteRoot 设为 ${root} 的父目录,remotePath 设为具体的产物目录(例如 ${root}/console)`
133
+ );
134
+ }
135
+ if (!target.startsWith(`${root}/`)) {
136
+ throw new GuardError(`remotePath 必须是 remoteRoot 的子目录(remoteRoot=${root},remotePath=${target})`);
137
+ }
138
+ return target;
139
+ }
140
+
141
+ /** 目标是否落在 root 内部(相等也算,用于根目录自身)。 */
142
+ export function isInside(root, target) {
143
+ if (root === '/') return target.startsWith('/');
144
+ return target === root || target.startsWith(`${root}/`);
145
+ }
146
+
147
+ /** 单层名字(文件名/目录名)白名单校验,挡住 ../ 一类的注入。 */
148
+ export function assertSafeEntryName(name) {
149
+ if (typeof name !== 'string' || name === '' || name === '.' || name === '..') {
150
+ throw new GuardError(`非法的文件/目录名:${JSON.stringify(name)}`);
151
+ }
152
+ if (CONTROL_CHARS.test(name) || name.includes('/') || name.includes('\\')) {
153
+ throw new GuardError(`非法的文件/目录名:${JSON.stringify(name)}`);
154
+ }
155
+ if (Buffer.byteLength(name, 'utf8') > 200) {
156
+ throw new GuardError(`文件/目录名过长:${name.slice(0, 40)}...`);
157
+ }
158
+ return name;
159
+ }
160
+
161
+ /** 拼接远程路径,并再次确认没有跑出 root。 */
162
+ export function joinInside(root, base, name) {
163
+ assertSafeEntryName(name);
164
+ const joined = base === '/' ? `/${name}` : `${base}/${name}`;
165
+ if (!isInside(root, joined)) {
166
+ throw new GuardError(`路径越界:${joined} 不在 ${root} 内`);
167
+ }
168
+ return joined;
169
+ }
170
+
171
+ /** OpenSSH 风格的主机公钥指纹:SHA256:base64(去掉 = 补位)。 */
172
+ export function hostFingerprint(keyBlob) {
173
+ const digest = createHash('sha256').update(keyBlob).digest('base64').replace(/=+$/, '');
174
+ return `SHA256:${digest}`;
175
+ }
176
+
177
+ export function assertFingerprint(value) {
178
+ if (typeof value !== 'string' || !/^SHA256:[A-Za-z0-9+/]{43}$/.test(value.trim())) {
179
+ throw new GuardError(`hostFingerprint 格式不对,应形如 SHA256:xxxxxxxx,实际为 ${JSON.stringify(value)}`);
180
+ }
181
+ return value.trim();
182
+ }
183
+
184
+ /** 时间戳目录名:20261126-174512 */
185
+ export function makeStamp(date = new Date()) {
186
+ const pad = (n, len = 2) => String(n).padStart(len, '0');
187
+ return (
188
+ `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}` +
189
+ `-${pad(date.getHours())}${pad(date.getMinutes())}${pad(date.getSeconds())}`
190
+ );
191
+ }
192
+
193
+ const CONFIG_KEYS = new Set([
194
+ 'host',
195
+ 'port',
196
+ 'username',
197
+ 'remoteRoot',
198
+ 'remotePath',
199
+ 'hostFingerprint',
200
+ 'keyFile',
201
+ 'keepBackups',
202
+ 'appName',
203
+ 'preserve',
204
+ 'setPermissions',
205
+ 'buildMode'
206
+ ]);
207
+
208
+ const DEFAULT_PRESERVE = ['.htaccess', '.user.ini', '.well-known'];
209
+
210
+ function assertSafeLocalFile(value, label) {
211
+ if (typeof value !== 'string' || value.trim() === '') {
212
+ throw new ConfigError(`${label}必须是非空的本地文件路径`);
213
+ }
214
+ return value.trim();
215
+ }
216
+
217
+ /**
218
+ * 校验并规范化配置文件。
219
+ * 只认识白名单里的键:拼错的键会直接报错,避免"写了配置但没生效"。
220
+ */
221
+ export function validateConfig(raw, { allowMissingFingerprint = true } = {}) {
222
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
223
+ throw new ConfigError('配置文件内容必须是一个 JSON 对象');
224
+ }
225
+ for (const key of Object.keys(raw)) {
226
+ if (!CONFIG_KEYS.has(key)) {
227
+ throw new ConfigError(`不认识的配置项 "${key}"(拼写错误?可用项:${[...CONFIG_KEYS].join(', ')})`);
228
+ }
229
+ }
230
+
231
+ const host = typeof raw.host === 'string' ? raw.host.trim() : '';
232
+ if (!host) throw new ConfigError('host(服务器地址)不能为空');
233
+ if (/[\s/\\@'"`]/.test(host)) throw new ConfigError(`host 不能包含空格、斜杠或引号:${host}`);
234
+ if (host.length > 253) throw new ConfigError('host 过长');
235
+
236
+ const port = raw.port === undefined ? 22 : raw.port;
237
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
238
+ throw new ConfigError(`port 必须是 1-65535 之间的整数,实际为 ${JSON.stringify(raw.port)}`);
239
+ }
240
+
241
+ const username = typeof raw.username === 'string' ? raw.username.trim() : '';
242
+ if (!username) throw new ConfigError('username(登录账号)不能为空');
243
+ if (/[\s:/\\@'"`]/.test(username)) {
244
+ throw new ConfigError(`username 不能包含空格、冒号、斜杠等字符:${username}`);
245
+ }
246
+
247
+ const remoteRoot = assertRemoteRoot(raw.remoteRoot);
248
+ const remotePath = assertRemotePath(raw.remotePath, remoteRoot);
249
+
250
+ let hostFingerprintValue = null;
251
+ if (raw.hostFingerprint !== undefined && raw.hostFingerprint !== null && raw.hostFingerprint !== '') {
252
+ hostFingerprintValue = assertFingerprint(raw.hostFingerprint);
253
+ } else if (!allowMissingFingerprint) {
254
+ throw new ConfigError(
255
+ 'hostFingerprint 不能为空:请先运行一次 `npx fe-deploy check` 来确认并记录服务器指纹'
256
+ );
257
+ }
258
+
259
+ const keyFile =
260
+ raw.keyFile === undefined || raw.keyFile === null || raw.keyFile === ''
261
+ ? null
262
+ : assertSafeLocalFile(raw.keyFile, 'keyFile');
263
+
264
+ const keepBackups = raw.keepBackups === undefined ? 5 : raw.keepBackups;
265
+ if (!Number.isInteger(keepBackups) || keepBackups < 0 || keepBackups > 50) {
266
+ throw new ConfigError(`keepBackups 必须是 0-50 之间的整数,实际为 ${JSON.stringify(raw.keepBackups)}`);
267
+ }
268
+
269
+ const buildMode = raw.buildMode === undefined ? 'production' : raw.buildMode;
270
+ if (typeof buildMode !== 'string' || !/^[A-Za-z0-9._-]{1,32}$/.test(buildMode)) {
271
+ throw new ConfigError('buildMode 只能是简单的模式名,例如 production / development');
272
+ }
273
+
274
+ const preserveInput = raw.preserve === undefined ? DEFAULT_PRESERVE : raw.preserve;
275
+ if (!Array.isArray(preserveInput)) throw new ConfigError('preserve 必须是字符串数组');
276
+ const preserve = preserveInput.map(name => assertSafeEntryName(name));
277
+
278
+ const setPermissions = raw.setPermissions === undefined ? false : raw.setPermissions;
279
+ if (typeof setPermissions !== 'boolean') throw new ConfigError('setPermissions 必须是 true / false');
280
+
281
+ const defaultApp = pathSegments(remotePath).pop() || 'app';
282
+ const appNameRaw = raw.appName === undefined ? defaultApp : raw.appName;
283
+ if (typeof appNameRaw !== 'string' || !/^[A-Za-z0-9._-]{1,64}$/.test(appNameRaw.trim())) {
284
+ throw new ConfigError(
285
+ `appName 只能包含字母、数字、点、下划线、短横线(1-64 位),实际为 ${JSON.stringify(raw.appName)}`
286
+ );
287
+ }
288
+
289
+ return Object.freeze({
290
+ host,
291
+ port,
292
+ username,
293
+ remoteRoot,
294
+ remotePath,
295
+ hostFingerprint: hostFingerprintValue,
296
+ keyFile,
297
+ keepBackups,
298
+ appName: appNameRaw.trim(),
299
+ preserve: Object.freeze([...new Set(preserve)]),
300
+ setPermissions,
301
+ buildMode
302
+ });
303
+ }
304
+
305
+ /** 供日志使用的安全副本(永不含密码)。 */
306
+ export function describeConfig(config) {
307
+ return {
308
+ host: config.host,
309
+ port: config.port,
310
+ username: config.username,
311
+ remoteRoot: config.remoteRoot,
312
+ remotePath: config.remotePath,
313
+ hostFingerprint: config.hostFingerprint,
314
+ keepBackups: config.keepBackups,
315
+ appName: config.appName,
316
+ preserve: config.preserve,
317
+ setPermissions: config.setPermissions,
318
+ buildMode: config.buildMode,
319
+ auth: config.keyFile ? 'private-key' : 'password'
320
+ };
321
+ }
@@ -0,0 +1,196 @@
1
+ /**
2
+ * 内存版远程文件系统,仅用于测试。
3
+ *
4
+ * 它实现了与 createSftpRemote 完全相同的接口,
5
+ * 因此部署/回滚逻辑可以在不连服务器的情况下被完整跑一遍,
6
+ * 包括"移动到一半失败"这种真实环境很难复现的情况(通过 hooks 注入)。
7
+ */
8
+ import { RemoteError } from './remote.js';
9
+
10
+ function parentOf(path) {
11
+ const index = path.lastIndexOf('/');
12
+ if (index <= 0) return '/';
13
+ return path.slice(0, index);
14
+ }
15
+
16
+ function baseName(path) {
17
+ return path.slice(path.lastIndexOf('/') + 1);
18
+ }
19
+
20
+ export function createMemoryRemote(initial = {}) {
21
+ const dirs = new Set(['/']);
22
+ const files = new Map();
23
+ const links = new Map();
24
+ const clock = { now: initial.now ?? 1_700_000_000_000 };
25
+ const hooks = {};
26
+
27
+ for (const dir of initial.dirs ?? []) dirs.add(dir);
28
+ const ensureParents = filePath => {
29
+ let parent = parentOf(filePath);
30
+ while (parent !== '/' && !dirs.has(parent)) {
31
+ dirs.add(parent);
32
+ parent = parentOf(parent);
33
+ }
34
+ };
35
+ for (const [path, size] of Object.entries(initial.files ?? {})) {
36
+ ensureParents(path);
37
+ files.set(path, { size, mode: 0o644, mtimeMs: clock.now });
38
+ }
39
+ for (const [path, target] of Object.entries(initial.links ?? {})) {
40
+ ensureParents(path);
41
+ links.set(path, target);
42
+ }
43
+
44
+ const exists = path => dirs.has(path) || files.has(path) || links.has(path);
45
+
46
+ const resolve = path => {
47
+ let current = path;
48
+ for (let i = 0; i < 8 && links.has(current); i += 1) current = links.get(current);
49
+ return current;
50
+ };
51
+
52
+ const assertParentDir = path => {
53
+ const parent = parentOf(path);
54
+ if (!dirs.has(parent)) throw new RemoteError(`父目录不存在:${parent}`, { path: parent, code: 2 });
55
+ };
56
+
57
+ const children = path => {
58
+ const result = [];
59
+ for (const candidate of [...dirs, ...files.keys(), ...links.keys()]) {
60
+ if (candidate === path) continue;
61
+ if (parentOf(candidate) === path) {
62
+ const type = dirs.has(candidate) ? 'dir' : files.has(candidate) ? 'file' : 'link';
63
+ const mtimeMs = files.get(candidate)?.mtimeMs ?? clock.now;
64
+ result.push({ name: baseName(candidate), type, size: files.get(candidate)?.size ?? 0, mtimeMs });
65
+ }
66
+ }
67
+ return result.toSorted((a, b) => a.name.localeCompare(b.name));
68
+ };
69
+
70
+ const removePath = path => {
71
+ if (files.delete(path)) return;
72
+ if (links.delete(path)) return;
73
+ dirs.delete(path);
74
+ };
75
+
76
+ const remote = {
77
+ kind: 'memory',
78
+ hooks,
79
+ clock,
80
+
81
+ setNow(value) {
82
+ clock.now = value;
83
+ },
84
+
85
+ /** 测试用:直接写入文件大小(模拟 SFTP 服务端收到的内容)。 */
86
+ setFile(path, size) {
87
+ ensureParents(path);
88
+ files.set(path, { size, mode: 0o644, mtimeMs: clock.now });
89
+ },
90
+
91
+ snapshot() {
92
+ return {
93
+ dirs: [...dirs].toSorted(),
94
+ files: [...files.entries()]
95
+ .toSorted(([a], [b]) => a.localeCompare(b))
96
+ .map(([path, meta]) => ({ path, size: meta.size })),
97
+ links: [...links.entries()].toSorted()
98
+ };
99
+ },
100
+
101
+ async realpath(path) {
102
+ if (!exists(path)) throw new RemoteError(`realpath 失败:文件不存在 ${path}`, { path, code: 2 });
103
+ return resolve(path);
104
+ },
105
+
106
+ async stat(path) {
107
+ if (links.has(path)) {
108
+ const target = resolve(path);
109
+ if (!exists(target)) return null;
110
+ return this.stat(target);
111
+ }
112
+ if (dirs.has(path)) return { type: 'dir', size: 0, mtimeMs: clock.now };
113
+ const file = files.get(path);
114
+ if (file) return { type: 'file', size: file.size, mtimeMs: file.mtimeMs };
115
+ return null;
116
+ },
117
+
118
+ async readdir(path) {
119
+ if (!dirs.has(path)) return null;
120
+ return children(path);
121
+ },
122
+
123
+ async mkdir(path) {
124
+ if (hooks.mkdir) hooks.mkdir(path);
125
+ if (exists(path)) throw new RemoteError(`目录已存在:${path}`, { path, code: 11 });
126
+ assertParentDir(path);
127
+ dirs.add(path);
128
+ },
129
+
130
+ async rmdir(path) {
131
+ if (hooks.rmdir) hooks.rmdir(path);
132
+ if (!dirs.has(path)) throw new RemoteError(`目录不存在:${path}`, { path, code: 2 });
133
+ if (children(path).length > 0) throw new RemoteError(`目录不为空:${path}`, { path, code: 4 });
134
+ dirs.delete(path);
135
+ },
136
+
137
+ async unlink(path) {
138
+ if (hooks.unlink) hooks.unlink(path);
139
+ if (!files.has(path)) throw new RemoteError(`文件不存在:${path}`, { path, code: 2 });
140
+ files.delete(path);
141
+ },
142
+
143
+ async rename(from, to) {
144
+ if (hooks.rename) hooks.rename(from, to);
145
+ if (!exists(from)) throw new RemoteError(`重命名源不存在:${from}`, { path: from, code: 2 });
146
+ if (exists(to)) throw new RemoteError(`重命名目标已存在:${to}`, { path: to, code: 4 });
147
+ assertParentDir(to);
148
+
149
+ if (dirs.has(from)) {
150
+ const affected = [...dirs].filter(dir => dir === from || dir.startsWith(`${from}/`)).toSorted();
151
+ for (const dir of affected) {
152
+ const suffix = dir.slice(from.length);
153
+ dirs.delete(dir);
154
+ dirs.add(`${to}${suffix}`);
155
+ }
156
+ const affectedFiles = [...files.keys()].filter(path => path.startsWith(`${from}/`));
157
+ for (const path of affectedFiles) {
158
+ const meta = files.get(path);
159
+ files.delete(path);
160
+ files.set(`${to}${path.slice(from.length)}`, meta);
161
+ }
162
+ const affectedLinks = [...links.keys()].filter(path => path.startsWith(`${from}/`));
163
+ for (const path of affectedLinks) {
164
+ const target = links.get(path);
165
+ links.delete(path);
166
+ links.set(`${to}${path.slice(from.length)}`, target);
167
+ }
168
+ } else if (files.has(from)) {
169
+ const meta = files.get(from);
170
+ files.delete(from);
171
+ files.set(to, meta);
172
+ } else {
173
+ const target = links.get(from);
174
+ links.delete(from);
175
+ links.set(to, target);
176
+ }
177
+ },
178
+
179
+ async chmod(path, mode) {
180
+ if (hooks.chmod) hooks.chmod(path, mode);
181
+ const file = files.get(path);
182
+ if (!file) throw new RemoteError(`chmod 目标不存在:${path}`, { path, code: 2 });
183
+ file.mode = mode;
184
+ },
185
+
186
+ async putFile(localPath, remotePath, { size } = {}) {
187
+ const override = hooks.putFile ? hooks.putFile(localPath, remotePath) : undefined;
188
+ assertParentDir(remotePath);
189
+ const finalSize = typeof override === 'number' ? override : typeof size === 'number' ? size : 0;
190
+ files.set(remotePath, { size: finalSize, mode: 0o644, mtimeMs: clock.now });
191
+ return finalSize;
192
+ }
193
+ };
194
+
195
+ return remote;
196
+ }
@@ -0,0 +1,162 @@
1
+ /**
2
+ * 远程文件系统抽象。
3
+ *
4
+ * 生产实现基于 ssh2 的 SFTP:全程只有文件传输操作,**不会在服务器上执行任何 shell 命令**,
5
+ * 因此不存在命令注入、也不依赖服务器上有 mv/cp/rm 等工具。
6
+ *
7
+ * 每个方法都做一次"是否在允许范围内"的检查(纵深防御):
8
+ * 即便上层逻辑写错,也不会写到 remoteRoot 之外。
9
+ */
10
+ import { isInside, GuardError } from './guard.js';
11
+
12
+ export class RemoteError extends Error {
13
+ constructor(message, { code, path } = {}) {
14
+ super(message);
15
+ this.name = 'RemoteError';
16
+ this.code = code;
17
+ this.path = path;
18
+ }
19
+ }
20
+
21
+ const ENOENT_CODES = new Set([2, 4]);
22
+ const EEXIST_CODES = new Set([11, 4]);
23
+
24
+ function isNoSuchFile(err) {
25
+ return ENOENT_CODES.has(err?.code) || /no such file/i.test(String(err?.message ?? ''));
26
+ }
27
+
28
+ function toRemoteError(action, err, path) {
29
+ const detail = err?.message || String(err);
30
+ let hint = '';
31
+ if (err?.code === 3) hint = '(权限不足:请确认该账号对目标目录有写权限)';
32
+ else if (/failure/i.test(detail) && /rename/i.test(action)) hint = '(移动失败:暂存目录与目标目录可能不在同一分区)';
33
+ return new RemoteError(`${action} 失败:${detail}${hint}`, { code: err?.code, path });
34
+ }
35
+
36
+ /**
37
+ * @param {import('ssh2').SFTPWrapper} sftp
38
+ * @param {{root: string, check?: (path: string) => void}} options
39
+ */
40
+ export function createSftpRemote(sftp, { root, check }) {
41
+ const guard = path => {
42
+ if (typeof path !== 'string' || !path.startsWith('/')) {
43
+ throw new GuardError(`远程操作路径必须是绝对路径:${path}`);
44
+ }
45
+ if (!isInside(root, path)) {
46
+ throw new GuardError(`拒绝操作 ${path}:超出允许范围 ${root}`);
47
+ }
48
+ if (check) check(path);
49
+ return path;
50
+ };
51
+
52
+ const invoke = (method, ...args) =>
53
+ new Promise((resolve, reject) => {
54
+ sftp[method](...args, (err, result) => (err ? reject(toRemoteError(method, err, args[0])) : resolve(result)));
55
+ });
56
+
57
+ return {
58
+ kind: 'sftp',
59
+
60
+ async realpath(path) {
61
+ guard(path);
62
+ const result = await invoke('realpath', path);
63
+ if (typeof result !== 'string' || !result.startsWith('/')) {
64
+ throw new RemoteError(`realpath 返回异常:${JSON.stringify(result)}`, { path });
65
+ }
66
+ return result;
67
+ },
68
+
69
+ async stat(path) {
70
+ guard(path);
71
+ try {
72
+ const attrs = await invoke('stat', path);
73
+ return {
74
+ type: attrs.isDirectory() ? 'dir' : attrs.isSymbolicLink() ? 'link' : 'file',
75
+ size: attrs.size ?? 0,
76
+ mtimeMs: (attrs.mtime ?? 0) * 1000
77
+ };
78
+ } catch (err) {
79
+ if (err instanceof RemoteError && isNoSuchFile({ code: err.code, message: err.message })) return null;
80
+ throw err;
81
+ }
82
+ },
83
+
84
+ async readdir(path) {
85
+ guard(path);
86
+ let list;
87
+ try {
88
+ list = await invoke('readdir', path);
89
+ } catch (err) {
90
+ if (err instanceof RemoteError && isNoSuchFile({ code: err.code, message: err.message })) return null;
91
+ throw err;
92
+ }
93
+ return list
94
+ .filter(entry => entry.filename !== '.' && entry.filename !== '..')
95
+ .map(entry => ({
96
+ name: entry.filename,
97
+ type: entry.attrs.isDirectory() ? 'dir' : entry.attrs.isSymbolicLink() ? 'link' : 'file',
98
+ size: entry.attrs.size ?? 0,
99
+ mtimeMs: (entry.attrs.mtime ?? 0) * 1000
100
+ }));
101
+ },
102
+
103
+ async mkdir(path) {
104
+ guard(path);
105
+ try {
106
+ await invoke('mkdir', path);
107
+ } catch (err) {
108
+ if (err instanceof RemoteError && EEXIST_CODES.has(err.code)) {
109
+ const existing = await this.stat(path);
110
+ if (existing?.type === 'dir') return;
111
+ }
112
+ throw err;
113
+ }
114
+ },
115
+
116
+ async rmdir(path) {
117
+ guard(path);
118
+ return invoke('rmdir', path);
119
+ },
120
+
121
+ async unlink(path) {
122
+ guard(path);
123
+ return invoke('unlink', path);
124
+ },
125
+
126
+ async rename(from, to) {
127
+ guard(from);
128
+ guard(to);
129
+ return invoke('rename', from, to);
130
+ },
131
+
132
+ async chmod(path, mode) {
133
+ guard(path);
134
+ return invoke('chmod', path, mode);
135
+ },
136
+
137
+ /**
138
+ * 上传一个文件。先传成临时名字再改名,避免服务器上出现写了一半的文件。
139
+ */
140
+ async putFile(localPath, remotePath, { size } = {}) {
141
+ guard(remotePath);
142
+ const tempPath = `${remotePath}.part`;
143
+ guard(tempPath);
144
+ await new Promise((resolve, reject) => {
145
+ sftp.fastPut(localPath, tempPath, { mode: 0o644, concurrency: 4, step: () => {} }, err =>
146
+ err ? reject(toRemoteError('fastPut', err, remotePath)) : resolve()
147
+ );
148
+ });
149
+ const written = await this.stat(tempPath);
150
+ if (!written || written.type !== 'file') {
151
+ throw new RemoteError(`上传后找不到临时文件:${tempPath}`, { path: tempPath });
152
+ }
153
+ if (typeof size === 'number' && written.size !== size) {
154
+ throw new RemoteError(`上传不完整:${remotePath} 本地 ${size} 字节,服务器 ${written.size} 字节`, {
155
+ path: remotePath
156
+ });
157
+ }
158
+ await this.rename(tempPath, remotePath);
159
+ return written.size;
160
+ }
161
+ };
162
+ }