@lzwme/sserver 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/LICENSE +21 -21
- package/README.MD +35 -18
- package/bin/sserver.js +0 -0
- package/dist/cli.d.ts +1 -1
- package/dist/cli.js +61 -26
- package/dist/config.d.ts +47 -17
- package/dist/config.js +61 -29
- package/dist/get-logger.d.ts +2 -2
- package/dist/get-logger.js +9 -9
- package/dist/index.d.ts +1 -1
- package/dist/index.js +5 -20
- package/dist/lib/get-cert.d.ts +6 -0
- package/dist/lib/get-cert.js +79 -0
- package/dist/lib/mkcert.d.ts +26 -0
- package/dist/lib/mkcert.js +86 -0
- package/dist/proxy/express-proxy.d.ts +2 -2
- package/dist/proxy/express-proxy.js +24 -24
- package/dist/proxy/php-proxy.d.ts +3 -0
- package/dist/proxy/php-proxy.js +188 -0
- package/dist/proxy/socket-proxy.d.ts +7 -7
- package/dist/proxy/socket-proxy.js +30 -30
- package/dist/static-server.d.ts +3 -3
- package/dist/static-server.js +66 -42
- package/package.json +20 -16
- package/ss.config.sample.js +5 -3
package/LICENSE
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2018 任侠
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
-
SOFTWARE.
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2018 任侠
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.MD
CHANGED
|
@@ -9,27 +9,21 @@
|
|
|
9
9
|
[![GitHub forks][forks-badge]][forks-url]
|
|
10
10
|
[![GitHub stars][stars-badge]][stars-url]
|
|
11
11
|
|
|
12
|
-
一个基于
|
|
12
|
+
一个基于 Node.js 的简易静态服务器,用于辅助开发调试随启随用。
|
|
13
13
|
|
|
14
14
|
## 安装
|
|
15
15
|
|
|
16
|
-
安装:
|
|
17
|
-
|
|
18
16
|
```bash
|
|
19
17
|
# 全局安装
|
|
20
18
|
npm i -g @lzwme/sserver
|
|
21
|
-
# 测试
|
|
22
19
|
sserver -h
|
|
23
20
|
|
|
24
|
-
#
|
|
21
|
+
# 或者在项目中安装
|
|
25
22
|
npm i -D @lzwme/sserver
|
|
26
|
-
|
|
27
|
-
```
|
|
23
|
+
npm exec ss -- -h
|
|
28
24
|
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
```bash
|
|
32
|
-
npx @lzwme/sserver -d ./dist
|
|
25
|
+
# 或者直接使用 `npx`
|
|
26
|
+
npx @lzwme/sserver -h
|
|
33
27
|
```
|
|
34
28
|
|
|
35
29
|
## 使用
|
|
@@ -37,21 +31,39 @@ npx @lzwme/sserver -d ./dist
|
|
|
37
31
|
示例:
|
|
38
32
|
|
|
39
33
|
```bash
|
|
40
|
-
#
|
|
41
|
-
|
|
34
|
+
# 以当前目录下的 dist 作为静态根目录
|
|
35
|
+
ss -d ./dist
|
|
36
|
+
|
|
37
|
+
# 启用 https
|
|
38
|
+
ss --https
|
|
39
|
+
|
|
40
|
+
# 启用 https,指定域名(默认为 localhost)
|
|
41
|
+
ss -H --host local.lzw.me
|
|
42
|
+
|
|
43
|
+
# 启用 https,并保存默认生成的 ssl 证书
|
|
44
|
+
ss -H --ssl-cache ./cache
|
|
42
45
|
```
|
|
43
46
|
|
|
44
47
|
### 配置代理转发
|
|
45
48
|
|
|
46
|
-
支持通过配置文件 `ss.config.js`
|
|
49
|
+
支持通过配置文件 `ss.config.js` 指定代理转发等详细配置规则。
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
# 在当前目录初始化一个 ss.config.js 配置文件
|
|
53
|
+
ss init
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
配置文件内容示例:
|
|
47
57
|
|
|
48
58
|
```js
|
|
49
59
|
// ss.config.js
|
|
50
60
|
|
|
51
61
|
/** @type {import('@lzwme/sserver').SSConfig} */
|
|
52
62
|
module.exports = {
|
|
53
|
-
port:
|
|
54
|
-
|
|
63
|
+
port: 8888,
|
|
64
|
+
https: false,
|
|
65
|
+
sslCache: '',
|
|
66
|
+
rootDir: '.',
|
|
55
67
|
// 代理转发配置
|
|
56
68
|
proxyConfig: [
|
|
57
69
|
// 内网代理企业微信机器人接口示例
|
|
@@ -74,10 +86,15 @@ module.exports = {
|
|
|
74
86
|
本地二次开发:
|
|
75
87
|
|
|
76
88
|
```bash
|
|
77
|
-
git clone https://github.com/lzwme/static-server
|
|
89
|
+
git clone https://github.com/lzwme/static-server.git
|
|
78
90
|
pnpm install
|
|
79
|
-
|
|
91
|
+
pnpm build
|
|
92
|
+
|
|
93
|
+
# dev
|
|
80
94
|
pnpm dev
|
|
95
|
+
|
|
96
|
+
# global link
|
|
97
|
+
npm link
|
|
81
98
|
```
|
|
82
99
|
|
|
83
100
|
或者 fork 本项目进行代码贡献。
|
package/bin/sserver.js
CHANGED
|
File without changes
|
package/dist/cli.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export {};
|
|
1
|
+
export {};
|
package/dist/cli.js
CHANGED
|
@@ -1,26 +1,61 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
const
|
|
4
|
-
const
|
|
5
|
-
const
|
|
6
|
-
const
|
|
7
|
-
const
|
|
8
|
-
const
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
.
|
|
13
|
-
|
|
14
|
-
.
|
|
15
|
-
.option('-
|
|
16
|
-
.option('-
|
|
17
|
-
.option('--
|
|
18
|
-
.option('--
|
|
19
|
-
.
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
(
|
|
25
|
-
|
|
26
|
-
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const node_fs_1 = require("node:fs");
|
|
4
|
+
const node_path_1 = require("node:path");
|
|
5
|
+
const commander_1 = require("commander");
|
|
6
|
+
const console_log_colors_1 = require("console-log-colors");
|
|
7
|
+
const config_1 = require("./config");
|
|
8
|
+
const get_logger_1 = require("./get-logger");
|
|
9
|
+
const static_server_1 = require("./static-server");
|
|
10
|
+
const pkg = require('../package.json');
|
|
11
|
+
commander_1.program
|
|
12
|
+
.aliases(['ss'])
|
|
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)}]`)
|
|
15
|
+
// .option('-c, --config-path [filepath]', `配置文件 ${color.yellow(config.configPath)} 的路径`)
|
|
16
|
+
.option('-d, --root-dir [dirpath]', '静态服务器的根目录路径')
|
|
17
|
+
.option('-p, --port [port]', '端口号')
|
|
18
|
+
.option('--host <hostname>', '域名。默认为 `localhost`')
|
|
19
|
+
.option('-H, --https', '启用 https 模式')
|
|
20
|
+
.option('--cert <filepath>', 'https 模式使用的 ssl cert。默认根据 host 随机生成')
|
|
21
|
+
.option('--key <filepath>', 'https 模式使用的 ssl key。默认根据 host 随机生成')
|
|
22
|
+
.option('--ssl-cache <dir>', '随机生成 cert 证书缓存的路径。未指定则不缓存')
|
|
23
|
+
.option('-o, --open', '启动后是否打开静态服务器首页')
|
|
24
|
+
.option('--coop-coep', '启用跨域隔离', false)
|
|
25
|
+
.option('--log [dirpath]', `指定日志路径`)
|
|
26
|
+
.option('--debug', `开启调试模式。`, false)
|
|
27
|
+
.action(async (opts) => {
|
|
28
|
+
if (opts.cert)
|
|
29
|
+
opts.ssl.cert = opts.cert;
|
|
30
|
+
if (opts.key)
|
|
31
|
+
opts.ssl.key = opts.key;
|
|
32
|
+
if (opts.debug) {
|
|
33
|
+
get_logger_1.logger.updateOptions({ levelType: 'debug' });
|
|
34
|
+
get_logger_1.logger.debug(opts);
|
|
35
|
+
}
|
|
36
|
+
if (opts.coopCoep) {
|
|
37
|
+
opts.headers = {
|
|
38
|
+
'Cross-Origin-Opener-Policy': 'same-origin',
|
|
39
|
+
'Cross-Origin-Embedder-Policy': 'require-corp',
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
(0, config_1.getConfig)(false, opts).then(() => (0, static_server_1.initServer)());
|
|
43
|
+
});
|
|
44
|
+
commander_1.program
|
|
45
|
+
.command('init [destination]')
|
|
46
|
+
.description('初始化一个 ss.config.js 文件至指定的目录。默认为当前目录')
|
|
47
|
+
.action((destination = process.cwd()) => {
|
|
48
|
+
const confFile = (0, node_path_1.resolve)(destination, 'ss.config.js');
|
|
49
|
+
if ((0, node_fs_1.existsSync)(confFile)) {
|
|
50
|
+
get_logger_1.logger.warn('配置文件已存在,请确认:', console_log_colors_1.color.cyanBright(confFile));
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
const tplFile = (0, node_path_1.resolve)(__dirname, '../ss.config.sample.js');
|
|
54
|
+
if (!(0, node_fs_1.existsSync)(tplFile)) {
|
|
55
|
+
get_logger_1.logger.error('未找到配置文件模板:', console_log_colors_1.color.red(tplFile));
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
(0, node_fs_1.writeFileSync)(confFile, (0, node_fs_1.readFileSync)(tplFile));
|
|
59
|
+
get_logger_1.logger.info('已生成配置文件:', console_log_colors_1.color.greenBright(confFile));
|
|
60
|
+
});
|
|
61
|
+
commander_1.program.parse(process.argv);
|
package/dist/config.d.ts
CHANGED
|
@@ -1,17 +1,47 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
/**
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
1
|
+
/// <reference types="node" />
|
|
2
|
+
/// <reference types="node" />
|
|
3
|
+
import { Stats } from 'node:fs';
|
|
4
|
+
import { type ServerOptions } from 'node:https';
|
|
5
|
+
import { type Options } from 'http-proxy-middleware';
|
|
6
|
+
import { type Response, type Express } from 'express';
|
|
7
|
+
import { type NLogger, type color } from '@lzwme/fe-utils';
|
|
8
|
+
export interface SSConfig {
|
|
9
|
+
/** 自定义 app 应用逻辑 */
|
|
10
|
+
custom?(app: Express, config: SSConfig, logger: NLogger, c: typeof color): void;
|
|
11
|
+
/** host 地址。默认为 127.0.0.1 */
|
|
12
|
+
host?: string;
|
|
13
|
+
/** 是否开启日志记录。默认为 false。若设置为 true 则默认为 ~/.sserver/log.log;若为字符串,则设置为日志路径 */
|
|
14
|
+
log?: boolean | string;
|
|
15
|
+
/** 启动后是否打开首页 */
|
|
16
|
+
open?: boolean;
|
|
17
|
+
/** 监听端口号。默认 80,开启 https 则为 443 */
|
|
18
|
+
port?: number;
|
|
19
|
+
/** 代理转发配置 */
|
|
20
|
+
proxyConfig?: {
|
|
21
|
+
api: string;
|
|
22
|
+
config: Options;
|
|
23
|
+
}[];
|
|
24
|
+
phpConfig?: {
|
|
25
|
+
/** 执行 php-cgi 的路径。默认系统可执行路径获取 */
|
|
26
|
+
cgiPath?: string;
|
|
27
|
+
/** php-cgi port。默认为 9010 */
|
|
28
|
+
port?: number | string;
|
|
29
|
+
/** php-cgi 命令行参数 */
|
|
30
|
+
args?: Record<string, string>;
|
|
31
|
+
/** 是否仅处理 php 文件的请求。否则会处理所有静态文件的请求。默认 true */
|
|
32
|
+
onlyPhpFile?: boolean;
|
|
33
|
+
};
|
|
34
|
+
/** 根目录 */
|
|
35
|
+
rootDir?: string;
|
|
36
|
+
/** 是否为 https 模式 */
|
|
37
|
+
https?: boolean;
|
|
38
|
+
/** 指定 https 模式相关的 ssl 配置 */
|
|
39
|
+
ssl?: ServerOptions;
|
|
40
|
+
/** 自动生成 ssl 的缓存目录 */
|
|
41
|
+
sslCache?: string;
|
|
42
|
+
/** 设置公共自定义 headers */
|
|
43
|
+
headers?: Record<string, string | string[] | undefined>;
|
|
44
|
+
/** 按请求自定义 headers。返回结果与 headers 内容合并 */
|
|
45
|
+
setHeaders?: (res: Response<any, Record<string, any>>, path: string, stat: Stats) => Record<string, string | string[] | undefined>;
|
|
46
|
+
}
|
|
47
|
+
export declare function getConfig(useCache?: boolean, cfg?: SSConfig): Promise<SSConfig>;
|
package/dist/config.js
CHANGED
|
@@ -1,29 +1,61 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.getConfig = void 0;
|
|
4
|
-
const node_path_1 = require("node:path");
|
|
5
|
-
const node_os_1 = require("node:os");
|
|
6
|
-
const node_fs_1 = require("node:fs");
|
|
7
|
-
const fe_utils_1 = require("@lzwme/fe-utils");
|
|
8
|
-
const get_logger_1 = require("./get-logger");
|
|
9
|
-
const
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.getConfig = void 0;
|
|
4
|
+
const node_path_1 = require("node:path");
|
|
5
|
+
const node_os_1 = require("node:os");
|
|
6
|
+
const node_fs_1 = require("node:fs");
|
|
7
|
+
const fe_utils_1 = require("@lzwme/fe-utils");
|
|
8
|
+
const get_logger_1 = require("./get-logger");
|
|
9
|
+
const get_cert_1 = require("./lib/get-cert");
|
|
10
|
+
const ssConfig = {
|
|
11
|
+
log: false,
|
|
12
|
+
open: false,
|
|
13
|
+
phpConfig: {
|
|
14
|
+
onlyPhpFile: true,
|
|
15
|
+
args: {},
|
|
16
|
+
},
|
|
17
|
+
proxyConfig: [],
|
|
18
|
+
rootDir: '.',
|
|
19
|
+
ssl: {
|
|
20
|
+
rejectUnauthorized: false,
|
|
21
|
+
requestCert: true,
|
|
22
|
+
},
|
|
23
|
+
headers: {
|
|
24
|
+
'Access-Control-Allow-Credentials': 'true',
|
|
25
|
+
'Access-Control-Allow-Headers': '*',
|
|
26
|
+
'Access-Control-Allow-Methods': 'GET,POST,OPTIONS',
|
|
27
|
+
'Access-Control-Allow-Origin': '*',
|
|
28
|
+
'Cross-Origin-Opener-Policy': 'cross-origin',
|
|
29
|
+
},
|
|
30
|
+
};
|
|
31
|
+
async function getConfig(useCache = true, cfg) {
|
|
32
|
+
if (ssConfig.port && useCache)
|
|
33
|
+
return ssConfig;
|
|
34
|
+
const cfgFile = (0, node_path_1.resolve)(process.cwd(), './ss.config.js');
|
|
35
|
+
if ((0, node_fs_1.existsSync)(cfgFile))
|
|
36
|
+
(0, fe_utils_1.assign)(ssConfig, require(cfgFile));
|
|
37
|
+
if (cfg)
|
|
38
|
+
(0, fe_utils_1.assign)(ssConfig, cfg);
|
|
39
|
+
ssConfig.rootDir = (0, node_path_1.resolve)(process.cwd(), typeof ssConfig.rootDir === 'string' ? ssConfig.rootDir : '.');
|
|
40
|
+
if (ssConfig.log) {
|
|
41
|
+
get_logger_1.logger.setLogDir(typeof ssConfig.log === 'boolean' ? (0, node_path_1.resolve)((0, node_os_1.homedir)(), '.sserver/log.log') : ssConfig.log);
|
|
42
|
+
}
|
|
43
|
+
if (ssConfig.https && ssConfig.ssl) {
|
|
44
|
+
const { ssl } = ssConfig;
|
|
45
|
+
if (ssConfig.https && !ssl.cert) {
|
|
46
|
+
const info = await (0, get_cert_1.getCert)(ssConfig.host, ssConfig.sslCache || '');
|
|
47
|
+
ssl.key = Buffer.from(info.certKey);
|
|
48
|
+
ssl.cert = Buffer.from(info.certCrt);
|
|
49
|
+
ssl.ca = Buffer.from(info.caKey);
|
|
50
|
+
}
|
|
51
|
+
for (const key of ['key', 'cert', 'ca']) {
|
|
52
|
+
const val = ssl[key];
|
|
53
|
+
if (typeof val === 'string' && (0, node_fs_1.existsSync)(val))
|
|
54
|
+
ssl[key] = (0, node_fs_1.readFileSync)(val);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
if (!ssConfig.port)
|
|
58
|
+
ssConfig.port = ssConfig.https ? 443 : 80;
|
|
59
|
+
return ssConfig;
|
|
60
|
+
}
|
|
61
|
+
exports.getConfig = getConfig;
|
package/dist/get-logger.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { NLogger } from '@lzwme/fe-utils';
|
|
2
|
-
export declare const logger: NLogger;
|
|
1
|
+
import { NLogger } from '@lzwme/fe-utils';
|
|
2
|
+
export declare const logger: NLogger;
|
package/dist/get-logger.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.logger = void 0;
|
|
4
|
-
const console_log_colors_1 = require("console-log-colors");
|
|
5
|
-
const fe_utils_1 = require("@lzwme/fe-utils");
|
|
6
|
-
function getLogger(levelType, logDir) {
|
|
7
|
-
return fe_utils_1.NLogger.getLogger('[sserver]', { levelType, color: console_log_colors_1.color, logDir });
|
|
8
|
-
}
|
|
9
|
-
exports.logger = getLogger();
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.logger = void 0;
|
|
4
|
+
const console_log_colors_1 = require("console-log-colors");
|
|
5
|
+
const fe_utils_1 = require("@lzwme/fe-utils");
|
|
6
|
+
function getLogger(levelType, logDir) {
|
|
7
|
+
return fe_utils_1.NLogger.getLogger('[sserver]', { levelType, color: console_log_colors_1.color, logDir });
|
|
8
|
+
}
|
|
9
|
+
exports.logger = getLogger();
|
package/dist/index.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export
|
|
1
|
+
export { initServer } from './static-server';
|
package/dist/index.js
CHANGED
|
@@ -1,20 +1,5 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
-
}
|
|
8
|
-
Object.defineProperty(o, k2, desc);
|
|
9
|
-
}) : (function(o, m, k, k2) {
|
|
10
|
-
if (k2 === undefined) k2 = k;
|
|
11
|
-
o[k2] = m[k];
|
|
12
|
-
}));
|
|
13
|
-
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
-
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
-
};
|
|
16
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
-
__exportStar(require("./static-server"), exports);
|
|
18
|
-
const static_server_1 = require("./static-server");
|
|
19
|
-
if (module === require.main)
|
|
20
|
-
(0, static_server_1.initServer)();
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.initServer = void 0;
|
|
4
|
+
var static_server_1 = require("./static-server");
|
|
5
|
+
Object.defineProperty(exports, "initServer", { enumerable: true, get: function () { return static_server_1.initServer; } });
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.getCert = void 0;
|
|
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");
|
|
9
|
+
const console_log_colors_1 = require("console-log-colors");
|
|
10
|
+
async function getCert(host = 'localhost', cacheDir = '') {
|
|
11
|
+
const result = {
|
|
12
|
+
caKey: '',
|
|
13
|
+
caCrt: '',
|
|
14
|
+
certKey: '',
|
|
15
|
+
certCrt: '',
|
|
16
|
+
};
|
|
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`),
|
|
22
|
+
};
|
|
23
|
+
if (cacheDir) {
|
|
24
|
+
if (!(0, fs_1.existsSync)(cacheDir))
|
|
25
|
+
(0, promises_1.mkdir)(cacheDir, { recursive: true });
|
|
26
|
+
for (const [key, filepath] of Object.entries(dirs)) {
|
|
27
|
+
if ((0, fs_1.existsSync)(filepath))
|
|
28
|
+
result[key] = await (0, promises_1.readFile)(filepath, 'utf8');
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
if (!result.caKey) {
|
|
32
|
+
const attributes = [
|
|
33
|
+
{ name: 'commonName', value: 'sserver' },
|
|
34
|
+
{ name: 'countryName', value: 'CN' },
|
|
35
|
+
{ name: 'stateOrProvinceName', value: 'gd' },
|
|
36
|
+
{ name: 'localityName', value: 'gz' },
|
|
37
|
+
{ name: 'organizationName', value: 'lzw.me' },
|
|
38
|
+
{ name: 'organizationalUnitName', value: 'lzw.me' },
|
|
39
|
+
// { name: 'emailAddress', value: `webmaster@${host}` },
|
|
40
|
+
];
|
|
41
|
+
// create a certificate authority
|
|
42
|
+
const ca = await (0, mkcert_1.createCA)({
|
|
43
|
+
subject: attributes,
|
|
44
|
+
issuer: attributes,
|
|
45
|
+
});
|
|
46
|
+
result.caKey = ca.key;
|
|
47
|
+
result.caCrt = ca.cert;
|
|
48
|
+
if (cacheDir) {
|
|
49
|
+
await (0, promises_1.writeFile)(dirs.caKey, result.caKey, 'utf8');
|
|
50
|
+
await (0, promises_1.writeFile)(dirs.caCrt, result.caCrt, 'utf8');
|
|
51
|
+
get_logger_1.logger.info('save SSL CA certificate privateKey:', (0, console_log_colors_1.greenBright)(dirs.caKey));
|
|
52
|
+
get_logger_1.logger.info('save SSL CA certificate publicKey:', (0, console_log_colors_1.greenBright)(dirs.caCrt));
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
if (!result.certKey) {
|
|
56
|
+
const cert = await (0, mkcert_1.createCert)({
|
|
57
|
+
domains: [host, '127.0.0.1'],
|
|
58
|
+
caKey: result.caKey,
|
|
59
|
+
caCert: result.caCrt,
|
|
60
|
+
subject: [
|
|
61
|
+
{ name: 'countryName', value: 'CN' },
|
|
62
|
+
{ name: 'stateOrProvinceName', value: 'gd' },
|
|
63
|
+
{ name: 'localityName', value: 'gz' },
|
|
64
|
+
{ name: 'organizationName', value: 'sserver' },
|
|
65
|
+
{ name: 'organizationalUnitName', value: 'sserver' },
|
|
66
|
+
],
|
|
67
|
+
});
|
|
68
|
+
result.certKey = cert.key;
|
|
69
|
+
result.certCrt = cert.cert;
|
|
70
|
+
if (cacheDir) {
|
|
71
|
+
await (0, promises_1.writeFile)(dirs.certKey, result.certKey, 'utf8');
|
|
72
|
+
await (0, promises_1.writeFile)(dirs.certCrt, result.certCrt, 'utf8');
|
|
73
|
+
get_logger_1.logger.info('save SSL server certificate privateKey:', (0, console_log_colors_1.greenBright)(dirs.certKey));
|
|
74
|
+
get_logger_1.logger.info('save SSL server certificate publicKey:', (0, console_log_colors_1.greenBright)(dirs.certCrt));
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return result;
|
|
78
|
+
}
|
|
79
|
+
exports.getCert = getCert;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { pki } from 'node-forge';
|
|
2
|
+
interface GenCertOptions {
|
|
3
|
+
subject: pki.CertificateField[];
|
|
4
|
+
issuer: pki.CertificateField[];
|
|
5
|
+
extensions?: any[];
|
|
6
|
+
validityDays?: number;
|
|
7
|
+
signWith?: string;
|
|
8
|
+
}
|
|
9
|
+
export declare function generateCert(options: GenCertOptions): Promise<{
|
|
10
|
+
key: string;
|
|
11
|
+
cert: string;
|
|
12
|
+
}>;
|
|
13
|
+
export declare function createCA(options: GenCertOptions): Promise<{
|
|
14
|
+
key: string;
|
|
15
|
+
cert: string;
|
|
16
|
+
}>;
|
|
17
|
+
interface CreateCert extends Omit<Partial<GenCertOptions>, 'issuer'> {
|
|
18
|
+
domains: string[];
|
|
19
|
+
caKey: string;
|
|
20
|
+
caCert: string;
|
|
21
|
+
}
|
|
22
|
+
export declare function createCert(options: CreateCert): Promise<{
|
|
23
|
+
key: string;
|
|
24
|
+
cert: string;
|
|
25
|
+
}>;
|
|
26
|
+
export {};
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// @see https://github.com/Subash/mkcert
|
|
3
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
+
exports.createCert = exports.createCA = exports.generateCert = void 0;
|
|
5
|
+
const node_forge_1 = require("node-forge");
|
|
6
|
+
const util_1 = require("util");
|
|
7
|
+
const generateKeyPair = (0, util_1.promisify)(node_forge_1.pki.rsa.generateKeyPair.bind(node_forge_1.pki.rsa));
|
|
8
|
+
async function generateCert(options) {
|
|
9
|
+
let { subject, issuer, extensions = [], validityDays = 36500, signWith } = options;
|
|
10
|
+
// create serial from and integer between 50000 and 99999
|
|
11
|
+
const serial = Math.floor(Math.random() * 95000 + 50000).toString();
|
|
12
|
+
const keyPair = await generateKeyPair({ bits: 2048, workers: 4 });
|
|
13
|
+
const cert = node_forge_1.pki.createCertificate();
|
|
14
|
+
cert.publicKey = keyPair.publicKey;
|
|
15
|
+
cert.serialNumber = Buffer.from(serial).toString('hex'); // serial number must be hex encoded
|
|
16
|
+
cert.validity.notBefore = new Date();
|
|
17
|
+
cert.validity.notAfter = new Date();
|
|
18
|
+
cert.validity.notAfter.setDate(cert.validity.notAfter.getDate() + validityDays);
|
|
19
|
+
// certificate Attributes: https://git.io/fptna
|
|
20
|
+
cert.setSubject(subject);
|
|
21
|
+
cert.setIssuer(issuer);
|
|
22
|
+
cert.setExtensions(extensions);
|
|
23
|
+
// sign the certificate with it's own private key if no separate signing key is provided
|
|
24
|
+
const signKey = signWith ? node_forge_1.pki.privateKeyFromPem(signWith) : keyPair.privateKey;
|
|
25
|
+
cert.sign(signKey, node_forge_1.md.sha256.create());
|
|
26
|
+
return {
|
|
27
|
+
key: node_forge_1.pki.privateKeyToPem(keyPair.privateKey),
|
|
28
|
+
cert: node_forge_1.pki.certificateToPem(cert),
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
exports.generateCert = generateCert;
|
|
32
|
+
function createCA(options) {
|
|
33
|
+
if (!options.extensions)
|
|
34
|
+
options.extensions = [];
|
|
35
|
+
// required certificate extensions for a certificate authority
|
|
36
|
+
options.extensions = [
|
|
37
|
+
{ name: 'basicConstraints', cA: true, critical: true },
|
|
38
|
+
{ name: 'keyUsage', keyCertSign: true, critical: true },
|
|
39
|
+
...options.extensions,
|
|
40
|
+
];
|
|
41
|
+
return generateCert(options);
|
|
42
|
+
}
|
|
43
|
+
exports.createCA = createCA;
|
|
44
|
+
function createCert(options) {
|
|
45
|
+
// certificate Attributes: https://git.io/fptna
|
|
46
|
+
if (!options.subject)
|
|
47
|
+
options.subject = [];
|
|
48
|
+
if (!options.subject.find(d => d.name === 'commonName')) {
|
|
49
|
+
// use the first address as common name
|
|
50
|
+
options.subject.push({ name: 'commonName', value: options.domains[0] });
|
|
51
|
+
}
|
|
52
|
+
// required certificate extensions for a tls certificate
|
|
53
|
+
const extensions = [
|
|
54
|
+
{ name: 'basicConstraints', cA: false, critical: true },
|
|
55
|
+
{ name: 'keyUsage', digitalSignature: true, keyEncipherment: true, critical: true },
|
|
56
|
+
{ name: 'extKeyUsage', serverAuth: true, clientAuth: true },
|
|
57
|
+
{
|
|
58
|
+
name: 'subjectAltName',
|
|
59
|
+
altNames: options.domains.map(domain => {
|
|
60
|
+
const types = { domain: 2, ip: 7 }; // available Types: https://git.io/fptng
|
|
61
|
+
const isIp = isIP(domain);
|
|
62
|
+
if (isIp)
|
|
63
|
+
return { type: types.ip, ip: domain };
|
|
64
|
+
return { type: types.domain, value: domain };
|
|
65
|
+
}),
|
|
66
|
+
},
|
|
67
|
+
...(options.extensions || []),
|
|
68
|
+
];
|
|
69
|
+
const ca = node_forge_1.pki.certificateFromPem(options.caCert);
|
|
70
|
+
return generateCert({
|
|
71
|
+
...options,
|
|
72
|
+
subject: options.subject,
|
|
73
|
+
issuer: ca.subject.attributes,
|
|
74
|
+
extensions,
|
|
75
|
+
signWith: options.caKey,
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
exports.createCert = createCert;
|
|
79
|
+
function isIP(ip) {
|
|
80
|
+
if (!ip)
|
|
81
|
+
return false;
|
|
82
|
+
if (/::/.test(ip))
|
|
83
|
+
return true; // ipv6
|
|
84
|
+
const v4 = /^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$/;
|
|
85
|
+
return v4.test(ip);
|
|
86
|
+
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { type Express } from 'express';
|
|
2
|
-
export declare function proxyByExpress(app: Express): void
|
|
1
|
+
import { type Express } from 'express';
|
|
2
|
+
export declare function proxyByExpress(app: Express): Promise<void>;
|
|
@@ -1,24 +1,24 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.proxyByExpress = void 0;
|
|
4
|
-
const console_log_colors_1 = require("console-log-colors");
|
|
5
|
-
const http_proxy_middleware_1 = require("http-proxy-middleware");
|
|
6
|
-
const config_1 = require("../config");
|
|
7
|
-
const get_logger_1 = require("../get-logger");
|
|
8
|
-
function proxyByExpress(app) {
|
|
9
|
-
const { proxyConfig } = (0, config_1.getConfig)();
|
|
10
|
-
if (!proxyConfig?.length)
|
|
11
|
-
return;
|
|
12
|
-
proxyConfig.forEach(({ api, config }) => {
|
|
13
|
-
const onProxyReq = config.onProxyReq;
|
|
14
|
-
config.onProxyReq = (pReq, req, res, options) => {
|
|
15
|
-
const now = new Date();
|
|
16
|
-
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.originalUrl), '=>', console_log_colors_1.color.cyanBright(`${pReq.protocol}${pReq.host}${pReq.path}`));
|
|
17
|
-
if (onProxyReq)
|
|
18
|
-
onProxyReq(pReq, req, res, options);
|
|
19
|
-
};
|
|
20
|
-
app.use(api, (0, http_proxy_middleware_1.createProxyMiddleware)(config));
|
|
21
|
-
get_logger_1.logger.log(`Init proxy for ${console_log_colors_1.color.cyanBright(api)}`);
|
|
22
|
-
});
|
|
23
|
-
}
|
|
24
|
-
exports.proxyByExpress = proxyByExpress;
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.proxyByExpress = void 0;
|
|
4
|
+
const console_log_colors_1 = require("console-log-colors");
|
|
5
|
+
const http_proxy_middleware_1 = require("http-proxy-middleware");
|
|
6
|
+
const config_1 = require("../config");
|
|
7
|
+
const get_logger_1 = require("../get-logger");
|
|
8
|
+
async function proxyByExpress(app) {
|
|
9
|
+
const { proxyConfig } = await (0, config_1.getConfig)();
|
|
10
|
+
if (!proxyConfig?.length)
|
|
11
|
+
return;
|
|
12
|
+
proxyConfig.forEach(({ api, config }) => {
|
|
13
|
+
const onProxyReq = config.onProxyReq;
|
|
14
|
+
config.onProxyReq = (pReq, req, res, options) => {
|
|
15
|
+
const now = new Date();
|
|
16
|
+
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.originalUrl), '=>', console_log_colors_1.color.cyanBright(`${pReq.protocol}${pReq.host}${pReq.path}`));
|
|
17
|
+
if (onProxyReq)
|
|
18
|
+
onProxyReq(pReq, req, res, options);
|
|
19
|
+
};
|
|
20
|
+
app.use(api, (0, http_proxy_middleware_1.createProxyMiddleware)(config));
|
|
21
|
+
get_logger_1.logger.log(`Init proxy for ${console_log_colors_1.color.cyanBright(api)}`);
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
exports.proxyByExpress = proxyByExpress;
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// @see https://www.npmjs.com/package/phpcgijs
|
|
3
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
+
exports.phpProxy = void 0;
|
|
5
|
+
const node_child_process_1 = require("node:child_process");
|
|
6
|
+
const node_url_1 = require("node:url");
|
|
7
|
+
const node_fs_1 = require("node:fs");
|
|
8
|
+
const node_path_1 = require("node:path");
|
|
9
|
+
const fe_utils_1 = require("@lzwme/fe-utils");
|
|
10
|
+
const get_logger_1 = require("../get-logger");
|
|
11
|
+
async function phpProxy(app, config) {
|
|
12
|
+
return app.use('/', createPhpMiddleware(config.rootDir, config.phpConfig));
|
|
13
|
+
}
|
|
14
|
+
exports.phpProxy = phpProxy;
|
|
15
|
+
let PHP_CGI;
|
|
16
|
+
function getPhpCgi() {
|
|
17
|
+
if (PHP_CGI == null) {
|
|
18
|
+
const which = process.platform === 'win32' ? 'where' : 'which';
|
|
19
|
+
PHP_CGI = (0, fe_utils_1.execSync)(`${which} php-cgi`).stdout.trim() || (0, fe_utils_1.execSync)(`${which} php-cgi`).stdout.trim();
|
|
20
|
+
}
|
|
21
|
+
return PHP_CGI;
|
|
22
|
+
}
|
|
23
|
+
async function findPhpFile(pathname, rootDir) {
|
|
24
|
+
let filepath = (0, node_path_1.join)(rootDir, pathname);
|
|
25
|
+
if (!filepath.includes(rootDir) || !(0, node_fs_1.existsSync)(filepath))
|
|
26
|
+
return false;
|
|
27
|
+
let stat = await node_fs_1.promises.stat(filepath);
|
|
28
|
+
if (stat.isDirectory()) {
|
|
29
|
+
filepath = (0, node_path_1.join)(filepath, 'index.php');
|
|
30
|
+
if (!(0, node_fs_1.existsSync)(filepath))
|
|
31
|
+
return false;
|
|
32
|
+
}
|
|
33
|
+
return filepath;
|
|
34
|
+
}
|
|
35
|
+
function formatArgs(args) {
|
|
36
|
+
return Object.entries(args).map(([key, value]) => `${key.startsWith('-') ? key : `-${key}`} ${value}`);
|
|
37
|
+
}
|
|
38
|
+
function runPhpCgi(req, response, url, filepath, phpConfig, rootDir) {
|
|
39
|
+
const pathname = url.pathname || req.url;
|
|
40
|
+
const pathinfo = pathname.includes('.php') ? pathname.split('.php')[0] + '.php' : pathname;
|
|
41
|
+
if (!phpConfig)
|
|
42
|
+
return;
|
|
43
|
+
const env = {
|
|
44
|
+
SERVER_SIGNATURE: 'NodeJS server at localhost',
|
|
45
|
+
// The extra path information, as given in the requested URL. In fact, scripts can be accessed by their virtual path, followed by extra information at the end of this path. The extra information is sent in PATH_INFO.
|
|
46
|
+
PATH_INFO: pathinfo,
|
|
47
|
+
// The virtual-to-real mapped version of PATH_INFO.
|
|
48
|
+
PATH_TRANSLATED: '',
|
|
49
|
+
// The virtual path of the script being executed.
|
|
50
|
+
SCRIPT_NAME: pathname,
|
|
51
|
+
SCRIPT_FILENAME: filepath,
|
|
52
|
+
// The real path of the script being executed.
|
|
53
|
+
REQUEST_FILENAME: filepath,
|
|
54
|
+
// The full URL to the current object requested by the client.
|
|
55
|
+
SCRIPT_URI: req.url,
|
|
56
|
+
// The full URI of the current request. It is made of the concatenation of SCRIPT_NAME and PATH_INFO (if available.)
|
|
57
|
+
URL: req.url,
|
|
58
|
+
SCRIPT_URL: req.url,
|
|
59
|
+
// The original request URI sent by the client.
|
|
60
|
+
REQUEST_URI: req.url,
|
|
61
|
+
// The method used by the current request; usually set to GET or POST.
|
|
62
|
+
REQUEST_METHOD: req.method,
|
|
63
|
+
// The information which follows the ? character in the requested URL.
|
|
64
|
+
QUERY_STRING: url.query || '',
|
|
65
|
+
// 'multipart/form-data', //'application/x-www-form-urlencoded', //The MIME type of the request body; set only for POST or PUT requests.
|
|
66
|
+
CONTENT_TYPE: req.get('Content-Type') || '',
|
|
67
|
+
// The length in bytes of the request body; set only for POST or PUT requests.
|
|
68
|
+
CONTENT_LENGTH: req.get('Content-Length') || '0',
|
|
69
|
+
// The authentication type if the client has authenticated itself to access the script.
|
|
70
|
+
AUTH_TYPE: '',
|
|
71
|
+
AUTH_USER: '',
|
|
72
|
+
// The name of the user as issued by the client when authenticating itself to access the script.
|
|
73
|
+
REMOTE_USER: '',
|
|
74
|
+
// 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.
|
|
75
|
+
ALL_HTTP: Object.entries(req.headers)
|
|
76
|
+
.map(([key, value]) => `HTTP__${key.toUpperCase().replace('-', '_')}: ${value}`)
|
|
77
|
+
.reduce((a, b) => a + b + '\n', ''),
|
|
78
|
+
// All HTTP headers as sent by the client in raw form. No transformation on the header names is applied.
|
|
79
|
+
ALL_RAW: Object.entries(req.headers)
|
|
80
|
+
.map(([key, value]) => `${key}: value`)
|
|
81
|
+
.reduce((a, b) => a + b + '\n', ''),
|
|
82
|
+
// The web server's software identity.
|
|
83
|
+
SERVER_SOFTWARE: 'NodeJS SServer',
|
|
84
|
+
// The host name or the IP address of the computer running the web server as given in the requested URL.
|
|
85
|
+
SERVER_NAME: 'localhost',
|
|
86
|
+
// The IP address of the computer running the web server.
|
|
87
|
+
SERVER_ADDR: '127.0.0.1',
|
|
88
|
+
// The port to which the request was sent.
|
|
89
|
+
SERVER_PORT: String(phpConfig.port || '9010'),
|
|
90
|
+
// The CGI Specification version supported by the web server; always set to CGI/1.1.
|
|
91
|
+
GATEWAY_INTERFACE: 'CGI/1.1',
|
|
92
|
+
// The HTTP protocol version used by the current request.
|
|
93
|
+
SERVER_PROTOCOL: '',
|
|
94
|
+
// The IP address of the computer that sent the request.
|
|
95
|
+
REMOTE_ADDR: req.ip || '',
|
|
96
|
+
// The port from which the request was sent.
|
|
97
|
+
REMOTE_PORT: '',
|
|
98
|
+
// The absolute path of the web site files. It has the same value as Documents Path.
|
|
99
|
+
DOCUMENT_ROOT: rootDir,
|
|
100
|
+
// The numerical identifier of the host which served the request. On Abyss Web Server X1, it is always set to 1 since there is only a single host.
|
|
101
|
+
INSTANCE_ID: '',
|
|
102
|
+
// The virtual path of the deepest alias which contains the request URI. If no alias contains the request URI, the variable is set to /.
|
|
103
|
+
APPL_MD_PATH: '',
|
|
104
|
+
// The real path of the deepest alias which contains the request URI. If no alias contains the request URI, the variable is set to the same value as DOCUMENT_ROOT.
|
|
105
|
+
APPL_PHYSICAL_PATH: '',
|
|
106
|
+
// It is set to true if the current request is a subrequest, i.e. a request not directly invoked by a client. Otherwise, it is set to true. Subrequests are generated by the server for internal processing. XSSI includes for example result in subrequests.
|
|
107
|
+
IS_SUBREQ: '',
|
|
108
|
+
REDIRECT_STATUS: '1',
|
|
109
|
+
};
|
|
110
|
+
Object.entries(req.headers).forEach(function ([key, value]) {
|
|
111
|
+
env['HTTP_' + key.toUpperCase().replace('-', '_')] = value;
|
|
112
|
+
});
|
|
113
|
+
if (filepath.endsWith('.php')) {
|
|
114
|
+
let childProc;
|
|
115
|
+
const cgiArgs = formatArgs(phpConfig.args);
|
|
116
|
+
let cgipath = phpConfig.cgiPath || getPhpCgi();
|
|
117
|
+
let res = '';
|
|
118
|
+
let err = '';
|
|
119
|
+
if (!cgipath || !(0, node_fs_1.existsSync)(cgipath))
|
|
120
|
+
throw new Error('"php-cgi" cannot be found');
|
|
121
|
+
childProc = (0, node_child_process_1.spawn)(cgipath, cgiArgs, { env });
|
|
122
|
+
// php.stdin.resume();
|
|
123
|
+
// logger.debug(req.rawBody);
|
|
124
|
+
// (new Stream(req.rawBody)).pipe(php.stdin);
|
|
125
|
+
// php.stdin.write('\n');
|
|
126
|
+
// php.stdin.end();
|
|
127
|
+
// pipe request stream directly into the php process
|
|
128
|
+
req.pipe(childProc.stdin);
|
|
129
|
+
childProc.stdin.on('error', () => {
|
|
130
|
+
get_logger_1.logger.error('[php]Error from server');
|
|
131
|
+
});
|
|
132
|
+
childProc.stdout.on('data', (data) => {
|
|
133
|
+
res += data.toString();
|
|
134
|
+
});
|
|
135
|
+
childProc.stderr.on('data', (data) => {
|
|
136
|
+
err += data.toString();
|
|
137
|
+
});
|
|
138
|
+
childProc.on('error', (err) => {
|
|
139
|
+
get_logger_1.logger.error('error', err);
|
|
140
|
+
});
|
|
141
|
+
childProc.on('exit', () => {
|
|
142
|
+
childProc.stdin.end();
|
|
143
|
+
const lines = res ? res.split('\r\n') : [];
|
|
144
|
+
let line = 0;
|
|
145
|
+
let body = '';
|
|
146
|
+
if (lines.length) {
|
|
147
|
+
do {
|
|
148
|
+
const m = lines[line].split(': ');
|
|
149
|
+
if (m[0] === '')
|
|
150
|
+
break;
|
|
151
|
+
if (m[0] == 'Status') {
|
|
152
|
+
response.statusCode = parseInt(m[1]);
|
|
153
|
+
}
|
|
154
|
+
if (m.length == 2) {
|
|
155
|
+
response.setHeader(m[0], m[1]);
|
|
156
|
+
}
|
|
157
|
+
line++;
|
|
158
|
+
} while (lines[line] !== '');
|
|
159
|
+
body = lines.splice(line + 1).join('\n');
|
|
160
|
+
}
|
|
161
|
+
else {
|
|
162
|
+
body = res || err;
|
|
163
|
+
}
|
|
164
|
+
get_logger_1.logger.debug('[php]STATUS: ', response.statusCode);
|
|
165
|
+
response.status(response.statusCode).end(body);
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
else {
|
|
169
|
+
response.sendFile(filepath);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
function createPhpMiddleware(rootDir, phpConfig = {}) {
|
|
173
|
+
return async function phpMiddleware(req, res, next) {
|
|
174
|
+
// stop stream until child-process is opened
|
|
175
|
+
req.pause();
|
|
176
|
+
const url = (0, node_url_1.parse)(req.url);
|
|
177
|
+
const filepath = await findPhpFile(url.pathname || req.path, rootDir);
|
|
178
|
+
if (filepath && (filepath.includes('.php') || phpConfig.onlyPhpFile === false)) {
|
|
179
|
+
get_logger_1.logger.info('[php][exec]', fe_utils_1.color.green(req.path), '=>', fe_utils_1.color.yellow(filepath));
|
|
180
|
+
runPhpCgi(req, res, url, filepath, phpConfig, rootDir);
|
|
181
|
+
req.resume();
|
|
182
|
+
}
|
|
183
|
+
else {
|
|
184
|
+
req.resume();
|
|
185
|
+
next();
|
|
186
|
+
}
|
|
187
|
+
};
|
|
188
|
+
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
/// <reference types="node" />
|
|
2
|
-
import net from 'node:net';
|
|
3
|
-
export declare function socketProxy(config?: {
|
|
4
|
-
localPort: number;
|
|
5
|
-
remotePort: number;
|
|
6
|
-
remoteHost: string;
|
|
7
|
-
}): net.Server;
|
|
1
|
+
/// <reference types="node" />
|
|
2
|
+
import net from 'node:net';
|
|
3
|
+
export declare function socketProxy(config?: {
|
|
4
|
+
localPort: number;
|
|
5
|
+
remotePort: number;
|
|
6
|
+
remoteHost: string;
|
|
7
|
+
}): net.Server;
|
|
@@ -1,30 +1,30 @@
|
|
|
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.socketProxy = void 0;
|
|
7
|
-
const node_net_1 = __importDefault(require("node:net"));
|
|
8
|
-
const console_log_colors_1 = require("console-log-colors");
|
|
9
|
-
function socketProxy(config = {
|
|
10
|
-
// 外网访问的端口
|
|
11
|
-
localPort: 3717,
|
|
12
|
-
// 代理转发的端口
|
|
13
|
-
remotePort: 27017,
|
|
14
|
-
//代理转发的 IP 地址
|
|
15
|
-
remoteHost: '127.0.0.1',
|
|
16
|
-
}) {
|
|
17
|
-
const server = node_net_1.default
|
|
18
|
-
.createServer(socket => {
|
|
19
|
-
console_log_colors_1.log.green('proxy for address', socket.address());
|
|
20
|
-
let to = node_net_1.default.createConnection({
|
|
21
|
-
host: config.remoteHost,
|
|
22
|
-
port: config.remotePort,
|
|
23
|
-
});
|
|
24
|
-
socket.pipe(to);
|
|
25
|
-
to.pipe(socket);
|
|
26
|
-
})
|
|
27
|
-
.listen(config.localPort);
|
|
28
|
-
return server;
|
|
29
|
-
}
|
|
30
|
-
exports.socketProxy = socketProxy;
|
|
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.socketProxy = void 0;
|
|
7
|
+
const node_net_1 = __importDefault(require("node:net"));
|
|
8
|
+
const console_log_colors_1 = require("console-log-colors");
|
|
9
|
+
function socketProxy(config = {
|
|
10
|
+
// 外网访问的端口
|
|
11
|
+
localPort: 3717,
|
|
12
|
+
// 代理转发的端口
|
|
13
|
+
remotePort: 27017,
|
|
14
|
+
//代理转发的 IP 地址
|
|
15
|
+
remoteHost: '127.0.0.1',
|
|
16
|
+
}) {
|
|
17
|
+
const server = node_net_1.default
|
|
18
|
+
.createServer(socket => {
|
|
19
|
+
console_log_colors_1.log.green('proxy for address', socket.address());
|
|
20
|
+
let to = node_net_1.default.createConnection({
|
|
21
|
+
host: config.remoteHost,
|
|
22
|
+
port: config.remotePort,
|
|
23
|
+
});
|
|
24
|
+
socket.pipe(to);
|
|
25
|
+
to.pipe(socket);
|
|
26
|
+
})
|
|
27
|
+
.listen(config.localPort);
|
|
28
|
+
return server;
|
|
29
|
+
}
|
|
30
|
+
exports.socketProxy = socketProxy;
|
package/dist/static-server.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { type Express } from 'express';
|
|
2
|
-
import { SSConfig } from './config';
|
|
3
|
-
export declare function initServer(
|
|
1
|
+
import { type Express } from 'express';
|
|
2
|
+
import { SSConfig } from './config';
|
|
3
|
+
export declare function initServer(c?: SSConfig): Promise<Express>;
|
package/dist/static-server.js
CHANGED
|
@@ -1,42 +1,66 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
/*
|
|
3
|
-
* @Author: lzw
|
|
4
|
-
* @Date: 2021-05-28 16:24:40
|
|
5
|
-
* @LastEditors: lzw
|
|
6
|
-
* @LastEditTime:
|
|
7
|
-
* @Description:
|
|
8
|
-
*/
|
|
9
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
10
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
11
|
-
};
|
|
12
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
13
|
-
exports.initServer = void 0;
|
|
14
|
-
const
|
|
15
|
-
const console_log_colors_1 = require("console-log-colors");
|
|
16
|
-
const express_1 = __importDefault(require("express"));
|
|
17
|
-
const child_process_1 = require("child_process");
|
|
18
|
-
const
|
|
19
|
-
const
|
|
20
|
-
const get_logger_1 = require("./get-logger");
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
const
|
|
25
|
-
const
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
1
|
+
"use strict";
|
|
2
|
+
/*
|
|
3
|
+
* @Author: lzw
|
|
4
|
+
* @Date: 2021-05-28 16:24:40
|
|
5
|
+
* @LastEditors: lzw
|
|
6
|
+
* @LastEditTime: 2023-02-03 13:32:07
|
|
7
|
+
* @Description:
|
|
8
|
+
*/
|
|
9
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
10
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
11
|
+
};
|
|
12
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
13
|
+
exports.initServer = void 0;
|
|
14
|
+
const node_https_1 = require("node:https");
|
|
15
|
+
const console_log_colors_1 = require("console-log-colors");
|
|
16
|
+
const express_1 = __importDefault(require("express"));
|
|
17
|
+
const child_process_1 = require("child_process");
|
|
18
|
+
const fe_utils_1 = require("@lzwme/fe-utils");
|
|
19
|
+
const config_1 = require("./config");
|
|
20
|
+
const get_logger_1 = require("./get-logger");
|
|
21
|
+
const express_proxy_1 = require("./proxy/express-proxy");
|
|
22
|
+
const php_proxy_1 = require("./proxy/php-proxy");
|
|
23
|
+
async function initServer(c) {
|
|
24
|
+
const app = (0, express_1.default)();
|
|
25
|
+
const config = await (0, config_1.getConfig)(!c, c);
|
|
26
|
+
const { rootDir = '.', port = 8888, host = 'localhost' } = config;
|
|
27
|
+
const url = `http${config.https ? 's' : ''}://${host}:${port}`;
|
|
28
|
+
app.use((_req, res, next) => {
|
|
29
|
+
Object.entries(config.headers).forEach(([key, value]) => res.header(key, value));
|
|
30
|
+
next();
|
|
31
|
+
});
|
|
32
|
+
if (typeof config.custom === 'function') {
|
|
33
|
+
await config.custom(app, config, get_logger_1.logger, console_log_colors_1.color);
|
|
34
|
+
}
|
|
35
|
+
await (0, php_proxy_1.phpProxy)(app, config);
|
|
36
|
+
await (0, express_proxy_1.proxyByExpress)(app);
|
|
37
|
+
// @see https://www.expressjs.com.cn/4x/api.html#express.static
|
|
38
|
+
app.use(express_1.default.static(rootDir, {
|
|
39
|
+
extensions: ['html', 'htm'],
|
|
40
|
+
setHeaders: (res, path, stat) => {
|
|
41
|
+
if (typeof config.setHeaders === 'function') {
|
|
42
|
+
const headers = { ...config.headers };
|
|
43
|
+
get_logger_1.logger.debug('[setHeader]', path, headers);
|
|
44
|
+
(0, fe_utils_1.assign)(headers, config.setHeaders(res, path, stat));
|
|
45
|
+
Object.entries(headers).forEach(([key, value]) => res.header(key, value));
|
|
46
|
+
}
|
|
47
|
+
},
|
|
48
|
+
}));
|
|
49
|
+
const onListen = () => {
|
|
50
|
+
get_logger_1.logger.log(console_log_colors_1.color.green(`Runing at : `.padStart(15, ' ')), console_log_colors_1.color.cyanBright(url));
|
|
51
|
+
get_logger_1.logger.log(console_log_colors_1.color.green(`ROOT DIR : `.padStart(15, ' ')), console_log_colors_1.color.cyanBright(rootDir));
|
|
52
|
+
};
|
|
53
|
+
if (config.https) {
|
|
54
|
+
(0, node_https_1.createServer)(config.ssl, app).listen(port, onListen);
|
|
55
|
+
}
|
|
56
|
+
else {
|
|
57
|
+
app.listen(port, onListen);
|
|
58
|
+
}
|
|
59
|
+
get_logger_1.logger.debug(config);
|
|
60
|
+
if (config.open) {
|
|
61
|
+
const openPageCmd = `${process.platform === 'win32' ? `start` : `open`} ${url}`;
|
|
62
|
+
(0, child_process_1.execSync)(openPageCmd);
|
|
63
|
+
}
|
|
64
|
+
return app;
|
|
65
|
+
}
|
|
66
|
+
exports.initServer = initServer;
|
package/package.json
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lzwme/sserver",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"description": "一个基于
|
|
3
|
+
"version": "0.0.6",
|
|
4
|
+
"description": "一个基于 Node.js 的简易静态服务器,用于辅助开发调试随启随用",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"type": "commonjs",
|
|
7
7
|
"bin": {
|
|
8
8
|
"sserver": "bin/sserver.js",
|
|
9
9
|
"ss": "bin/sserver.js"
|
|
10
10
|
},
|
|
11
|
-
"repository": "
|
|
11
|
+
"repository": "https://github.com/lzwme/static-server.git",
|
|
12
12
|
"author": {
|
|
13
13
|
"name": "renxia",
|
|
14
14
|
"email": "lzwy0820@qq.com",
|
|
@@ -37,27 +37,31 @@
|
|
|
37
37
|
"scripts": {
|
|
38
38
|
"prepare": "husky install",
|
|
39
39
|
"ss": "node bin/sserver.js",
|
|
40
|
-
"start": "
|
|
40
|
+
"start": "npm run stop && pm2 start dist/index.js --name sserver",
|
|
41
41
|
"stop": "pm2 stop sserver",
|
|
42
|
-
"
|
|
42
|
+
"watch": "tsc -w",
|
|
43
|
+
"dev": "ts-node -T src/cli.ts",
|
|
43
44
|
"build": "npm run clean && tsc",
|
|
44
45
|
"clean": "flh rm -f dist",
|
|
45
|
-
"version": "standard-version"
|
|
46
|
+
"version": "standard-version",
|
|
47
|
+
"release": "npm run build"
|
|
46
48
|
},
|
|
47
49
|
"dependencies": {
|
|
48
|
-
"@lzwme/fe-utils": "^1.
|
|
49
|
-
"commander": "^
|
|
50
|
-
"console-log-colors": "^0.
|
|
51
|
-
"express": "^4.18.
|
|
52
|
-
"http-proxy-middleware": "^2.0.6"
|
|
50
|
+
"@lzwme/fe-utils": "^1.3.3",
|
|
51
|
+
"commander": "^10.0.0",
|
|
52
|
+
"console-log-colors": "^0.3.5",
|
|
53
|
+
"express": "^4.18.2",
|
|
54
|
+
"http-proxy-middleware": "^2.0.6",
|
|
55
|
+
"node-forge": "^1.3.1"
|
|
53
56
|
},
|
|
54
57
|
"devDependencies": {
|
|
55
|
-
"@lzwme/fed-lint-helper": "^2.0
|
|
56
|
-
"@types/express": "^4.17.
|
|
57
|
-
"@types/node": "^18.
|
|
58
|
-
"
|
|
58
|
+
"@lzwme/fed-lint-helper": "^2.2.0",
|
|
59
|
+
"@types/express": "^4.17.16",
|
|
60
|
+
"@types/node": "^18.11.18",
|
|
61
|
+
"@types/node-forge": "^1.3.1",
|
|
62
|
+
"husky": "^8.0.3",
|
|
59
63
|
"standard-version": "^9.5.0",
|
|
60
64
|
"ts-node": "^10.9.1",
|
|
61
|
-
"typescript": "^4.
|
|
65
|
+
"typescript": "^4.9.5"
|
|
62
66
|
}
|
|
63
67
|
}
|
package/ss.config.sample.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
/** @type {import('@lzwme/sserver').SSConfig} */
|
|
2
2
|
module.exports = {
|
|
3
|
-
port:
|
|
4
|
-
|
|
3
|
+
// port: 8888,
|
|
4
|
+
https: false,
|
|
5
|
+
sslCache: '',
|
|
6
|
+
rootDir: '.',
|
|
5
7
|
proxyConfig: [
|
|
6
8
|
// 内网代理企业微信机器人接口示例
|
|
7
9
|
{
|
|
@@ -15,4 +17,4 @@ module.exports = {
|
|
|
15
17
|
},
|
|
16
18
|
},
|
|
17
19
|
],
|
|
18
|
-
}
|
|
20
|
+
};
|