@lzwme/sserver 0.0.11 → 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.
Files changed (67) hide show
  1. package/README.MD +71 -108
  2. package/dist/assets/assets/localsend/style.css +2 -0
  3. package/dist/assets/assets/localsend/vendor/qr-code-styling.js +2 -0
  4. package/dist/assets/localsend/style.css +2 -0
  5. package/dist/assets/localsend/vendor/qr-code-styling.js +2 -0
  6. package/dist/cli.js +9 -6
  7. package/dist/config.d.ts +38 -1
  8. package/dist/config.js +54 -9
  9. package/dist/lib/get-cert.js +1 -1
  10. package/dist/lib/merge-config.d.ts +9 -0
  11. package/dist/lib/merge-config.js +66 -0
  12. package/dist/lib/utils.d.ts +27 -1
  13. package/dist/lib/utils.js +94 -14
  14. package/dist/localsend/audit.d.ts +36 -0
  15. package/dist/localsend/audit.js +104 -0
  16. package/dist/localsend/auth.d.ts +94 -0
  17. package/dist/localsend/auth.js +227 -0
  18. package/dist/localsend/cache.d.ts +34 -0
  19. package/dist/localsend/cache.js +269 -0
  20. package/dist/localsend/chunk.d.ts +114 -0
  21. package/dist/localsend/chunk.js +475 -0
  22. package/dist/localsend/cleaner.d.ts +19 -0
  23. package/dist/localsend/cleaner.js +80 -0
  24. package/dist/localsend/client/app.js +4131 -0
  25. package/dist/localsend/client/crypto.js +233 -0
  26. package/dist/localsend/client/favicon.png +0 -0
  27. package/dist/localsend/client/icons/icon-192.png +0 -0
  28. package/dist/localsend/client/icons/icon-512.png +0 -0
  29. package/dist/localsend/client/index.html +451 -0
  30. package/dist/localsend/client/manifest.webmanifest +33 -0
  31. package/dist/localsend/client/sw.js +128 -0
  32. package/dist/localsend/guard.d.ts +58 -0
  33. package/dist/localsend/guard.js +210 -0
  34. package/dist/localsend/index.d.ts +52 -0
  35. package/dist/localsend/index.js +1771 -0
  36. package/dist/localsend/manage.d.ts +96 -0
  37. package/dist/localsend/manage.js +304 -0
  38. package/dist/localsend/metrics.d.ts +26 -0
  39. package/dist/localsend/metrics.js +58 -0
  40. package/dist/localsend/paste.d.ts +72 -0
  41. package/dist/localsend/paste.js +125 -0
  42. package/dist/localsend/path.d.ts +33 -0
  43. package/dist/localsend/path.js +151 -0
  44. package/dist/localsend/query.d.ts +78 -0
  45. package/dist/localsend/query.js +147 -0
  46. package/dist/localsend/secret.d.ts +31 -0
  47. package/dist/localsend/secret.js +96 -0
  48. package/dist/localsend/settings.d.ts +53 -0
  49. package/dist/localsend/settings.js +285 -0
  50. package/dist/localsend/share.d.ts +35 -0
  51. package/dist/localsend/share.js +117 -0
  52. package/dist/localsend/temp.d.ts +10 -0
  53. package/dist/localsend/temp.js +47 -0
  54. package/dist/localsend/ticket.d.ts +40 -0
  55. package/dist/localsend/ticket.js +98 -0
  56. package/dist/localsend/trash.d.ts +39 -0
  57. package/dist/localsend/trash.js +261 -0
  58. package/dist/localsend/webdav.d.ts +50 -0
  59. package/dist/localsend/webdav.js +530 -0
  60. package/dist/localsend/zip.d.ts +20 -0
  61. package/dist/localsend/zip.js +186 -0
  62. package/dist/proxy/php-proxy.js +31 -20
  63. package/dist/static-server.js +10 -3
  64. package/package.json +13 -5
  65. package/dist/localsend/index.html +0 -531
  66. package/dist/localsend.d.ts +0 -19
  67. package/dist/localsend.js +0 -217
@@ -0,0 +1,530 @@
1
+ "use strict";
2
+ /*
3
+ * LocalSend WebDAV
4
+ *
5
+ * 让电脑资源管理器、iOS「文件」App、手机文件管理器等把存储目录挂载成一个网络盘,
6
+ * 生态兼容性比网页界面好得多:可以直接在文件管理器里拖拽上传、双击打开。
7
+ *
8
+ * 支持的方法:
9
+ * - OPTIONS:声明支持的 DAV 能力
10
+ * - PROPFIND:列出目录内容(支持 Depth 0 / 1 / infinity)
11
+ * - GET / HEAD:下载文件(目录返回简易 HTML 列表)
12
+ * - PUT:上传/覆盖文件(流式写入,不占内存)
13
+ * - DELETE:删除文件或目录
14
+ * - MKCOL:新建目录
15
+ * - COPY / MOVE:复制、移动(部分文件管理器拖拽时会用到)
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.davDirSize = davDirSize;
19
+ exports.checkDavAuth = checkDavAuth;
20
+ exports.buildMultistatus = buildMultistatus;
21
+ exports.createWebDavHandler = createWebDavHandler;
22
+ const node_crypto_1 = require("node:crypto");
23
+ const node_fs_1 = require("node:fs");
24
+ const node_path_1 = require("node:path");
25
+ const auth_1 = require("./auth");
26
+ const path_1 = require("./path");
27
+ const DAV_NS = 'DAV:';
28
+ /** 常见扩展名的 Content-Type,避免引入额外依赖 */
29
+ const MIME_TYPES = {
30
+ txt: 'text/plain; charset=utf-8',
31
+ md: 'text/markdown; charset=utf-8',
32
+ html: 'text/html; charset=utf-8',
33
+ htm: 'text/html; charset=utf-8',
34
+ css: 'text/css; charset=utf-8',
35
+ csv: 'text/csv; charset=utf-8',
36
+ json: 'application/json; charset=utf-8',
37
+ xml: 'application/xml; charset=utf-8',
38
+ js: 'text/javascript; charset=utf-8',
39
+ pdf: 'application/pdf',
40
+ zip: 'application/zip',
41
+ gz: 'application/gzip',
42
+ tar: 'application/x-tar',
43
+ rar: 'application/vnd.rar',
44
+ '7z': 'application/x-7z-compressed',
45
+ mp3: 'audio/mpeg',
46
+ wav: 'audio/wav',
47
+ flac: 'audio/flac',
48
+ m4a: 'audio/mp4',
49
+ ogg: 'audio/ogg',
50
+ mp4: 'video/mp4',
51
+ webm: 'video/webm',
52
+ mov: 'video/quicktime',
53
+ avi: 'video/x-msvideo',
54
+ mkv: 'video/x-matroska',
55
+ jpg: 'image/jpeg',
56
+ jpeg: 'image/jpeg',
57
+ png: 'image/png',
58
+ gif: 'image/gif',
59
+ webp: 'image/webp',
60
+ bmp: 'image/bmp',
61
+ svg: 'image/svg+xml',
62
+ ico: 'image/x-icon',
63
+ heic: 'image/heic',
64
+ doc: 'application/msword',
65
+ docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
66
+ xls: 'application/vnd.ms-excel',
67
+ xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
68
+ ppt: 'application/vnd.ms-powerpoint',
69
+ pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
70
+ };
71
+ function mimeOf(name) {
72
+ const idx = name.lastIndexOf('.');
73
+ if (idx < 0)
74
+ return 'application/octet-stream';
75
+ return MIME_TYPES[name.slice(idx + 1).toLowerCase()] || 'application/octet-stream';
76
+ }
77
+ /** RFC1123 时间格式(GMT) */
78
+ function httpDate(date) {
79
+ return date.toUTCString();
80
+ }
81
+ /** XML 转义 */
82
+ function escapeXml(value) {
83
+ return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
84
+ }
85
+ /** 计算目录下所有文件的总大小(字节),与上传接口保持一致 */
86
+ function davDirSize(target) {
87
+ if (!(0, node_fs_1.existsSync)(target))
88
+ return 0;
89
+ let total = 0;
90
+ const walk = (current) => {
91
+ let names;
92
+ try {
93
+ names = (0, node_fs_1.readdirSync)(current);
94
+ }
95
+ catch {
96
+ return;
97
+ }
98
+ for (const name of names) {
99
+ try {
100
+ const st = (0, node_fs_1.statSync)((0, node_path_1.join)(current, name));
101
+ if (st.isDirectory())
102
+ walk((0, node_path_1.join)(current, name));
103
+ else if (st.isFile())
104
+ total += st.size;
105
+ }
106
+ catch {
107
+ // 忽略读取失败的条目
108
+ }
109
+ }
110
+ };
111
+ walk(target);
112
+ return total;
113
+ }
114
+ /** 递归复制目录/文件(COPY 目录时 copyFileSync 会抛 EISDIR) */
115
+ function copyRecursive(src, dest) {
116
+ if ((0, node_fs_1.statSync)(src).isDirectory()) {
117
+ (0, node_fs_1.mkdirSync)(dest, { recursive: true });
118
+ for (const name of (0, node_fs_1.readdirSync)(src))
119
+ copyRecursive((0, node_path_1.join)(src, name), (0, node_path_1.join)(dest, name));
120
+ }
121
+ else {
122
+ (0, node_fs_1.copyFileSync)(src, dest);
123
+ }
124
+ }
125
+ /** 常量时间比较,避免令牌/口令被逐字符试探 */
126
+ function safeEqual(a, b) {
127
+ const bufA = Buffer.from(a);
128
+ const bufB = Buffer.from(b);
129
+ if (bufA.length !== bufB.length)
130
+ return false;
131
+ return (0, node_crypto_1.timingSafeEqual)(bufA, bufB);
132
+ }
133
+ /** 提取 Basic Auth 的用户名与密码 */
134
+ function basicCredentials(req) {
135
+ const auth = req.headers.authorization || '';
136
+ if (!auth.startsWith('Basic '))
137
+ return null;
138
+ try {
139
+ const decoded = Buffer.from(auth.slice(6), 'base64').toString('utf8');
140
+ const index = decoded.indexOf(':');
141
+ if (index < 0)
142
+ return null;
143
+ return { user: decoded.slice(0, index), pass: decoded.slice(index + 1) };
144
+ }
145
+ catch {
146
+ return null;
147
+ }
148
+ }
149
+ /**
150
+ * 校验 Basic Auth。
151
+ * 未配置令牌时直接放行;配置后要求用户名为 localsend、密码为令牌。
152
+ *
153
+ * @deprecated 令牌已改为摘要校验,WebDAV 处理函数内部直接调用 verifyToken
154
+ */
155
+ function checkDavAuth(req, token) {
156
+ if (!token)
157
+ return true;
158
+ // 也允许通过 ?key= 传递令牌(便于手工调试)
159
+ const queryKey = String(req.query?.key ?? '');
160
+ if (queryKey && safeEqual(queryKey, token))
161
+ return true;
162
+ const basic = basicCredentials(req);
163
+ return !!basic && basic.user === 'localsend' && safeEqual(basic.pass, token);
164
+ }
165
+ /** 递归收集目录下的条目 */
166
+ function collect(dirAbs, rel, depth, out) {
167
+ let names;
168
+ try {
169
+ names = (0, node_fs_1.readdirSync)(dirAbs).sort((a, b) => a.localeCompare(b, 'zh-CN'));
170
+ }
171
+ catch {
172
+ return;
173
+ }
174
+ for (const name of names) {
175
+ const full = (0, node_path_1.join)(dirAbs, name);
176
+ let st;
177
+ try {
178
+ st = (0, node_fs_1.statSync)(full);
179
+ }
180
+ catch {
181
+ continue;
182
+ }
183
+ const childRel = rel ? `${rel}/${name}` : name;
184
+ const isDir = st.isDirectory();
185
+ // 内部目录(如分片暂存区)不对外暴露
186
+ if (isDir && !rel && (0, path_1.isInternalDirName)(name))
187
+ continue;
188
+ out.push({ name, rel: childRel, isDir, size: isDir ? 0 : st.size, mtime: st.mtime });
189
+ if (isDir && depth > 0)
190
+ collect(full, childRel, depth - 1, out);
191
+ }
192
+ }
193
+ /** 生成 PROPFIND 的 207 响应 */
194
+ function buildMultistatus(baseUrl, dir, relPath, depth) {
195
+ const items = [];
196
+ if (relPath === '') {
197
+ const st = (0, node_fs_1.statSync)(dir);
198
+ items.push({ name: '/', rel: '', isDir: true, size: 0, mtime: st.mtime });
199
+ if (depth > 0)
200
+ collect(dir, '', depth, items);
201
+ }
202
+ else {
203
+ const full = (0, path_1.resolveInDir)(dir, relPath);
204
+ if (full && (0, node_fs_1.existsSync)(full)) {
205
+ const st = (0, node_fs_1.statSync)(full);
206
+ const name = relPath.split('/').pop() || relPath;
207
+ items.push({ name, rel: relPath, isDir: st.isDirectory(), size: st.isDirectory() ? 0 : st.size, mtime: st.mtime });
208
+ if (st.isDirectory() && depth > 0)
209
+ collect(full, relPath, depth, items);
210
+ }
211
+ }
212
+ const responses = items
213
+ .map((item) => {
214
+ // 集合(目录)的 href 必须以 / 结尾,这是 Windows 资源管理器挂载的硬性要求
215
+ const suffix = item.rel ? `/${item.rel.split('/').map(encodeURIComponent).join('/')}` : '';
216
+ const href = `${baseUrl}${suffix}${item.isDir ? '/' : ''}`;
217
+ const resourcetype = item.isDir ? '<D:resourcetype><D:collection/></D:resourcetype>' : '<D:resourcetype/>';
218
+ const contentlength = item.isDir ? '' : `<D:getcontentlength>${item.size}</D:getcontentlength>`;
219
+ const contenttype = item.isDir ? '' : `<D:getcontenttype>${mimeOf(item.name)}</D:getcontenttype>`;
220
+ return ('<D:response>' +
221
+ `<D:href>${escapeXml(href)}</D:href>` +
222
+ '<D:propstat><D:prop>' +
223
+ `<D:displayname>${escapeXml(item.name)}</D:displayname>` +
224
+ resourcetype +
225
+ contentlength +
226
+ contenttype +
227
+ `<D:getlastmodified>${httpDate(item.mtime)}</D:getlastmodified>` +
228
+ `<D:creationdate>${item.mtime.toISOString()}</D:creationdate>` +
229
+ '<D:supportedlock/>' +
230
+ '</D:prop><D:status>HTTP/1.1 200 OK</D:status></D:propstat>' +
231
+ '</D:response>');
232
+ })
233
+ .join('');
234
+ return `<?xml version="1.0" encoding="utf-8"?><D:multistatus xmlns:D="${DAV_NS}">${responses}</D:multistatus>`;
235
+ }
236
+ /** 简易目录页(浏览器直接访问时) */
237
+ function buildDirHtml(dir, relPath) {
238
+ const items = [];
239
+ collect(dir, relPath, 1, items);
240
+ const rows = items
241
+ .filter((f) => f.rel !== relPath)
242
+ .map((f) => {
243
+ const child = f.rel.slice(relPath ? relPath.length + 1 : 0);
244
+ const href = `${child.split('/').map(encodeURIComponent).join('/')}${f.isDir ? '/' : ''}`;
245
+ return `<li><a href="${href}">${escapeXml(child)}${f.isDir ? '/' : ''}</a> <span>${f.isDir ? '-' : `${f.size} B`}</span></li>`;
246
+ })
247
+ .join('');
248
+ const parent = relPath ? `../` : '';
249
+ return `<!DOCTYPE html><html lang="zh-CN"><head><meta charset="utf-8"><title>LocalSend</title></head><body><h1>LocalSend</h1><p><a href="${parent}">..</a></p><ul>${rows}</ul></body></html>`;
250
+ }
251
+ /**
252
+ * 生成 WebDAV 处理函数
253
+ */
254
+ function createWebDavHandler(options) {
255
+ const { dir } = options;
256
+ const basePath = (options.basePath || '/localsend/dav').replace(/\/+$/, '');
257
+ /** 运行时读取当前生效的访问令牌 */
258
+ const getHasToken = () => {
259
+ if (typeof options.hasToken === 'function')
260
+ return !!options.hasToken();
261
+ return !!options.hasToken;
262
+ };
263
+ /** 校验访问令牌(明文或摘要均可) */
264
+ const verifyToken = (presented) => {
265
+ if (typeof options.verifyToken !== 'function')
266
+ return false;
267
+ return options.verifyToken(presented);
268
+ };
269
+ /** 运行时读取当前生效的单文件大小上限 */
270
+ const getMaxSize = () => {
271
+ const value = typeof options.maxSize === 'function' ? options.maxSize() : options.maxSize;
272
+ return value ?? 0;
273
+ };
274
+ /** 运行时读取当前生效的容量上限 */
275
+ const getMaxTotalSize = () => {
276
+ const value = typeof options.maxTotalSize === 'function' ? options.maxTotalSize() : options.maxTotalSize;
277
+ return value ?? 0;
278
+ };
279
+ /** 运行时读取当前生效的禁止扩展名 */
280
+ const getBlockExts = () => {
281
+ const list = typeof options.blockExtensions === 'function' ? options.blockExtensions() : options.blockExtensions;
282
+ return new Set((list || []).map((e) => (e.startsWith('.') ? e : `.${e}`).toLowerCase()));
283
+ };
284
+ /** 运行时读取口令校验方式(Basic Auth 只能传明文,服务端用盐值现场算摘要再比对) */
285
+ const readRole = (plaintext) => {
286
+ if (typeof options.verifyPlain !== 'function')
287
+ return null;
288
+ return options.verifyPlain(plaintext) ?? null;
289
+ };
290
+ /** 是否处于开放模式(未配置任何口令) */
291
+ const isOpen = () => (typeof options.isOpen === 'function' ? !!options.isOpen() : true);
292
+ /** 是否配置了访客口令 */
293
+ const hasVisitor = () => (typeof options.hasVisitor === 'function' ? !!options.hasVisitor() : false);
294
+ /** 从请求中解析相对路径(逐段解码,避免 %2F 造成的歧义) */
295
+ const relOf = (req) => {
296
+ const raw = String(req.originalUrl || req.url || '/').split('?')[0];
297
+ let path = raw;
298
+ if (path.startsWith(basePath))
299
+ path = path.slice(basePath.length);
300
+ const segments = path.split('/').filter(Boolean);
301
+ const decoded = segments
302
+ .map((seg) => {
303
+ try {
304
+ return decodeURIComponent(seg);
305
+ }
306
+ catch {
307
+ return '';
308
+ }
309
+ })
310
+ .join('/');
311
+ const rel = (0, path_1.safeRelPath)(decoded);
312
+ // 原始路径非空但规范化后为空 => 路径非法(如 `..` 穿越)
313
+ const invalid = segments.length > 0 && !rel;
314
+ return { rel, invalid };
315
+ };
316
+ return async function handleWebDav(req, res) {
317
+ const basic = basicCredentials(req);
318
+ const queryKey = String(req.query?.key ?? '');
319
+ // Basic Auth 里带的就是口令明文(客户端只能这样传)
320
+ const pass = basic?.user === 'localsend' ? basic.pass : '';
321
+ // 站点令牌是进门的第一道锁:查询串里的令牌或 Basic 口令里的令牌都算通过
322
+ const tokenOk = !getHasToken() || (queryKey && verifyToken(queryKey)) || (basic?.user === 'localsend' && verifyToken(pass));
323
+ if (!tokenOk) {
324
+ res.setHeader('WWW-Authenticate', 'Basic realm="LocalSend"');
325
+ res.status(401).send('需要访问令牌');
326
+ return;
327
+ }
328
+ const method = (req.method || 'GET').toUpperCase();
329
+ // 身份分级:口令未配置时保持开放模式;配置后用 Basic Auth 的口令区分管理员/访客,
330
+ // 防止 WebDAV 的删除与整理绕过 JSON 接口上的 requireAdmin 校验。
331
+ // 服务端用盐值现场算摘要再比对,明文口令不会离开客户端。
332
+ const matchedRole = readRole(pass);
333
+ const role = isOpen() ? 'open' : matchedRole || 'guest';
334
+ const needsWrite = method === 'PUT';
335
+ const needsManage = method === 'DELETE' || method === 'MKCOL' || method === 'COPY' || method === 'MOVE';
336
+ // 没有配置访客口令时,未认证的客户端也能上传(与网页端保持一致)
337
+ if ((needsWrite && !(0, auth_1.canWrite)(role, hasVisitor())) || (needsManage && !(0, auth_1.canManage)(role))) {
338
+ res.setHeader('WWW-Authenticate', 'Basic realm="LocalSend"');
339
+ res.status(403).send(needsManage ? '该操作需要管理员口令' : '该操作需要访客口令');
340
+ return;
341
+ }
342
+ const { rel: relPath, invalid } = relOf(req);
343
+ if (invalid) {
344
+ res.status(403).send('非法路径');
345
+ return;
346
+ }
347
+ if (method === 'OPTIONS') {
348
+ res.setHeader('DAV', '1, 2');
349
+ res.setHeader('MS-Author-Via', 'DAV');
350
+ res.setHeader('Allow', 'OPTIONS, GET, HEAD, PUT, DELETE, PROPFIND, MKCOL, COPY, MOVE');
351
+ res.status(200).end();
352
+ return;
353
+ }
354
+ if (method === 'PROPFIND') {
355
+ const rawDepth = String(req.headers.depth ?? '1').toLowerCase();
356
+ const depth = rawDepth === '0' ? 0 : rawDepth === 'infinity' ? 32 : 1;
357
+ const xml = buildMultistatus(basePath, dir, relPath, depth);
358
+ res.setHeader('Content-Type', 'application/xml; charset="utf-8"');
359
+ res.setHeader('DAV', '1, 2');
360
+ res.status(207).send(xml);
361
+ return;
362
+ }
363
+ if (method === 'GET' || method === 'HEAD') {
364
+ const full = relPath ? (0, path_1.resolveInDir)(dir, relPath) : dir;
365
+ if (!full || !(0, node_fs_1.existsSync)(full)) {
366
+ res.status(404).send('文件不存在');
367
+ return;
368
+ }
369
+ const st = (0, node_fs_1.statSync)(full);
370
+ if (st.isDirectory()) {
371
+ res.setHeader('Content-Type', 'text/html; charset=utf-8');
372
+ res.status(200).send(buildDirHtml(dir, relPath));
373
+ return;
374
+ }
375
+ res.setHeader('Content-Length', String(st.size));
376
+ res.setHeader('Last-Modified', httpDate(st.mtime));
377
+ res.setHeader('Content-Type', mimeOf(relPath.split('/').pop() || relPath));
378
+ res.setHeader('Accept-Ranges', 'bytes');
379
+ if (method === 'HEAD') {
380
+ res.status(200).end();
381
+ return;
382
+ }
383
+ const stream = (0, node_fs_1.createReadStream)(full);
384
+ stream.on('error', () => res.end());
385
+ stream.pipe(res);
386
+ return;
387
+ }
388
+ if (method === 'PUT') {
389
+ if (!relPath) {
390
+ res.status(405).send('缺少文件路径');
391
+ return;
392
+ }
393
+ const name = relPath.split('/').pop() || '';
394
+ const ext = name.includes('.') ? name.slice(name.lastIndexOf('.')).toLowerCase() : '';
395
+ if (ext && getBlockExts().has(ext)) {
396
+ res.status(403).send(`出于安全考虑,禁止上传 ${ext} 类型的文件`);
397
+ return;
398
+ }
399
+ const full = (0, path_1.resolveInDir)(dir, relPath);
400
+ if (!full) {
401
+ res.status(403).send('非法路径');
402
+ return;
403
+ }
404
+ const maxSize = getMaxSize();
405
+ const maxTotalSize = getMaxTotalSize();
406
+ const declared = Number(req.headers['content-length'] || 0);
407
+ if (maxSize && declared > maxSize) {
408
+ res.status(413).send(`文件超出大小限制(${Math.round(maxSize / 1024 / 1024)}MB)`);
409
+ return;
410
+ }
411
+ if (maxTotalSize) {
412
+ const used = davDirSize(dir);
413
+ if (used + declared > maxTotalSize) {
414
+ res.status(413).send(`存储空间不足:已用 ${(used / 1024 / 1024).toFixed(1)}MB / ${(maxTotalSize / 1024 / 1024).toFixed(1)}MB`);
415
+ return;
416
+ }
417
+ }
418
+ const parent = (0, node_path_1.dirname)(full);
419
+ if (!(0, node_fs_1.existsSync)(parent))
420
+ (0, node_fs_1.mkdirSync)(parent, { recursive: true });
421
+ // 先写临时文件,成功后再转正,避免中断时留下半截文件
422
+ const tempPath = (0, node_path_1.join)(parent, `.dav-${(0, node_crypto_1.randomBytes)(12).toString('hex')}.tmp`);
423
+ try {
424
+ await new Promise((resolve, reject) => {
425
+ const stream = (0, node_fs_1.createWriteStream)(tempPath);
426
+ req.pipe(stream);
427
+ stream.on('finish', () => resolve());
428
+ stream.on('error', reject);
429
+ req.on('aborted', () => reject(new Error('客户端中断上传')));
430
+ });
431
+ (0, node_fs_1.renameSync)(tempPath, full);
432
+ }
433
+ catch (err) {
434
+ try {
435
+ (0, node_fs_1.rmSync)(tempPath, { force: true });
436
+ }
437
+ catch {
438
+ // 忽略清理失败
439
+ }
440
+ res.status(400).send(`上传失败:${err?.message || '未知错误'}`);
441
+ return;
442
+ }
443
+ options.onWrite?.('dav.upload', relPath, req, role);
444
+ res.status(201).send('已保存');
445
+ return;
446
+ }
447
+ if (method === 'DELETE') {
448
+ const full = relPath ? (0, path_1.resolveInDir)(dir, relPath) : '';
449
+ if (!full || !(0, node_fs_1.existsSync)(full)) {
450
+ res.status(404).send('文件不存在');
451
+ return;
452
+ }
453
+ (0, node_fs_1.rmSync)(full, { recursive: true, force: true });
454
+ options.onWrite?.('dav.delete', relPath, req, role);
455
+ res.status(204).end();
456
+ return;
457
+ }
458
+ if (method === 'MKCOL') {
459
+ const full = (0, path_1.resolveInDir)(dir, relPath);
460
+ if (!full) {
461
+ res.status(403).send('非法路径');
462
+ return;
463
+ }
464
+ if ((0, node_fs_1.existsSync)(full)) {
465
+ res.status(405).send('已存在');
466
+ return;
467
+ }
468
+ (0, node_fs_1.mkdirSync)(full, { recursive: true });
469
+ options.onWrite?.('dav.mkdir', relPath, req, role);
470
+ res.status(201).send('已创建');
471
+ return;
472
+ }
473
+ if (method === 'COPY' || method === 'MOVE') {
474
+ const destHeader = String(req.headers.destination || '');
475
+ if (!destHeader) {
476
+ res.status(400).send('缺少 Destination 头');
477
+ return;
478
+ }
479
+ // Destination 可能是绝对 URL,也可能只是路径
480
+ let destPath = destHeader;
481
+ try {
482
+ destPath = new URL(destHeader, 'http://localhost').pathname;
483
+ }
484
+ catch {
485
+ // 保持原样
486
+ }
487
+ if (destPath.startsWith(basePath))
488
+ destPath = destPath.slice(basePath.length);
489
+ const destRel = (0, path_1.safeRelPath)(destPath);
490
+ const destFull = destRel ? (0, path_1.resolveInDir)(dir, destRel) : '';
491
+ if (!destFull) {
492
+ res.status(403).send('非法目标路径');
493
+ return;
494
+ }
495
+ const srcFull = relPath ? (0, path_1.resolveInDir)(dir, relPath) : '';
496
+ if (!srcFull || !(0, node_fs_1.existsSync)(srcFull)) {
497
+ res.status(404).send('源文件不存在');
498
+ return;
499
+ }
500
+ const destParent = (0, node_path_1.dirname)(destFull);
501
+ if (!(0, node_fs_1.existsSync)(destParent))
502
+ (0, node_fs_1.mkdirSync)(destParent, { recursive: true });
503
+ try {
504
+ if ((0, node_fs_1.statSync)(srcFull).isDirectory()) {
505
+ // 目录移动用 rename,复制时递归复制子项
506
+ if (method === 'MOVE') {
507
+ (0, node_fs_1.renameSync)(srcFull, destFull);
508
+ }
509
+ else {
510
+ copyRecursive(srcFull, destFull);
511
+ }
512
+ }
513
+ else if (method === 'MOVE') {
514
+ (0, node_fs_1.renameSync)(srcFull, destFull);
515
+ }
516
+ else {
517
+ (0, node_fs_1.copyFileSync)(srcFull, destFull);
518
+ }
519
+ }
520
+ catch (err) {
521
+ res.status(500).send(`操作失败:${err?.message || '未知错误'}`);
522
+ return;
523
+ }
524
+ options.onWrite?.(method === 'MOVE' ? 'dav.move' : 'dav.copy', `${relPath} → ${destRel}`, req, role);
525
+ res.status(method === 'MOVE' ? 201 : 204).end();
526
+ return;
527
+ }
528
+ res.status(405).send('不支持的方法');
529
+ };
530
+ }
@@ -0,0 +1,20 @@
1
+ /** 增量计算 CRC32(可与标准 zlib.crc32 结果比对) */
2
+ export declare function crc32Update(crc: number, buf: Buffer): number;
3
+ export interface ZipEntry {
4
+ /** zip 中的条目名(相对路径,用 `/` 分隔) */
5
+ name: string;
6
+ /** 磁盘上的绝对路径 */
7
+ path: string;
8
+ /** 修改时间 */
9
+ mtime: Date;
10
+ }
11
+ /**
12
+ * 生成 ZIP 内容的异步迭代器,可直接 pipe 到响应流。
13
+ *
14
+ * 为了兼容 Windows 资源管理器 / PowerShell Expand-Archive 等工具,
15
+ * 这里不使用 data descriptor(部分实现无法正确解析它),
16
+ * 而是先流式扫描一遍算出 CRC32 与大小,写入 local file header,
17
+ * 再扫描一遍输出文件内容。代价是本地文件读两遍,
18
+ * 相比网络传输耗时通常可以忽略。
19
+ */
20
+ export declare function createZipChunks(entries: ZipEntry[], readFile: (path: string) => AsyncIterable<Buffer>): AsyncGenerator<Buffer>;