@lzwme/sserver 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
@@ -9,27 +9,21 @@
9
9
  [![GitHub forks][forks-badge]][forks-url]
10
10
  [![GitHub stars][stars-badge]][stars-url]
11
11
 
12
- 一个基于 nodejs 的简易静态服务器,方便随时开发调试使用。
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
- yarn add -D @lzwme/sserver
27
- ```
28
-
29
- 也可以不安装,直接使用 `npx` 执行:
23
+ npm exec ss -- -h
30
24
 
31
- ```bash
32
- npx @lzwme/sserver -d ./dist
25
+ # 或者直接使用 `npx`
26
+ npx @lzwme/sserver -h
33
27
  ```
34
28
 
35
29
  ## 使用
@@ -37,49 +31,49 @@ npx @lzwme/sserver -d ./dist
37
31
  示例:
38
32
 
39
33
  ```bash
40
- # 已当前目录下的 dist 作为静态目录
41
- ssserver -d ./dist
42
- ```
43
-
44
- ### 帮助信息
45
-
46
- ```bash
47
- sserver -h
34
+ # 以当前目录下的 dist 作为静态根目录
35
+ ss -d ./dist
48
36
 
49
- Usage: sserver|ss [options]
37
+ # 启用 https
38
+ ss --https
50
39
 
51
- 一个基于 nodejs 的简易静态服务器,方便随时调试使用 [version@1.0.0]
40
+ # 启用 https,指定域名(默认为 localhost)
41
+ ss -H --host local.lzw.me
52
42
 
53
- Options:
54
- -v, --version output the version number
55
- -d, --dir [rootDir] 静态服务器的根目录路径
56
- -p, --port 端口号 (default: 8890)
57
- -o, --open 启动后是否打开静态服务器首页
58
- --debug 开启调试模式。 (default: false)
59
- -h, --help display help for command
43
+ # 启用 https,并保存默认生成的 ssl 证书
44
+ ss -H --ssl-cache ./cache
60
45
  ```
61
46
 
62
47
  ### 配置代理转发
63
48
 
64
- 支持通过配置文件 `ss.config.js` 指定代理转发信息。示例:
49
+ 支持通过配置文件 `ss.config.js` 指定代理转发等详细配置规则。
50
+
51
+ ```bash
52
+ # 在当前目录初始化一个 ss.config.js 配置文件
53
+ ss init
54
+ ```
55
+
56
+ 配置文件内容示例:
65
57
 
66
58
  ```js
67
59
  // ss.config.js
68
60
 
69
61
  /** @type {import('@lzwme/sserver').SSConfig} */
70
62
  module.exports = {
71
- port: 8890,
72
- baseDir: './dist',
63
+ port: 8888,
64
+ https: false,
65
+ sslCache: '',
66
+ rootDir: '.',
73
67
  // 代理转发配置
74
68
  proxyConfig: [
75
- // 代理企业微信机器人接口示例
69
+ // 内网代理企业微信机器人接口示例
76
70
  {
77
71
  api: '/proxy/cgi-bin/webhook/send',
78
72
  config: {
79
73
  target: 'https://qyapi.weixin.qq.com',
80
74
  changeOrigin: true,
81
75
  pathRewrite: {
82
- '^/proxy': '',
76
+ '^/proxy/cgi-bin': '/cgi-bin',
83
77
  },
84
78
  },
85
79
  },
@@ -92,10 +86,15 @@ module.exports = {
92
86
  本地二次开发:
93
87
 
94
88
  ```bash
95
- git clone https://github.com/lzwme/static-server
89
+ git clone https://github.com/lzwme/static-server.git
96
90
  pnpm install
97
- npm link
91
+ pnpm build
92
+
93
+ # dev
98
94
  pnpm dev
95
+
96
+ # global link
97
+ npm link
99
98
  ```
100
99
 
101
100
  或者 fork 本项目进行代码贡献。
package/dist/cli.js CHANGED
@@ -2,20 +2,53 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const commander_1 = require("commander");
4
4
  const console_log_colors_1 = require("console-log-colors");
5
+ const config_1 = require("./config");
6
+ const get_logger_1 = require("./get-logger");
5
7
  const static_server_1 = require("./static-server");
8
+ const node_path_1 = require("node:path");
9
+ const node_fs_1 = require("node:fs");
6
10
  const pkg = require('../package.json');
7
11
  commander_1.program
8
12
  .aliases(['ss'])
9
13
  .version(pkg.version, '-v, --version')
10
14
  .description(console_log_colors_1.color.yellow(pkg.description) + ` [version@${console_log_colors_1.color.cyanBright(pkg.version)}]`)
11
15
  // .option('-c, --config-path [filepath]', `配置文件 ${color.yellow(config.configPath)} 的路径`)
12
- .option('-d, --base-dir [baseDir]', '静态服务器的根目录路径')
16
+ .option('-d, --root-dir [dirpath]', '静态服务器的根目录路径')
13
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 证书缓存的路径。未指定则不缓存')
14
23
  .option('-o, --open', '启动后是否打开静态服务器首页')
24
+ .option('--log [dirpath]', `指定日志路径`)
15
25
  .option('--debug', `开启调试模式。`, false)
16
- .action(opts => {
17
- if (opts.debug)
18
- console.log(opts);
19
- (0, static_server_1.initServer)(opts);
26
+ .action(async (opts) => {
27
+ if (opts.cert)
28
+ opts.ssl.cert = opts.cert;
29
+ if (opts.key)
30
+ opts.ssl.key = opts.key;
31
+ if (opts.debug) {
32
+ get_logger_1.logger.updateOptions({ levelType: 'debug' });
33
+ get_logger_1.logger.debug(opts);
34
+ }
35
+ (0, config_1.getConfig)(false, opts).then(() => (0, static_server_1.initServer)());
36
+ });
37
+ commander_1.program
38
+ .command('init [destination]')
39
+ .description('初始化一个 ss.config.js 文件至指定的目录。默认为当前目录')
40
+ .action((destination = process.cwd()) => {
41
+ const confFile = (0, node_path_1.resolve)(destination, 'ss.config.js');
42
+ if ((0, node_fs_1.existsSync)(confFile)) {
43
+ get_logger_1.logger.warn('配置文件已存在,请确认:', console_log_colors_1.color.cyanBright(confFile));
44
+ return;
45
+ }
46
+ const tplFile = (0, node_path_1.resolve)(__dirname, '../ss.config.sample.js');
47
+ if (!(0, node_fs_1.existsSync)(tplFile)) {
48
+ get_logger_1.logger.error('未找到配置文件模板:', console_log_colors_1.color.red(tplFile));
49
+ return;
50
+ }
51
+ (0, node_fs_1.writeFileSync)(confFile, (0, node_fs_1.readFileSync)(tplFile));
52
+ get_logger_1.logger.info('已生成配置文件:', console_log_colors_1.color.greenBright(confFile));
20
53
  });
21
54
  commander_1.program.parse(process.argv);
package/dist/config.d.ts CHANGED
@@ -1,15 +1,27 @@
1
+ /// <reference types="node" />
1
2
  import { type Options } from 'http-proxy-middleware';
3
+ import { type ServerOptions } from 'node:https';
2
4
  export interface SSConfig {
3
5
  /** 根目录 */
4
- baseDir?: string;
6
+ rootDir?: string;
5
7
  /** 启动后是否打开首页 */
6
8
  open?: boolean;
7
- /** 监听端口号 */
9
+ /** 监听端口号。默认 80,开启 https 则为 443 */
8
10
  port?: number;
11
+ /** host 地址。默认为 127.0.0.1 */
12
+ host?: string;
9
13
  /** 代理转发配置 */
10
14
  proxyConfig?: {
11
15
  api: string;
12
16
  config: Options;
13
17
  }[];
18
+ /** 是否开启日志记录。默认为 false。若设置为 true 则默认为 ~/.sserver/log.log;若为字符串,则设置为日志路径 */
19
+ log?: boolean | string;
20
+ /** 是否为 https 模式 */
21
+ https?: boolean;
22
+ /** 指定 https 模式相关的 ssl 配置 */
23
+ ssl?: ServerOptions;
24
+ /** 自动生成 ssl 的缓存目录 */
25
+ sslCache?: string;
14
26
  }
15
- export declare function getConfig(useCache?: boolean, cfg?: SSConfig): SSConfig;
27
+ export declare function getConfig(useCache?: boolean, cfg?: SSConfig): Promise<SSConfig>;
package/dist/config.js CHANGED
@@ -1,22 +1,49 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getConfig = void 0;
4
- const path_1 = require("path");
5
- const child_process_1 = require("child_process");
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");
6
10
  const ssConfig = {
7
- baseDir: '.',
8
- open: true,
9
- port: 8890,
11
+ rootDir: '.',
12
+ open: false,
10
13
  proxyConfig: [],
14
+ log: false,
15
+ ssl: {
16
+ rejectUnauthorized: false,
17
+ requestCert: true,
18
+ },
11
19
  };
12
- function getConfig(useCache = true, cfg) {
20
+ async function getConfig(useCache = true, cfg) {
13
21
  if (ssConfig.port && useCache)
14
22
  return ssConfig;
15
- const cfgFile = (0, path_1.resolve)(process.cwd(), './ss.config.js');
16
- if ((0, child_process_1.execSync)(cfgFile))
17
- Object.assign(ssConfig, require(cfgFile));
23
+ const cfgFile = (0, node_path_1.resolve)(process.cwd(), './ss.config.js');
24
+ if ((0, node_fs_1.existsSync)(cfgFile))
25
+ (0, fe_utils_1.assign)(ssConfig, require(cfgFile));
18
26
  if (cfg)
19
- Object.assign(ssConfig, cfg);
27
+ (0, fe_utils_1.assign)(ssConfig, cfg);
28
+ if (ssConfig.log) {
29
+ get_logger_1.logger.setLogDir(typeof ssConfig.log === 'boolean' ? (0, node_path_1.resolve)((0, node_os_1.homedir)(), '.sserver/log.log') : ssConfig.log);
30
+ }
31
+ if (ssConfig.https && ssConfig.ssl) {
32
+ const { ssl } = ssConfig;
33
+ if (ssConfig.https && !ssl.cert) {
34
+ const info = await (0, get_cert_1.getCert)(ssConfig.host, ssConfig.sslCache || '');
35
+ ssl.key = Buffer.from(info.certKey);
36
+ ssl.cert = Buffer.from(info.certCrt);
37
+ ssl.ca = Buffer.from(info.caKey);
38
+ }
39
+ for (const key of ['key', 'cert', 'ca']) {
40
+ const val = ssl[key];
41
+ if (typeof val === 'string' && (0, node_fs_1.existsSync)(val))
42
+ ssl[key] = (0, node_fs_1.readFileSync)(val);
43
+ }
44
+ }
45
+ if (!ssConfig.port)
46
+ ssConfig.port = ssConfig.https ? 443 : 80;
20
47
  return ssConfig;
21
48
  }
22
49
  exports.getConfig = getConfig;
@@ -0,0 +1,2 @@
1
+ import { NLogger } from '@lzwme/fe-utils';
2
+ export declare const logger: NLogger;
@@ -0,0 +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();
package/dist/index.d.ts CHANGED
@@ -1 +1 @@
1
- export * from './static-server';
1
+ export { initServer } from './static-server';
package/dist/index.js CHANGED
@@ -1,20 +1,5 @@
1
1
  "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
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
2
  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)();
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,6 @@
1
+ export declare function getCert(host?: string, cacheDir?: string): Promise<{
2
+ caKey: string;
3
+ caCrt: string;
4
+ certKey: string;
5
+ certCrt: string;
6
+ }>;
@@ -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
1
  import { type Express } from 'express';
2
- export declare function proxyByExpress(app: Express): void;
2
+ export declare function proxyByExpress(app: Express): Promise<void>;
@@ -4,20 +4,21 @@ exports.proxyByExpress = void 0;
4
4
  const console_log_colors_1 = require("console-log-colors");
5
5
  const http_proxy_middleware_1 = require("http-proxy-middleware");
6
6
  const config_1 = require("../config");
7
- function proxyByExpress(app) {
8
- const { proxyConfig } = (0, config_1.getConfig)();
9
- if (!proxyConfig)
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)
10
11
  return;
11
12
  proxyConfig.forEach(({ api, config }) => {
12
13
  const onProxyReq = config.onProxyReq;
13
14
  config.onProxyReq = (pReq, req, res, options) => {
14
15
  const now = new Date();
15
- console.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}`));
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}`));
16
17
  if (onProxyReq)
17
18
  onProxyReq(pReq, req, res, options);
18
19
  };
19
20
  app.use(api, (0, http_proxy_middleware_1.createProxyMiddleware)(config));
20
- console.log(`Init proxy for ${console_log_colors_1.color.cyanBright(api)}`);
21
+ get_logger_1.logger.log(`Init proxy for ${console_log_colors_1.color.cyanBright(api)}`);
21
22
  });
22
23
  }
23
24
  exports.proxyByExpress = proxyByExpress;
@@ -1,5 +1,5 @@
1
1
  /// <reference types="node" />
2
- import net from 'net';
2
+ import net from 'node:net';
3
3
  export declare function socketProxy(config?: {
4
4
  localPort: number;
5
5
  remotePort: number;
@@ -4,7 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.socketProxy = void 0;
7
- const net_1 = __importDefault(require("net"));
7
+ const node_net_1 = __importDefault(require("node:net"));
8
8
  const console_log_colors_1 = require("console-log-colors");
9
9
  function socketProxy(config = {
10
10
  // 外网访问的端口
@@ -14,10 +14,10 @@ function socketProxy(config = {
14
14
  //代理转发的 IP 地址
15
15
  remoteHost: '127.0.0.1',
16
16
  }) {
17
- const server = net_1.default
17
+ const server = node_net_1.default
18
18
  .createServer(socket => {
19
19
  console_log_colors_1.log.green('proxy for address', socket.address());
20
- let to = net_1.default.createConnection({
20
+ let to = node_net_1.default.createConnection({
21
21
  host: config.remoteHost,
22
22
  port: config.remotePort,
23
23
  });
@@ -1,3 +1,3 @@
1
1
  import { type Express } from 'express';
2
2
  import { SSConfig } from './config';
3
- export declare function initServer(options?: SSConfig): Express;
3
+ export declare function initServer(options?: SSConfig): Promise<Express>;
@@ -1,10 +1,9 @@
1
1
  "use strict";
2
- /* eslint-disable no-console */
3
2
  /*
4
3
  * @Author: lzw
5
4
  * @Date: 2021-05-28 16:24:40
6
5
  * @LastEditors: lzw
7
- * @LastEditTime: 2022-07-01 17:43:51
6
+ * @LastEditTime: 2022-09-23 17:21:36
8
7
  * @Description:
9
8
  */
10
9
  var __importDefault = (this && this.__importDefault) || function (mod) {
@@ -12,27 +11,40 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
12
11
  };
13
12
  Object.defineProperty(exports, "__esModule", { value: true });
14
13
  exports.initServer = void 0;
14
+ const node_path_1 = require("node:path");
15
+ const node_https_1 = require("node:https");
15
16
  const console_log_colors_1 = require("console-log-colors");
16
17
  const express_1 = __importDefault(require("express"));
17
18
  const child_process_1 = require("child_process");
18
19
  const config_1 = require("./config");
19
20
  const express_proxy_1 = require("./proxy/express-proxy");
20
- function initServer(options) {
21
- options = (0, config_1.getConfig)(true, options);
21
+ const get_logger_1 = require("./get-logger");
22
+ async function initServer(options) {
23
+ options = await (0, config_1.getConfig)(!options, options);
22
24
  const app = (0, express_1.default)();
23
- const { baseDir = '.', port = 8890 } = options;
25
+ const { port = 8888, host = 'localhost' } = options;
26
+ const url = `http${options.https ? 's' : ''}://${host}:${port}`;
27
+ const rootDir = (0, node_path_1.resolve)(process.cwd(), typeof options.rootDir === 'string' ? options.rootDir : '.');
24
28
  // @see https://www.expressjs.com.cn/4x/api.html#express.static
25
- app.use(express_1.default.static(baseDir));
26
- (0, express_proxy_1.proxyByExpress)(app);
27
- app.listen(port, () => {
28
- console.log(console_log_colors_1.color.green(`Static server Listening Port:`), port);
29
- console.log(console_log_colors_1.color.green(`Static DIR:`), console_log_colors_1.color.cyanBright(baseDir));
30
- });
31
- if (options.open !== false) {
32
- const openPageCmd = `${process.platform === 'win32' ? `start` : `open`} http://localhost:${port}`;
29
+ app.use(express_1.default.static(rootDir, {
30
+ // extensions: ['html', 'htm'],
31
+ }));
32
+ await (0, express_proxy_1.proxyByExpress)(app);
33
+ const onListen = () => {
34
+ get_logger_1.logger.log(console_log_colors_1.color.green(`START : `.padStart(15, ' ')), console_log_colors_1.color.cyanBright(url));
35
+ get_logger_1.logger.log(console_log_colors_1.color.green(`ROOT DIR : `.padStart(15, ' ')), console_log_colors_1.color.cyanBright(rootDir));
36
+ };
37
+ if (options.https) {
38
+ (0, node_https_1.createServer)(options.ssl, app).listen(port, onListen);
39
+ }
40
+ else {
41
+ app.listen(port, onListen);
42
+ }
43
+ get_logger_1.logger.debug(options);
44
+ if (options.open) {
45
+ const openPageCmd = `${process.platform === 'win32' ? `start` : `open`} ${url}`;
33
46
  (0, child_process_1.execSync)(openPageCmd);
34
47
  }
35
48
  return app;
36
49
  }
37
50
  exports.initServer = initServer;
38
- ;
package/package.json CHANGED
@@ -1,14 +1,14 @@
1
1
  {
2
2
  "name": "@lzwme/sserver",
3
- "version": "0.0.3",
4
- "description": "一个基于 nodejs 的简易静态服务器,方便随时开发调试使用",
3
+ "version": "0.0.5",
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": "http://github.com/lzwme/static-server.git",
11
+ "repository": "https://github.com/lzwme/static-server.git",
12
12
  "author": {
13
13
  "name": "renxia",
14
14
  "email": "lzwy0820@qq.com",
@@ -17,7 +17,7 @@
17
17
  "license": "MIT",
18
18
  "private": false,
19
19
  "engines": {
20
- "node": ">=14"
20
+ "node": "^14.18.0 || >=16.15.0"
21
21
  },
22
22
  "packageManager": "pnpm@7.2.0",
23
23
  "keywords": [
@@ -30,30 +30,38 @@
30
30
  "access": "public",
31
31
  "registry": "https://registry.npmjs.com"
32
32
  },
33
- "files": ["dist", "ss.config.sample.js"],
33
+ "files": [
34
+ "dist",
35
+ "ss.config.sample.js"
36
+ ],
34
37
  "scripts": {
35
38
  "prepare": "husky install",
36
39
  "ss": "node bin/sserver.js",
37
- "start": "pnpm run stop && pm2 start dist/index.js --name sserver",
40
+ "start": "npm run stop && pm2 start dist/index.js --name sserver",
38
41
  "stop": "pm2 stop sserver",
39
- "dev": "ts-node -T src/index.ts",
42
+ "watch": "tsc -w",
43
+ "dev": "ts-node -T src/cli.ts",
40
44
  "build": "npm run clean && tsc",
41
45
  "clean": "flh rm -f dist",
42
- "version": "standard-version"
46
+ "version": "standard-version",
47
+ "release": "npm run build"
43
48
  },
44
49
  "dependencies": {
45
- "commander": "^9.4.0",
46
- "console-log-colors": "^0.2.3",
47
- "express": "^4.18.1",
48
- "http-proxy-middleware": "^2.0.6"
50
+ "@lzwme/fe-utils": "^1.3.2",
51
+ "commander": "^9.4.1",
52
+ "console-log-colors": "^0.3.3",
53
+ "express": "^4.18.2",
54
+ "http-proxy-middleware": "^2.0.6",
55
+ "node-forge": "^1.3.1"
49
56
  },
50
57
  "devDependencies": {
51
- "@lzwme/fed-lint-helper": "^2.0.1",
52
- "@types/express": "^4.17.14",
53
- "@types/node": "^18.7.18",
54
- "husky": "^8.0.1",
58
+ "@lzwme/fed-lint-helper": "^2.1.5",
59
+ "@types/express": "^4.17.15",
60
+ "@types/node": "^18.11.16",
61
+ "@types/node-forge": "^1.3.1",
62
+ "husky": "^8.0.2",
55
63
  "standard-version": "^9.5.0",
56
64
  "ts-node": "^10.9.1",
57
- "typescript": "^4.8.3"
65
+ "typescript": "^4.9.4"
58
66
  }
59
67
  }
@@ -1,18 +1,20 @@
1
1
  /** @type {import('@lzwme/sserver').SSConfig} */
2
2
  module.exports = {
3
- port: 8890,
4
- baseDir: '.',
3
+ // port: 8888,
4
+ https: false,
5
+ sslCache: '',
6
+ rootDir: '.',
5
7
  proxyConfig: [
6
- // 代理企业微信机器人接口示例
8
+ // 内网代理企业微信机器人接口示例
7
9
  {
8
10
  api: '/proxy/cgi-bin/webhook/send',
9
11
  config: {
10
12
  target: 'https://qyapi.weixin.qq.com',
11
13
  changeOrigin: true,
12
14
  pathRewrite: {
13
- '^/proxy': '',
15
+ '^/proxy/cgi-bin': '/cgi-bin',
14
16
  },
15
17
  },
16
18
  },
17
19
  ],
18
- }
20
+ };