file-handle 0.0.3 → 0.0.5

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
@@ -19,22 +19,25 @@ A simple local web file server with a user-friendly interface, allowing easy fil
19
19
  - X Optional file deletion and editing functionality
20
20
  - X Secure file operations and access control
21
21
 
22
- ## Installation
22
+ ## Usage
23
23
 
24
+ ### Quick Usage
24
25
  ```bash
25
- npm install -g file-handle
26
+ > npx file-handle
26
27
  ```
27
28
 
28
- ## Usage
29
+ ## Installation Usage
29
30
 
30
- ### Basic Usage
31
+ ```bash
32
+ > npm install -g file-handle
33
+ ```
31
34
 
32
35
  Run the following command in the directory you wish to share to start the file server:
33
36
 
34
37
  ```bash
35
38
  > file-handle
36
39
  ```
37
-
40
+ or
38
41
  ```bash
39
42
  > fh
40
43
  ```
@@ -79,6 +82,7 @@ file-handle
79
82
  ## License
80
83
 
81
84
  Copyright [gaoyuan]
85
+
82
86
  Link: www.npmjs.com/package/file-handle
83
87
 
84
88
  Licensed under the Apache License, Version 2.0 (the "License");
package/README.zh-CN.md CHANGED
@@ -16,25 +16,28 @@
16
16
  - X 可选的文件删除和编辑功能
17
17
  - X 安全的文件操作和访问控制
18
18
 
19
- ## 安装
20
-
21
- ```bash
22
- npm install -g file-handle
23
- ```
24
19
 
25
20
  ## 使用方法
26
21
 
27
- ### 基本使用
22
+ ### 快捷使用
23
+ ```bash
24
+ > npx file-handle
25
+ ```
28
26
 
29
- 在希望共享的目录下运行以下命令,以启动文件服务器:
27
+ ### 安装使用
30
28
 
31
29
  ```bash
32
- > file-handle
30
+ > npm i -g file-handle
33
31
  ```
32
+ 在希望共享的目录下运行以下命令,以启动文件服务器:
34
33
 
35
34
  ```bash
36
35
  > fh
37
36
  ```
37
+ 或者
38
+ ```bash
39
+ > file-handle
40
+ ```
38
41
 
39
42
  这将在默认端口(6688)启动服务器,并使用当前工作目录作为根目录。
40
43
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "file-handle",
3
- "version": "0.0.3",
3
+ "version": "0.0.5",
4
4
  "author": "jsonhandle@gmail.com",
5
5
  "description": "A simple local web file server with a user-friendly interface, allowing easy file upload, download, preview, and management through a browser. \n一个简易的文件服务器,方便通过浏览器来浏览、上传或管理目录和文件. ",
6
6
  "main": "server/index.js",
@@ -33,8 +33,9 @@
33
33
  "test": "echo \"Error: no test specified\" && exit 1"
34
34
  },
35
35
  "dependencies": {
36
- "@electron/asar": "^3.3.1",
36
+ "unzipper": "^0.12.3",
37
37
  "archiver": "^7.0.1",
38
+ "debug": "^4.4.0",
38
39
  "cli-color": "^2.0.4",
39
40
  "cookie-parser": "^1.4.7",
40
41
  "express": "^4.18.2",
package/server/bin/cli.js CHANGED
@@ -1,3 +1,105 @@
1
- #!/usr/bin/env node
1
+ #!/usr/bin/env node --title=File-Handle-Server
2
+ import yargs from 'yargs';
3
+ import { hideBin } from 'yargs/helpers';
4
+ import path from 'path';
2
5
  import { startServer } from "../index.js";
3
- startServer();
6
+ import { getText } from '../common/i18n.js';
7
+ import packageData from '../../package.json' with { type: "json" };
8
+ import { parseFileSize } from '../config.js';
9
+ const cmdConfig = loadCmdArgs(process.argv);
10
+ startServer(cmdConfig);
11
+ // 加载命令行参数
12
+ function loadCmdArgs(args) {
13
+ const lang = getText();
14
+ const argv = yargs(hideBin(args))
15
+ .version(false)
16
+ .options({
17
+ 'w': {
18
+ alias: 'wan',
19
+ type: 'boolean',
20
+ description: lang.config.allowWanDesc,
21
+ default: false
22
+ },
23
+ 'd': {
24
+ alias: 'dir',
25
+ type: 'string',
26
+ description: lang.config.dirDesc,
27
+ default: process.cwd()
28
+ },
29
+ 'p': {
30
+ alias: 'port',
31
+ type: 'number',
32
+ description: lang.config.portDesc,
33
+ default: 6688
34
+ },
35
+ 'i': {
36
+ alias: 'ip',
37
+ type: 'string',
38
+ description: lang.config.ipDesc
39
+ },
40
+ 'tls': {
41
+ type: 'array',
42
+ description: lang.config.tlsDesc
43
+ },
44
+ 'del': {
45
+ type: 'boolean',
46
+ description: lang.config.delDesc,
47
+ default: false
48
+ },
49
+ 'password': {
50
+ type: 'string',
51
+ description: lang.config.passwordDesc
52
+ },
53
+ 'edit': {
54
+ type: 'boolean',
55
+ description: lang.config.editDesc,
56
+ default: false
57
+ },
58
+ 'log': {
59
+ type: 'boolean',
60
+ description: lang.config.logDesc,
61
+ default: false
62
+ },
63
+ 'limit': {
64
+ type: 'string',
65
+ description: lang.config.limitDesc,
66
+ default: '3GB'
67
+ },
68
+ 'V': {
69
+ alias: 'version',
70
+ type: 'string',
71
+ description: lang.config.versionDesc,
72
+ },
73
+ 'v': {
74
+ alias: 'version',
75
+ type: 'string',
76
+ description: lang.config.versionDesc,
77
+ }
78
+ })
79
+ .help()
80
+ .argv;
81
+ if ('V' in argv || 'v' in argv) {
82
+ console.log(`v${packageData.version}`);
83
+ process.exit(0);
84
+ }
85
+ const config = {
86
+ rootDir: path.resolve(argv.dir),
87
+ port: argv.port,
88
+ version: argv.version,
89
+ allowDelete: argv.del,
90
+ allowEdit: argv.edit,
91
+ writeLog: argv.log ? true : undefined,
92
+ password: argv.password,
93
+ uploadLimit: parseFileSize(argv.limit),
94
+ allowWan: argv.w || false,
95
+ allowedIPs: argv.i ? argv.i.split(',').map((ip) => ip.trim()) : undefined
96
+ };
97
+ // 配置TLS
98
+ if (Array.isArray(argv.tls) && argv.tls.length === 2) {
99
+ config.tls = {
100
+ cert: path.resolve(argv.tls[0]),
101
+ key: path.resolve(argv.tls[1])
102
+ };
103
+ }
104
+ return config;
105
+ }
@@ -1,23 +1,21 @@
1
1
  import { createProxyMiddleware } from 'http-proxy-middleware';
2
- import { loadConfig } from '../config.js';
3
- import path from 'path';
4
2
  import { resolve } from 'path';
5
3
  import { debug } from '../utils/logger.js';
6
- import asar from '@electron/asar';
7
4
  import mime from 'mime-types';
5
+ import unzip from 'unzipper';
8
6
  const isDevelopment = process.env.NODE_ENV === 'development';
9
7
  let resMap;
10
8
  export function buildPreviewerHtml(html) {
11
9
  const modifiedBody = html.replace('<base id="baseUrl" />', `<base id="baseUrl" href="/fh/" />`);
12
10
  return modifiedBody;
13
11
  }
14
- export function sendFeReq(uri, req, res, next, sendBefore) {
15
- const config = loadConfig();
12
+ export async function sendFeReq(uri, req, res, next, sendBefore) {
13
+ const config = global.config;
16
14
  // 获取node入口目录的绝对路径
17
15
  const fhDir = config.mdDir;
18
16
  debug('sendFeReq uri: ' + uri + ' | path: ' + req.path);
19
17
  if (!isDevelopment && !resMap) {
20
- resMap = getRes(resolve(fhDir, './fh.app.dat'));
18
+ resMap = await getRes(resolve(fhDir, './fh.app.dat'));
21
19
  }
22
20
  const bCb = !!sendBefore;
23
21
  const filePath = req.path;
@@ -70,21 +68,27 @@ export function sendFeReq(uri, req, res, next, sendBefore) {
70
68
  debug('req.path: ' + req.path);
71
69
  debug('resFilePath: ' + resFilePath);
72
70
  res.set('Content-Type', mime.lookup(resFilePath) || 'application/octet-stream');
73
- res.end(resMap.get((resFilePath).replace(/\//g, '\\')));
71
+ res.end(resMap.get((resFilePath).replace(/\\/g, '\/')));
74
72
  }
75
73
  }
76
- // 获取asar资源
77
- function getRes(asarPath) {
78
- const aFilePath = asar.listPackage(asarPath, { isPack: false });
74
+ // 获取zip资源
75
+ async function getRes(zipPath) {
76
+ const directory = await unzip.Open.file(zipPath);
79
77
  // 创建资源映射
80
78
  const resourceMap = new Map();
81
- aFilePath.forEach(filePath => {
82
- filePath = filePath.replace(/[\\\/]/g, '/').split('/').filter(s => s.trim()).join(path.sep);
83
- try {
84
- resourceMap.set(filePath, asar.extractFile(asarPath, filePath));
85
- }
86
- catch (error) { }
87
- });
88
- asar.uncacheAll();
79
+ // 处理所有文件
80
+ for (const file of directory.files) {
81
+ const chunks = [];
82
+ await new Promise((resolve, reject) => {
83
+ file.stream()
84
+ .on('data', (chunk) => chunks.push(chunk))
85
+ .on('error', reject)
86
+ .on('end', () => {
87
+ const content = Buffer.concat(chunks);
88
+ resourceMap.set(file.path, content);
89
+ resolve(file.path);
90
+ });
91
+ });
92
+ }
89
93
  return resourceMap;
90
94
  }
@@ -27,7 +27,8 @@ const i18n = {
27
27
  passwordDesc: '设置服务器访问的密码',
28
28
  editDesc: '启用文件编辑修改功能',
29
29
  logDesc: '保持日志文件',
30
- limitDesc: '设置文件上传大小限制'
30
+ limitDesc: '设置文件上传大小限制',
31
+ versionDesc: '显示当前版本号'
31
32
  }
32
33
  },
33
34
  'en-US': {
@@ -58,7 +59,8 @@ const i18n = {
58
59
  passwordDesc: 'Set server access password',
59
60
  editDesc: 'Enable file editing',
60
61
  logDesc: 'Keep log file',
61
- limitDesc: 'Set file upload size limit'
62
+ limitDesc: 'Set file upload size limit',
63
+ versionDesc: 'Show current version'
62
64
  }
63
65
  }
64
66
  };
package/server/config.js CHANGED
@@ -1,12 +1,12 @@
1
- import yargs from 'yargs';
2
- import { hideBin } from 'yargs/helpers';
3
- import path from 'path';
4
1
  import crypto from 'crypto';
2
+ import path from 'path';
3
+ import os from 'os';
4
+ import fs from 'fs';
5
5
  import { fileURLToPath } from 'url';
6
- import { getText } from './common/i18n.js';
7
- const runtimeConfig = {
8
- config: null
9
- };
6
+ import Debug from 'debug';
7
+ import packageData from '../package.json' with { type: "json" };
8
+ const debug = Debug('FH config');
9
+ export const appName = 'File-Handle';
10
10
  // 文件大小单位转换
11
11
  const sizeUnits = {
12
12
  PB: 1024 * 1024 * 1024 * 1024 * 1024,
@@ -16,8 +16,47 @@ const sizeUnits = {
16
16
  KB: 1024,
17
17
  B: 1
18
18
  };
19
+ global.config = global.config || {
20
+ mdDir: path.dirname(fileURLToPath(import.meta.url)),
21
+ dataDir: getUserDataDir(),
22
+ port: 6688,
23
+ version: packageData.version,
24
+ allowDelete: false,
25
+ allowEdit: false,
26
+ writeLog: false,
27
+ uploadLimit: parseFileSize('3GB'),
28
+ allowWan: false,
29
+ };
30
+ export function loadConfig(opt) {
31
+ const runConfig = Object.assign(Object.create(global.config), opt);
32
+ if (runConfig.password === '') {
33
+ runConfig.password = createRandomPassword(16);
34
+ }
35
+ createAppKey(global.config);
36
+ return runConfig;
37
+ }
38
+ export function getAppKeyPath() {
39
+ const priKeyPath = path.join(config.dataDir, 'hostPri.key');
40
+ const pubKeyPath = path.join(config.dataDir, 'hostPub.key');
41
+ return {
42
+ priKeyPath,
43
+ pubKeyPath
44
+ };
45
+ }
46
+ export function getAppKey() {
47
+ const { priKeyPath, pubKeyPath } = getAppKeyPath();
48
+ return {
49
+ priKey: fs.readFileSync(priKeyPath, 'utf-8'),
50
+ pubKey: fs.readFileSync(priKeyPath, 'utf-8')
51
+ };
52
+ }
53
+ function createAppKey(config) {
54
+ const { priKeyPath, pubKeyPath } = getAppKeyPath();
55
+ debug('Creating priKeyPath: ' + priKeyPath);
56
+ generatePrivateKey(priKeyPath, pubKeyPath);
57
+ }
19
58
  // 解析文件大小字符串
20
- function parseFileSize(sizeStr) {
59
+ export function parseFileSize(sizeStr) {
21
60
  if (sizeStr.toLowerCase() === 'no')
22
61
  return Infinity;
23
62
  const match = sizeStr.match(/^(\d+)\s*([PTGMK]B|B)?$/i);
@@ -27,91 +66,17 @@ function parseFileSize(sizeStr) {
27
66
  const unit = (match[2] || 'B').toUpperCase();
28
67
  return size * (sizeUnits[unit] || 1);
29
68
  }
30
- // 加载配置
31
- export function loadConfig(opt) {
32
- if (runtimeConfig.config) {
33
- return runtimeConfig.config;
34
- }
35
- const lang = getText();
36
- const argv = yargs(hideBin(process.argv))
37
- .options({
38
- 'w': {
39
- alias: 'wan',
40
- type: 'boolean',
41
- description: lang.config.allowWanDesc,
42
- default: false
43
- },
44
- 'd': {
45
- alias: 'dir',
46
- type: 'string',
47
- description: lang.config.dirDesc,
48
- default: process.cwd()
49
- },
50
- 'p': {
51
- alias: 'port',
52
- type: 'number',
53
- description: lang.config.portDesc,
54
- default: 6688
55
- },
56
- 'i': {
57
- alias: 'ip',
58
- type: 'string',
59
- description: lang.config.ipDesc
60
- },
61
- 'tls': {
62
- type: 'array',
63
- description: lang.config.tlsDesc
64
- },
65
- 'del': {
66
- type: 'boolean',
67
- description: lang.config.delDesc,
68
- default: false
69
- },
70
- 'password': {
71
- type: 'string',
72
- description: lang.config.passwordDesc
73
- },
74
- 'edit': {
75
- type: 'boolean',
76
- description: lang.config.editDesc,
77
- default: false
78
- },
79
- 'log': {
80
- type: 'boolean',
81
- description: lang.config.logDesc,
82
- default: false
83
- },
84
- 'limit': {
85
- type: 'string',
86
- description: lang.config.limitDesc,
87
- default: '3GB'
88
- }
89
- })
90
- .help()
91
- .argv;
92
- const config = {
93
- rootDir: path.resolve(argv.d),
94
- mdDir: path.dirname(fileURLToPath(import.meta.url)),
95
- port: argv.p,
96
- allowDelete: argv.del,
97
- allowEdit: argv.edit,
98
- writeLog: argv.log ? true : undefined,
99
- password: argv.password === '' ? createRandomPassword(16) : argv.password,
100
- uploadLimit: parseFileSize(argv.limit),
101
- allowWan: argv.w || opt?.allowWan || false,
102
- allowedIPs: argv.i ? argv.i.split(',').map((ip) => ip.trim()) : undefined
103
- };
104
- // 配置TLS
105
- if (Array.isArray(argv.tls) && argv.tls.length === 2) {
106
- config.tls = {
107
- cert: path.resolve(argv.tls[0]),
108
- key: path.resolve(argv.tls[1])
109
- };
69
+ // 将bit数转成可读单位的字符串
70
+ export function formatFileSize(size) {
71
+ const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
72
+ let unitIndex = 0;
73
+ while (size >= 1024 && unitIndex < units.length - 1) {
74
+ size /= 1024;
75
+ unitIndex++;
110
76
  }
111
- runtimeConfig.config = config;
112
- return config;
77
+ return `${size.toFixed(2)} ${units[unitIndex]}`;
113
78
  }
114
- function createRandomPassword(n) {
79
+ export function createRandomPassword(n) {
115
80
  // 生成一个包括大小写字母和数字的n位随机密码
116
81
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
117
82
  let password = '';
@@ -121,3 +86,96 @@ function createRandomPassword(n) {
121
86
  }
122
87
  return password;
123
88
  }
89
+ // 加密信息
90
+ export function encryptData(msg, pubKey) {
91
+ try {
92
+ const maxChunkSize = 190;
93
+ const messageBuffer = Buffer.from(msg);
94
+ const chunks = [];
95
+ for (let i = 0; i < messageBuffer.length; i += maxChunkSize) {
96
+ const chunk = messageBuffer.subarray(i, i + maxChunkSize);
97
+ const encryptedChunk = crypto.publicEncrypt({
98
+ key: pubKey,
99
+ padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
100
+ oaepHash: 'sha256'
101
+ }, chunk);
102
+ chunks.push(encryptedChunk);
103
+ }
104
+ const encryptedData = Buffer.concat(chunks);
105
+ const encryptedBase64 = encryptedData.toString('base64');
106
+ return encryptedBase64;
107
+ }
108
+ catch (error) {
109
+ debug('加密失败:', error);
110
+ console.log(error);
111
+ throw error;
112
+ }
113
+ }
114
+ export function decryptData(msg, priKey) {
115
+ try {
116
+ const encryptedBuffer = Buffer.from(msg, 'base64');
117
+ const chunkSize = 256;
118
+ const chunks = [];
119
+ for (let i = 0; i < encryptedBuffer.length; i += chunkSize) {
120
+ const chunk = encryptedBuffer.subarray(i, i + chunkSize);
121
+ const decryptedChunk = crypto.privateDecrypt({
122
+ key: priKey,
123
+ padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
124
+ oaepHash: 'sha256'
125
+ }, chunk);
126
+ chunks.push(decryptedChunk);
127
+ }
128
+ const decryptedData = Buffer.concat(chunks);
129
+ debug('解密后的数据:', decryptedData.toString());
130
+ return decryptedData.toString();
131
+ }
132
+ catch (error) {
133
+ debug('解密失败:', error);
134
+ throw error;
135
+ }
136
+ }
137
+ function getUserDataDir() {
138
+ let dir = path.join(os.homedir(), `.${appName}`);
139
+ switch (process.platform) {
140
+ case 'win32':
141
+ dir = path.join(process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming'), `.${appName}`);
142
+ break;
143
+ case 'darwin':
144
+ dir = path.join(os.homedir(), 'Library', 'Application Support', `.${appName}`);
145
+ break;
146
+ case 'linux':
147
+ dir = path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config'), `.${appName}`);
148
+ break;
149
+ }
150
+ if (!fs.existsSync(dir)) {
151
+ fs.mkdirSync(dir, { recursive: true });
152
+ }
153
+ return dir;
154
+ }
155
+ // 生成RSA密钥对函数
156
+ async function generatePrivateKey(priKeyPath, pubKeyPath) {
157
+ try {
158
+ // 检查密钥文件是否存在
159
+ if (!fs.existsSync(priKeyPath) || !fs.existsSync(pubKeyPath)) {
160
+ // 生成RSA密钥对
161
+ const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
162
+ modulusLength: 2048,
163
+ publicKeyEncoding: {
164
+ type: 'spki',
165
+ format: 'pem'
166
+ },
167
+ privateKeyEncoding: {
168
+ type: 'pkcs8',
169
+ format: 'pem'
170
+ }
171
+ });
172
+ // 保存私钥和公钥到文件
173
+ fs.writeFileSync(priKeyPath, privateKey);
174
+ fs.writeFileSync(pubKeyPath, publicKey);
175
+ debug('RSA密钥对已生成并保存');
176
+ }
177
+ }
178
+ catch (error) {
179
+ debug('生成RSA密钥对时发生错误:' + error);
180
+ }
181
+ }
package/server/fh.app.dat CHANGED
Binary file
package/server/index.js CHANGED
@@ -9,15 +9,20 @@ import { loadConfig } from './config.js';
9
9
  import { createFileSystemRouter } from './routes/fh.js';
10
10
  import { createApiRouter } from './routes/api.js';
11
11
  import { createResourcesRouter } from './routes/res.js';
12
+ import { createAppRouter } from './routes/app.js';
12
13
  import { handleUploadError } from './middlewares/upload.js';
13
- import { validatePassword, validateFileOperation, errorHandler, corsMiddleware } from './middlewares/security.js';
14
+ import { validatePassword, validateFileOperation, errorHandler } from './middlewares/security.js';
14
15
  import { validateIpAccess } from './middlewares/ipValidation.js';
15
16
  import { getText } from './common/i18n.js';
16
17
  import { info, debug } from './utils/logger.js';
17
18
  const lang = getText();
18
- export async function startServer() {
19
+ export async function startServer(opt) {
19
20
  // 加载配置
20
- const config = loadConfig();
21
+ const config = Object.freeze(loadConfig(opt));
22
+ global.config = config;
23
+ if (!global.config.rootDir) {
24
+ throw new Error('Root directory is required');
25
+ }
21
26
  debug(`Server config loaded: ${JSON.stringify(config, null, 2)}`);
22
27
  // 创建Express应用
23
28
  const app = express();
@@ -28,7 +33,8 @@ export async function startServer() {
28
33
  res.setHeader('Server', 'File-Handle Server');
29
34
  next();
30
35
  });
31
- app.use(corsMiddleware);
36
+ // app.use(corsMiddleware);
37
+ app.use('/app', createAppRouter(config));
32
38
  app.use(validateIpAccess(config));
33
39
  app.use(validatePassword(config));
34
40
  app.use(validateFileOperation(config));
@@ -61,9 +67,9 @@ export async function startServer() {
61
67
  const localIPs = getLocalNetworkIPs();
62
68
  if (config.allowedIPs) {
63
69
  // 如果指定了允许访问的IP地址,则只允许这些IP访问
64
- server.listen(port, '127.0.0.1', () => {
70
+ server.listen(port, '0.0.0.0', () => {
65
71
  info(lang.server.allowedIpsOnly);
66
- info(`${lang.server.running}${port}`);
72
+ info(`${lang.server.running}${color.blueBright(port)}`);
67
73
  info(`${lang.server.rootDirectory}${color.yellow(config.rootDir)}`);
68
74
  info(lang.server.accessibleAddresses);
69
75
  info(color.green(`http://127.0.0.1:${port}/fh/`));
@@ -75,9 +81,9 @@ export async function startServer() {
75
81
  }
76
82
  else if (localIPs.length > 0 && !config.allowWan) {
77
83
  // 如果存在局域网IP且未启用公网访问,则只监听局域网IP
78
- server.listen(port, '127.0.0.1', () => {
84
+ server.listen(port, '0.0.0.0', () => {
79
85
  info(lang.server.localAndLanOnly);
80
- info(`${lang.server.running}${port}`);
86
+ info(`${lang.server.running}${color.blueBright(port)}`);
81
87
  info(`${lang.server.rootDirectory}${color.yellow(config.rootDir)}`);
82
88
  info(lang.server.accessibleAddresses);
83
89
  info(color.green(`http://127.0.0.1:${port}/fh/`));
@@ -89,8 +95,8 @@ export async function startServer() {
89
95
  }
90
96
  else {
91
97
  // 允许所有IP访问
92
- server.listen(port, '127.0.0.1', () => {
93
- info(`${lang.server.running}${port}`);
98
+ server.listen(port, '0.0.0.0', () => {
99
+ info(`${lang.server.running}${color.blueBright(port)}`);
94
100
  info(`${lang.server.rootDirectory}${color.yellow(config.rootDir)}`);
95
101
  info(lang.server.accessibleAddresses);
96
102
  info(`http://0.0.0.0:${port}/fh/`);
@@ -116,7 +122,7 @@ async function findAvailablePort(startPort, maxAttempts = 50) {
116
122
  server.close();
117
123
  resolve(port);
118
124
  })
119
- .listen(port, '127.0.0.1');
125
+ .listen(port, '0.0.0.0');
120
126
  });
121
127
  return port;
122
128
  }
@@ -4,7 +4,7 @@ import { error } from '../utils/logger.js';
4
4
  export function validateIpAccess(config) {
5
5
  return (req, res, next) => {
6
6
  // 如果没有配置IP限制,直接通过
7
- if (!config.allowedIPs && !config.allowWan) {
7
+ if (!config.allowedIPs && config.allowWan) {
8
8
  return next();
9
9
  }
10
10
  const clientIp = req.ip || req.socket.remoteAddress || '';
@@ -24,12 +24,12 @@ export function validateFileOperation(config) {
24
24
  // 验证删除权限
25
25
  if (operation === 'delete' && !config.allowDelete) {
26
26
  error('Delete operation not allowed');
27
- throw new FileOperationError('Operation not allowed: Delete is disabled', 403);
27
+ return next(new FileOperationError('Operation not allowed: Delete is disabled', 403));
28
28
  }
29
29
  // 验证编辑权限
30
30
  if (operation === 'edit' && !config.allowEdit) {
31
31
  error('Edit operation not allowed');
32
- throw new FileOperationError('Operation not allowed: Edit is disabled', 403);
32
+ return next(new FileOperationError('Operation not allowed: Edit is disabled', 403));
33
33
  }
34
34
  next();
35
35
  };
@@ -37,6 +37,10 @@ export function validateFileOperation(config) {
37
37
  // 错误处理中间件
38
38
  export function errorHandler(err, req, res, next) {
39
39
  error(err);
40
+ // 检查响应是否已经发送
41
+ if (res.headersSent) {
42
+ return next(err);
43
+ }
40
44
  if (err instanceof FileOperationError) {
41
45
  return res.status(err.code).json({
42
46
  code: -err.code,
@@ -3,7 +3,7 @@ import fs from 'fs/promises';
3
3
  import path from 'path';
4
4
  import { ApiResponseBuilder } from '../types/response.js';
5
5
  import { normalizePath, validateFileName } from '../utils/path.js';
6
- import { isEditorAble, isPreviewAble, getMime } from '../types/index.js';
6
+ import { isEditorAble, isPreviewAble, getMime, extname } from '../types/index.js';
7
7
  import { createUploadMiddleware } from '../middlewares/upload.js';
8
8
  import { info } from '../utils/logger.js';
9
9
  export function createApiRouter(config) {
@@ -93,6 +93,7 @@ export function createApiRouter(config) {
93
93
  isDirectory: beDir,
94
94
  isLink: item.isSymbolicLink(),
95
95
  size: itemStats.size,
96
+ extension: extname(item.name) || null,
96
97
  modifiedTime: itemStats.mtime.toISOString(),
97
98
  mimeType: item.isDirectory() ? false : getMime(item.name),
98
99
  isPreviewable: item.isDirectory() ? false : isPreviewAble(item.name),
@@ -119,6 +120,7 @@ export function createApiRouter(config) {
119
120
  name: fileName,
120
121
  path: path.relative(config.rootDir, fullPath).replace(/\\/g, '/'),
121
122
  size: stats.size,
123
+ extension: extname(fileName) || null,
122
124
  modifiedTime: stats.mtime.toISOString(),
123
125
  mimeType: stats.isDirectory() ? false : getMime(fileName),
124
126
  isPreviewable: stats.isDirectory() ? false : isPreviewAble(fileName),
@@ -0,0 +1,41 @@
1
+ import { Router } from 'express';
2
+ import Debug from 'debug';
3
+ import { getAppKey } from '../config.js';
4
+ import { decryptData, encryptData } from '../config.js';
5
+ import { ApiResponseBuilder } from '../types/response.js';
6
+ const debug = Debug('app:route');
7
+ const { priKey, pubKey } = getAppKey();
8
+ export function createAppRouter(config) {
9
+ const router = Router();
10
+ router.get('/getServerInfo', (req, res, next) => {
11
+ checkAuth(req, res, next);
12
+ res.json(ApiResponseBuilder.success(encryptData(JSON.stringify(config), pubKey)));
13
+ });
14
+ router.get('/shutdown', (req, res, next) => {
15
+ checkAuth(req, res, next);
16
+ res.json(ApiResponseBuilder.success({
17
+ rootDir: config.rootDir,
18
+ port: config.port,
19
+ shutdown: true
20
+ }));
21
+ setTimeout(() => {
22
+ process.exit(0);
23
+ }, 500);
24
+ });
25
+ router.get('/test', (req, res, next) => {
26
+ let msg = encryptData('xxx', pubKey);
27
+ let text = decryptData(msg, priKey);
28
+ console.log(text);
29
+ res.status(404).send('Not Found');
30
+ });
31
+ router.get('/*', (req, res, next) => {
32
+ res.status(404).send('Not Found');
33
+ });
34
+ return router;
35
+ }
36
+ function checkAuth(req, res, next) {
37
+ const authInHeader = req.headers['authorization'];
38
+ if (!authInHeader || decryptData(authInHeader, priKey) != 'file-handle-mc') {
39
+ res.status(403).send('Unauthorized');
40
+ }
41
+ }
@@ -49,8 +49,10 @@ export function createFileSystemRouter(config) {
49
49
  else {
50
50
  let mimeType = getMime(fullPath);
51
51
  // 使用浏览器默认行为,否则viewable的使用text/plain,否则会触发下载
52
- if (!viewFlag && !editFlag) {
53
- !!mimeType && res.set('Content-Type', mimeType);
52
+ if (!viewFlag && !editFlag && mimeType) {
53
+ mimeType = mimeType.replace('/x-', '/')
54
+ .replace('/wave', '/wav');
55
+ res.set('Content-Type', mimeType);
54
56
  res.sendFile(fullPath, { dotfiles: 'allow' });
55
57
  }
56
58
  else if (editFlag) {
@@ -52,7 +52,7 @@ export const editAbleExtensions = [];
52
52
  editAbleExtensions.push([ext, config.name]);
53
53
  });
54
54
  });
55
- function extname(path) {
55
+ export function extname(path) {
56
56
  // 去除路径末尾的斜杠
57
57
  path = path.replace(/[\\\/]+$/, '');
58
58
  const parts = path.split('/');
@@ -1,6 +1,6 @@
1
1
  import winston from 'winston';
2
2
  import { loadConfig } from '../config.js';
3
- const config = loadConfig();
3
+ const config = global.config || loadConfig();
4
4
  // 创建日志格式
5
5
  const logFormat = winston.format.combine(winston.format.timestamp(), winston.format.printf(({ level, message, timestamp }) => {
6
6
  return `${timestamp} ${level.toUpperCase()}: ${message}`;