file-handle 0.0.4 → 0.0.6
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 +8 -5
- package/README.zh-CN.md +11 -8
- package/package.json +2 -1
- package/server/bin/cli.js +104 -2
- package/server/bin/fork.js +27 -0
- package/server/common/adapter.js +1 -2
- package/server/common/i18n.js +4 -2
- package/server/config.js +210 -91
- package/server/fh.app.dat +0 -0
- package/server/index.js +55 -45
- package/server/middlewares/security.js +6 -2
- package/server/routes/app.js +54 -0
- package/server/utils/logger.js +1 -1
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
|
-
##
|
|
22
|
+
## Usage
|
|
23
23
|
|
|
24
|
+
### Quick Usage
|
|
24
25
|
```bash
|
|
25
|
-
|
|
26
|
+
> npx file-handle
|
|
26
27
|
```
|
|
27
28
|
|
|
28
|
-
|
|
29
|
+
### Installation Usage
|
|
29
30
|
|
|
30
|
-
|
|
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
|
```
|
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
|
+
"version": "0.0.6",
|
|
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",
|
|
@@ -35,6 +35,7 @@
|
|
|
35
35
|
"dependencies": {
|
|
36
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
|
-
|
|
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
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { startServer } from "../index.js";
|
|
2
|
+
import Debug from 'debug';
|
|
3
|
+
const debug = Debug('FH fork');
|
|
4
|
+
process.on('message', (msg) => {
|
|
5
|
+
Debug(JSON.stringify(msg, null, 2));
|
|
6
|
+
if (msg && msg.cmd) {
|
|
7
|
+
switch (msg.cmd) {
|
|
8
|
+
case 'startServer':
|
|
9
|
+
startServer(msg.data).then(config => {
|
|
10
|
+
if (process.send) {
|
|
11
|
+
process.send({ cmd: 'started', data: config });
|
|
12
|
+
}
|
|
13
|
+
}).catch(err => {
|
|
14
|
+
if (process.send) {
|
|
15
|
+
process.send({ cmd: 'error', data: err.message });
|
|
16
|
+
}
|
|
17
|
+
});
|
|
18
|
+
break;
|
|
19
|
+
default:
|
|
20
|
+
break;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
});
|
|
24
|
+
// 可选:发送初始化就绪信号
|
|
25
|
+
if (process.send) {
|
|
26
|
+
process.send({ cmd: 'ready' });
|
|
27
|
+
}
|
package/server/common/adapter.js
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { createProxyMiddleware } from 'http-proxy-middleware';
|
|
2
|
-
import { loadConfig } from '../config.js';
|
|
3
2
|
import { resolve } from 'path';
|
|
4
3
|
import { debug } from '../utils/logger.js';
|
|
5
4
|
import mime from 'mime-types';
|
|
@@ -11,7 +10,7 @@ export function buildPreviewerHtml(html) {
|
|
|
11
10
|
return modifiedBody;
|
|
12
11
|
}
|
|
13
12
|
export async function sendFeReq(uri, req, res, next, sendBefore) {
|
|
14
|
-
const config =
|
|
13
|
+
const config = global.config;
|
|
15
14
|
// 获取node入口目录的绝对路径
|
|
16
15
|
const fhDir = config.mdDir;
|
|
17
16
|
debug('sendFeReq uri: ' + uri + ' | path: ' + req.path);
|
package/server/common/i18n.js
CHANGED
|
@@ -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,14 @@
|
|
|
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
|
|
7
|
-
|
|
8
|
-
|
|
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
|
+
const keyPath = 'app.key';
|
|
11
|
+
let oKey;
|
|
10
12
|
// 文件大小单位转换
|
|
11
13
|
const sizeUnits = {
|
|
12
14
|
PB: 1024 * 1024 * 1024 * 1024 * 1024,
|
|
@@ -16,8 +18,55 @@ const sizeUnits = {
|
|
|
16
18
|
KB: 1024,
|
|
17
19
|
B: 1
|
|
18
20
|
};
|
|
21
|
+
global.config = global.config || {
|
|
22
|
+
mdDir: path.dirname(fileURLToPath(import.meta.url)),
|
|
23
|
+
dataDir: getUserDataDir(),
|
|
24
|
+
port: 6688,
|
|
25
|
+
version: packageData.version,
|
|
26
|
+
allowDelete: false,
|
|
27
|
+
allowEdit: false,
|
|
28
|
+
writeLog: false,
|
|
29
|
+
uploadLimit: parseFileSize('3GB'),
|
|
30
|
+
allowWan: false,
|
|
31
|
+
};
|
|
32
|
+
export function loadConfig(opt) {
|
|
33
|
+
if (!fs.existsSync(opt.rootDir)) {
|
|
34
|
+
throw new Error(`Root directory does not exist. => ${opt.rootDir}`);
|
|
35
|
+
}
|
|
36
|
+
for (const key in global.config) {
|
|
37
|
+
if (opt[key] === undefined) {
|
|
38
|
+
opt[key] = global.config[key];
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
if (opt.password === '') {
|
|
42
|
+
opt.password = createRandomPassword(16);
|
|
43
|
+
}
|
|
44
|
+
global.config = opt;
|
|
45
|
+
createAppKey(global.config);
|
|
46
|
+
return opt;
|
|
47
|
+
}
|
|
48
|
+
export function getAppKeyPath() {
|
|
49
|
+
const priKeyPath = path.join(config.dataDir, 'hostPri.key');
|
|
50
|
+
const pubKeyPath = path.join(config.dataDir, 'hostPub.key');
|
|
51
|
+
return {
|
|
52
|
+
priKeyPath,
|
|
53
|
+
pubKeyPath
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
export function getAppKey() {
|
|
57
|
+
const { priKeyPath, pubKeyPath } = getAppKeyPath();
|
|
58
|
+
return {
|
|
59
|
+
priKey: fs.readFileSync(priKeyPath, 'utf-8'),
|
|
60
|
+
pubKey: fs.readFileSync(priKeyPath, 'utf-8')
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
function createAppKey(config) {
|
|
64
|
+
const { priKeyPath, pubKeyPath } = getAppKeyPath();
|
|
65
|
+
debug('Creating priKeyPath: ' + priKeyPath);
|
|
66
|
+
generatePrivateKey(priKeyPath, pubKeyPath);
|
|
67
|
+
}
|
|
19
68
|
// 解析文件大小字符串
|
|
20
|
-
function parseFileSize(sizeStr) {
|
|
69
|
+
export function parseFileSize(sizeStr) {
|
|
21
70
|
if (sizeStr.toLowerCase() === 'no')
|
|
22
71
|
return Infinity;
|
|
23
72
|
const match = sizeStr.match(/^(\d+)\s*([PTGMK]B|B)?$/i);
|
|
@@ -27,91 +76,17 @@ function parseFileSize(sizeStr) {
|
|
|
27
76
|
const unit = (match[2] || 'B').toUpperCase();
|
|
28
77
|
return size * (sizeUnits[unit] || 1);
|
|
29
78
|
}
|
|
30
|
-
//
|
|
31
|
-
export function
|
|
32
|
-
|
|
33
|
-
|
|
79
|
+
// 将bit数转成可读单位的字符串
|
|
80
|
+
export function formatFileSize(size) {
|
|
81
|
+
const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
|
|
82
|
+
let unitIndex = 0;
|
|
83
|
+
while (size >= 1024 && unitIndex < units.length - 1) {
|
|
84
|
+
size /= 1024;
|
|
85
|
+
unitIndex++;
|
|
34
86
|
}
|
|
35
|
-
|
|
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
|
-
};
|
|
110
|
-
}
|
|
111
|
-
runtimeConfig.config = config;
|
|
112
|
-
return config;
|
|
87
|
+
return `${size.toFixed(2)} ${units[unitIndex]}`;
|
|
113
88
|
}
|
|
114
|
-
function createRandomPassword(n) {
|
|
89
|
+
export function createRandomPassword(n) {
|
|
115
90
|
// 生成一个包括大小写字母和数字的n位随机密码
|
|
116
91
|
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
|
|
117
92
|
let password = '';
|
|
@@ -121,3 +96,147 @@ function createRandomPassword(n) {
|
|
|
121
96
|
}
|
|
122
97
|
return password;
|
|
123
98
|
}
|
|
99
|
+
// 加密信息
|
|
100
|
+
export function encryptDataRsa(msg, pubKey) {
|
|
101
|
+
try {
|
|
102
|
+
const maxChunkSize = 190;
|
|
103
|
+
const messageBuffer = Buffer.from(msg);
|
|
104
|
+
const chunks = [];
|
|
105
|
+
for (let i = 0; i < messageBuffer.length; i += maxChunkSize) {
|
|
106
|
+
const chunk = messageBuffer.subarray(i, i + maxChunkSize);
|
|
107
|
+
const encryptedChunk = crypto.publicEncrypt({
|
|
108
|
+
key: pubKey,
|
|
109
|
+
padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
|
|
110
|
+
oaepHash: 'sha256'
|
|
111
|
+
}, chunk);
|
|
112
|
+
chunks.push(encryptedChunk);
|
|
113
|
+
}
|
|
114
|
+
const encryptedData = Buffer.concat(chunks);
|
|
115
|
+
const encryptedBase64 = encryptedData.toString('base64');
|
|
116
|
+
return encryptedBase64;
|
|
117
|
+
}
|
|
118
|
+
catch (error) {
|
|
119
|
+
debug('加密失败:', error);
|
|
120
|
+
// console.log(error);
|
|
121
|
+
throw error;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
export function decryptDataRsa(msg, priKey) {
|
|
125
|
+
try {
|
|
126
|
+
const encryptedBuffer = Buffer.from(msg, 'base64');
|
|
127
|
+
const chunkSize = 256;
|
|
128
|
+
const chunks = [];
|
|
129
|
+
for (let i = 0; i < encryptedBuffer.length; i += chunkSize) {
|
|
130
|
+
const chunk = encryptedBuffer.subarray(i, i + chunkSize);
|
|
131
|
+
const decryptedChunk = crypto.privateDecrypt({
|
|
132
|
+
key: priKey,
|
|
133
|
+
padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
|
|
134
|
+
oaepHash: 'sha256'
|
|
135
|
+
}, chunk);
|
|
136
|
+
chunks.push(decryptedChunk);
|
|
137
|
+
}
|
|
138
|
+
const decryptedData = Buffer.concat(chunks);
|
|
139
|
+
debug('解密后的数据:', decryptedData.toString());
|
|
140
|
+
return decryptedData.toString();
|
|
141
|
+
}
|
|
142
|
+
catch (error) {
|
|
143
|
+
debug('解密失败:', error);
|
|
144
|
+
throw error;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
function getKey() {
|
|
148
|
+
const thirtyDaysInMillis = 30 * 24 * 60 * 60 * 1000;
|
|
149
|
+
const currentTime = +new Date();
|
|
150
|
+
let keyData;
|
|
151
|
+
const keyFilePath = path.join(config.dataDir, keyPath);
|
|
152
|
+
if (!oKey) {
|
|
153
|
+
if (fs.existsSync(keyFilePath)) {
|
|
154
|
+
const keyContent = fs.readFileSync(keyFilePath, 'utf8');
|
|
155
|
+
keyData = JSON.parse(keyContent);
|
|
156
|
+
oKey = keyData;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
if (!oKey || Math.abs(currentTime - oKey.time) > thirtyDaysInMillis) {
|
|
160
|
+
oKey = createKey();
|
|
161
|
+
}
|
|
162
|
+
// console.log('get: ', JSON.stringify(oKey, null, 2));
|
|
163
|
+
return {
|
|
164
|
+
key: Buffer.from(oKey.key, 'base64'),
|
|
165
|
+
iv: Buffer.from(oKey.iv, 'base64'),
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
function createKey() {
|
|
169
|
+
const keyFilePath = path.join(config.dataDir, keyPath);
|
|
170
|
+
const key = crypto.randomBytes(32); // 256位密钥
|
|
171
|
+
const iv = crypto.randomBytes(16); // 初始化向量
|
|
172
|
+
const oKey = {
|
|
173
|
+
key: key.toString('base64'),
|
|
174
|
+
iv: iv.toString('base64'),
|
|
175
|
+
time: +new Date()
|
|
176
|
+
};
|
|
177
|
+
fs.writeFileSync(keyFilePath, JSON.stringify(oKey));
|
|
178
|
+
const oData = JSON.parse(fs.readFileSync(keyFilePath).toString());
|
|
179
|
+
// console.log('create: ', JSON.stringify(oData, null, 2));
|
|
180
|
+
return oData;
|
|
181
|
+
}
|
|
182
|
+
// 加密函数
|
|
183
|
+
export function encrypt(text) {
|
|
184
|
+
const { key, iv } = getKey();
|
|
185
|
+
const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
|
|
186
|
+
let encrypted = cipher.update(text, 'utf8', 'hex');
|
|
187
|
+
encrypted += cipher.final('hex');
|
|
188
|
+
return encrypted;
|
|
189
|
+
}
|
|
190
|
+
// 解密函数
|
|
191
|
+
export function decrypt(encrypted) {
|
|
192
|
+
const { key, iv } = getKey();
|
|
193
|
+
const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
|
|
194
|
+
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
|
|
195
|
+
decrypted += decipher.final('utf8');
|
|
196
|
+
return decrypted;
|
|
197
|
+
}
|
|
198
|
+
function getUserDataDir() {
|
|
199
|
+
let dir = path.join(os.homedir(), `.${appName}`);
|
|
200
|
+
switch (process.platform) {
|
|
201
|
+
case 'win32':
|
|
202
|
+
dir = path.join(process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming'), `.${appName}`);
|
|
203
|
+
break;
|
|
204
|
+
case 'darwin':
|
|
205
|
+
dir = path.join(os.homedir(), 'Library', 'Application Support', `.${appName}`);
|
|
206
|
+
break;
|
|
207
|
+
case 'linux':
|
|
208
|
+
dir = path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config'), `.${appName}`);
|
|
209
|
+
break;
|
|
210
|
+
}
|
|
211
|
+
if (!fs.existsSync(dir)) {
|
|
212
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
213
|
+
}
|
|
214
|
+
return dir;
|
|
215
|
+
}
|
|
216
|
+
// 生成RSA密钥对函数
|
|
217
|
+
async function generatePrivateKey(priKeyPath, pubKeyPath) {
|
|
218
|
+
try {
|
|
219
|
+
// 检查密钥文件是否存在
|
|
220
|
+
if (!fs.existsSync(priKeyPath) || !fs.existsSync(pubKeyPath)) {
|
|
221
|
+
// 生成RSA密钥对
|
|
222
|
+
const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
|
|
223
|
+
modulusLength: 2048,
|
|
224
|
+
publicKeyEncoding: {
|
|
225
|
+
type: 'spki',
|
|
226
|
+
format: 'pem'
|
|
227
|
+
},
|
|
228
|
+
privateKeyEncoding: {
|
|
229
|
+
type: 'pkcs8',
|
|
230
|
+
format: 'pem'
|
|
231
|
+
}
|
|
232
|
+
});
|
|
233
|
+
// 保存私钥和公钥到文件
|
|
234
|
+
fs.writeFileSync(priKeyPath, privateKey);
|
|
235
|
+
fs.writeFileSync(pubKeyPath, publicKey);
|
|
236
|
+
debug('RSA密钥对已生成并保存');
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
catch (error) {
|
|
240
|
+
debug('生成RSA密钥对时发生错误:' + error);
|
|
241
|
+
}
|
|
242
|
+
}
|
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
|
|
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 = 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));
|
|
@@ -59,48 +65,52 @@ export async function startServer() {
|
|
|
59
65
|
}
|
|
60
66
|
const port = await findAvailablePort(config.port);
|
|
61
67
|
const localIPs = getLocalNetworkIPs();
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
info(
|
|
68
|
+
global.config.port = port;
|
|
69
|
+
global.config = Object.freeze(global.config);
|
|
70
|
+
return new Promise((resolve, reject) => {
|
|
71
|
+
if (config.allowedIPs) {
|
|
72
|
+
// 如果指定了允许访问的IP地址,则只允许这些IP访问
|
|
73
|
+
server.once('listening', () => resolve(global.config)).listen(port, '0.0.0.0', () => {
|
|
74
|
+
info(lang.server.allowedIpsOnly);
|
|
75
|
+
info(`${lang.server.running}${color.blueBright(port)}`);
|
|
76
|
+
info(`${lang.server.rootDirectory}${color.yellow(config.rootDir)}`);
|
|
77
|
+
info(lang.server.accessibleAddresses);
|
|
78
|
+
info(color.green(`http://127.0.0.1:${port}/fh/`));
|
|
79
|
+
config.allowedIPs && config.allowedIPs.forEach(ip => {
|
|
80
|
+
info(color.green(`http://${ip}:${port}/fh/`));
|
|
81
|
+
});
|
|
82
|
+
info('\n\n');
|
|
72
83
|
});
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
info(
|
|
84
|
+
}
|
|
85
|
+
else if (localIPs.length > 0 && !config.allowWan) {
|
|
86
|
+
// 如果存在局域网IP且未启用公网访问,则只监听局域网IP
|
|
87
|
+
server.once('listening', () => resolve(global.config)).listen(port, '0.0.0.0', () => {
|
|
88
|
+
info(lang.server.localAndLanOnly);
|
|
89
|
+
info(`${lang.server.running}${color.blueBright(port)}`);
|
|
90
|
+
info(`${lang.server.rootDirectory}${color.yellow(config.rootDir)}`);
|
|
91
|
+
info(lang.server.accessibleAddresses);
|
|
92
|
+
info(color.green(`http://127.0.0.1:${port}/fh/`));
|
|
93
|
+
localIPs.forEach(ip => {
|
|
94
|
+
info(color.green(`http://${ip}:${port}/fh/`));
|
|
95
|
+
});
|
|
96
|
+
info('\n\n');
|
|
86
97
|
});
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
}
|
|
98
|
+
}
|
|
99
|
+
else {
|
|
100
|
+
// 允许所有IP访问
|
|
101
|
+
server.once('listening', () => resolve(global.config)).listen(port, '0.0.0.0', () => {
|
|
102
|
+
info(`${lang.server.running}${color.blueBright(port)}`);
|
|
103
|
+
info(`${lang.server.rootDirectory}${color.yellow(config.rootDir)}`);
|
|
104
|
+
info(lang.server.accessibleAddresses);
|
|
105
|
+
info(`http://0.0.0.0:${port}/fh/`);
|
|
106
|
+
info(color.green(`http://127.0.0.1:${port}/fh/`));
|
|
107
|
+
info(`\n\n`);
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
if (config.password) {
|
|
111
|
+
info(`${lang.server.loginPassword}${color.green(config.password)}`);
|
|
112
|
+
}
|
|
113
|
+
});
|
|
104
114
|
}
|
|
105
115
|
async function findAvailablePort(startPort, maxAttempts = 50) {
|
|
106
116
|
const app = express();
|
|
@@ -116,7 +126,7 @@ async function findAvailablePort(startPort, maxAttempts = 50) {
|
|
|
116
126
|
server.close();
|
|
117
127
|
resolve(port);
|
|
118
128
|
})
|
|
119
|
-
.listen(port, '
|
|
129
|
+
.listen(port, '0.0.0.0');
|
|
120
130
|
});
|
|
121
131
|
return port;
|
|
122
132
|
}
|
|
@@ -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
|
-
|
|
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
|
-
|
|
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,
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { Router } from 'express';
|
|
2
|
+
import Debug from 'debug';
|
|
3
|
+
import { decrypt, encrypt } from '../config.js';
|
|
4
|
+
import { ApiResponseBuilder } from '../types/response.js';
|
|
5
|
+
const debug = Debug('app:route');
|
|
6
|
+
export function createAppRouter(config) {
|
|
7
|
+
const router = Router();
|
|
8
|
+
router.get('/getServerInfo', (req, res, next) => {
|
|
9
|
+
checkAuth('getServerInfo', req, res, next);
|
|
10
|
+
res.json(ApiResponseBuilder.success(encrypt(JSON.stringify(config))));
|
|
11
|
+
});
|
|
12
|
+
router.get('/shutdown', (req, res, next) => {
|
|
13
|
+
checkAuth('shutdown', req, res, next);
|
|
14
|
+
res.json(ApiResponseBuilder.success(encrypt(JSON.stringify({
|
|
15
|
+
rootDir: config.rootDir,
|
|
16
|
+
port: config.port,
|
|
17
|
+
shutdown: true
|
|
18
|
+
}))));
|
|
19
|
+
setTimeout(() => {
|
|
20
|
+
process.exit(0);
|
|
21
|
+
}, 500);
|
|
22
|
+
});
|
|
23
|
+
router.get('/test', (req, res, next) => {
|
|
24
|
+
let msg = encrypt('ok');
|
|
25
|
+
let text = decrypt(msg);
|
|
26
|
+
console.log(text);
|
|
27
|
+
res.send(text);
|
|
28
|
+
});
|
|
29
|
+
router.get('/token', (req, res, next) => {
|
|
30
|
+
let token = encrypt(JSON.stringify({
|
|
31
|
+
token: (+new Date()).toString(),
|
|
32
|
+
version: config.version
|
|
33
|
+
}));
|
|
34
|
+
res.json(ApiResponseBuilder.success(token));
|
|
35
|
+
});
|
|
36
|
+
// router.get('/*', (req, res, next) => {
|
|
37
|
+
// res.status(404).send('Not Found');
|
|
38
|
+
// });
|
|
39
|
+
return router;
|
|
40
|
+
}
|
|
41
|
+
function checkAuth(act, req, res, next) {
|
|
42
|
+
const authInHeader = req.headers['authorization'];
|
|
43
|
+
if (authInHeader) {
|
|
44
|
+
try {
|
|
45
|
+
const oAuth = JSON.parse(decrypt(authInHeader));
|
|
46
|
+
if (Math.abs(+new Date() - +oAuth.time) < 1000 && oAuth.act === act) {
|
|
47
|
+
next();
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
catch (error) { }
|
|
52
|
+
}
|
|
53
|
+
res.status(403).send('Unauthorized');
|
|
54
|
+
}
|
package/server/utils/logger.js
CHANGED
|
@@ -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}`;
|