env-plugin 0.6.0 → 0.7.0

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 (50) hide show
  1. package/dist/Container.js +20 -1
  2. package/dist/PostProxyServer.js +37 -12
  3. package/dist/client/assets/element-plus-BN_JcO6B.js +19 -0
  4. package/dist/client/assets/element-plus-SrDBYmqw.css +1 -0
  5. package/dist/client/assets/index-CcOgzo-G.js +1 -0
  6. package/dist/client/assets/index-DcxBCPsx.css +1 -0
  7. package/dist/client/index.html +4 -4
  8. package/dist/controllers/DevServerController.js +10 -2
  9. package/dist/controllers/EnvController.js +43 -3
  10. package/dist/controllers/ImportExportController.js +44 -0
  11. package/dist/controllers/PasswordController.js +1 -0
  12. package/dist/controllers/RequestLogController.js +34 -0
  13. package/dist/controllers/RouteRuleController.js +1 -0
  14. package/dist/controllers/SystemSettingController.js +43 -0
  15. package/dist/index.js +13 -11
  16. package/dist/models/EnvModel.js +31 -3
  17. package/dist/repositories/DevServerRepo.js +14 -69
  18. package/dist/repositories/EnvRepo.js +30 -95
  19. package/dist/repositories/PasswordRepo.js +44 -106
  20. package/dist/repositories/RouteRuleRepo.js +26 -79
  21. package/dist/repositories/SystemSettingRepo.js +21 -0
  22. package/dist/repositories/database.js +11 -84
  23. package/dist/repositories/migrate.js +198 -0
  24. package/dist/repositories/store.js +118 -0
  25. package/dist/routes/index.js +197 -29
  26. package/dist/service/DevServerService.js +4 -2
  27. package/dist/service/EnvService.js +67 -7
  28. package/dist/service/ImportExportService.js +337 -0
  29. package/dist/service/PasswordService.js +11 -9
  30. package/dist/service/PreProxyServer.js +158 -36
  31. package/dist/service/ProxyAutoStarterService.js +3 -0
  32. package/dist/service/RequestLogService.js +77 -0
  33. package/dist/service/RouteRuleService.js +18 -16
  34. package/dist/service/SystemSettingService.js +90 -0
  35. package/dist/types/index.js +3 -0
  36. package/dist/types/shared/EnvItem.js +8 -0
  37. package/dist/types/shared/ImportExport.js +55 -0
  38. package/dist/types/shared/RequestLog.js +28 -0
  39. package/dist/types/shared/SystemSetting.js +18 -0
  40. package/dist/utils/ResolveConfig.js +4 -2
  41. package/dist/utils/asyncHandler.js +12 -0
  42. package/dist/utils/errors.js +2 -0
  43. package/dist/utils/resourceType.js +42 -0
  44. package/dist/utils/routeBuilder.js +19 -0
  45. package/package.json +36 -29
  46. package/templates/inject/envm-switcher.js +1418 -0
  47. package/dist/client/assets/element-plus-4FTV-s7u.js.gz +0 -0
  48. package/dist/client/assets/index-C2AH0x8U.css.gz +0 -0
  49. package/dist/client/assets/index-Db97pusF.js.gz +0 -0
  50. package/dist/client/assets/vue-CRjr1oeH.js.gz +0 -0
@@ -0,0 +1,337 @@
1
+ import { randomUUID } from "node:crypto";
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
+ envRepo;
14
+ devServerRepo;
15
+ routeRuleRepo;
16
+ passwordRepo;
17
+ constructor(envRepo, devServerRepo, routeRuleRepo, passwordRepo) {
18
+ this.envRepo = envRepo;
19
+ this.devServerRepo = devServerRepo;
20
+ this.routeRuleRepo = routeRuleRepo;
21
+ this.passwordRepo = passwordRepo;
22
+ }
23
+ // ==================== 导出 ====================
24
+ /**
25
+ * 导出指定环境(或全部环境)的完整配置数据
26
+ */
27
+ exportEnvs(request) {
28
+ const allEnvs = this.envRepo.getAll();
29
+ const targetEnvs = request.envIds && request.envIds.length > 0
30
+ ? allEnvs.filter((e) => request.envIds.includes(e.id))
31
+ : allEnvs;
32
+ const devServerMap = new Map();
33
+ const exportedEnvs = [];
34
+ for (const env of targetEnvs) {
35
+ // 解析 devServerUrl
36
+ let devServerUrl;
37
+ if (env.devServerId) {
38
+ const ds = this.devServerRepo.findOneById({ id: env.devServerId });
39
+ if (ds) {
40
+ devServerUrl = ds.devServerUrl;
41
+ // 收集关联的 DevServer(去重)
42
+ if (!devServerMap.has(ds.devServerUrl)) {
43
+ devServerMap.set(ds.devServerUrl, {
44
+ name: ds.name,
45
+ devServerUrl: ds.devServerUrl,
46
+ description: ds.description,
47
+ });
48
+ }
49
+ }
50
+ }
51
+ // 获取路由规则(targetEnvId → targetEnvApiBaseUrl)
52
+ const routeRules = this.routeRuleRepo
53
+ .getByEnvId(env.id)
54
+ .map((rule) => {
55
+ const result = {
56
+ pathPrefix: rule.pathPrefix,
57
+ description: rule.description,
58
+ enabled: rule.enabled,
59
+ };
60
+ if (rule.targetEnvId) {
61
+ const targetEnv = this.envRepo.findOneById(rule.targetEnvId);
62
+ if (targetEnv) {
63
+ result.targetEnvApiBaseUrl = targetEnv.apiBaseUrl;
64
+ }
65
+ }
66
+ return result;
67
+ });
68
+ // 获取密码
69
+ const passwords = this.passwordRepo
70
+ .getByEnvId(env.id)
71
+ .map((pwd) => ({
72
+ name: pwd.name,
73
+ username: pwd.username,
74
+ password: pwd.password,
75
+ description: pwd.description,
76
+ isDefault: pwd.isDefault,
77
+ }));
78
+ exportedEnvs.push({
79
+ apiBaseUrl: env.apiBaseUrl,
80
+ port: env.port,
81
+ name: env.name,
82
+ description: env.description,
83
+ devServerUrl,
84
+ homePage: env.homePage,
85
+ routeRules,
86
+ passwords,
87
+ });
88
+ }
89
+ const data = {
90
+ version: EXPORT_VERSION,
91
+ exportedAt: new Date().toISOString(),
92
+ encrypted: false,
93
+ devServers: Array.from(devServerMap.values()),
94
+ envs: exportedEnvs,
95
+ };
96
+ // 可选加密
97
+ if (request.encryptPassword) {
98
+ this.encryptPasswords(data, request.encryptPassword);
99
+ }
100
+ envLogger.info({ envCount: exportedEnvs.length, devServerCount: data.devServers.length }, "环境配置导出完成");
101
+ return data;
102
+ }
103
+ // ==================== 导入 ====================
104
+ /**
105
+ * 导入环境配置数据
106
+ */
107
+ importEnvs(request) {
108
+ const { data, conflictStrategy } = request;
109
+ const result = {
110
+ created: { envs: 0, devServers: 0, routeRules: 0, passwords: 0 },
111
+ skipped: { envs: 0, devServers: 0 },
112
+ overwritten: { envs: 0, devServers: 0 },
113
+ errors: [],
114
+ };
115
+ // 解密(如果需要)
116
+ if (data.encrypted && request.decryptPassword) {
117
+ try {
118
+ this.decryptPasswords(data, request.decryptPassword);
119
+ }
120
+ catch (error) {
121
+ throw new AppError(`密码解密失败:${error instanceof Error ? error.message : "密码错误或数据损坏"}`, 400);
122
+ }
123
+ }
124
+ // 第一步:导入 DevServer(建立 devServerUrl → id 映射)
125
+ const devServerIdMap = new Map();
126
+ for (const ds of data.devServers) {
127
+ try {
128
+ const existing = this.devServerRepo.findOneByUrl(ds.devServerUrl);
129
+ if (existing) {
130
+ if (conflictStrategy === "overwrite") {
131
+ this.devServerRepo.update({
132
+ id: existing.id,
133
+ name: ds.name,
134
+ description: ds.description,
135
+ });
136
+ devServerIdMap.set(ds.devServerUrl, existing.id);
137
+ result.overwritten.devServers++;
138
+ }
139
+ else {
140
+ devServerIdMap.set(ds.devServerUrl, existing.id);
141
+ result.skipped.devServers++;
142
+ }
143
+ }
144
+ else {
145
+ const id = randomUUID();
146
+ this.devServerRepo.addDevServer({
147
+ id,
148
+ name: ds.name,
149
+ devServerUrl: ds.devServerUrl,
150
+ description: ds.description ?? "",
151
+ sortOrder: 0,
152
+ });
153
+ devServerIdMap.set(ds.devServerUrl, id);
154
+ result.created.devServers++;
155
+ }
156
+ }
157
+ catch (error) {
158
+ result.errors.push(`DevServer [${ds.devServerUrl}]: ${error instanceof Error ? error.message : String(error)}`);
159
+ }
160
+ }
161
+ // 第二步:导入环境
162
+ for (const exportEnv of data.envs) {
163
+ try {
164
+ const existingEnv = this.envRepo.findOne({
165
+ apiBaseUrl: exportEnv.apiBaseUrl,
166
+ });
167
+ let envId;
168
+ if (existingEnv) {
169
+ if (conflictStrategy === "overwrite") {
170
+ // 解析 devServerId
171
+ const devServerId = exportEnv.devServerUrl
172
+ ? devServerIdMap.get(exportEnv.devServerUrl)
173
+ : undefined;
174
+ this.envRepo.update({
175
+ id: existingEnv.id,
176
+ port: exportEnv.port,
177
+ name: exportEnv.name,
178
+ description: exportEnv.description,
179
+ devServerId,
180
+ homePage: exportEnv.homePage,
181
+ apiBaseUrl: exportEnv.apiBaseUrl,
182
+ });
183
+ envId = existingEnv.id;
184
+ // 删除旧的 routeRules 和 passwords
185
+ this.routeRuleRepo.deleteByEnvId(envId);
186
+ this.passwordRepo.deleteByEnvId(envId);
187
+ result.overwritten.envs++;
188
+ }
189
+ else {
190
+ result.skipped.envs++;
191
+ continue;
192
+ }
193
+ }
194
+ else {
195
+ // 创建新环境
196
+ envId = randomUUID();
197
+ const devServerId = exportEnv.devServerUrl
198
+ ? devServerIdMap.get(exportEnv.devServerUrl)
199
+ : undefined;
200
+ this.envRepo.addEnv({
201
+ id: envId,
202
+ apiBaseUrl: exportEnv.apiBaseUrl,
203
+ port: exportEnv.port,
204
+ name: exportEnv.name,
205
+ description: exportEnv.description,
206
+ devServerId,
207
+ homePage: exportEnv.homePage,
208
+ status: "stopped",
209
+ sortOrder: 0,
210
+ });
211
+ result.created.envs++;
212
+ }
213
+ // 创建 routeRules
214
+ for (const rule of exportEnv.routeRules) {
215
+ try {
216
+ const targetEnvId = rule.targetEnvApiBaseUrl
217
+ ? this.resolveTargetEnvId(rule.targetEnvApiBaseUrl)
218
+ : undefined;
219
+ const now = new Date().toISOString();
220
+ this.routeRuleRepo.create({
221
+ id: randomUUID(),
222
+ envId,
223
+ pathPrefix: rule.pathPrefix,
224
+ targetEnvId,
225
+ description: rule.description,
226
+ enabled: rule.enabled ?? true,
227
+ createdAt: now,
228
+ updatedAt: now,
229
+ });
230
+ result.created.routeRules++;
231
+ }
232
+ catch (error) {
233
+ result.errors.push(`RouteRule [${rule.pathPrefix}]: ${error instanceof Error ? error.message : String(error)}`);
234
+ }
235
+ }
236
+ // 创建 passwords
237
+ for (const pwd of exportEnv.passwords) {
238
+ try {
239
+ const now = new Date().toISOString();
240
+ this.passwordRepo.create({
241
+ id: randomUUID(),
242
+ envId,
243
+ name: pwd.name,
244
+ username: pwd.username,
245
+ password: pwd.password,
246
+ description: pwd.description,
247
+ isDefault: pwd.isDefault ?? false,
248
+ createdAt: now,
249
+ updatedAt: now,
250
+ });
251
+ result.created.passwords++;
252
+ }
253
+ catch (error) {
254
+ result.errors.push(`Password [${pwd.name}]: ${error instanceof Error ? error.message : String(error)}`);
255
+ }
256
+ }
257
+ }
258
+ catch (error) {
259
+ result.errors.push(`Env [${exportEnv.apiBaseUrl}]: ${error instanceof Error ? error.message : String(error)}`);
260
+ }
261
+ }
262
+ envLogger.info(result, "环境配置导入完成");
263
+ return result;
264
+ }
265
+ // ==================== 加密 / 解密 ====================
266
+ /**
267
+ * 对导出数据中的所有 password 字段进行加密
268
+ */
269
+ encryptPasswords(data, passphrase) {
270
+ const { key, iv } = this.deriveKeyAndIV(passphrase);
271
+ let hasPasswords = false;
272
+ for (const env of data.envs) {
273
+ for (const pwd of env.passwords) {
274
+ pwd.password = this.encryptField(pwd.password, key, iv);
275
+ hasPasswords = true;
276
+ }
277
+ }
278
+ data.encrypted = hasPasswords;
279
+ }
280
+ /**
281
+ * 对导入数据中的所有 password 字段进行解密
282
+ */
283
+ decryptPasswords(data, passphrase) {
284
+ const { key, iv } = this.deriveKeyAndIV(passphrase);
285
+ for (const env of data.envs) {
286
+ for (const pwd of env.passwords) {
287
+ pwd.password = this.decryptField(pwd.password, key, iv);
288
+ }
289
+ }
290
+ }
291
+ /**
292
+ * 从密码短语派生 AES-256-CBC 密钥和 IV
293
+ */
294
+ deriveKeyAndIV(passphrase) {
295
+ const key = crypto.createHash("sha256").update(passphrase).digest();
296
+ const iv = crypto
297
+ .createHash("sha256")
298
+ .update(passphrase + "envm-iv-salt")
299
+ .digest()
300
+ .subarray(0, 16);
301
+ return { key, iv };
302
+ }
303
+ /**
304
+ * 加密单个字段(hex 输出,带魔术字前缀)
305
+ */
306
+ encryptField(plaintext, key, iv) {
307
+ const cipher = crypto.createCipheriv(ENCRYPTION_ALGORITHM, key, iv);
308
+ const encrypted = Buffer.concat([
309
+ MAGIC_BYTES,
310
+ cipher.update(plaintext, "utf8"),
311
+ cipher.final(),
312
+ ]);
313
+ return encrypted.toString("hex");
314
+ }
315
+ /**
316
+ * 解密单个字段(hex 输入,验证魔术字)
317
+ */
318
+ decryptField(hexCiphertext, key, iv) {
319
+ const encrypted = Buffer.from(hexCiphertext, "hex");
320
+ const magic = encrypted.subarray(0, MAGIC_BYTES.length).toString("utf8");
321
+ if (magic !== MAGIC_BYTES.toString("utf8")) {
322
+ throw new AppError("密码解密失败:密码错误或数据损坏", 400);
323
+ }
324
+ const ciphertext = encrypted.subarray(MAGIC_BYTES.length);
325
+ const decipher = crypto.createDecipheriv(ENCRYPTION_ALGORITHM, key, iv);
326
+ return decipher.update(ciphertext).toString("utf8") + decipher.final("utf8");
327
+ }
328
+ // ==================== 辅助方法 ====================
329
+ /**
330
+ * 根据 apiBaseUrl 查找本地 envId
331
+ */
332
+ resolveTargetEnvId(apiBaseUrl) {
333
+ const env = this.envRepo.findOne({ apiBaseUrl });
334
+ return env?.id;
335
+ }
336
+ }
337
+ export { ImportExportService };
@@ -1,10 +1,12 @@
1
- import { v4 as uuidv4 } from "uuid";
1
+ import { randomUUID } from "node:crypto";
2
+ import { AppError } from "../utils/errors.js";
2
3
  /**
3
4
  * 密码服务类
4
5
  * 负责处理与密码相关的核心业务逻辑,包括密码的增删改查等操作
5
6
  * 依赖密码仓库(PasswordRepo)实现数据持久化
6
7
  */
7
8
  class PasswordService {
9
+ passwordRepo;
8
10
  /**
9
11
  * 构造函数 - 通过依赖注入初始化仓库实例
10
12
  * @param passwordRepo - 密码仓库实例,用于密码数据的持久化操作
@@ -25,13 +27,13 @@ class PasswordService {
25
27
  * 1. 校验输入参数合法性 2. 检查是否已存在相同名称 3. 如果设为默认密码则先清除其他默认密码 4. 生成唯一ID 5. 保存
26
28
  * @param passwordItem - 待添加的密码信息(不含ID)
27
29
  * @returns 新创建的密码
28
- * @throws {Error} 当输入参数不合法或已存在相同名称时抛出
30
+ * @throws {AppError} 当输入参数不合法或已存在相同名称时抛出
29
31
  */
30
32
  handleAdd(passwordItem) {
31
33
  const { envId, name, isDefault } = passwordItem;
32
34
  // 检查是否已存在相同名称的密码(同一环境下)
33
35
  if (this.passwordRepo.existsByEnvIdAndName(envId, name)) {
34
- throw new Error(`添加失败,该环境下已存在名称为【${name}】的密码`);
36
+ throw new AppError(`添加失败,该环境下已存在名称为【${name}】的密码`);
35
37
  }
36
38
  // 如果设为默认密码,先清除其他默认密码
37
39
  if (isDefault) {
@@ -41,7 +43,7 @@ class PasswordService {
41
43
  const now = new Date().toISOString();
42
44
  const newPassword = {
43
45
  ...passwordItem,
44
- id: uuidv4(),
46
+ id: randomUUID(),
45
47
  createdAt: now,
46
48
  updatedAt: now,
47
49
  };
@@ -54,19 +56,19 @@ class PasswordService {
54
56
  * 1. 校验输入参数 2. 检查密码是否存在 3. 如果设为默认密码则先清除其他默认密码 4. 执行更新
55
57
  * @param passwordItem - 包含待更新密码ID及字段的对象
56
58
  * @returns 更新后的密码
57
- * @throws {Error} 当输入参数不合法或密码不存在时抛出
59
+ * @throws {AppError} 当输入参数不合法或密码不存在时抛出
58
60
  */
59
61
  handleUpdate(passwordItem) {
60
62
  const { id, isDefault } = passwordItem;
61
63
  // 检查密码是否存在
62
64
  const existingPassword = this.passwordRepo.findOneById(id);
63
65
  if (!existingPassword) {
64
- throw new Error(`更新失败,密码【${id}】不存在`);
66
+ throw new AppError(`更新失败,密码【${id}】不存在`);
65
67
  }
66
68
  // 如果更新了名称,检查是否与其他密码冲突
67
69
  if (passwordItem.name && passwordItem.name !== existingPassword.name) {
68
70
  if (this.passwordRepo.existsByEnvIdAndName(existingPassword.envId, passwordItem.name)) {
69
- throw new Error(`更新失败,该环境下已存在名称为【${passwordItem.name}】的密码`);
71
+ throw new AppError(`更新失败,该环境下已存在名称为【${passwordItem.name}】的密码`);
70
72
  }
71
73
  }
72
74
  // 如果设为默认密码(从false改为true),先清除其他默认密码
@@ -84,14 +86,14 @@ class PasswordService {
84
86
  * 删除指定密码
85
87
  * 1. 校验输入参数 2. 检查密码是否存在 3. 执行删除操作
86
88
  * @param passwordItem - 包含待删除密码ID的对象
87
- * @throws {Error} 当输入参数不合法或密码不存在时抛出
89
+ * @throws {AppError} 当输入参数不合法或密码不存在时抛出
88
90
  */
89
91
  handleDelete(passwordItem) {
90
92
  const { id } = passwordItem;
91
93
  // 检查密码是否存在
92
94
  const existingPassword = this.passwordRepo.findOneById(id);
93
95
  if (!existingPassword) {
94
- throw new Error(`删除失败,密码【${id}】不存在`);
96
+ throw new AppError(`删除失败,密码【${id}】不存在`);
95
97
  }
96
98
  // 执行删除
97
99
  this.passwordRepo.delete(passwordItem);