@lzwme/sserver 0.0.9 → 0.0.10

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/README.MD CHANGED
@@ -47,6 +47,9 @@ ss -H --host local.lzw.me
47
47
 
48
48
  # 启用 https,并保存默认生成的 ssl 证书
49
49
  ss -H --ssl-cache ./cache
50
+
51
+ # 开启 localsend 局域网文件传输功能
52
+ ss --localsend
50
53
  ```
51
54
 
52
55
  ### 配置代理转发
@@ -86,6 +89,34 @@ module.exports = {
86
89
  }
87
90
  ```
88
91
 
92
+ ### LocalSend 局域网文件传输
93
+
94
+ 开启后可通过 `http://<本机IP>:<port>/localsend` 访问,实现同网段设备间的文件快速传输(支持多文件上传/下载、实时进度、二维码扫码访问、扫码直连下载、文件预览与排序等):
95
+
96
+ ```bash
97
+ # 命令行方式开启
98
+ ss --localsend
99
+
100
+ # 指定文件存储目录(也可用环境变量 SS_LOCALSEND_DIR 指定)
101
+ ss --localsend --localsend-dir /tmp/localsend
102
+ ```
103
+
104
+ 配置文件方式开启:
105
+
106
+ ```js
107
+ // ss.config.js
108
+ module.exports = {
109
+ port: 8888,
110
+ localsend: {
111
+ enabled: true,
112
+ // 文件存储目录。默认 ~/.static-server/localsend,可用环境变量 SS_LOCALSEND_DIR 覆盖
113
+ dir: '/tmp/localsend',
114
+ // 单个文件上传大小限制(字节),默认 1GB
115
+ maxSize: 1024 * 1024 * 1024,
116
+ },
117
+ };
118
+ ```
119
+
89
120
  ## 开发
90
121
 
91
122
  本地二次开发:
package/dist/cli.js CHANGED
@@ -11,7 +11,7 @@ const pkg = require('../package.json');
11
11
  commander_1.program
12
12
  .aliases(['ss'])
13
13
  .version(pkg.version, '-v, --version')
14
- .description(console_log_colors_1.color.yellow(pkg.description) + ` [version@${console_log_colors_1.color.cyanBright(pkg.version)}]`)
14
+ .description(`${console_log_colors_1.color.yellow(pkg.description)} [version@${console_log_colors_1.color.cyanBright(pkg.version)}]`)
15
15
  // .option('-c, --config-path [filepath]', `配置文件 ${color.yellow(config.configPath)} 的路径`)
16
16
  .option('-d, --root-dir [dirpath]', '静态服务器的根目录路径')
17
17
  .option('-a, --autoindex', '是否开启目录列表浏览')
@@ -26,6 +26,8 @@ commander_1.program
26
26
  .option('--cors', '是否启用 cors。会全局设置 cors 的 header')
27
27
  .option('--no-cors', '是否禁用 cors')
28
28
  .option('--log [dirpath]', `指定日志路径`)
29
+ .option('--localsend', '开启 localsend 局域网文件传输功能')
30
+ .option('--localsend-dir <dir>', 'localsend 文件存储目录。默认 ~/.static-server/localsend,可用环境变量 SS_LOCALSEND_DIR 覆盖')
29
31
  .option('--debug', `开启调试模式。`, false)
30
32
  .action(async (opts) => {
31
33
  if (opts.cert)
@@ -42,6 +44,9 @@ commander_1.program
42
44
  'Cross-Origin-Embedder-Policy': 'require-corp',
43
45
  };
44
46
  }
47
+ if (opts.localsend) {
48
+ opts.localsend = { enabled: true, dir: opts.localsendDir || undefined };
49
+ }
45
50
  (0, config_1.getConfig)(false, opts).then(() => (0, static_server_1.initServer)());
46
51
  });
47
52
  commander_1.program
package/dist/config.d.ts CHANGED
@@ -1,8 +1,16 @@
1
- import { Stats } from 'node:fs';
2
- import { type ServerOptions } from 'node:https';
3
- import { type Options } from 'http-proxy-middleware';
4
- import { type Response, type Express } from 'express';
5
- import { type NLogger, type color } from '@lzwme/fe-utils';
1
+ import { type Stats } from 'node:fs';
2
+ import type { ServerOptions } from 'node:https';
3
+ import { type color, type NLogger } from '@lzwme/fe-utils';
4
+ import type { Express, Response } from 'express';
5
+ import type { Options } from 'http-proxy-middleware';
6
+ export interface LocalSendConfig {
7
+ /** 是否开启 localsend 局域网文件传输功能 */
8
+ enabled?: boolean;
9
+ /** 文件存储目录。默认 ~/.static-server/localsend,可通过环境变量 SS_LOCALSEND_DIR 指定 */
10
+ dir?: string;
11
+ /** 单个文件上传大小限制(字节)。默认 1GB */
12
+ maxSize?: number;
13
+ }
6
14
  export interface SSConfig {
7
15
  /** 是否开启目录列表 */
8
16
  autoindex?: boolean;
@@ -12,6 +20,8 @@ export interface SSConfig {
12
20
  host?: string;
13
21
  /** 是否开启日志记录。默认为 false。若设置为 true 则默认为 ~/.sserver/log.log;若为字符串,则设置为日志路径 */
14
22
  log?: boolean | string;
23
+ /** localsend 局域网文件传输功能。可设置为 true 开启,或传入配置对象 */
24
+ localsend?: LocalSendConfig | boolean;
15
25
  /** 启动后是否打开首页 */
16
26
  open?: boolean;
17
27
  /** 监听端口号。默认 80,开启 https 则为 443 */
package/dist/config.js CHANGED
@@ -1,9 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getConfig = getConfig;
4
- const node_path_1 = require("node:path");
5
- const node_os_1 = require("node:os");
6
4
  const node_fs_1 = require("node:fs");
5
+ const node_os_1 = require("node:os");
6
+ const node_path_1 = require("node:path");
7
7
  const fe_utils_1 = require("@lzwme/fe-utils");
8
8
  const get_logger_1 = require("./get-logger");
9
9
  const get_cert_1 = require("./lib/get-cert");
@@ -32,6 +32,14 @@ async function getConfig(useCache = true, cfg) {
32
32
  if (cfg)
33
33
  (0, fe_utils_1.assign)(ssConfig, cfg);
34
34
  ssConfig.rootDir = (0, node_path_1.resolve)(process.cwd(), typeof ssConfig.rootDir === 'string' ? ssConfig.rootDir : '.');
35
+ // localsend 配置归一化:支持 true / 配置对象,支持环境变量 SS_LOCALSEND_DIR 指定存储目录
36
+ if (ssConfig.localsend) {
37
+ const localsend = typeof ssConfig.localsend === 'boolean' ? { enabled: ssConfig.localsend } : { ...ssConfig.localsend };
38
+ localsend.enabled = typeof ssConfig.localsend === 'boolean' ? ssConfig.localsend : localsend.enabled !== false;
39
+ localsend.dir = process.env.SS_LOCALSEND_DIR || localsend.dir || (0, node_path_1.resolve)((0, node_os_1.homedir)(), '.static-server/localsend');
40
+ localsend.maxSize = localsend.maxSize || 1024 * 1024 * 1024;
41
+ ssConfig.localsend = localsend;
42
+ }
35
43
  if (ssConfig.log) {
36
44
  get_logger_1.logger.setLogDir(typeof ssConfig.log === 'boolean' ? (0, node_path_1.resolve)((0, node_os_1.homedir)(), '.sserver/log.log') : ssConfig.log);
37
45
  }
@@ -1,8 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.logger = void 0;
4
- const console_log_colors_1 = require("console-log-colors");
5
4
  const fe_utils_1 = require("@lzwme/fe-utils");
5
+ const console_log_colors_1 = require("console-log-colors");
6
6
  function getLogger(levelType, logDir) {
7
7
  return fe_utils_1.NLogger.getLogger('[sserver]', { levelType, color: console_log_colors_1.color, logDir });
8
8
  }
package/dist/index.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export { initServer } from './static-server';
2
1
  export type { SSConfig } from './config';
2
+ export { initServer } from './static-server';
@@ -1,12 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getCert = getCert;
4
- const fs_1 = require("fs");
5
- const promises_1 = require("fs/promises");
6
- const mkcert_1 = require("./mkcert");
7
- const path_1 = require("path");
8
- const get_logger_1 = require("../get-logger");
4
+ const node_fs_1 = require("node:fs");
5
+ const promises_1 = require("node:fs/promises");
6
+ const node_path_1 = require("node:path");
9
7
  const console_log_colors_1 = require("console-log-colors");
8
+ const get_logger_1 = require("../get-logger");
9
+ const mkcert_1 = require("./mkcert");
10
10
  async function getCert(host = 'localhost', cacheDir = '') {
11
11
  const result = {
12
12
  caKey: '',
@@ -15,16 +15,16 @@ async function getCert(host = 'localhost', cacheDir = '') {
15
15
  certCrt: '',
16
16
  };
17
17
  const dirs = {
18
- caKey: (0, path_1.resolve)(cacheDir, 'ca.key'),
19
- caCrt: (0, path_1.resolve)(cacheDir, 'ca.crt'),
20
- certKey: (0, path_1.resolve)(cacheDir, `${host}.key`),
21
- certCrt: (0, path_1.resolve)(cacheDir, `${host}.crt`),
18
+ caKey: (0, node_path_1.resolve)(cacheDir, 'ca.key'),
19
+ caCrt: (0, node_path_1.resolve)(cacheDir, 'ca.crt'),
20
+ certKey: (0, node_path_1.resolve)(cacheDir, `${host}.key`),
21
+ certCrt: (0, node_path_1.resolve)(cacheDir, `${host}.crt`),
22
22
  };
23
23
  if (cacheDir) {
24
- if (!(0, fs_1.existsSync)(cacheDir))
24
+ if (!(0, node_fs_1.existsSync)(cacheDir))
25
25
  (0, promises_1.mkdir)(cacheDir, { recursive: true });
26
26
  for (const [key, filepath] of Object.entries(dirs)) {
27
- if ((0, fs_1.existsSync)(filepath))
27
+ if ((0, node_fs_1.existsSync)(filepath))
28
28
  result[key] = await (0, promises_1.readFile)(filepath, 'utf8');
29
29
  }
30
30
  }
@@ -4,11 +4,11 @@ Object.defineProperty(exports, "__esModule", { value: true });
4
4
  exports.generateCert = generateCert;
5
5
  exports.createCA = createCA;
6
6
  exports.createCert = createCert;
7
+ const node_util_1 = require("node:util");
7
8
  const node_forge_1 = require("node-forge");
8
- const util_1 = require("util");
9
- const generateKeyPair = (0, util_1.promisify)(node_forge_1.pki.rsa.generateKeyPair.bind(node_forge_1.pki.rsa));
9
+ const generateKeyPair = (0, node_util_1.promisify)(node_forge_1.pki.rsa.generateKeyPair.bind(node_forge_1.pki.rsa));
10
10
  async function generateCert(options) {
11
- let { subject, issuer, extensions = [], validityDays = 36500, signWith } = options;
11
+ const { subject, issuer, extensions = [], validityDays = 36500, signWith } = options;
12
12
  // create serial from and integer between 50000 and 99999
13
13
  const serial = Math.floor(Math.random() * 95000 + 50000).toString();
14
14
  const keyPair = await generateKeyPair({ bits: 2048, workers: 4 });
@@ -45,7 +45,7 @@ function createCert(options) {
45
45
  // certificate Attributes: https://git.io/fptna
46
46
  if (!options.subject)
47
47
  options.subject = [];
48
- if (!options.subject.find(d => d.name === 'commonName')) {
48
+ if (!options.subject.find((d) => d.name === 'commonName')) {
49
49
  // use the first address as common name
50
50
  options.subject.push({ name: 'commonName', value: options.domains[0] });
51
51
  }
@@ -56,7 +56,7 @@ function createCert(options) {
56
56
  { name: 'extKeyUsage', serverAuth: true, clientAuth: true },
57
57
  {
58
58
  name: 'subjectAltName',
59
- altNames: options.domains.map(domain => {
59
+ altNames: options.domains.map((domain) => {
60
60
  const types = { domain: 2, ip: 7 }; // available Types: https://git.io/fptng
61
61
  const isIp = isIP(domain);
62
62
  if (isIp)
package/dist/lib/utils.js CHANGED
@@ -1,9 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getIp = getIp;
4
- const os_1 = require("os");
4
+ const node_os_1 = require("node:os");
5
5
  function getIp() {
6
- const nif = (0, os_1.networkInterfaces)();
6
+ const nif = (0, node_os_1.networkInterfaces)();
7
7
  let list = [];
8
8
  for (const key of Object.keys(nif)) {
9
9
  for (const item of nif[key]) {
@@ -11,7 +11,7 @@ function getIp() {
11
11
  list.push(item);
12
12
  }
13
13
  }
14
- list = list.sort((a, b) => {
14
+ list = list.sort((_a, b) => {
15
15
  if (b.address.startsWith('172.'))
16
16
  return -1;
17
17
  return 0;
@@ -0,0 +1,481 @@
1
+ <!DOCTYPE html>
2
+ <html lang="zh-CN">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>LocalSend · 局域网文件传输</title>
7
+ <link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>📡</text></svg>" />
8
+ <script src="https://cdn.tailwindcss.com"></script>
9
+ <script src="https://cdn.jsdelivr.net/npm/qr-code-styling@1/lib/qr-code-styling.js"></script>
10
+ <style>
11
+ #fileInput { display: none; }
12
+ #toast { transition: opacity .25s; }
13
+ #toast.hidden { opacity: 0; pointer-events: none; }
14
+ #pageQr canvas { width: 100% !important; height: auto !important; display: block; }
15
+ ::-webkit-scrollbar { width: 8px; height: 8px; }
16
+ ::-webkit-scrollbar-thumb { background: #334155; border-radius: 4px; }
17
+ </style>
18
+ </head>
19
+ <body class="min-h-screen bg-slate-950 text-slate-200">
20
+ <div class="max-w-5xl mx-auto px-3 sm:px-4 py-6 sm:py-8">
21
+
22
+ <header class="flex items-center justify-between gap-3 sm:gap-4 mb-6 sm:mb-8 flex-wrap">
23
+ <div>
24
+ <h1 class="text-xl sm:text-2xl font-bold flex items-center gap-2">
25
+ <span class="inline-block w-2.5 h-2.5 sm:w-3 sm:h-3 bg-emerald-400 rounded-full animate-pulse"></span>
26
+ LocalSend
27
+ </h1>
28
+ <p class="text-xs sm:text-sm text-slate-400 mt-1">局域网文件传输 · 同网段设备扫码即可访问</p>
29
+ </div>
30
+ <div class="text-left sm:text-right">
31
+ <div class="text-xs text-slate-500">本机访问地址</div>
32
+ <div id="pageUrl" class="text-emerald-400 font-mono text-xs sm:text-sm break-all"></div>
33
+ </div>
34
+ </header>
35
+
36
+ <section class="grid md:grid-cols-[auto_1fr] gap-5 sm:gap-6 items-start mb-6 sm:mb-8">
37
+ <div id="pageQrCard" class="bg-slate-900 border border-slate-700 rounded-2xl p-3 sm:p-4 flex flex-col items-center gap-3 w-full sm:w-fit mx-auto md:mx-0 cursor-pointer hover:border-emerald-500/50 transition-colors group">
38
+ <div class="text-xs text-slate-400 group-hover:text-emerald-400 transition-colors">手机扫码访问页面(点击放大)</div>
39
+ <div id="pageQr" class="bg-white p-2 rounded-lg w-40 sm:w-36 flex items-center justify-center"></div>
40
+ <button id="openPageBtn" class="text-xs text-slate-400 hover:text-white transition">在新窗口打开页面</button>
41
+ </div>
42
+
43
+ <div>
44
+ <div id="dropZone" class="border-2 border-dashed border-slate-600 hover:border-emerald-400 rounded-2xl p-6 sm:p-8 text-center transition cursor-pointer select-none">
45
+ <div class="text-3xl sm:text-4xl mb-2">📤</div>
46
+ <p class="font-medium text-sm sm:text-base text-slate-200">点击选择或拖拽文件到此处上传</p>
47
+ <p class="text-[11px] sm:text-xs text-slate-500 mt-1">支持多文件同时上传 · 文件保存在本机 · 实时显示传输进度</p>
48
+ <input id="fileInput" type="file" multiple />
49
+ </div>
50
+ <div id="uploadList" class="mt-4 space-y-2"></div>
51
+ </div>
52
+ </section>
53
+
54
+ <section>
55
+ <div class="flex items-center justify-between gap-3 mb-4 flex-wrap">
56
+ <h2 class="font-semibold text-base sm:text-lg">文件列表 <span id="fileCount" class="text-xs sm:text-sm text-slate-400 font-normal"></span></h2>
57
+ <div class="flex gap-2 text-xs sm:text-sm">
58
+ <select id="sortSelect" class="bg-slate-800 border border-slate-700 rounded-lg px-2.5 sm:px-3 py-1.5 outline-none cursor-pointer">
59
+ <option value="time">按时间排序</option>
60
+ <option value="size">按大小排序</option>
61
+ </select>
62
+ <button id="orderBtn" class="bg-slate-800 border border-slate-700 rounded-lg px-3 py-1.5 hover:bg-slate-700 transition">↓ 降序</button>
63
+ </div>
64
+ </div>
65
+ <div id="batchBar" class="hidden mb-2 px-3 sm:px-4 py-2 bg-slate-900 border border-slate-800 rounded-2xl flex items-center gap-2 sm:gap-3 text-xs">
66
+ <label class="flex items-center gap-1.5 cursor-pointer select-none text-slate-400 hover:text-slate-200 shrink-0">
67
+ <input type="checkbox" id="selectAll" class="accent-emerald-500 w-3.5 h-3.5">
68
+ <span class="hidden sm:inline">全选</span>
69
+ </label>
70
+ <span id="selectedCount" class="text-slate-500 hidden shrink-0"><em class="text-emerald-400 not-italic">0</em><span class="hidden sm:inline"> 项已选</span></span>
71
+ <div class="flex-1 hidden sm:block"></div>
72
+ <button id="batchDownload" disabled class="px-2 py-1 rounded text-emerald-400 hover:bg-emerald-500/10 border border-emerald-500/30 disabled:opacity-30 disabled:cursor-not-allowed transition shrink-0" title="批量下载">
73
+ <span class="sm:hidden">📥</span><span class="hidden sm:inline">📥 批量下载</span>
74
+ </button>
75
+ <button id="batchDelete" disabled class="px-2 py-1 rounded text-red-400 hover:bg-red-500/10 border border-red-500/30 disabled:opacity-30 disabled:cursor-not-allowed transition shrink-0" title="批量删除">
76
+ <span class="sm:hidden">🗑</span><span class="hidden sm:inline">🗑 批量删除</span>
77
+ </button>
78
+ </div>
79
+ <div id="fileList" class="bg-slate-900 border border-slate-800 rounded-2xl divide-y divide-slate-800"></div>
80
+ <div id="emptyTip" class="hidden text-center text-slate-500 py-16">暂无文件,上传第一个文件开始传输吧</div>
81
+ </section>
82
+ </div>
83
+
84
+ <!-- 二维码弹窗 -->
85
+ <div id="qrModal" class="hidden fixed inset-0 z-50 bg-black/60 backdrop-blur-sm flex items-center justify-center p-4">
86
+ <div class="bg-slate-900 border border-slate-700 rounded-2xl p-6 flex flex-col items-center gap-4 max-w-sm w-full">
87
+ <div class="text-sm text-slate-300">手机扫码</div>
88
+ <div id="modalQr" class="bg-white p-2 rounded-lg"></div>
89
+ <div id="modalText" class="text-xs text-slate-400 font-mono break-all max-w-xs text-center"></div>
90
+ <button id="closeModal" class="text-sm bg-slate-700 hover:bg-slate-600 rounded-lg px-4 py-1.5 transition">关闭</button>
91
+ </div>
92
+ </div>
93
+
94
+ <!-- 文本预览弹窗 -->
95
+ <div id="previewModal" class="hidden fixed inset-0 z-50 bg-black/60 backdrop-blur-sm flex items-center justify-center p-4">
96
+ <div class="bg-slate-900 border border-slate-700 rounded-2xl p-5 max-w-2xl w-full max-h-[80vh] flex flex-col gap-3">
97
+ <div class="flex items-center justify-between gap-3">
98
+ <div id="previewTitle" class="text-sm font-medium truncate"></div>
99
+ <button id="closePreview" class="text-xs bg-slate-700 hover:bg-slate-600 rounded-lg px-3 py-1 transition shrink-0">关闭</button>
100
+ </div>
101
+ <pre id="previewContent" class="whitespace-pre-wrap break-all text-xs font-mono bg-slate-950 border border-slate-800 rounded-xl p-4 overflow-auto flex-1 text-slate-300"></pre>
102
+ </div>
103
+ </div>
104
+
105
+ <!-- Toast -->
106
+ <div id="toast" class="hidden fixed bottom-6 left-1/2 -translate-x-1/2 z-[60] rounded-xl px-5 py-3 text-sm shadow-xl border border-white/10"></div>
107
+
108
+ <script>
109
+ (function () {
110
+ 'use strict';
111
+ var API = '/localsend/api';
112
+ var $ = function (id) { return document.getElementById(id); };
113
+ var pageUrl = location.origin + location.pathname;
114
+ var sortType = 'time';
115
+ var sortOrder = 'desc';
116
+ var modalQrCode = null;
117
+ var selected = {};
118
+ var fileItems = [];
119
+
120
+ $('pageUrl').textContent = pageUrl;
121
+ $('pageUrl').title = pageUrl;
122
+ if (typeof QRCodeStyling !== 'undefined') {
123
+ var pageQrCode = new QRCodeStyling({
124
+ width: 220, height: 220, type: 'canvas', data: pageUrl, margin: 0,
125
+ dotsOptions: { type: 'rounded', color: '#10b981' },
126
+ backgroundOptions: { color: '#ffffff' },
127
+ cornersSquareOptions: { type: 'extra-rounded', color: '#10b981' },
128
+ cornersDotOptions: { type: 'dot', color: '#10b981' },
129
+ });
130
+ pageQrCode.append($('pageQr'));
131
+ }
132
+
133
+ function fmtSize(n) {
134
+ if (n < 1024) return n + ' B';
135
+ var units = ['KB', 'MB', 'GB', 'TB'];
136
+ var i = -1;
137
+ do { n /= 1024; i += 1; } while (n >= 1024 && i < units.length - 1);
138
+ return n.toFixed(1) + ' ' + units[i];
139
+ }
140
+ function fmtTime(ms) {
141
+ var d = new Date(ms);
142
+ var p = function (x) { return String(x).padStart(2, '0'); };
143
+ return d.getFullYear() + '-' + p(d.getMonth() + 1) + '-' + p(d.getDate()) + ' ' + p(d.getHours()) + ':' + p(d.getMinutes());
144
+ }
145
+ function escapeHtml(s) {
146
+ return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
147
+ }
148
+ function toast(msg, type) {
149
+ var el = $('toast');
150
+ el.textContent = msg;
151
+ el.className = 'fixed bottom-6 left-1/2 -translate-x-1/2 z-[60] max-w-[92vw] rounded-xl px-4 sm:px-5 py-2.5 sm:py-3 text-xs sm:text-sm shadow-xl border border-white/10 ' + (type === 'ok' ? 'bg-emerald-600/90' : type === 'err' ? 'bg-red-600/90' : 'bg-slate-800/90');
152
+ el.classList.remove('hidden');
153
+ clearTimeout(el._t);
154
+ el._t = setTimeout(function () { el.classList.add('hidden'); }, 2600);
155
+ }
156
+ function copyText(text) {
157
+ var done = function () { toast('已复制到剪贴板', 'ok'); };
158
+ if (navigator.clipboard && window.isSecureContext) {
159
+ return navigator.clipboard.writeText(text).then(done).catch(function () { toast('复制失败', 'err'); });
160
+ }
161
+ var ta = document.createElement('textarea');
162
+ ta.value = text;
163
+ ta.style.position = 'fixed';
164
+ ta.style.opacity = '0';
165
+ document.body.appendChild(ta);
166
+ ta.select();
167
+ try { document.execCommand('copy'); done(); } catch (e) { toast('复制失败', 'err'); }
168
+ document.body.removeChild(ta);
169
+ }
170
+
171
+ var iconMap = {
172
+ jpg: '🖼️', jpeg: '🖼️', png: '🖼️', gif: '🖼️', webp: '🖼️', svg: '🖼️', bmp: '🖼️', ico: '🖼️',
173
+ mp4: '🎬', mov: '🎬', avi: '🎬', mkv: '🎬', webm: '🎬', flv: '🎬',
174
+ mp3: '🎵', wav: '🎵', flac: '🎵', m4a: '🎵', ogg: '🎵',
175
+ zip: '🗜️', rar: '🗜️', '7z': '🗜️', tar: '🗜️', gz: '🗜️', tgz: '🗜️',
176
+ pdf: '📕', doc: '📘', docx: '📘', xls: '📊', xlsx: '📊', ppt: '📊', pptx: '📊', csv: '📊',
177
+ txt: '📃', md: '📃', html: '🌐', htm: '🌐', js: '💻', ts: '💻', json: '🧩', css: '🎨', xml: '🧾', log: '📝'
178
+ };
179
+ function fileIcon(name) {
180
+ var ext = (name.split('.').pop() || '').toLowerCase();
181
+ return iconMap[ext] || '📄';
182
+ }
183
+ function btn(label, act, danger, icon) {
184
+ var cls = danger ? 'text-red-400 hover:bg-red-500/10 border-red-500/30' : 'text-slate-300 hover:bg-slate-700/70 border-slate-600/60';
185
+ return '<button data-act="' + act + '" title="' + label + '" class="px-1.5 sm:px-2.5 py-1 rounded-lg text-xs border transition ' + cls + '">' +
186
+ '<span class="sm:hidden" aria-hidden="true">' + icon + '</span>' +
187
+ '<span class="hidden sm:inline">' + label + '</span>' +
188
+ '</button>';
189
+ }
190
+
191
+ function loadFiles() {
192
+ return fetch(API + '/list?sort=' + sortType + '&order=' + sortOrder)
193
+ .then(function (r) { return r.json(); })
194
+ .then(function (json) { renderList(json.data || []); })
195
+ .catch(function () { toast('文件列表加载失败', 'err'); });
196
+ }
197
+ function updateBatchUI() {
198
+ var names = Object.keys(selected).filter(function(n) { return selected[n]; });
199
+ var count = names.length;
200
+ var total = fileItems.length;
201
+ $('batchBar').classList.toggle('hidden', total === 0);
202
+ $('selectAll').checked = total > 0 && count === total;
203
+ $('selectAll').indeterminate = count > 0 && count < total;
204
+ if (count > 0) {
205
+ $('selectedCount').classList.remove('hidden');
206
+ $('selectedCount').querySelector('em').textContent = count;
207
+ $('batchDownload').disabled = false;
208
+ $('batchDelete').disabled = false;
209
+ } else {
210
+ $('selectedCount').classList.add('hidden');
211
+ $('batchDownload').disabled = true;
212
+ $('batchDelete').disabled = true;
213
+ }
214
+ }
215
+ function renderList(list) {
216
+ fileItems = list;
217
+ // 保留仍在列表中的文件的选中状态
218
+ var keep = {};
219
+ list.forEach(function(f) { if (selected[f.name]) keep[f.name] = true; });
220
+ selected = keep;
221
+
222
+ var wrap = $('fileList');
223
+ wrap.innerHTML = '';
224
+ $('emptyTip').classList.toggle('hidden', list.length > 0);
225
+ $('fileCount').textContent = '(' + list.length + ')';
226
+ updateBatchUI();
227
+ list.forEach(function (f) {
228
+ var div = document.createElement('div');
229
+ div.className = 'flex items-center gap-2 sm:gap-3 px-3 sm:px-4 py-2.5 sm:py-3 hover:bg-slate-800/60 transition flex-wrap' + (selected[f.name] ? ' bg-slate-800/40' : '');
230
+ div.innerHTML =
231
+ '<label class="flex items-center shrink-0 cursor-pointer"><input type="checkbox" class="file-check accent-emerald-500 w-3.5 h-3.5" data-name="' + escapeHtml(f.name) + '"' + (selected[f.name] ? ' checked' : '') + '></label>' +
232
+ '<span class="text-xl sm:text-2xl shrink-0">' + fileIcon(f.name) + '</span>' +
233
+ '<div class="min-w-0 flex-1">' +
234
+ '<div class="text-sm truncate text-slate-200" title="' + escapeHtml(f.name) + '">' + escapeHtml(f.name) + '</div>' +
235
+ '<div class="text-xs text-slate-500 mt-0.5">' + fmtSize(f.size) + ' · ' + fmtTime(f.mtime) + '</div>' +
236
+ '</div>' +
237
+ '<div class="flex items-center gap-1 sm:gap-1.5 shrink-0 justify-end w-full sm:w-auto">' +
238
+ btn('预览', 'preview', false, '👁') + btn('下载', 'download', false, '⬇️') + btn('复制', 'copy', false, '📋') + btn('扫码', 'qr', false, '📱') + btn('删除', 'delete', true, '🗑') +
239
+ '</div>';
240
+ Array.prototype.forEach.call(div.querySelectorAll('button'), function (b) { b.dataset.name = f.name; });
241
+ wrap.appendChild(div);
242
+ });
243
+ }
244
+
245
+ function uploadFiles(fileList) {
246
+ Array.prototype.forEach.call(fileList, uploadOne);
247
+ }
248
+ function uploadOne(file) {
249
+ var fd = new FormData();
250
+ fd.append('files', file);
251
+ var row = document.createElement('div');
252
+ row.className = 'bg-slate-800/70 border border-slate-700 rounded-xl px-4 py-3';
253
+ row.innerHTML =
254
+ '<div class="flex items-center justify-between gap-3 mb-2">' +
255
+ '<span class="text-xs truncate text-slate-300">' + escapeHtml(file.name) + '</span>' +
256
+ '<span class="text-xs text-emerald-400 shrink-0 font-mono" data-pct>0%</span>' +
257
+ '</div>' +
258
+ '<div class="h-1.5 bg-slate-700 rounded-full overflow-hidden">' +
259
+ '<div class="h-full bg-emerald-500 transition-all duration-200" style="width:0%"></div>' +
260
+ '</div>' +
261
+ '<div class="flex justify-between mt-1.5 text-[10px] text-slate-500"><span data-status>等待上传…</span><span data-speed class="font-mono"></span></div>';
262
+ $('uploadList').appendChild(row);
263
+ var pctEl = row.querySelector('[data-pct]');
264
+ var barEl = row.querySelector('.h-full');
265
+ var statusEl = row.querySelector('[data-status]');
266
+ var speedEl = row.querySelector('[data-speed]');
267
+ var xhr = new XMLHttpRequest();
268
+ xhr.open('POST', API + '/upload');
269
+ var lastLoaded = 0;
270
+ var lastTime = Date.now();
271
+ xhr.upload.onprogress = function (e) {
272
+ if (!e.lengthComputable) return;
273
+ var pct = Math.round(e.loaded / e.total * 100);
274
+ pctEl.textContent = pct + '%';
275
+ barEl.style.width = pct + '%';
276
+ var now = Date.now();
277
+ var dt = (now - lastTime) / 1000;
278
+ if (dt > 0.3) {
279
+ speedEl.textContent = fmtSize((e.loaded - lastLoaded) / dt) + '/s';
280
+ lastLoaded = e.loaded;
281
+ lastTime = now;
282
+ }
283
+ };
284
+ xhr.onload = function () {
285
+ var ok = xhr.status === 200;
286
+ var json = null;
287
+ try { json = JSON.parse(xhr.responseText); } catch (e) { json = null; }
288
+ ok = ok && json && json.code === 0;
289
+ barEl.style.width = '100%';
290
+ if (ok) {
291
+ barEl.className = 'h-full bg-emerald-500';
292
+ statusEl.textContent = '上传完成';
293
+ pctEl.textContent = '100%';
294
+ toast('上传完成:' + file.name, 'ok');
295
+ loadFiles();
296
+ setTimeout(function () { row.remove(); }, 1500);
297
+ } else {
298
+ barEl.className = 'h-full bg-red-500';
299
+ statusEl.textContent = (json && json.msg) || '上传失败';
300
+ toast((json && json.msg) || '上传失败', 'err');
301
+ }
302
+ };
303
+ xhr.onerror = function () {
304
+ barEl.className = 'h-full bg-red-500';
305
+ statusEl.textContent = '网络错误';
306
+ toast('上传失败:' + file.name, 'err');
307
+ };
308
+ xhr.send(fd);
309
+ }
310
+
311
+ function downloadFile(name) {
312
+ var url = API + '/download/' + encodeURIComponent(name);
313
+ var xhr = new XMLHttpRequest();
314
+ xhr.open('GET', url);
315
+ xhr.responseType = 'blob';
316
+ xhr.onprogress = function (e) {
317
+ if (e.lengthComputable && e.total) {
318
+ toast('下载中 ' + name + ' ' + Math.round(e.loaded / e.total * 100) + '%');
319
+ }
320
+ };
321
+ xhr.onload = function () {
322
+ if (xhr.status !== 200) { toast('下载失败:' + name, 'err'); return; }
323
+ var blob = xhr.response;
324
+ var a = document.createElement('a');
325
+ a.href = URL.createObjectURL(blob);
326
+ a.download = name;
327
+ document.body.appendChild(a);
328
+ a.click();
329
+ setTimeout(function () { URL.revokeObjectURL(a.href); a.remove(); }, 5000);
330
+ toast('下载完成:' + name, 'ok');
331
+ };
332
+ xhr.onerror = function () { toast('下载失败:' + name, 'err'); };
333
+ xhr.send();
334
+ }
335
+
336
+ var imgExts = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp', 'ico'];
337
+ var textExts = ['txt', 'md', 'json', 'js', 'ts', 'html', 'css', 'xml', 'log', 'csv', 'yml', 'yaml', 'ini', 'conf'];
338
+ function previewFile(name) {
339
+ var ext = (name.split('.').pop() || '').toLowerCase();
340
+ var url = API + '/preview/' + encodeURIComponent(name);
341
+ if (imgExts.indexOf(ext) >= 0 || textExts.indexOf(ext) < 0) {
342
+ window.open(url, '_blank');
343
+ return;
344
+ }
345
+ fetch(url)
346
+ .then(function (r) { return r.text(); })
347
+ .then(function (t) {
348
+ $('previewModal').classList.remove('hidden');
349
+ $('previewTitle').textContent = name;
350
+ $('previewContent').textContent = t.length > 200000 ? t.slice(0, 200000) + '... (内容过长已截断)' : t;
351
+ })
352
+ .catch(function () { toast('预览失败', 'err'); });
353
+ }
354
+
355
+ function copyLink(name) {
356
+ copyText(location.origin + API + '/download/' + encodeURIComponent(name));
357
+ }
358
+ function showQr(text, label) {
359
+ $('qrModal').classList.remove('hidden');
360
+ $('modalText').textContent = label || text;
361
+ if (modalQrCode) {
362
+ modalQrCode.update({ data: text });
363
+ } else {
364
+ $('modalQr').innerHTML = '';
365
+ modalQrCode = new QRCodeStyling({
366
+ width: 240, height: 240, type: 'canvas', data: text, margin: 0,
367
+ dotsOptions: { type: 'rounded', color: '#10b981' },
368
+ backgroundOptions: { color: '#ffffff' },
369
+ cornersSquareOptions: { type: 'extra-rounded', color: '#10b981' },
370
+ cornersDotOptions: { type: 'dot', color: '#10b981' },
371
+ });
372
+ modalQrCode.append($('modalQr'));
373
+ }
374
+ }
375
+ function deleteFile(name) {
376
+ if (!window.confirm('确定删除文件:' + name + ' ?')) return;
377
+ fetch(API + '/delete/' + encodeURIComponent(name), { method: 'DELETE' })
378
+ .then(function (r) { return r.json(); })
379
+ .then(function (json) {
380
+ if (json.code === 0) { toast('已删除:' + name, 'ok'); loadFiles(); }
381
+ else { toast(json.msg || '删除失败', 'err'); }
382
+ })
383
+ .catch(function () { toast('删除失败', 'err'); });
384
+ }
385
+
386
+ // 事件绑定
387
+ $('dropZone').addEventListener('click', function () { $('fileInput').click(); });
388
+ $('dropZone').addEventListener('dragover', function (e) { e.preventDefault(); $('dropZone').classList.add('border-emerald-400'); });
389
+ $('dropZone').addEventListener('dragleave', function () { $('dropZone').classList.remove('border-emerald-400'); });
390
+ $('dropZone').addEventListener('drop', function (e) {
391
+ e.preventDefault();
392
+ $('dropZone').classList.remove('border-emerald-400');
393
+ if (e.dataTransfer && e.dataTransfer.files.length) uploadFiles(e.dataTransfer.files);
394
+ });
395
+ $('fileInput').addEventListener('change', function (e) { uploadFiles(e.target.files); e.target.value = ''; });
396
+ $('openPageBtn').addEventListener('click', function () { window.open(pageUrl, '_blank'); });
397
+ $('pageQrCard').addEventListener('click', function (e) {
398
+ if (e.target.closest('button')) return; // 不拦截 openPageBtn
399
+ showQr(pageUrl, '手机扫码访问页面');
400
+ });
401
+ $('sortSelect').addEventListener('change', function (e) { sortType = e.target.value; loadFiles(); });
402
+ $('orderBtn').addEventListener('click', function () {
403
+ sortOrder = sortOrder === 'desc' ? 'asc' : 'desc';
404
+ $('orderBtn').textContent = sortOrder === 'desc' ? '↓ 降序' : '↑ 升序';
405
+ loadFiles();
406
+ });
407
+ $('closeModal').addEventListener('click', function () { $('qrModal').classList.add('hidden'); });
408
+ $('qrModal').addEventListener('click', function (e) { if (e.target === $('qrModal')) $('qrModal').classList.add('hidden'); });
409
+ $('closePreview').addEventListener('click', function () { $('previewModal').classList.add('hidden'); });
410
+ $('previewModal').addEventListener('click', function (e) { if (e.target === $('previewModal')) $('previewModal').classList.add('hidden'); });
411
+ $('fileList').addEventListener('click', function (e) {
412
+ var btnEl = e.target.closest('button[data-act]');
413
+ if (!btnEl) return;
414
+ var name = btnEl.dataset.name;
415
+ var act = btnEl.dataset.act;
416
+ if (act === 'download') downloadFile(name);
417
+ else if (act === 'preview') previewFile(name);
418
+ else if (act === 'copy') copyLink(name);
419
+ else if (act === 'qr') showQr(location.origin + API + '/download/' + encodeURIComponent(name), '扫码直连下载:' + name);
420
+ else if (act === 'delete') deleteFile(name);
421
+ });
422
+
423
+ // 全选 / 批量操作
424
+ $('selectAll').addEventListener('change', function (e) {
425
+ var checked = e.target.checked;
426
+ fileItems.forEach(function (f) { selected[f.name] = checked; });
427
+ updateBatchUI();
428
+ document.querySelectorAll('#fileList input.file-check').forEach(function (cb) { cb.checked = checked; });
429
+ document.querySelectorAll('#fileList > div').forEach(function (div) {
430
+ div.classList.toggle('bg-slate-800/40', checked);
431
+ });
432
+ });
433
+ $('fileList').addEventListener('change', function (e) {
434
+ if (!e.target.classList.contains('file-check')) return;
435
+ var name = e.target.dataset.name;
436
+ selected[name] = e.target.checked;
437
+ updateBatchUI();
438
+ e.target.closest('div').classList.toggle('bg-slate-800/40', e.target.checked);
439
+ });
440
+ $('batchDownload').addEventListener('click', function () {
441
+ var names = Object.keys(selected).filter(function (n) { return selected[n]; });
442
+ if (!names.length) return;
443
+ toast('开始批量下载 ' + names.length + ' 个文件');
444
+ var i = 0;
445
+ function next() {
446
+ if (i >= names.length) { toast('批量下载完成(共 ' + names.length + ' 个)', 'ok'); return; }
447
+ downloadFile(names[i]);
448
+ i += 1;
449
+ setTimeout(next, 800);
450
+ }
451
+ next();
452
+ });
453
+ $('batchDelete').addEventListener('click', function () {
454
+ var names = Object.keys(selected).filter(function (n) { return selected[n]; });
455
+ if (!names.length) return;
456
+ if (!window.confirm('确定删除选中的 ' + names.length + ' 个文件?此操作不可撤销。')) return;
457
+ toast('正在删除 ' + names.length + ' 个文件');
458
+ var total = names.length;
459
+ var done = 0;
460
+ var failed = 0;
461
+ function next() {
462
+ if (done >= total) {
463
+ if (failed) toast('已完成 ' + (total - failed) + '/' + total + ',' + failed + ' 个失败', 'err');
464
+ else toast('已删除 ' + total + ' 个文件', 'ok');
465
+ selected = {};
466
+ loadFiles();
467
+ return;
468
+ }
469
+ fetch(API + '/delete/' + encodeURIComponent(names[done]), { method: 'DELETE' })
470
+ .then(function (r) { return r.json(); })
471
+ .then(function (j) { if (j.code !== 0) failed++; done++; next(); })
472
+ .catch(function () { failed++; done++; next(); });
473
+ }
474
+ next();
475
+ });
476
+
477
+ loadFiles();
478
+ })();
479
+ </script>
480
+ </body>
481
+ </html>
@@ -0,0 +1,2 @@
1
+ import type { Express } from 'express';
2
+ export declare function initLocalsend(app: Express): Promise<void>;
@@ -0,0 +1,148 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.initLocalsend = initLocalsend;
7
+ /*
8
+ * LocalSend 局域网文件传输服务端模块
9
+ * 路由:
10
+ * - GET /localsend 页面
11
+ * - GET /localsend/api/list 文件列表(支持 ?sort=time|size&order=asc|desc)
12
+ * - POST /localsend/api/upload 多文件上传(multipart,字段名 files)
13
+ * - GET /localsend/api/download/:name 下载(attachment)
14
+ * - GET /localsend/api/preview/:name 预览(inline)
15
+ * - DELETE /localsend/api/delete/:name 删除
16
+ */
17
+ const node_fs_1 = require("node:fs");
18
+ const node_path_1 = require("node:path");
19
+ const console_log_colors_1 = require("console-log-colors");
20
+ const multer_1 = __importDefault(require("multer"));
21
+ const config_1 = require("./config");
22
+ const get_logger_1 = require("./get-logger");
23
+ const utils_1 = require("./lib/utils");
24
+ /**
25
+ * 前端页面单文件路径(相对本模块)。
26
+ * 构建后页面位于 dist/localsend/index.html;dev(ts-node)运行时位于 src/localsend/index.html。
27
+ */
28
+ const PAGE_REL_PATH = './localsend/index.html';
29
+ /** 去除文件名中的路径分隔符,防止目录穿越。非法返回空串 */
30
+ function safeName(name) {
31
+ const n = (0, node_path_1.basename)(String(name || '').trim());
32
+ if (!n || n === '.' || n === '..' || n.includes('/') || n.includes('\\'))
33
+ return '';
34
+ return n;
35
+ }
36
+ /** 同名文件自动追加 _1/_2 后缀 */
37
+ function uniqueName(targetDir, name) {
38
+ const ext = (0, node_path_1.extname)(name);
39
+ const base = name.slice(0, name.length - ext.length);
40
+ let finalName = name;
41
+ let i = 1;
42
+ while ((0, node_fs_1.existsSync)((0, node_path_1.join)(targetDir, finalName))) {
43
+ finalName = `${base}_${i}${ext}`;
44
+ i += 1;
45
+ }
46
+ return finalName;
47
+ }
48
+ async function initLocalsend(app) {
49
+ const config = await (0, config_1.getConfig)();
50
+ const raw = config.localsend;
51
+ if (!raw)
52
+ return;
53
+ const ls = typeof raw === 'boolean' ? { enabled: raw } : raw;
54
+ if (!ls.enabled)
55
+ return;
56
+ const dir = ls.dir || '';
57
+ const maxSize = ls.maxSize || 1024 * 1024 * 1024;
58
+ if (!(0, node_fs_1.existsSync)(dir))
59
+ (0, node_fs_1.mkdirSync)(dir, { recursive: true });
60
+ const port = config.port || 80;
61
+ const ipUrl = `http://${(0, utils_1.getIp)() || 'localhost'}:${port}`;
62
+ get_logger_1.logger.log(console_log_colors_1.color.green('LocalSend : '.padStart(15, ' ')), console_log_colors_1.color.greenBright('局域网文件传输功能已开启'));
63
+ get_logger_1.logger.log(console_log_colors_1.color.green('LocalSend DIR : '.padStart(15, ' ')), console_log_colors_1.color.cyanBright(dir));
64
+ get_logger_1.logger.log(console_log_colors_1.color.green('LocalSend URL : '.padStart(15, ' ')), console_log_colors_1.color.cyanBright(`${ipUrl}/localsend`));
65
+ // 页面:初始化时读入独立 html 单文件
66
+ const pageHtml = (0, node_fs_1.readFileSync)((0, node_path_1.resolve)(__dirname, PAGE_REL_PATH), 'utf8');
67
+ app.get('/localsend', (_req, res) => {
68
+ res.type('html').send(pageHtml);
69
+ });
70
+ // 文件列表
71
+ app.get('/localsend/api/list', (req, res) => {
72
+ const sort = String(req.query.sort || 'time');
73
+ const asc = String(req.query.order || 'desc') !== 'desc';
74
+ const list = (0, node_fs_1.readdirSync)(dir)
75
+ .map((name) => {
76
+ const full = (0, node_path_1.join)(dir, name);
77
+ const stat = (0, node_fs_1.statSync)(full);
78
+ return {
79
+ name,
80
+ size: stat.size,
81
+ mtime: stat.mtimeMs,
82
+ ext: (0, node_path_1.extname)(name).slice(1),
83
+ isDir: stat.isDirectory(),
84
+ };
85
+ })
86
+ .filter((item) => !item.isDir);
87
+ list.sort((a, b) => (sort === 'size' ? (asc ? a.size - b.size : b.size - a.size) : asc ? a.mtime - b.mtime : b.mtime - a.mtime));
88
+ res.json({ code: 0, data: list });
89
+ });
90
+ // 多文件上传
91
+ const upload = (0, multer_1.default)({
92
+ dest: dir,
93
+ limits: { fileSize: maxSize, files: 200 },
94
+ });
95
+ app.post('/localsend/api/upload', upload.array('files'), (req, res) => {
96
+ const files = (req.files || []);
97
+ const results = [];
98
+ const errors = [];
99
+ for (const f of files) {
100
+ try {
101
+ const name = uniqueName(dir, safeName(f.originalname) || `file_${Date.now()}`);
102
+ (0, node_fs_1.renameSync)(f.path, (0, node_path_1.join)(dir, name));
103
+ results.push({ name, size: f.size });
104
+ }
105
+ catch (err) {
106
+ get_logger_1.logger.error('[localsend upload]', err);
107
+ errors.push(f.originalname || '');
108
+ }
109
+ }
110
+ res.json({ code: 0, data: { results, errors } });
111
+ });
112
+ // 下载。dotfiles: 'allow' 以兼容 ~/.static-server 这类隐藏目录作为存储目录
113
+ app.get('/localsend/api/download/:name', (req, res) => {
114
+ const name = safeName(req.params.name);
115
+ if (!name)
116
+ return void res.status(400).json({ code: 1, msg: '非法的文件名' });
117
+ const filePath = (0, node_path_1.resolve)(dir, name);
118
+ if (!(0, node_fs_1.existsSync)(filePath) || !(0, node_fs_1.statSync)(filePath).isFile()) {
119
+ return void res.status(404).json({ code: 1, msg: '文件不存在' });
120
+ }
121
+ res.download(filePath, name, { dotfiles: 'allow' });
122
+ });
123
+ // 预览(inline 方式返回,浏览器可直读图片/文本等)
124
+ app.get('/localsend/api/preview/:name', (req, res) => {
125
+ const name = safeName(req.params.name);
126
+ if (!name)
127
+ return void res.status(400).json({ code: 1, msg: '非法的文件名' });
128
+ const filePath = (0, node_path_1.resolve)(dir, name);
129
+ if (!(0, node_fs_1.existsSync)(filePath) || !(0, node_fs_1.statSync)(filePath).isFile()) {
130
+ return void res.status(404).json({ code: 1, msg: '文件不存在' });
131
+ }
132
+ res.sendFile(filePath, {
133
+ dotfiles: 'allow',
134
+ headers: { 'Content-Disposition': `inline; filename*=UTF-8''${encodeURIComponent(name)}` },
135
+ });
136
+ });
137
+ // 删除
138
+ app.delete('/localsend/api/delete/:name', (req, res) => {
139
+ const name = safeName(req.params.name);
140
+ if (!name)
141
+ return void res.status(400).json({ code: 1, msg: '非法的文件名' });
142
+ const filePath = (0, node_path_1.resolve)(dir, name);
143
+ if (!(0, node_fs_1.existsSync)(filePath))
144
+ return void res.status(404).json({ code: 1, msg: '文件不存在' });
145
+ (0, node_fs_1.rmSync)(filePath);
146
+ res.json({ code: 0 });
147
+ });
148
+ }
@@ -1,2 +1,2 @@
1
- import { type Express } from 'express';
1
+ import type { Express } from 'express';
2
2
  export declare function proxyByExpress(app: Express): Promise<void>;
@@ -10,13 +10,13 @@ async function proxyByExpress(app) {
10
10
  if (!proxyConfig?.length)
11
11
  return;
12
12
  proxyConfig.forEach(({ api, config }) => {
13
- // @ts-ignore 兼容 2.0 api
13
+ // @ts-expect-error 兼容 2.0 api
14
14
  const onProxyReq = config.on?.proxyReq || config.onProxyReq;
15
15
  config.on = {
16
16
  ...(config.on || {}),
17
17
  proxyReq: (pReq, req, res, options) => {
18
18
  const now = new Date();
19
- get_logger_1.logger.log(now.toTimeString().slice(0, 8) + '.' + String(now.getMilliseconds()).padStart(3, '0'), console_log_colors_1.color.gray('[proxyReq]'), console_log_colors_1.color.cyan(req.url), '=>', console_log_colors_1.color.cyanBright(`${pReq.protocol}${pReq.host}${pReq.path}`));
19
+ get_logger_1.logger.log(`${now.toTimeString().slice(0, 8)}.${String(now.getMilliseconds()).padStart(3, '0')}`, console_log_colors_1.color.gray('[proxyReq]'), console_log_colors_1.color.cyan(req.url), '=>', console_log_colors_1.color.cyanBright(`${pReq.protocol}${pReq.host}${pReq.path}`));
20
20
  if (onProxyReq)
21
21
  onProxyReq(pReq, req, res, options);
22
22
  },
@@ -1,3 +1,3 @@
1
1
  import type { Express } from 'express';
2
- import { type SSConfig } from '../config';
2
+ import type { SSConfig } from '../config';
3
3
  export declare function phpProxy(app: Express, config: SSConfig): Promise<Express>;
@@ -3,9 +3,9 @@
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
4
  exports.phpProxy = phpProxy;
5
5
  const node_child_process_1 = require("node:child_process");
6
- const node_url_1 = require("node:url");
7
6
  const node_fs_1 = require("node:fs");
8
7
  const node_path_1 = require("node:path");
8
+ const node_url_1 = require("node:url");
9
9
  const fe_utils_1 = require("@lzwme/fe-utils");
10
10
  const get_logger_1 = require("../get-logger");
11
11
  async function phpProxy(app, config) {
@@ -23,7 +23,7 @@ async function findPhpFile(pathname, rootDir) {
23
23
  let filepath = (0, node_path_1.join)(rootDir, pathname);
24
24
  if (!filepath.includes(rootDir) || !(0, node_fs_1.existsSync)(filepath))
25
25
  return false;
26
- let stat = await node_fs_1.promises.stat(filepath);
26
+ const stat = await node_fs_1.promises.stat(filepath);
27
27
  if (stat.isDirectory()) {
28
28
  filepath = (0, node_path_1.join)(filepath, 'index.php');
29
29
  if (!(0, node_fs_1.existsSync)(filepath))
@@ -36,7 +36,7 @@ function formatArgs(args) {
36
36
  }
37
37
  function runPhpCgi(req, response, url, filepath, phpConfig, rootDir) {
38
38
  const pathname = url.pathname || req.url;
39
- const pathinfo = pathname.includes('.php') ? pathname.split('.php')[0] + '.php' : pathname;
39
+ const pathinfo = pathname.includes('.php') ? `${pathname.split('.php')[0]}.php` : pathname;
40
40
  if (!phpConfig)
41
41
  return;
42
42
  const env = {
@@ -73,11 +73,11 @@ function runPhpCgi(req, response, url, filepath, phpConfig, rootDir) {
73
73
  // All HTTP headers sent by the client. Headers are separated by carriage return characters (ASCII 13 - \n) and each header name is prefixed by HTTP_, transformed to upper cases, and - characters it contains are replaced by _ characters.
74
74
  ALL_HTTP: Object.entries(req.headers)
75
75
  .map(([key, value]) => `HTTP__${key.toUpperCase().replace('-', '_')}: ${value}`)
76
- .reduce((a, b) => a + b + '\n', ''),
76
+ .reduce((a, b) => `${a + b}\n`, ''),
77
77
  // All HTTP headers as sent by the client in raw form. No transformation on the header names is applied.
78
78
  ALL_RAW: Object.entries(req.headers)
79
- .map(([key, value]) => `${key}: value`)
80
- .reduce((a, b) => a + b + '\n', ''),
79
+ .map(([key, value]) => `${key}: ${value}`)
80
+ .reduce((a, b) => `${a + b}\n`, ''),
81
81
  // The web server's software identity.
82
82
  SERVER_SOFTWARE: 'NodeJS SServer',
83
83
  // The host name or the IP address of the computer running the web server as given in the requested URL.
@@ -106,13 +106,13 @@ function runPhpCgi(req, response, url, filepath, phpConfig, rootDir) {
106
106
  IS_SUBREQ: '',
107
107
  REDIRECT_STATUS: '1',
108
108
  };
109
- Object.entries(req.headers).forEach(function ([key, value]) {
110
- env['HTTP_' + key.toUpperCase().replace('-', '_')] = value;
109
+ Object.entries(req.headers).forEach(([key, value]) => {
110
+ env[`HTTP_${key.toUpperCase().replace('-', '_')}`] = value;
111
111
  });
112
112
  if (filepath.endsWith('.php')) {
113
113
  let childProc;
114
114
  const cgiArgs = formatArgs(phpConfig.args);
115
- let cgipath = phpConfig.cgiPath || getPhpCgi();
115
+ const cgipath = phpConfig.cgiPath || getPhpCgi();
116
116
  let res = '';
117
117
  let err = '';
118
118
  if (!cgipath || !(0, node_fs_1.existsSync)(cgipath))
@@ -147,10 +147,10 @@ function runPhpCgi(req, response, url, filepath, phpConfig, rootDir) {
147
147
  const m = lines[line].split(': ');
148
148
  if (m[0] === '')
149
149
  break;
150
- if (m[0] == 'Status') {
151
- response.statusCode = parseInt(m[1]);
150
+ if (m[0] === 'Status') {
151
+ response.statusCode = parseInt(m[1], 10);
152
152
  }
153
- if (m.length == 2) {
153
+ if (m.length === 2) {
154
154
  response.setHeader(m[0], m[1]);
155
155
  }
156
156
  line++;
@@ -15,9 +15,9 @@ function socketProxy(config = {
15
15
  remoteHost: '127.0.0.1',
16
16
  }) {
17
17
  const server = node_net_1.default
18
- .createServer(socket => {
18
+ .createServer((socket) => {
19
19
  console_log_colors_1.log.green('proxy for address', socket.address());
20
- let to = node_net_1.default.createConnection({
20
+ const to = node_net_1.default.createConnection({
21
21
  host: config.remoteHost,
22
22
  port: config.remotePort,
23
23
  });
@@ -44,16 +44,17 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
44
44
  };
45
45
  Object.defineProperty(exports, "__esModule", { value: true });
46
46
  exports.initServer = initServer;
47
- const node_https_1 = require("node:https");
48
47
  const node_child_process_1 = require("node:child_process");
48
+ const node_https_1 = require("node:https");
49
+ const fe_utils_1 = require("@lzwme/fe-utils");
49
50
  const console_log_colors_1 = require("console-log-colors");
50
51
  const express_1 = __importDefault(require("express"));
51
- const fe_utils_1 = require("@lzwme/fe-utils");
52
52
  const config_1 = require("./config");
53
53
  const get_logger_1 = require("./get-logger");
54
+ const utils_js_1 = require("./lib/utils.js");
55
+ const localsend_1 = require("./localsend");
54
56
  const express_proxy_1 = require("./proxy/express-proxy");
55
57
  const php_proxy_1 = require("./proxy/php-proxy");
56
- const utils_js_1 = require("./lib/utils.js");
57
58
  async function initServer(c) {
58
59
  const app = (0, express_1.default)();
59
60
  const config = await (0, config_1.getConfig)(!c, c);
@@ -71,6 +72,10 @@ async function initServer(c) {
71
72
  }
72
73
  await (0, php_proxy_1.phpProxy)(app, config);
73
74
  await (0, express_proxy_1.proxyByExpress)(app);
75
+ // localsend 局域网文件传输
76
+ if (config.localsend) {
77
+ await (0, localsend_1.initLocalsend)(app);
78
+ }
74
79
  // @see https://www.expressjs.com.cn/4x/api.html#express.static
75
80
  app.use(express_1.default.static(rootDir, {
76
81
  extensions: ['html', 'htm'],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lzwme/sserver",
3
- "version": "0.0.9",
3
+ "version": "0.0.10",
4
4
  "description": "一个基于 Node.js 的简易静态服务器,用于辅助开发调试随启随用",
5
5
  "main": "dist/index.js",
6
6
  "type": "commonjs",
@@ -34,34 +34,38 @@
34
34
  "ss.config.sample.js"
35
35
  ],
36
36
  "scripts": {
37
- "prepare": "husky install",
38
37
  "ss": "node bin/sserver.js",
39
38
  "start": "npm run stop && pm2 start dist/index.js --name sserver",
40
39
  "stop": "pm2 stop sserver",
41
40
  "watch": "tsc -w",
41
+ "lint": "biome check",
42
+ "fix": "biome check --fix",
42
43
  "dev": "ts-node -T src/cli.ts",
43
- "build": "npm run clean && tsc",
44
+ "build": "npm run clean && tsc && node scripts/copy-assets.js",
44
45
  "clean": "flh rm -f dist",
45
46
  "version": "standard-version",
46
47
  "release": "npm run build"
47
48
  },
48
49
  "dependencies": {
49
50
  "@lzwme/fe-utils": "^1.9.2",
50
- "commander": "^14.0.2",
51
+ "commander": "^15.0.0",
51
52
  "console-log-colors": "^0.5.0",
52
- "express": "^5.1.0",
53
- "http-proxy-middleware": "^3.0.5",
54
- "node-forge": "^1.3.1",
55
- "serve-index": "^1.9.1"
53
+ "express": "^5.2.1",
54
+ "http-proxy-middleware": "^4.2.0",
55
+ "multer": "^2.2.0",
56
+ "node-forge": "^1.4.0",
57
+ "serve-index": "^1.9.2"
56
58
  },
57
59
  "devDependencies": {
60
+ "@biomejs/biome": "^2.5.6",
58
61
  "@lzwme/fed-lint-helper": "^2.6.6",
59
- "@types/express": "^5.0.5",
60
- "@types/node": "^24.10.0",
62
+ "@types/express": "^5.0.6",
63
+ "@types/multer": "^2.2.0",
64
+ "@types/node": "^26.1.2",
61
65
  "@types/node-forge": "^1.3.14",
62
66
  "husky": "^9.1.7",
63
67
  "standard-version": "^9.5.0",
64
68
  "ts-node": "^10.9.2",
65
- "typescript": "^5.9.3"
69
+ "typescript": "^7.0.2"
66
70
  }
67
71
  }
@@ -4,6 +4,14 @@ module.exports = {
4
4
  https: false,
5
5
  sslCache: '',
6
6
  rootDir: '.',
7
+ // localsend 局域网文件传输。可设为 true 开启,或传入对象配置
8
+ // localsend: {
9
+ // enabled: true,
10
+ // // 文件存储目录。默认 ~/.static-server/localsend,可用环境变量 SS_LOCALSEND_DIR 覆盖
11
+ // dir: '~/localsend',
12
+ // // 单个文件上传大小限制(字节),默认 1GB
13
+ // maxSize: 1024 * 1024 * 1024,
14
+ // },
7
15
  proxyConfig: [
8
16
  // 内网代理企业微信机器人接口示例
9
17
  {