env-plugin 0.5.9 → 0.6.1

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.
Files changed (44) hide show
  1. package/bin/index.js +8 -2
  2. package/dist/Container.js +18 -0
  3. package/dist/PostProxyServer.js +33 -6
  4. package/dist/client/assets/element-plus-aWS7wRSd.js.gz +0 -0
  5. package/dist/client/assets/index-CBMR4n-V.js.gz +0 -0
  6. package/dist/client/assets/index-a3AJbcK4.css.gz +0 -0
  7. package/dist/client/assets/vue-uvJWWccw.js.gz +0 -0
  8. package/dist/client/index.html +4 -4
  9. package/dist/controllers/DevServerController.js +27 -2
  10. package/dist/controllers/EnvController.js +61 -3
  11. package/dist/controllers/ImportExportController.js +43 -0
  12. package/dist/controllers/RequestLogController.js +33 -0
  13. package/dist/controllers/SystemSettingController.js +43 -0
  14. package/dist/index.js +5 -0
  15. package/dist/repositories/DevServerRepo.js +14 -3
  16. package/dist/repositories/EnvRepo.js +12 -5
  17. package/dist/repositories/PasswordRepo.js +5 -3
  18. package/dist/repositories/RouteRuleRepo.js +5 -3
  19. package/dist/repositories/SystemSettingRepo.js +42 -0
  20. package/dist/repositories/database.js +12 -0
  21. package/dist/routes/index.js +196 -26
  22. package/dist/service/DevServerService.js +26 -2
  23. package/dist/service/EnvService.js +101 -0
  24. package/dist/service/ImportExportService.js +333 -0
  25. package/dist/service/PasswordService.js +8 -7
  26. package/dist/service/PreProxyServer.js +105 -12
  27. package/dist/service/RequestLogService.js +69 -0
  28. package/dist/service/RouteRuleService.js +14 -14
  29. package/dist/service/SystemSettingService.js +90 -0
  30. package/dist/types/index.js +3 -0
  31. package/dist/types/shared/DevServerItem.js +14 -1
  32. package/dist/types/shared/EnvItem.js +19 -0
  33. package/dist/types/shared/ImportExport.js +55 -0
  34. package/dist/types/shared/RequestLog.js +28 -0
  35. package/dist/types/shared/SystemSetting.js +18 -0
  36. package/dist/utils/asyncHandler.js +12 -0
  37. package/dist/utils/resourceType.js +42 -0
  38. package/dist/utils/routeBuilder.js +19 -0
  39. package/package.json +18 -5
  40. package/templates/inject/envm-switcher.js +1418 -0
  41. package/dist/client/assets/element-plus-ketO_xfq.js.gz +0 -0
  42. package/dist/client/assets/index-C-jtdEqj.js.gz +0 -0
  43. package/dist/client/assets/index-Crqzm-vz.css.gz +0 -0
  44. package/dist/client/assets/vue-BGFZjnqd.js.gz +0 -0
@@ -0,0 +1,333 @@
1
+ import { v4 as uuidv4 } from "uuid";
2
+ import * as crypto from "crypto";
3
+ import { EXPORT_VERSION, } from "../types/index.js";
4
+ import { AppError } from "../utils/errors.js";
5
+ import { envLogger } from "../utils/logger.js";
6
+ const ENCRYPTION_ALGORITHM = "aes-256-cbc";
7
+ const MAGIC_BYTES = Buffer.from("ENVM");
8
+ /**
9
+ * 导入/导出服务
10
+ * 负责环境配置的导出(打包为 JSON)和导入(解析并重建数据)
11
+ */
12
+ class ImportExportService {
13
+ constructor(envRepo, devServerRepo, routeRuleRepo, passwordRepo) {
14
+ this.envRepo = envRepo;
15
+ this.devServerRepo = devServerRepo;
16
+ this.routeRuleRepo = routeRuleRepo;
17
+ this.passwordRepo = passwordRepo;
18
+ }
19
+ // ==================== 导出 ====================
20
+ /**
21
+ * 导出指定环境(或全部环境)的完整配置数据
22
+ */
23
+ exportEnvs(request) {
24
+ const allEnvs = this.envRepo.getAll();
25
+ const targetEnvs = request.envIds && request.envIds.length > 0
26
+ ? allEnvs.filter((e) => request.envIds.includes(e.id))
27
+ : allEnvs;
28
+ const devServerMap = new Map();
29
+ const exportedEnvs = [];
30
+ for (const env of targetEnvs) {
31
+ // 解析 devServerUrl
32
+ let devServerUrl;
33
+ if (env.devServerId) {
34
+ const ds = this.devServerRepo.findOneById({ id: env.devServerId });
35
+ if (ds) {
36
+ devServerUrl = ds.devServerUrl;
37
+ // 收集关联的 DevServer(去重)
38
+ if (!devServerMap.has(ds.devServerUrl)) {
39
+ devServerMap.set(ds.devServerUrl, {
40
+ name: ds.name,
41
+ devServerUrl: ds.devServerUrl,
42
+ description: ds.description,
43
+ });
44
+ }
45
+ }
46
+ }
47
+ // 获取路由规则(targetEnvId → targetEnvApiBaseUrl)
48
+ const routeRules = this.routeRuleRepo
49
+ .getByEnvId(env.id)
50
+ .map((rule) => {
51
+ const result = {
52
+ pathPrefix: rule.pathPrefix,
53
+ description: rule.description,
54
+ enabled: rule.enabled,
55
+ };
56
+ if (rule.targetEnvId) {
57
+ const targetEnv = this.envRepo.findOneById(rule.targetEnvId);
58
+ if (targetEnv) {
59
+ result.targetEnvApiBaseUrl = targetEnv.apiBaseUrl;
60
+ }
61
+ }
62
+ return result;
63
+ });
64
+ // 获取密码
65
+ const passwords = this.passwordRepo
66
+ .getByEnvId(env.id)
67
+ .map((pwd) => ({
68
+ name: pwd.name,
69
+ username: pwd.username,
70
+ password: pwd.password,
71
+ description: pwd.description,
72
+ isDefault: pwd.isDefault,
73
+ }));
74
+ exportedEnvs.push({
75
+ apiBaseUrl: env.apiBaseUrl,
76
+ port: env.port,
77
+ name: env.name,
78
+ description: env.description,
79
+ devServerUrl,
80
+ homePage: env.homePage,
81
+ routeRules,
82
+ passwords,
83
+ });
84
+ }
85
+ const data = {
86
+ version: EXPORT_VERSION,
87
+ exportedAt: new Date().toISOString(),
88
+ encrypted: false,
89
+ devServers: Array.from(devServerMap.values()),
90
+ envs: exportedEnvs,
91
+ };
92
+ // 可选加密
93
+ if (request.encryptPassword) {
94
+ this.encryptPasswords(data, request.encryptPassword);
95
+ }
96
+ envLogger.info({ envCount: exportedEnvs.length, devServerCount: data.devServers.length }, "环境配置导出完成");
97
+ return data;
98
+ }
99
+ // ==================== 导入 ====================
100
+ /**
101
+ * 导入环境配置数据
102
+ */
103
+ importEnvs(request) {
104
+ const { data, conflictStrategy } = request;
105
+ const result = {
106
+ created: { envs: 0, devServers: 0, routeRules: 0, passwords: 0 },
107
+ skipped: { envs: 0, devServers: 0 },
108
+ overwritten: { envs: 0, devServers: 0 },
109
+ errors: [],
110
+ };
111
+ // 解密(如果需要)
112
+ if (data.encrypted && request.decryptPassword) {
113
+ try {
114
+ this.decryptPasswords(data, request.decryptPassword);
115
+ }
116
+ catch (error) {
117
+ throw new AppError(`密码解密失败:${error instanceof Error ? error.message : "密码错误或数据损坏"}`, 400);
118
+ }
119
+ }
120
+ // 第一步:导入 DevServer(建立 devServerUrl → id 映射)
121
+ const devServerIdMap = new Map();
122
+ for (const ds of data.devServers) {
123
+ try {
124
+ const existing = this.devServerRepo.findOneByUrl(ds.devServerUrl);
125
+ if (existing) {
126
+ if (conflictStrategy === "overwrite") {
127
+ this.devServerRepo.update({
128
+ id: existing.id,
129
+ name: ds.name,
130
+ description: ds.description,
131
+ });
132
+ devServerIdMap.set(ds.devServerUrl, existing.id);
133
+ result.overwritten.devServers++;
134
+ }
135
+ else {
136
+ devServerIdMap.set(ds.devServerUrl, existing.id);
137
+ result.skipped.devServers++;
138
+ }
139
+ }
140
+ else {
141
+ const id = uuidv4();
142
+ this.devServerRepo.addDevServer({
143
+ id,
144
+ name: ds.name,
145
+ devServerUrl: ds.devServerUrl,
146
+ description: ds.description ?? "",
147
+ sortOrder: 0,
148
+ });
149
+ devServerIdMap.set(ds.devServerUrl, id);
150
+ result.created.devServers++;
151
+ }
152
+ }
153
+ catch (error) {
154
+ result.errors.push(`DevServer [${ds.devServerUrl}]: ${error instanceof Error ? error.message : String(error)}`);
155
+ }
156
+ }
157
+ // 第二步:导入环境
158
+ for (const exportEnv of data.envs) {
159
+ try {
160
+ const existingEnv = this.envRepo.findOne({
161
+ apiBaseUrl: exportEnv.apiBaseUrl,
162
+ });
163
+ let envId;
164
+ if (existingEnv) {
165
+ if (conflictStrategy === "overwrite") {
166
+ // 解析 devServerId
167
+ const devServerId = exportEnv.devServerUrl
168
+ ? devServerIdMap.get(exportEnv.devServerUrl)
169
+ : undefined;
170
+ this.envRepo.update({
171
+ id: existingEnv.id,
172
+ port: exportEnv.port,
173
+ name: exportEnv.name,
174
+ description: exportEnv.description,
175
+ devServerId,
176
+ homePage: exportEnv.homePage,
177
+ apiBaseUrl: exportEnv.apiBaseUrl,
178
+ });
179
+ envId = existingEnv.id;
180
+ // 删除旧的 routeRules 和 passwords
181
+ this.routeRuleRepo.deleteByEnvId(envId);
182
+ this.passwordRepo.deleteByEnvId(envId);
183
+ result.overwritten.envs++;
184
+ }
185
+ else {
186
+ result.skipped.envs++;
187
+ continue;
188
+ }
189
+ }
190
+ else {
191
+ // 创建新环境
192
+ envId = uuidv4();
193
+ const devServerId = exportEnv.devServerUrl
194
+ ? devServerIdMap.get(exportEnv.devServerUrl)
195
+ : undefined;
196
+ this.envRepo.addEnv({
197
+ id: envId,
198
+ apiBaseUrl: exportEnv.apiBaseUrl,
199
+ port: exportEnv.port,
200
+ name: exportEnv.name,
201
+ description: exportEnv.description,
202
+ devServerId,
203
+ homePage: exportEnv.homePage,
204
+ status: "stopped",
205
+ sortOrder: 0,
206
+ });
207
+ result.created.envs++;
208
+ }
209
+ // 创建 routeRules
210
+ for (const rule of exportEnv.routeRules) {
211
+ try {
212
+ const targetEnvId = rule.targetEnvApiBaseUrl
213
+ ? this.resolveTargetEnvId(rule.targetEnvApiBaseUrl)
214
+ : undefined;
215
+ const now = new Date().toISOString();
216
+ this.routeRuleRepo.create({
217
+ id: uuidv4(),
218
+ envId,
219
+ pathPrefix: rule.pathPrefix,
220
+ targetEnvId,
221
+ description: rule.description,
222
+ enabled: rule.enabled ?? true,
223
+ createdAt: now,
224
+ updatedAt: now,
225
+ });
226
+ result.created.routeRules++;
227
+ }
228
+ catch (error) {
229
+ result.errors.push(`RouteRule [${rule.pathPrefix}]: ${error instanceof Error ? error.message : String(error)}`);
230
+ }
231
+ }
232
+ // 创建 passwords
233
+ for (const pwd of exportEnv.passwords) {
234
+ try {
235
+ const now = new Date().toISOString();
236
+ this.passwordRepo.create({
237
+ id: uuidv4(),
238
+ envId,
239
+ name: pwd.name,
240
+ username: pwd.username,
241
+ password: pwd.password,
242
+ description: pwd.description,
243
+ isDefault: pwd.isDefault ?? false,
244
+ createdAt: now,
245
+ updatedAt: now,
246
+ });
247
+ result.created.passwords++;
248
+ }
249
+ catch (error) {
250
+ result.errors.push(`Password [${pwd.name}]: ${error instanceof Error ? error.message : String(error)}`);
251
+ }
252
+ }
253
+ }
254
+ catch (error) {
255
+ result.errors.push(`Env [${exportEnv.apiBaseUrl}]: ${error instanceof Error ? error.message : String(error)}`);
256
+ }
257
+ }
258
+ envLogger.info(result, "环境配置导入完成");
259
+ return result;
260
+ }
261
+ // ==================== 加密 / 解密 ====================
262
+ /**
263
+ * 对导出数据中的所有 password 字段进行加密
264
+ */
265
+ encryptPasswords(data, passphrase) {
266
+ const { key, iv } = this.deriveKeyAndIV(passphrase);
267
+ let hasPasswords = false;
268
+ for (const env of data.envs) {
269
+ for (const pwd of env.passwords) {
270
+ pwd.password = this.encryptField(pwd.password, key, iv);
271
+ hasPasswords = true;
272
+ }
273
+ }
274
+ data.encrypted = hasPasswords;
275
+ }
276
+ /**
277
+ * 对导入数据中的所有 password 字段进行解密
278
+ */
279
+ decryptPasswords(data, passphrase) {
280
+ const { key, iv } = this.deriveKeyAndIV(passphrase);
281
+ for (const env of data.envs) {
282
+ for (const pwd of env.passwords) {
283
+ pwd.password = this.decryptField(pwd.password, key, iv);
284
+ }
285
+ }
286
+ }
287
+ /**
288
+ * 从密码短语派生 AES-256-CBC 密钥和 IV
289
+ */
290
+ deriveKeyAndIV(passphrase) {
291
+ const key = crypto.createHash("sha256").update(passphrase).digest();
292
+ const iv = crypto
293
+ .createHash("sha256")
294
+ .update(passphrase + "envm-iv-salt")
295
+ .digest()
296
+ .subarray(0, 16);
297
+ return { key, iv };
298
+ }
299
+ /**
300
+ * 加密单个字段(hex 输出,带魔术字前缀)
301
+ */
302
+ encryptField(plaintext, key, iv) {
303
+ const cipher = crypto.createCipheriv(ENCRYPTION_ALGORITHM, key, iv);
304
+ const encrypted = Buffer.concat([
305
+ MAGIC_BYTES,
306
+ cipher.update(plaintext, "utf8"),
307
+ cipher.final(),
308
+ ]);
309
+ return encrypted.toString("hex");
310
+ }
311
+ /**
312
+ * 解密单个字段(hex 输入,验证魔术字)
313
+ */
314
+ decryptField(hexCiphertext, key, iv) {
315
+ const encrypted = Buffer.from(hexCiphertext, "hex");
316
+ const magic = encrypted.subarray(0, MAGIC_BYTES.length).toString("utf8");
317
+ if (magic !== MAGIC_BYTES.toString("utf8")) {
318
+ throw new AppError("密码解密失败:密码错误或数据损坏", 400);
319
+ }
320
+ const ciphertext = encrypted.subarray(MAGIC_BYTES.length);
321
+ const decipher = crypto.createDecipheriv(ENCRYPTION_ALGORITHM, key, iv);
322
+ return decipher.update(ciphertext).toString("utf8") + decipher.final("utf8");
323
+ }
324
+ // ==================== 辅助方法 ====================
325
+ /**
326
+ * 根据 apiBaseUrl 查找本地 envId
327
+ */
328
+ resolveTargetEnvId(apiBaseUrl) {
329
+ const env = this.envRepo.findOne({ apiBaseUrl });
330
+ return env?.id;
331
+ }
332
+ }
333
+ export { ImportExportService };
@@ -1,4 +1,5 @@
1
1
  import { v4 as uuidv4 } from "uuid";
2
+ import { AppError } from "../utils/errors.js";
2
3
  /**
3
4
  * 密码服务类
4
5
  * 负责处理与密码相关的核心业务逻辑,包括密码的增删改查等操作
@@ -25,13 +26,13 @@ class PasswordService {
25
26
  * 1. 校验输入参数合法性 2. 检查是否已存在相同名称 3. 如果设为默认密码则先清除其他默认密码 4. 生成唯一ID 5. 保存
26
27
  * @param passwordItem - 待添加的密码信息(不含ID)
27
28
  * @returns 新创建的密码
28
- * @throws {Error} 当输入参数不合法或已存在相同名称时抛出
29
+ * @throws {AppError} 当输入参数不合法或已存在相同名称时抛出
29
30
  */
30
31
  handleAdd(passwordItem) {
31
32
  const { envId, name, isDefault } = passwordItem;
32
33
  // 检查是否已存在相同名称的密码(同一环境下)
33
34
  if (this.passwordRepo.existsByEnvIdAndName(envId, name)) {
34
- throw new Error(`添加失败,该环境下已存在名称为【${name}】的密码`);
35
+ throw new AppError(`添加失败,该环境下已存在名称为【${name}】的密码`);
35
36
  }
36
37
  // 如果设为默认密码,先清除其他默认密码
37
38
  if (isDefault) {
@@ -54,19 +55,19 @@ class PasswordService {
54
55
  * 1. 校验输入参数 2. 检查密码是否存在 3. 如果设为默认密码则先清除其他默认密码 4. 执行更新
55
56
  * @param passwordItem - 包含待更新密码ID及字段的对象
56
57
  * @returns 更新后的密码
57
- * @throws {Error} 当输入参数不合法或密码不存在时抛出
58
+ * @throws {AppError} 当输入参数不合法或密码不存在时抛出
58
59
  */
59
60
  handleUpdate(passwordItem) {
60
61
  const { id, isDefault } = passwordItem;
61
62
  // 检查密码是否存在
62
63
  const existingPassword = this.passwordRepo.findOneById(id);
63
64
  if (!existingPassword) {
64
- throw new Error(`更新失败,密码【${id}】不存在`);
65
+ throw new AppError(`更新失败,密码【${id}】不存在`);
65
66
  }
66
67
  // 如果更新了名称,检查是否与其他密码冲突
67
68
  if (passwordItem.name && passwordItem.name !== existingPassword.name) {
68
69
  if (this.passwordRepo.existsByEnvIdAndName(existingPassword.envId, passwordItem.name)) {
69
- throw new Error(`更新失败,该环境下已存在名称为【${passwordItem.name}】的密码`);
70
+ throw new AppError(`更新失败,该环境下已存在名称为【${passwordItem.name}】的密码`);
70
71
  }
71
72
  }
72
73
  // 如果设为默认密码(从false改为true),先清除其他默认密码
@@ -84,14 +85,14 @@ class PasswordService {
84
85
  * 删除指定密码
85
86
  * 1. 校验输入参数 2. 检查密码是否存在 3. 执行删除操作
86
87
  * @param passwordItem - 包含待删除密码ID的对象
87
- * @throws {Error} 当输入参数不合法或密码不存在时抛出
88
+ * @throws {AppError} 当输入参数不合法或密码不存在时抛出
88
89
  */
89
90
  handleDelete(passwordItem) {
90
91
  const { id } = passwordItem;
91
92
  // 检查密码是否存在
92
93
  const existingPassword = this.passwordRepo.findOneById(id);
93
94
  if (!existingPassword) {
94
- throw new Error(`删除失败,密码【${id}】不存在`);
95
+ throw new AppError(`删除失败,密码【${id}】不存在`);
95
96
  }
96
97
  // 执行删除
97
98
  this.passwordRepo.delete(passwordItem);
@@ -5,8 +5,13 @@ import * as libCookie from "cookie";
5
5
  import { minimatch } from "minimatch";
6
6
  import * as fs from "fs";
7
7
  import * as path from "path";
8
+ import * as zlib from "zlib";
8
9
  import { getConfig } from "../utils/ResolveConfig.js";
9
10
  import { devServerLogger } from "../utils/logger.js";
11
+ import { requestLogEmitter } from "./RequestLogService.js";
12
+ import { getInjectEnabled } from "./SystemSettingService.js";
13
+ import { classifyResourceType } from "../utils/resourceType.js";
14
+ import { v4 as uuidv4 } from "uuid";
10
15
  class PreProxyServer {
11
16
  /**
12
17
  * 判断该端口是否已经有服务存在
@@ -32,7 +37,7 @@ class PreProxyServer {
32
37
  this.devServerRepo = devServerRepo;
33
38
  this.routeRuleRepo = routeRuleRepo;
34
39
  this.app = app;
35
- app.use([`${getConfig().apiPrefix}/inject/getcurrentenv`], (req, res) => {
40
+ app.use([`${getConfig().apiPrefix}/inject/getcurrentenv`], (_req, res) => {
36
41
  res.json({ envId: this.envId });
37
42
  res.end();
38
43
  });
@@ -109,6 +114,24 @@ class PreProxyServer {
109
114
  }
110
115
  return null;
111
116
  }
117
+ /**
118
+ * 根据请求路径匹配路由规则,返回命中的 pathPrefix
119
+ * @param requestPath 请求路径
120
+ * @returns 命中的规则 pathPrefix,未命中返回 'default'
121
+ */
122
+ getMatchedRule(requestPath) {
123
+ const routeRules = this.routeRuleRepo.getByEnvId(this.envId);
124
+ // 过滤出已启用的规则
125
+ const enabledRules = routeRules.filter((rule) => rule.enabled !== false);
126
+ // 按 pathPrefix 长度降序排序,确保最长前缀匹配优先
127
+ const sortedRules = [...enabledRules].sort((a, b) => b.pathPrefix.length - a.pathPrefix.length);
128
+ for (const rule of sortedRules) {
129
+ if (minimatch(requestPath, rule.pathPrefix, { dot: true })) {
130
+ return rule.pathPrefix;
131
+ }
132
+ }
133
+ return "default";
134
+ }
112
135
  /**
113
136
  * 生成代理中间件
114
137
  * @returns
@@ -136,6 +159,9 @@ class PreProxyServer {
136
159
  on: {
137
160
  proxyReq: (proxyReq, req) => {
138
161
  const requestPath = req.path || "/";
162
+ // 记录请求开始时间和日志 ID(用于 proxyRes 中的日志捕获)
163
+ req.__logStartTime = Date.now();
164
+ req.__logId = uuidv4();
139
165
  // 优先使用路由规则的目标地址,否则使用环境默认的 apiBaseUrl
140
166
  const customTarget = this.matchRouteRule(requestPath);
141
167
  const target = customTarget || `${this.getEnvItem()?.apiBaseUrl}`;
@@ -143,6 +169,28 @@ class PreProxyServer {
143
169
  this._rewrieCookieOnProxyReq(proxyReq, req);
144
170
  },
145
171
  proxyRes: (proxyRes, req, res) => {
172
+ // --- 请求日志捕获 ---
173
+ const startTime = req
174
+ .__logStartTime;
175
+ if (startTime) {
176
+ const duration = Date.now() - startTime;
177
+ const requestPath = req.path || "/";
178
+ const envItem = this.getEnvItem();
179
+ // 确定命中的路由规则
180
+ const matchedRule = this.getMatchedRule(requestPath);
181
+ requestLogEmitter.emit("log", {
182
+ id: req.__logId || uuidv4(),
183
+ timestamp: startTime,
184
+ method: req.method || "UNKNOWN",
185
+ url: requestPath,
186
+ statusCode: proxyRes.statusCode || 0,
187
+ duration,
188
+ matchedRule,
189
+ resourceType: classifyResourceType(matchedRule, proxyRes.headers["content-type"], requestPath),
190
+ envId: this.envId,
191
+ envName: envItem?.name || envItem?.apiBaseUrl || "",
192
+ });
193
+ }
146
194
  this._rewriteSetCookieOnProxyRes(proxyRes);
147
195
  this._rewriteLoginRedirect(proxyRes, req, res);
148
196
  },
@@ -151,6 +199,21 @@ class PreProxyServer {
151
199
  const customTarget = this.matchRouteRule(requestPath);
152
200
  const target = customTarget || `${this.getEnvItem()?.apiBaseUrl}`;
153
201
  proxyReq.setHeader("x-api-server", `${target}`);
202
+ // WebSocket 连接日志(无真实 HTTP 状态码,约定 101 Switching Protocols)
203
+ const matchedRule = this.getMatchedRule(requestPath);
204
+ const envItem = this.getEnvItem();
205
+ requestLogEmitter.emit("log", {
206
+ id: uuidv4(),
207
+ timestamp: Date.now(),
208
+ method: "WS",
209
+ url: requestPath,
210
+ statusCode: 101,
211
+ duration: 0,
212
+ matchedRule,
213
+ resourceType: "websocket",
214
+ envId: this.envId,
215
+ envName: envItem?.name || envItem?.apiBaseUrl || "",
216
+ });
154
217
  },
155
218
  },
156
219
  });
@@ -211,18 +274,48 @@ class PreProxyServer {
211
274
  try {
212
275
  const body = Buffer.concat(chunks);
213
276
  // 只对 HTML 且配置了注入脚本目录
214
- if (contentType.includes("text/html")) {
277
+ // 且注入资源功能开关开启时,才执行脚本注入
278
+ if (contentType.includes("text/html") && getInjectEnabled()) {
215
279
  const config = getConfig();
216
280
  const scriptDir = config.injectScriptDir;
217
- if (!scriptDir) {
218
- res.end(body);
219
- return;
281
+ // 开发服务器(Vite/Webpack/Rspack 等)可能对响应开启 gzip/br 压缩,
282
+ // 此时 body 是压缩后的二进制数据:直接按 utf8 解码会得到乱码,
283
+ // 注入后返回的未压缩内容却仍带着 Content-Encoding 头,浏览器按
284
+ // 该编码解压就会报 ERR_CONTENT_DECODING_FAILED。
285
+ // 因此先解压再注入,最后按原编码重新压缩,保持响应头与响应体一致。
286
+ const contentEncoding = String(proxyRes.headers["content-encoding"] || "").toLowerCase();
287
+ let decodedBody = body;
288
+ if (contentEncoding === "gzip" || contentEncoding === "x-gzip") {
289
+ decodedBody = zlib.gunzipSync(body);
290
+ }
291
+ else if (contentEncoding === "deflate") {
292
+ decodedBody = zlib.inflateSync(body);
293
+ }
294
+ else if (contentEncoding === "br") {
295
+ decodedBody = zlib.brotliDecompressSync(body);
296
+ }
297
+ let html = decodedBody.toString("utf8");
298
+ // 读取用户自定义文件夹下所有 js 文件(排除 # 开头的文件)
299
+ const userScriptTags = scriptDir
300
+ ? this.generateImportScripts(scriptDir)
301
+ : "";
302
+ // 始终注入内置的环境快速切换面板脚本
303
+ const builtInScriptTag = '<script type="module" src="/envm-inject/envm-switcher.js"></script>';
304
+ const allScriptTags = [userScriptTags, builtInScriptTag]
305
+ .filter(Boolean)
306
+ .join("\n");
307
+ html = html.replace(/<\/body>\s*<\/html>/gi, `${allScriptTags}</body></html>`);
308
+ let newBody = Buffer.from(html, "utf8");
309
+ // 若原响应为压缩内容,注入后按相同编码重新压缩
310
+ if (contentEncoding === "gzip" || contentEncoding === "x-gzip") {
311
+ newBody = zlib.gzipSync(newBody);
312
+ }
313
+ else if (contentEncoding === "deflate") {
314
+ newBody = zlib.deflateSync(newBody);
315
+ }
316
+ else if (contentEncoding === "br") {
317
+ newBody = zlib.brotliCompressSync(newBody);
220
318
  }
221
- let html = body.toString("utf8");
222
- // 读取文件夹下所有 js 文件(排除 # 开头的文件)
223
- const scriptTags = this.generateImportScripts(scriptDir);
224
- html = html.replace(/<\/body>\s*<\/html>/gi, `${scriptTags}</body></html>`);
225
- const newBody = Buffer.from(html, "utf8");
226
319
  res.setHeader("Content-Length", newBody.length);
227
320
  res.end(newBody);
228
321
  }
@@ -247,16 +340,16 @@ class PreProxyServer {
247
340
  return "";
248
341
  }
249
342
  const fullPath = path.resolve(scriptDir);
343
+ // 检查目录是否存在且是一个文件夹
250
344
  if (!fs.existsSync(fullPath) || !fs.statSync(fullPath).isDirectory()) {
251
- devServerLogger.warn(`注入脚本目录不存在: ${fullPath}`);
252
345
  return "";
253
346
  }
254
347
  const files = fs.readdirSync(fullPath);
255
348
  const jsFiles = files
256
349
  .filter((file) => file.endsWith(".js") && !file.startsWith("#"))
257
350
  .sort();
351
+ // 如果没有符合要求的 js 文件,返回空字符串
258
352
  if (jsFiles.length === 0) {
259
- devServerLogger.warn(`注入脚本目录没有 js 文件: ${fullPath}`);
260
353
  return "";
261
354
  }
262
355
  const importStatements = jsFiles
@@ -0,0 +1,69 @@
1
+ import { EventEmitter } from "events";
2
+ import { proxyLogger } from "../utils/logger.js";
3
+ import { getLogEnabled } from "./SystemSettingService.js";
4
+ const MAX_LOG_ENTRIES = 500;
5
+ /** 模块级单例 EventEmitter — PreProxyServer 直接导入使用 */
6
+ export const requestLogEmitter = new EventEmitter();
7
+ class RequestLogService {
8
+ constructor() {
9
+ this.logs = [];
10
+ this.logSubscribers = new Set();
11
+ // 监听 PreProxyServer 发出的日志事件
12
+ requestLogEmitter.on("log", (entry) => {
13
+ this.addLog(entry);
14
+ });
15
+ }
16
+ /**
17
+ * 添加日志条目(环形缓冲区,最多保留 MAX_LOG_ENTRIES 条)
18
+ */
19
+ addLog(entry) {
20
+ // 请求日志记录开关关闭(默认暂停)时不记录、不推送
21
+ if (!getLogEnabled()) {
22
+ return;
23
+ }
24
+ if (this.logs.length >= MAX_LOG_ENTRIES) {
25
+ this.logs.shift();
26
+ }
27
+ this.logs.push(entry);
28
+ // 通知所有订阅者(用于 WebSocket 实时推送)
29
+ for (const subscriber of this.logSubscribers) {
30
+ try {
31
+ subscriber(entry);
32
+ }
33
+ catch (err) {
34
+ proxyLogger.error(err, "日志订阅者通知失败");
35
+ }
36
+ }
37
+ }
38
+ /**
39
+ * 获取日志列表(支持 URL 模糊匹配和状态码精确过滤)
40
+ */
41
+ getLogs(filter) {
42
+ let result = [...this.logs];
43
+ if (filter?.url) {
44
+ const lower = filter.url.toLowerCase();
45
+ result = result.filter((e) => e.url.toLowerCase().includes(lower));
46
+ }
47
+ if (filter?.statusCode !== undefined) {
48
+ result = result.filter((e) => e.statusCode === filter.statusCode);
49
+ }
50
+ return result;
51
+ }
52
+ /**
53
+ * 获取全部日志历史
54
+ */
55
+ getAllLogs() {
56
+ return [...this.logs];
57
+ }
58
+ /**
59
+ * 订阅新日志条目(用于 WebSocket 客户端推送)
60
+ * 返回取消订阅函数
61
+ */
62
+ subscribe(callback) {
63
+ this.logSubscribers.add(callback);
64
+ return () => {
65
+ this.logSubscribers.delete(callback);
66
+ };
67
+ }
68
+ }
69
+ export { RequestLogService };