@oipage/cli 0.3.0-alpha.1 → 0.3.0-alpha.3

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/CHANGELOG CHANGED
@@ -23,11 +23,24 @@ v0.3.0:
23
23
  date:
24
24
  changes:
25
25
  - 修复bug
26
- 1、修复路径穿越漏洞(Path Traversal)
27
- 比如: printf 'GET /../../../../../Users/admin/.codex/auth.json HTTP/1.1\r\nHost: 127.0.0.1:8080\r\nConnection: close\r\n\r\n' | nc 127.0.0.1 8080
26
+ 1、修复服务器若干问题
27
+ * 路径穿越漏洞(Path Traversal)
28
+ 比如: printf 'GET /../../../../../Users/admin/.codex/auth.json HTTP/1.1\r\nHost: 127.0.0.1:8080\r\nConnection: close\r\n\r\n' | nc 127.0.0.1 8080
29
+ * 404 页面 XSS 漏洞
30
+ * 畸形URL导致客户端持续挂起等待问题
31
+ * 加固阻止 Nmap 等扫描器的服务探测
32
+ * 文件扩展名提取可能抛出 TypeError 问题
33
+ * 路径匹配添加更多兼容,防止意外错误
34
+ * 修复对文件夹判断未考虑符号链接指向的目录问题导致import语句解析出错问题
28
35
  2、修复错误读取导致服务器奔溃问题
36
+ 3、对于二进制文件,采用流式传输
29
37
  - 优化改造
30
38
  1、优化命令行相关文档优化,提高可读性
39
+ 2、优化服务器若干问题
40
+ * proxy中decodeURIComponent捕获错误,方便调试
41
+ * 打印访问IP,方便后续追踪攻击
31
42
  - 新增功能
32
43
  1、oipage-cli notebook
33
44
  快速笔记
45
+ 2、devServer
46
+ * 支持gzip
@@ -8,6 +8,18 @@ const encodeWsFrame = require('./encodeWsFrame');
8
8
  module.exports = function (port, name, version, isRun) {
9
9
  let sockets = [];
10
10
 
11
+ // 连接速率限制:每IP每分钟最多允许的连接数
12
+ const RATE_LIMIT = 20;
13
+ const RATE_WINDOW = 60000; // 1分钟
14
+ const connectionCount = {};
15
+
16
+ // 定期清理连接计数器
17
+ setInterval(() => {
18
+ for (let ip in connectionCount) {
19
+ delete connectionCount[ip];
20
+ }
21
+ }, RATE_WINDOW);
22
+
11
23
  let handler = {
12
24
  notifyBrowser: (msg) => {
13
25
  for (let socket of sockets) {
@@ -18,19 +30,30 @@ module.exports = function (port, name, version, isRun) {
18
30
 
19
31
  const server = net.createServer(socket => {
20
32
 
33
+ // 连接速率限制
34
+ const ip = socket.remoteAddress;
35
+ connectionCount[ip] = (connectionCount[ip] || 0) + 1;
36
+ if (connectionCount[ip] > RATE_LIMIT) {
37
+ socket.destroy();
38
+ return;
39
+ }
40
+
21
41
  // 错误
22
42
  socket.on('error', (error) => {
23
43
  console.log('Connection error:', error.message);
24
44
  });
25
45
 
26
- // 数据
27
- socket.on('data', buffer => {
28
- console.log('Connection data:' + (decodeWsFrame(buffer).payloadData?.toString() || "断开连接......"));
29
- });
30
-
31
46
  // 连接
32
47
  socket.once('data', buffer => {
33
48
 
49
+ // 协议过滤:只接受以 HTTP 方法开头的连接,拒绝扫描器探测
50
+ // 2026年8月9日 于南宁
51
+ const head = buffer.toString('ascii', 0, 20);
52
+ if (!/^(GET|POST|OPTIONS|HEAD|PUT|DELETE|PATCH) /i.test(head)) {
53
+ socket.destroy();
54
+ return;
55
+ }
56
+
34
57
  // 把请求头变成容易操作的json
35
58
  const headers = headersToJSON(buffer.toString());
36
59
 
@@ -65,7 +88,7 @@ module.exports = function (port, name, version, isRun) {
65
88
  // 否则就普通的,
66
89
  // 普通的由http服务器提供支持
67
90
  else {
68
- socket.end();
91
+ socket.destroy();
69
92
 
70
93
  }
71
94
  });
package/bin/help.js CHANGED
@@ -24,6 +24,8 @@ module.exports = function () {
24
24
  --proxy [转发前缀] [转发地址]
25
25
  (注意:转发前缀会被替换为空,相当于设置了 pathRewrite: { '^/myapi': '' })
26
26
  (eg: oipage-cli serve --open --proxy /myapi http://localhost:20000/myapi)
27
+ --gzip [true|false]
28
+ 是否开启gzip(默认true表示开启)
27
29
 
28
30
  【2】oipage-cli notebook 快速笔记
29
31
 
package/bin/proxy.js CHANGED
@@ -21,10 +21,17 @@ module.exports = function (args, proxy) {
21
21
  };
22
22
 
23
23
  let headers = request.headers;
24
- let url = decodeURIComponent(request.url);
24
+ let url
25
+
26
+ try {
27
+ url = decodeURIComponent(request.url);
28
+ } catch (e) {
29
+ console.log("decodeURIComponent error: ", e);
30
+ throw e;
31
+ }
25
32
 
26
33
  if (proxyItem.pathRewrite) {
27
- for (pathRewrite_key in proxyItem.pathRewrite) {
34
+ for (let pathRewrite_key in proxyItem.pathRewrite) {
28
35
  url = url.replace(new RegExp(pathRewrite_key), proxyItem.pathRewrite[pathRewrite_key]);
29
36
  }
30
37
  }
package/bin/run CHANGED
@@ -24,6 +24,7 @@ if (process.argv[2] === "serve") {
24
24
  baseUrl: "./",
25
25
  open: false,
26
26
  cache: true,
27
+ gzip: true,
27
28
  proxy: {},
28
29
  intercept: [],
29
30
  404: null,
@@ -53,11 +54,14 @@ if (process.argv[2] === "serve") {
53
54
  }
54
55
  }
55
56
 
56
- if (argvObj["--port"]) config.devServer.port = argvObj["--port"][0];
57
- if (argvObj["--baseUrl"]) config.devServer.baseUrl = argvObj["--baseUrl"][0];
58
- if (argvObj["--cache"]) config.devServer.cache = argvObj["--cache"][0] === "true";
59
- if (argvObj["--open"]) config.devServer.open = argvObj["--open"][0] || true;
60
- if (argvObj["--website"]) config.devServer.website = argvObj["--website"][0] === "true";
57
+ let resolveBoolean = input => input[0] !== "false";
58
+
59
+ if (argvObj["--port"]) config.devServer.port = resolveBoolean(argvObj["--port"]);
60
+ if (argvObj["--baseUrl"]) config.devServer.baseUrl = resolveBoolean(argvObj["--baseUrl"]);
61
+ if (argvObj["--cache"]) config.devServer.cache = resolveBoolean(argvObj["--cache"]);
62
+ if (argvObj["--gzip"]) config.devServer.gzip = resolveBoolean(argvObj["--gzip"]);
63
+ if (argvObj["--open"]) config.devServer.open = resolveBoolean(argvObj["--open"]);
64
+ if (argvObj["--website"]) config.devServer.website = resolveBoolean(argvObj["--website"]);
61
65
 
62
66
  require("./serve.js")(config);
63
67
  }
package/bin/serve.js CHANGED
@@ -1,6 +1,7 @@
1
- const { join } = require("path");
1
+ const { join, resolve, sep } = require("path");
2
2
  const { existsSync, lstatSync, statSync, createReadStream } = require("fs");
3
3
  const { createServer } = require('http');
4
+ const { gzipSync, createGzip } = require("zlib");
4
5
  const packageValue = require("../package.json");
5
6
  const network = require("./tools/network.js");
6
7
  const mineTypes = require("./data/mineTypes.json");
@@ -9,11 +10,51 @@ const openBrowser = require("./tools/openBrowser.js");
9
10
  const { doIntercept } = require("./intercept.js");
10
11
  const proxy = require("./proxy.js");
11
12
  const resolve404_default = require("./tools/resolve404.js");
13
+ const isBinary = require("./tools/isBinary.js");
12
14
  const websiteIntercept = require("./website-plugins/intercept/index.js");
13
15
  const websiteLoader = require("./website-plugins/loader/index.js");
14
16
 
15
17
  const WebSocketClass = require("./WebSocket/index.js");
16
18
 
19
+ // 可压缩的 MIME 类型集合(文本类资源,压缩收益大)
20
+ const compressibleTypes = new Set([
21
+ "text/html", "text/css", "text/plain", "text/xml", "text/mathml",
22
+ "text/vnd.sun.j2me.app-descriptor", "text/vnd.wap.wml", "text/x-component",
23
+ "application/javascript", "application/json", "application/xml",
24
+ "application/xhtml+xml", "application/atom+xml", "application/rss+xml",
25
+ "application/xspf+xml", "application/x-tcl", "application/x-perl",
26
+ "image/svg+xml"
27
+ ]);
28
+
29
+ // 需要设置 charset 的 MIME 类型前缀/精确匹配集合
30
+ // 文本类资源需要 charset 告知浏览器字符编码,二进制资源不需要
31
+ const charsetPrefixes = ["text/"];
32
+ const charsetTypes = new Set([
33
+ "application/javascript", "application/json", "application/xml",
34
+ "application/xhtml+xml", "application/atom+xml", "application/rss+xml",
35
+ "application/xspf+xml", "application/x-tcl", "application/x-perl",
36
+ "application/rtf", "application/postscript",
37
+ "application/vnd.google-earth.kml+xml", "application/x-javascript",
38
+ "image/svg+xml"
39
+ ]);
40
+
41
+ /**
42
+ * 根据 MIME 类型构建 Content-Type 值
43
+ * 文本类型追加 charset=utf-8,二进制类型不追加
44
+ * @param {string} mimeType MIME 类型
45
+ * @returns {string} 完整的 Content-Type 值
46
+ */
47
+ function buildContentType(mimeType) {
48
+ if (!mimeType) return "text/plain;charset=utf-8";
49
+ if (charsetPrefixes.some(prefix => mimeType.startsWith(prefix))) {
50
+ return mimeType + ";charset=utf-8";
51
+ }
52
+ if (charsetTypes.has(mimeType)) {
53
+ return mimeType + ";charset=utf-8";
54
+ }
55
+ return mimeType;
56
+ }
57
+
17
58
  // 开发服务器
18
59
  module.exports = function (config) {
19
60
  let startTime = new Date().valueOf();
@@ -21,8 +62,9 @@ module.exports = function (config) {
21
62
  const resolve404 = config.devServer["404"] || resolve404_default;
22
63
  const cache = "cache" in config.devServer ? config.devServer.cache : true;
23
64
  const website = "website" in config.devServer ? config.devServer.website : true;
65
+ const gzip = "gzip" in config.devServer ? config.devServer.gzip : false;
24
66
  const port = +config.devServer.port; // 端口号
25
- const basePath = (/^\./.test(config.devServer.baseUrl)) ? join(process.cwd(), config.devServer.baseUrl) : config.devServer.baseUrl; // 服务器根路径
67
+ const basePath = resolve((/^\./.test(config.devServer.baseUrl)) ? join(process.cwd(), config.devServer.baseUrl) : config.devServer.baseUrl); // 服务器根路径
26
68
 
27
69
  const name = (config.name || "OIPage") + "-http-server";
28
70
  const version = config.version || packageValue.version;
@@ -30,6 +72,7 @@ module.exports = function (config) {
30
72
  const wsHandler = WebSocketClass(port + 1, (config.name || "OIPage") + "-ws-server", version, website);
31
73
 
32
74
  // 全局错误捕获,防止服务器因任何未捕获的错误而停机
75
+ // 2026年8月8日 于南宁
33
76
  process.on('uncaughtException', function (err) {
34
77
  console.log("<i> \x1b[1m\x1b[31m[" + name + "] uncaughtException: " + err.message + "\x1b[0m " + new Date().toLocaleString());
35
78
  console.log(err.stack);
@@ -40,7 +83,29 @@ module.exports = function (config) {
40
83
 
41
84
  let Server = createServer(function (request, response) {
42
85
  let headers = request.headers;
43
- let url = decodeURIComponent(request.url);
86
+
87
+ const rawIp = (request.socket.remoteAddress || '').replace(/^::ffff:/, "").replace(/^::1/, "127.0.0.1");
88
+
89
+ let url;
90
+ try {
91
+
92
+ // 上游网关二次解码的架构层面风险(%252e 双重编码),导致文件路径被二次解码,导致路径穿越漏洞
93
+ // 后续处理中,对url不要再decodeURIComponent进行解码,防止路径穿越漏洞
94
+ // 2026年8月9日 于南宁
95
+ url = decodeURIComponent(request.url);
96
+ } catch (e) {
97
+
98
+ // 如果 URL 包含无效的百分号编码(如 %ZZ),decodeURIComponent 会抛出 URIError
99
+ // 虽然被 uncaughtException 捕获,但会导致当前请求处理中断且无响应返回,客户端会挂起等待
100
+ // 2026年8月9日 于南宁
101
+ response.writeHead(400, {
102
+ 'Content-Type': buildContentType('text/plain'),
103
+ 'Access-Control-Allow-Origin': '*',
104
+ 'Server': 'Powered by ' + name + '@' + version
105
+ });
106
+ response.end('Bad Request');
107
+ return;
108
+ }
44
109
 
45
110
  let urlArray = url.split("?");
46
111
  url = urlArray[0];
@@ -55,6 +120,8 @@ module.exports = function (config) {
55
120
  filePath = join(basePath, url == "/" ? "index.html" : url.replace(/^\//, ""));
56
121
  }
57
122
 
123
+ filePath = resolve(filePath);
124
+
58
125
  let proxyIntercept = proxy({
59
126
  name,
60
127
  version
@@ -66,7 +133,7 @@ module.exports = function (config) {
66
133
 
67
134
  // 请求拦截
68
135
  if (doIntercept(url.replace(/^\/@website/, "").replace(/^\/@modules\//, ""), isWebsite ? websiteIntercept : config.devServer.intercept, request, response, wsHandler)) {
69
- console.log("<i> \x1b[1m\x1b[32m[" + name + "] intercept: " + url + '\x1b[0m ' + new Date().toLocaleString());
136
+ console.log("<i> \x1b[1m\x1b[32m[" + name + "] intercept: " + url + '\x1b[0m ' + new Date().toLocaleString() + " " + rawIp);
70
137
  } else {
71
138
 
72
139
  // 对应前置都没有找到的,默认去当前命令行找
@@ -77,15 +144,17 @@ module.exports = function (config) {
77
144
 
78
145
  // 禁止访问沙箱外文件,路径穿越拦截
79
146
  // 2026年8月8日 于南宁
80
- if (!filePath.startsWith(basePath)) {
147
+ if ((!(filePath.startsWith(basePath + sep) || filePath === basePath) &&
148
+ !(filePath.startsWith(process.cwd() + sep) || filePath === process.cwd())
149
+ ) || filePath.includes('\0')) {
81
150
  response.writeHead(403, {
82
- 'Content-Type': "text/plain;charset=utf-8",
151
+ 'Content-Type': buildContentType("text/plain"),
83
152
  'Access-Control-Allow-Origin': '*',
84
153
  'Server': 'Powered by ' + name + '@' + version
85
154
  });
86
155
  response.write("Path Traversal attack");
87
156
  response.end();
88
- console.log("<i> \x1b[1m\x1b[31m[" + name + "] Path Traversal attack, path: " + url + "\x1b[0m " + new Date().toLocaleString());
157
+ console.log("<i> \x1b[1m\x1b[31m[" + name + "] Path Traversal attack, path: " + url + "\x1b[0m " + new Date().toLocaleString() + " " + rawIp);
89
158
  return;
90
159
  }
91
160
 
@@ -96,14 +165,14 @@ module.exports = function (config) {
96
165
  // 2025年12月5日 于南京
97
166
  let isXHR = headers["sec-fetch-dest"] === "empty";
98
167
 
99
- let dotName = /\./.test(filePath) ? filePath.match(/\.([^.]+)$/)[1] : "";
168
+ let dotName = (filePath.match(/\.([^.]+)$/) || [])[1] || "";
100
169
  let fileType = mineTypes[dotName]; // 文件类型
101
170
  let fileInfo = statSync(filePath);
102
171
 
103
172
  let fileModifiedTime = new Date(fileInfo.mtime).toGMTString();
104
173
 
105
174
  let responseHeader = {
106
- 'Content-Type': (fileType || "text/plain") + ";charset=utf-8",
175
+ 'Content-Type': buildContentType(fileType || "text/plain"),
107
176
  'Access-Control-Allow-Origin': '*',
108
177
  'Server': 'Powered by ' + name + '@' + version,
109
178
  'Cache-Control': 'no-cache',
@@ -113,7 +182,11 @@ module.exports = function (config) {
113
182
  'Last-Modified': fileModifiedTime,
114
183
 
115
184
  // 与if-none-match配合使用,做缓存验证
116
- // 'ETag': basePath + "-" + new Date(fileInfo.mtime).toString()
185
+ // ETag 包含 gzip 标志,确保 gzip 配置变化时缓存正确失效
186
+ 'ETag': '"' + fileInfo.mtime.getTime() + (gzip ? '-gz' : '') + '"',
187
+
188
+ // 告知代理/缓存:响应内容会根据 Accept-Encoding 不同而变化
189
+ 'Vary': 'Accept-Encoding'
117
190
  };
118
191
 
119
192
  if (cache && headers["if-modified-since"]) {
@@ -125,10 +198,16 @@ module.exports = function (config) {
125
198
  // 2、作为开发服务器,可能同一个url地址对应的文件不同,被误判为未修改
126
199
  // 2025年12月29日 于南京
127
200
  // if (lastModified <= ifModifiedSince) {}
128
- if (lastModified === ifModifiedSince) {
129
- response.writeHead('304', responseHeader);
201
+
202
+ // 同时检查 ETag(If-None-Match),确保 gzip 配置变化时不会错误返回 304
203
+ // 比如:gzip 从关闭改为开启,响应内容从原始变为压缩,ETag 不同,必须重新传输
204
+ // 2026年08月15日 于南宁
205
+ let etagMatch = !headers["if-none-match"] || headers["if-none-match"] === responseHeader['ETag'];
206
+
207
+ if (lastModified === ifModifiedSince && etagMatch) {
208
+ response.writeHead(304, responseHeader);
130
209
  response.end();
131
- console.log("<i> \x1b[1m\x1b[32m[" + name + "] Cache File: " + url + "\x1b[0m " + new Date().toLocaleString() + "\x1b[33m\x1b[1m 304" + (isXHR ? " " + request.method : "") + "\x1b[0m");
210
+ console.log("<i> \x1b[1m\x1b[32m[" + name + "] Cache File: " + url + "\x1b[0m " + new Date().toLocaleString() + " \x1b[33m\x1b[1m304\x1b[0m" + (isXHR ? " \x1b[33m\x1b[1m" + request.method + "\x1b[0m" : "") + " " + rawIp);
132
211
  return;
133
212
  }
134
213
  }
@@ -136,8 +215,13 @@ module.exports = function (config) {
136
215
  let sendType = "";
137
216
  let entry = headers.accept !== "*/*";
138
217
 
139
- // 如果文件小于10M,认为不大,直接读取
140
- if (fileInfo.size < 10 * 1024 * 1024) {
218
+ // 判断是否需要 gzip 压缩:配置开启 && 客户端支持 && 文件类型可压缩
219
+ let acceptEncoding = headers["accept-encoding"] || "";
220
+ let shouldGzip = gzip && /\bgzip\b/.test(acceptEncoding) && compressibleTypes.has(fileType);
221
+
222
+ // 如果文件小于1M且不是二进制,认为不大,直接读取
223
+ // 如果是二进制文件,即使小于10M也使用流(避免不必要的加载器处理和import解析)
224
+ if (fileInfo.size < 10 * 1024 * 1024 && !isBinary(filePath)) {
141
225
  let { source, resolveImport } = resolveImportFactory(basePath, filePath, entry, isWebsite ? websiteIntercept : config.devServer.intercept, urlArray[1] === "download", isWebsite)
142
226
 
143
227
  // 只处理非下载文件
@@ -154,7 +238,7 @@ module.exports = function (config) {
154
238
  entry, // 是否是浏览器地址栏直接访问
155
239
  setFileType(_fileType) { // 设置文件类型
156
240
  fileType = _fileType;
157
- responseHeader['Content-Type'] = _fileType + ";charset=utf-8";
241
+ responseHeader['Content-Type'] = buildContentType(_fileType);
158
242
  }
159
243
  }, source);
160
244
  break;
@@ -164,8 +248,16 @@ module.exports = function (config) {
164
248
  }
165
249
 
166
250
  sendType = "Read";
167
- response.writeHead('200', responseHeader);
168
- response.write(isXHR ? source : resolveImport(source, fileType !== "application/javascript"));
251
+ let body = isXHR ? source : resolveImport(source, fileType !== "application/javascript");
252
+
253
+ // gzip 压缩后发送(需要重新判断 fileType,因为 loader 可能修改了它)
254
+ if (shouldGzip && compressibleTypes.has(fileType)) {
255
+ responseHeader['Content-Encoding'] = 'gzip';
256
+ body = gzipSync(Buffer.from(body));
257
+ }
258
+
259
+ response.writeHead(200, responseHeader);
260
+ response.write(body);
169
261
  response.end();
170
262
  }
171
263
 
@@ -173,23 +265,30 @@ module.exports = function (config) {
173
265
  else {
174
266
  sendType = "Stream";
175
267
 
176
- responseHeader['Content-Length'] = fileInfo.size
268
+ if (shouldGzip) {
269
+ // gzip 流式压缩:文件大小变化,不能设置 Content-Length
270
+ responseHeader['Content-Encoding'] = 'gzip';
271
+ response.writeHead(200, responseHeader);
272
+ createReadStream(filePath).pipe(createGzip()).pipe(response);
273
+ } else {
274
+ responseHeader['Content-Length'] = fileInfo.size
177
275
 
178
- response.writeHead('200', responseHeader);
179
- createReadStream(filePath).pipe(response);
276
+ response.writeHead(200, responseHeader);
277
+ createReadStream(filePath).pipe(response);
278
+ }
180
279
  }
181
280
 
182
- console.log("<i> \x1b[1m\x1b[32m[" + name + "] " + sendType + " File: " + url + '\x1b[0m ' + new Date().toLocaleString() + "\x1b[33m\x1b[1m" + (isXHR ? " " + request.method : "") + "\x1b[0m");
281
+ console.log("<i> \x1b[1m\x1b[32m[" + name + "] " + sendType + " File: " + url + '\x1b[0m ' + new Date().toLocaleString() + (shouldGzip ? " \x1b[33m\x1b[1mgzip\x1b[0m" : "") + (isXHR ? " \x1b[33m\x1b[1m" + request.method + "\x1b[0m" : "") + " " + rawIp);
183
282
  }
184
283
 
185
284
  // 否则就是404
186
285
  else {
187
286
  response.writeHead(404, {
188
- 'Content-Type': "text/html;charset=utf-8",
287
+ 'Content-Type': buildContentType("text/html"),
189
288
  'Access-Control-Allow-Origin': '*',
190
289
  'Server': 'Powered by ' + name + '@' + version
191
290
  });
192
- response.write(resolve404(filePath, url, website, config.name || "OIPage"));
291
+ response.write(resolve404(filePath, url, website, config.name || "OIPage", rawIp));
193
292
  response.end();
194
293
  }
195
294
  }
@@ -215,5 +314,6 @@ module.exports = function (config) {
215
314
  }
216
315
 
217
316
  if (!cache) console.log('<i> \x1b[1m\x1b[32m[' + name + '] Cancel 304 Cache!\x1b[0m');
317
+ if (gzip) console.log('<i> \x1b[1m\x1b[32m[' + name + '] Gzip Compression: \x1b[36menabled\x1b[0m');
218
318
  console.log('\n' + (config.name || "OIPage") + ' ' + version + ' compiled \x1b[1m\x1b[32msuccessfully\x1b[0m in ' + (new Date().valueOf() - startTime) + ' ms\n');
219
319
  };
@@ -0,0 +1,83 @@
1
+ const { openSync, readSync, closeSync } = require("fs");
2
+ const mineTypes = require("../data/mineTypes.json");
3
+
4
+ // 读取文件头部用于判断的字节数
5
+ const CHECK_BYTES = 4096;
6
+
7
+ // 文本类型白名单(即使 Content-Type 是 application/* 也视为文本)
8
+ // 仅在文件内容读取失败时作为回退判断依据
9
+ const TEXT_TYPES = new Set([
10
+ "application/javascript",
11
+ "application/json",
12
+ "application/xml",
13
+ "application/xhtml+xml",
14
+ "application/rss+xml",
15
+ "application/atom+xml",
16
+ "image/svg+xml",
17
+ "application/xspf+xml",
18
+ "application/vnd.google-earth.kml+xml"
19
+ ]);
20
+
21
+ /**
22
+ * 通过后缀名回退判断(仅在文件内容读取失败时使用)
23
+ * @param {string} filepath 文件路径
24
+ * @returns {boolean} 是否为二进制文件
25
+ */
26
+ function isBinaryByExtension(filepath) {
27
+ const dotName = (filepath.match(/\.([^.]+)$/) || [])[1] || "";
28
+ const fileType = mineTypes[dotName];
29
+
30
+ if (!fileType) {
31
+ // 未知类型默认视为二进制
32
+ return true;
33
+ }
34
+
35
+ if (fileType.startsWith("text/")) {
36
+ return false;
37
+ }
38
+
39
+ if (TEXT_TYPES.has(fileType)) {
40
+ return false;
41
+ }
42
+
43
+ return true;
44
+ }
45
+
46
+ /**
47
+ * 判断文件是否是二进制文件
48
+ * 通过读取文件前若干字节,检查是否包含 NULL 字节(\0)来判断
49
+ * 文本文件(UTF-8/ASCII)通常不包含 NULL 字节,而二进制文件通常包含
50
+ * 如果文件读取失败,回退到后缀名判断
51
+ * @param {string} filepath 文件路径
52
+ * @returns {boolean} 是否为二进制文件
53
+ */
54
+ module.exports = function isBinary(filepath) {
55
+ let fd;
56
+ try {
57
+ fd = openSync(filepath, 'r');
58
+ const buffer = Buffer.alloc(CHECK_BYTES);
59
+ const bytesRead = readSync(fd, buffer, 0, CHECK_BYTES, 0);
60
+
61
+ // 检查是否包含 NULL 字节
62
+ // NULL 字节是二进制文件的可靠标志,文本文件(UTF-8/ASCII)不会包含
63
+ for (let i = 0; i < bytesRead; i++) {
64
+ if (buffer[i] === 0) {
65
+ return true;
66
+ }
67
+ }
68
+
69
+ return false;
70
+ } catch (e) {
71
+ // 文件读取失败时,回退到后缀名判断
72
+ console.log(e);
73
+ return isBinaryByExtension(filepath);
74
+ } finally {
75
+ if (fd !== undefined) {
76
+ try {
77
+ closeSync(fd);
78
+ } catch (e) {
79
+ // 关闭失败不影响判断结果
80
+ }
81
+ }
82
+ }
83
+ };
@@ -2,25 +2,34 @@ const { exec } = require('child_process');
2
2
  const os = require('os');
3
3
 
4
4
  module.exports = function (url) {
5
- const platform = os.platform();
6
- let command;
7
5
 
8
- switch (platform) {
9
- case 'win32': // Windows
10
- command = `start ${url}`;
11
- break;
12
- case 'darwin': // macOS
13
- command = `open ${url}`;
14
- break;
15
- default: // Linux及其他
16
- command = `xdg-open ${url}`;
17
- }
6
+ // 防止命令注入
7
+ // 对 URL 进行严格校验(仅允许 http:// 或 https:// 开头,拒绝特殊字符)
8
+ // 2026年8月9日 于南宁
9
+ if (/^http:\/\//.test(url) || /^https:\/\//.test(url)) {
10
+
11
+ const platform = os.platform();
12
+ let command;
18
13
 
19
- exec(command, (error) => {
20
- if (error) {
21
- console.error(`无法打开浏览器: ${error}`);
22
- } else {
23
- // todo
14
+ switch (platform) {
15
+ case 'win32': // Windows
16
+ command = `start ${url}`;
17
+ break;
18
+ case 'darwin': // macOS
19
+ command = `open ${url}`;
20
+ break;
21
+ default: // Linux及其他
22
+ command = `xdg-open ${url}`;
24
23
  }
25
- });
24
+
25
+ exec(command, (error) => {
26
+ if (error) {
27
+ console.error(`无法打开浏览器: ${error}`);
28
+ } else {
29
+ // todo
30
+ }
31
+ });
32
+ } else {
33
+ console.error('请输入正确的url');
34
+ }
26
35
  }
@@ -3,6 +3,21 @@ const { join } = require("path");
3
3
  const { formatByte, formatTime } = require("./format");
4
4
  const mineTypes = require("../data/mineTypes.json");
5
5
 
6
+ // HTML 实体转义,防止 XSS
7
+ function escapeHtml(str) {
8
+ return String(str)
9
+ .replace(/&/g, "&amp;")
10
+ .replace(/</g, "&lt;")
11
+ .replace(/>/g, "&gt;")
12
+ .replace(/"/g, "&quot;")
13
+ .replace(/'/g, "&#39;");
14
+ }
15
+
16
+ // URL 路径编码,防止 href 属性注入
17
+ function encodePath(str) {
18
+ return encodeURIComponent(str);
19
+ }
20
+
6
21
  const img_folder = "data:image/png;base64," + readFileSync(join(__dirname, "../images/folder.png")).toString('base64');
7
22
  const img_file = "data:image/png;base64," + readFileSync(join(__dirname, "../images/file.png")).toString('base64');
8
23
 
@@ -12,15 +27,15 @@ const template_404 = readFileSync(join(__dirname, "../template/404.html"), {
12
27
  .replace("${img_folder}", img_folder)
13
28
  .replace("${img_file}", img_file);
14
29
 
15
- module.exports = function (filePath, url, website, name) {
30
+ module.exports = function (filePath, url, website, name, rawIp) {
16
31
 
17
32
  let subItems = [];
18
33
 
19
34
  try {
20
35
  subItems = readdirSync(filePath);
21
- console.log("<i> \x1b[1m\x1b[32m[" + name + "-http-server] Read Folder: " + url + '\x1b[0m ' + new Date().toLocaleString());
36
+ console.log("<i> \x1b[1m\x1b[32m[" + name + "-http-server] Read Folder: " + url + '\x1b[0m ' + new Date().toLocaleString() + " " + rawIp);
22
37
  } catch (e) {
23
- console.log("<i> \x1b[1m\x1b[32m[" + name + "-http-server] Read " + (/\/$/.test(url) ? "Folder" : "File") + ": \x1b[35m" + url + ' 404 Not Found\x1b[0m ' + new Date().toLocaleString());
38
+ console.log("<i> \x1b[1m\x1b[32m[" + name + "-http-server] Read " + (/\/$/.test(url) ? "Folder" : "File") + ": \x1b[35m" + url + ' 404 Not Found\x1b[0m ' + new Date().toLocaleString() + " " + rawIp);
24
39
  try {
25
40
  if (!/\/$/.test(url) || url === "/") {
26
41
  filePath = join(filePath, "../");
@@ -38,7 +53,7 @@ module.exports = function (filePath, url, website, name) {
38
53
  if (isDirectory) {
39
54
  template += `<tr class="folder">
40
55
  <th class="name">
41
- <a href='./${subItems[i]}/'>${subItems[i]}</a>
56
+ <a href='./${encodePath(subItems[i])}/'>${escapeHtml(subItems[i])}</a>
42
57
  </th>
43
58
  <th>
44
59
  ${formatTime(statObj.mtime)}
@@ -50,18 +65,18 @@ module.exports = function (filePath, url, website, name) {
50
65
  -
51
66
  </th>
52
67
  <th>
53
- <a href='./${subItems[i]}/' class="btn">打开</a>
68
+ <a href='./${encodePath(subItems[i])}/' class="btn">打开</a>
54
69
  </th>
55
70
  </tr>`;
56
71
  }
57
72
 
58
73
  // 文件
59
74
  else {
60
- let dotName = /\./.test(subItems[i]) ? subItems[i].match(/\.([^.]+)$/)[1] : "";
75
+ let dotName = (subItems[i].match(/\.([^.]+)$/) || [])[1] || "";
61
76
 
62
77
  template += `<tr class="file">
63
78
  <th class="name">
64
- <a href='./${subItems[i]}'>${subItems[i]}</a>
79
+ <a href='./${encodePath(subItems[i])}'>${escapeHtml(subItems[i])}</a>
65
80
  </th>
66
81
  <th>
67
82
  ${formatTime(statObj.mtime)}
@@ -73,12 +88,12 @@ module.exports = function (filePath, url, website, name) {
73
88
  ${formatByte(statObj.size)}
74
89
  </th>
75
90
  <th>
76
- <a href='./${subItems[i]}' class="btn">访问</a>
77
- <a href='./${subItems[i]}?download' class="btn" download='${subItems[i]}'>下载</a>
91
+ <a href='./${encodePath(subItems[i])}' class="btn">访问</a>
92
+ <a href='./${encodePath(subItems[i])}?download' class="btn" download='${escapeHtml(subItems[i])}'>下载</a>
78
93
  </th>
79
94
  </tr>`;
80
95
  }
81
96
  }
82
97
 
83
- return template_404.replace("${website}", website ? '<a class="website-link" href="/@website/index.html">打开应用市场</a>' : '').replace("${current}", filePath).replace("${template}", template);
98
+ return template_404.replace("${website}", website ? '<a class="website-link" href="/@website/index.html">打开应用市场</a>' : '').replace("${current}", escapeHtml(filePath)).replace("${template}", template);
84
99
  };
@@ -1,11 +1,11 @@
1
- const { readFileSync, existsSync, lstatSync } = require("fs");
1
+ const { readFileSync, existsSync, statSync } = require("fs");
2
2
  const { join } = require("path");
3
3
  const { testIntercept } = require("../intercept.js");
4
4
 
5
5
  module.exports = function (basePath, filePath, entry, intercept, isDownload, isWebsite) {
6
6
  basePath = join(basePath, "./");
7
7
 
8
- if (lstatSync(filePath).isDirectory()) { return { source: "", resolveImport: content => content }; }
8
+ if (statSync(filePath).isDirectory()) { return { source: "", resolveImport: content => content }; }
9
9
  let source = readFileSync(filePath);
10
10
  let resolveImport = content => content;
11
11
 
@@ -26,7 +26,7 @@ module.exports = function (basePath, filePath, entry, intercept, isDownload, isW
26
26
  let npmBundlePath = join(node_modulesRootPath, "./node_modules/", npmName);
27
27
 
28
28
  // 如果存在
29
- if (existsSync(npmBundlePath) && lstatSync(npmBundlePath).isDirectory()) {
29
+ if (existsSync(npmBundlePath) && statSync(npmBundlePath).isDirectory()) {
30
30
  let npmNameValue = npmName;
31
31
 
32
32
  // 对于类似 import VISLite from "vislite"
@@ -43,7 +43,10 @@ module.exports = function (basePath, filePath, entry, intercept, isDownload, isW
43
43
 
44
44
  // 如果命令行根目录是一个项目
45
45
  let packagePath = join(basePath, "./package.json");
46
- if (existsSync(packagePath) && !lstatSync(packagePath).isDirectory()) {
46
+
47
+ // statSync代替lstatSync,修复符号链接指向文件夹时无法正确判断文件
48
+ // 2026年09月10日 于南宁
49
+ if (existsSync(packagePath) && !statSync(packagePath).isDirectory()) {
47
50
  let bundlePackage = require(packagePath);
48
51
  if (!/\//.test(_importUrl)) {
49
52
  return "/" + bundlePackage.main;
package/docs/config.md CHANGED
@@ -18,6 +18,28 @@
18
18
 
19
19
  是否开启304缓存,默认true,表示开启。
20
20
 
21
+ ### gzip
22
+
23
+ > 始于 v0.3.0
24
+
25
+ 是否开启 gzip 压缩,默认true,表示开启。
26
+
27
+ 开启后,服务器会对支持 gzip 的客户端请求,自动压缩可压缩类型的文本资源(如 HTML、CSS、JS、JSON、SVG 等),可以有效减少传输体积,加快页面加载速度。
28
+
29
+ 使用 Node.js 内置 `zlib` 模块实现,无需安装额外依赖。可通过命令行参数控制:
30
+
31
+ ```shell
32
+ oipage-cli serve --gzip true
33
+ ```
34
+
35
+ 或在配置文件中开启:
36
+
37
+ ```js
38
+ devServer: {
39
+ gzip: true
40
+ }
41
+ ```
42
+
21
43
  ### port
22
44
 
23
45
  端口,默认8080。此外,可以在执行的时候,通过命令参数覆盖(下同):
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@oipage/cli",
3
- "version": "0.3.0-alpha.1",
3
+ "version": "0.3.0-alpha.3",
4
4
  "description": "开发快速助手,一个包含常用功能的命令行工具,旨在提升开发效率",
5
5
  "sideEffects": false,
6
6
  "main": "./src/index.js",
7
7
  "typings": "./types/index.d.ts",
8
8
  "scripts": {
9
- "serve": "node ./bin/run serve --config ./oipage.config.js --open -p 20000"
9
+ "serve": "node ./bin/run serve --config ./oipage.config.js"
10
10
  },
11
11
  "bin": {
12
12
  "oipage-cli": "bin/run"
package/src/index.js CHANGED
@@ -8,6 +8,7 @@ exports.serve = function (config) {
8
8
  baseUrl: "./",
9
9
  open: false,
10
10
  cache: true,
11
+ gzip: true,
11
12
  proxy: {},
12
13
  intercept: [],
13
14
  404: null,
package/types/serve.d.ts CHANGED
@@ -23,6 +23,13 @@ interface DevServerType {
23
23
  */
24
24
  cache: boolean
25
25
 
26
+ /**
27
+ * 是否开启 gzip 压缩,默认不开启
28
+ *
29
+ * 开启后,对支持 gzip 的客户端请求,自动压缩可压缩类型的文本资源(如 HTML、CSS、JS、JSON、SVG 等)
30
+ */
31
+ gzip?: boolean
32
+
26
33
  /**
27
34
  * 是否开启应用市场,默认true表示开启
28
35
  */