file-handle 0.0.5 → 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 CHANGED
@@ -26,7 +26,7 @@ A simple local web file server with a user-friendly interface, allowing easy fil
26
26
  > npx file-handle
27
27
  ```
28
28
 
29
- ## Installation Usage
29
+ ### Installation Usage
30
30
 
31
31
  ```bash
32
32
  > npm install -g file-handle
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "file-handle",
3
- "version": "0.0.5",
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",
@@ -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/config.js CHANGED
@@ -7,6 +7,8 @@ import Debug from 'debug';
7
7
  import packageData from '../package.json' with { type: "json" };
8
8
  const debug = Debug('FH config');
9
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,
@@ -28,12 +30,20 @@ global.config = global.config || {
28
30
  allowWan: false,
29
31
  };
30
32
  export function loadConfig(opt) {
31
- const runConfig = Object.assign(Object.create(global.config), opt);
32
- if (runConfig.password === '') {
33
- runConfig.password = createRandomPassword(16);
33
+ if (!fs.existsSync(opt.rootDir)) {
34
+ throw new Error(`Root directory does not exist. => ${opt.rootDir}`);
34
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;
35
45
  createAppKey(global.config);
36
- return runConfig;
46
+ return opt;
37
47
  }
38
48
  export function getAppKeyPath() {
39
49
  const priKeyPath = path.join(config.dataDir, 'hostPri.key');
@@ -87,7 +97,7 @@ export function createRandomPassword(n) {
87
97
  return password;
88
98
  }
89
99
  // 加密信息
90
- export function encryptData(msg, pubKey) {
100
+ export function encryptDataRsa(msg, pubKey) {
91
101
  try {
92
102
  const maxChunkSize = 190;
93
103
  const messageBuffer = Buffer.from(msg);
@@ -107,11 +117,11 @@ export function encryptData(msg, pubKey) {
107
117
  }
108
118
  catch (error) {
109
119
  debug('加密失败:', error);
110
- console.log(error);
120
+ // console.log(error);
111
121
  throw error;
112
122
  }
113
123
  }
114
- export function decryptData(msg, priKey) {
124
+ export function decryptDataRsa(msg, priKey) {
115
125
  try {
116
126
  const encryptedBuffer = Buffer.from(msg, 'base64');
117
127
  const chunkSize = 256;
@@ -134,6 +144,57 @@ export function decryptData(msg, priKey) {
134
144
  throw error;
135
145
  }
136
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
+ }
137
198
  function getUserDataDir() {
138
199
  let dir = path.join(os.homedir(), `.${appName}`);
139
200
  switch (process.platform) {
package/server/fh.app.dat CHANGED
Binary file
package/server/index.js CHANGED
@@ -18,7 +18,7 @@ import { info, debug } from './utils/logger.js';
18
18
  const lang = getText();
19
19
  export async function startServer(opt) {
20
20
  // 加载配置
21
- const config = Object.freeze(loadConfig(opt));
21
+ const config = loadConfig(opt);
22
22
  global.config = config;
23
23
  if (!global.config.rootDir) {
24
24
  throw new Error('Root directory is required');
@@ -65,48 +65,52 @@ export async function startServer(opt) {
65
65
  }
66
66
  const port = await findAvailablePort(config.port);
67
67
  const localIPs = getLocalNetworkIPs();
68
- if (config.allowedIPs) {
69
- // 如果指定了允许访问的IP地址,则只允许这些IP访问
70
- server.listen(port, '0.0.0.0', () => {
71
- info(lang.server.allowedIpsOnly);
72
- info(`${lang.server.running}${color.blueBright(port)}`);
73
- info(`${lang.server.rootDirectory}${color.yellow(config.rootDir)}`);
74
- info(lang.server.accessibleAddresses);
75
- info(color.green(`http://127.0.0.1:${port}/fh/`));
76
- config.allowedIPs && config.allowedIPs.forEach(ip => {
77
- info(color.green(`http://${ip}:${port}/fh/`));
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');
78
83
  });
79
- info('\n\n');
80
- });
81
- }
82
- else if (localIPs.length > 0 && !config.allowWan) {
83
- // 如果存在局域网IP且未启用公网访问,则只监听局域网IP
84
- server.listen(port, '0.0.0.0', () => {
85
- info(lang.server.localAndLanOnly);
86
- info(`${lang.server.running}${color.blueBright(port)}`);
87
- info(`${lang.server.rootDirectory}${color.yellow(config.rootDir)}`);
88
- info(lang.server.accessibleAddresses);
89
- info(color.green(`http://127.0.0.1:${port}/fh/`));
90
- localIPs.forEach(ip => {
91
- info(color.green(`http://${ip}:${port}/fh/`));
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');
92
97
  });
93
- info('\n\n');
94
- });
95
- }
96
- else {
97
- // 允许所有IP访问
98
- server.listen(port, '0.0.0.0', () => {
99
- info(`${lang.server.running}${color.blueBright(port)}`);
100
- info(`${lang.server.rootDirectory}${color.yellow(config.rootDir)}`);
101
- info(lang.server.accessibleAddresses);
102
- info(`http://0.0.0.0:${port}/fh/`);
103
- info(color.green(`http://127.0.0.1:${port}/fh/`));
104
- info(`\n\n`);
105
- });
106
- }
107
- if (config.password) {
108
- info(`${lang.server.loginPassword}${color.green(config.password)}`);
109
- }
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
+ });
110
114
  }
111
115
  async function findAvailablePort(startPort, maxAttempts = 50) {
112
116
  const app = express();
@@ -1,41 +1,54 @@
1
1
  import { Router } from 'express';
2
2
  import Debug from 'debug';
3
- import { getAppKey } from '../config.js';
4
- import { decryptData, encryptData } from '../config.js';
3
+ import { decrypt, encrypt } from '../config.js';
5
4
  import { ApiResponseBuilder } from '../types/response.js';
6
5
  const debug = Debug('app:route');
7
- const { priKey, pubKey } = getAppKey();
8
6
  export function createAppRouter(config) {
9
7
  const router = Router();
10
8
  router.get('/getServerInfo', (req, res, next) => {
11
- checkAuth(req, res, next);
12
- res.json(ApiResponseBuilder.success(encryptData(JSON.stringify(config), pubKey)));
9
+ checkAuth('getServerInfo', req, res, next);
10
+ res.json(ApiResponseBuilder.success(encrypt(JSON.stringify(config))));
13
11
  });
14
12
  router.get('/shutdown', (req, res, next) => {
15
- checkAuth(req, res, next);
16
- res.json(ApiResponseBuilder.success({
13
+ checkAuth('shutdown', req, res, next);
14
+ res.json(ApiResponseBuilder.success(encrypt(JSON.stringify({
17
15
  rootDir: config.rootDir,
18
16
  port: config.port,
19
17
  shutdown: true
20
- }));
18
+ }))));
21
19
  setTimeout(() => {
22
20
  process.exit(0);
23
21
  }, 500);
24
22
  });
25
23
  router.get('/test', (req, res, next) => {
26
- let msg = encryptData('xxx', pubKey);
27
- let text = decryptData(msg, priKey);
24
+ let msg = encrypt('ok');
25
+ let text = decrypt(msg);
28
26
  console.log(text);
29
- res.status(404).send('Not Found');
27
+ res.send(text);
30
28
  });
31
- router.get('/*', (req, res, next) => {
32
- res.status(404).send('Not Found');
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));
33
35
  });
36
+ // router.get('/*', (req, res, next) => {
37
+ // res.status(404).send('Not Found');
38
+ // });
34
39
  return router;
35
40
  }
36
- function checkAuth(req, res, next) {
41
+ function checkAuth(act, req, res, next) {
37
42
  const authInHeader = req.headers['authorization'];
38
- if (!authInHeader || decryptData(authInHeader, priKey) != 'file-handle-mc') {
39
- res.status(403).send('Unauthorized');
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) { }
40
52
  }
53
+ res.status(403).send('Unauthorized');
41
54
  }