env-plugin 0.6.0 → 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 (41) hide show
  1. package/dist/Container.js +18 -0
  2. package/dist/PostProxyServer.js +33 -6
  3. package/dist/client/assets/element-plus-aWS7wRSd.js.gz +0 -0
  4. package/dist/client/assets/index-CBMR4n-V.js.gz +0 -0
  5. package/dist/client/assets/index-a3AJbcK4.css.gz +0 -0
  6. package/dist/client/assets/vue-uvJWWccw.js.gz +0 -0
  7. package/dist/client/index.html +4 -4
  8. package/dist/controllers/DevServerController.js +9 -2
  9. package/dist/controllers/EnvController.js +42 -3
  10. package/dist/controllers/ImportExportController.js +43 -0
  11. package/dist/controllers/RequestLogController.js +33 -0
  12. package/dist/controllers/SystemSettingController.js +43 -0
  13. package/dist/index.js +5 -0
  14. package/dist/repositories/DevServerRepo.js +1 -3
  15. package/dist/repositories/EnvRepo.js +6 -3
  16. package/dist/repositories/PasswordRepo.js +5 -3
  17. package/dist/repositories/RouteRuleRepo.js +5 -3
  18. package/dist/repositories/SystemSettingRepo.js +42 -0
  19. package/dist/repositories/database.js +12 -0
  20. package/dist/routes/index.js +196 -28
  21. package/dist/service/EnvService.js +58 -0
  22. package/dist/service/ImportExportService.js +333 -0
  23. package/dist/service/PasswordService.js +8 -7
  24. package/dist/service/PreProxyServer.js +102 -9
  25. package/dist/service/RequestLogService.js +69 -0
  26. package/dist/service/RouteRuleService.js +14 -14
  27. package/dist/service/SystemSettingService.js +90 -0
  28. package/dist/types/index.js +3 -0
  29. package/dist/types/shared/EnvItem.js +8 -0
  30. package/dist/types/shared/ImportExport.js +55 -0
  31. package/dist/types/shared/RequestLog.js +28 -0
  32. package/dist/types/shared/SystemSetting.js +18 -0
  33. package/dist/utils/asyncHandler.js +12 -0
  34. package/dist/utils/resourceType.js +42 -0
  35. package/dist/utils/routeBuilder.js +19 -0
  36. package/package.json +16 -3
  37. package/templates/inject/envm-switcher.js +1418 -0
  38. package/dist/client/assets/element-plus-4FTV-s7u.js.gz +0 -0
  39. package/dist/client/assets/index-C2AH0x8U.css.gz +0 -0
  40. package/dist/client/assets/index-Db97pusF.js.gz +0 -0
  41. package/dist/client/assets/vue-CRjr1oeH.js.gz +0 -0
@@ -1,46 +1,209 @@
1
1
  // routes/index.ts
2
2
  import express, { Router } from "express";
3
3
  import * as libCookie from "cookie";
4
+ import { z } from "zod";
4
5
  import { Container } from "../Container.js";
5
6
  import { getConfig } from "../utils/ResolveConfig.js";
6
7
  import { toDTO } from "../middleware/dto.middleware.js";
7
- import { EnvPrimarySchema, EnvCreateSchema, EnvUpdateSchema, EnvSortSchema, DevServerCreateSchema, DevServerDeleteSchema, DevServerUpdateSchema, DevServerSortSchema, RouteRuleCreateSchema, RouteRuleDeleteSchema, RouteRuleUpdateSchema, PasswordCreateSchema, PasswordDeleteSchema, PasswordUpdateSchema, } from "../types/index.js";
8
- // 1. 创建各模块路由
9
- const createEnvRoutes = (controller) => {
8
+ import { asyncHandler } from "../utils/asyncHandler.js";
9
+ import { registerRoutes } from "../utils/routeBuilder.js";
10
+ import { EnvPrimarySchema, EnvCreateSchema, EnvUpdateSchema, EnvSortSchema, EnvSwitchSchema, DevServerCreateSchema, DevServerDeleteSchema, DevServerUpdateSchema, DevServerSortSchema, RouteRuleCreateSchema, RouteRuleDeleteSchema, RouteRuleUpdateSchema, PasswordCreateSchema, PasswordDeleteSchema, PasswordUpdateSchema, ExportRequestSchema, ImportRequestSchema, SystemSettingUpdateSchema, } from "../types/index.js";
11
+ // 辅助函数:绑定 Controller 方法,确保 this 指向正确
12
+ const bind = (obj, method) =>
13
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
14
+ obj[method].bind(obj);
15
+ // 1. 创建各模块路由(声明式 RouteDefinition 配置)
16
+ const createEnvRoutes = (controller, importExportController) => {
10
17
  const router = Router();
11
- router.get("/getlist", (...res) => controller.handleGetList(...res));
12
- router.post("/add", toDTO(EnvCreateSchema), (...res) => controller.handleAddEnv(...res));
13
- router.post("/delete", toDTO(EnvPrimarySchema), (...res) => controller.handleDeleteEnv(...res));
14
- router.post("/update", toDTO(EnvUpdateSchema), (...res) => controller.handleUpdateEnv(...res));
15
- router.post("/start", toDTO(EnvPrimarySchema), (...res) => controller.handleStartServer(...res));
16
- router.post("/stop", toDTO(EnvPrimarySchema), (...res) => controller.handleStopServer(...res));
17
- router.put("/sort", toDTO(EnvSortSchema), (...res) => controller.handleUpdateSortOrder(...res));
18
- return router;
18
+ const routes = [
19
+ {
20
+ method: "get",
21
+ path: "/getlist",
22
+ handler: bind(controller, "handleGetList"),
23
+ },
24
+ {
25
+ method: "post",
26
+ path: "/add",
27
+ middleware: [toDTO(EnvCreateSchema)],
28
+ handler: bind(controller, "handleAddEnv"),
29
+ },
30
+ {
31
+ method: "post",
32
+ path: "/delete",
33
+ middleware: [toDTO(EnvPrimarySchema)],
34
+ handler: asyncHandler(bind(controller, "handleDeleteEnv")),
35
+ },
36
+ {
37
+ method: "post",
38
+ path: "/update",
39
+ middleware: [toDTO(EnvUpdateSchema)],
40
+ handler: bind(controller, "handleUpdateEnv"),
41
+ },
42
+ {
43
+ method: "post",
44
+ path: "/start",
45
+ middleware: [toDTO(EnvPrimarySchema)],
46
+ handler: asyncHandler(bind(controller, "handleStartServer")),
47
+ },
48
+ {
49
+ method: "post",
50
+ path: "/stop",
51
+ middleware: [toDTO(EnvPrimarySchema)],
52
+ handler: asyncHandler(bind(controller, "handleStopServer")),
53
+ },
54
+ {
55
+ method: "post",
56
+ path: "/switch",
57
+ middleware: [toDTO(EnvSwitchSchema)],
58
+ handler: asyncHandler(bind(controller, "handleSwitchEnv")),
59
+ },
60
+ {
61
+ method: "post",
62
+ path: "/proxy/switch",
63
+ middleware: [toDTO(z.object({ envId: z.string(), devServerId: z.string() }))],
64
+ handler: bind(controller, "handleSwitchProxy"),
65
+ },
66
+ {
67
+ method: "put",
68
+ path: "/sort",
69
+ middleware: [toDTO(EnvSortSchema)],
70
+ handler: bind(controller, "handleUpdateSortOrder"),
71
+ },
72
+ {
73
+ method: "post",
74
+ path: "/export",
75
+ middleware: [toDTO(ExportRequestSchema)],
76
+ handler: bind(importExportController, "handleExport"),
77
+ },
78
+ {
79
+ method: "post",
80
+ path: "/import",
81
+ middleware: [toDTO(ImportRequestSchema)],
82
+ handler: bind(importExportController, "handleImport"),
83
+ },
84
+ ];
85
+ return registerRoutes(router, routes);
19
86
  };
20
87
  const createDevServerRoutes = (controller) => {
21
88
  const router = Router();
22
- router.get("/list", (...res) => controller.handleGetDevServerList(...res));
23
- router.post("/add", toDTO(DevServerCreateSchema), (...res) => controller.handleCreateDevServer(...res));
24
- router.put("/update", toDTO(DevServerUpdateSchema), (...res) => controller.handleUpdateDevServer(...res));
25
- router.put("/sort", toDTO(DevServerSortSchema), (...res) => controller.handleUpdateSortOrder(...res));
26
- router.delete("/", toDTO(DevServerDeleteSchema), (...res) => controller.handleDeleteDevServer(...res));
27
- return router;
89
+ const routes = [
90
+ {
91
+ method: "get",
92
+ path: "/list",
93
+ handler: bind(controller, "handleGetDevServerList"),
94
+ },
95
+ {
96
+ method: "post",
97
+ path: "/add",
98
+ middleware: [toDTO(DevServerCreateSchema)],
99
+ handler: bind(controller, "handleCreateDevServer"),
100
+ },
101
+ {
102
+ method: "put",
103
+ path: "/update",
104
+ middleware: [toDTO(DevServerUpdateSchema)],
105
+ handler: bind(controller, "handleUpdateDevServer"),
106
+ },
107
+ {
108
+ method: "put",
109
+ path: "/sort",
110
+ middleware: [toDTO(DevServerSortSchema)],
111
+ handler: bind(controller, "handleUpdateSortOrder"),
112
+ },
113
+ {
114
+ method: "delete",
115
+ path: "/",
116
+ middleware: [toDTO(DevServerDeleteSchema)],
117
+ handler: bind(controller, "handleDeleteDevServer"),
118
+ },
119
+ ];
120
+ return registerRoutes(router, routes);
28
121
  };
29
122
  const createRouteRuleRoutes = (controller) => {
30
123
  const router = Router();
31
- router.get("/list/:envId", (...res) => controller.handleGetList(...res));
32
- router.post("/add", toDTO(RouteRuleCreateSchema), (...res) => controller.handleAdd(...res));
33
- router.post("/update", toDTO(RouteRuleUpdateSchema), (...res) => controller.handleUpdate(...res));
34
- router.post("/delete", toDTO(RouteRuleDeleteSchema), (...res) => controller.handleDelete(...res));
35
- return router;
124
+ const routes = [
125
+ {
126
+ method: "get",
127
+ path: "/list/:envId",
128
+ handler: bind(controller, "handleGetList"),
129
+ },
130
+ {
131
+ method: "post",
132
+ path: "/add",
133
+ middleware: [toDTO(RouteRuleCreateSchema)],
134
+ handler: bind(controller, "handleAdd"),
135
+ },
136
+ {
137
+ method: "post",
138
+ path: "/update",
139
+ middleware: [toDTO(RouteRuleUpdateSchema)],
140
+ handler: bind(controller, "handleUpdate"),
141
+ },
142
+ {
143
+ method: "post",
144
+ path: "/delete",
145
+ middleware: [toDTO(RouteRuleDeleteSchema)],
146
+ handler: bind(controller, "handleDelete"),
147
+ },
148
+ ];
149
+ return registerRoutes(router, routes);
36
150
  };
37
151
  const createPasswordRoutes = (controller) => {
38
152
  const router = Router();
39
- router.get("/list/:envId", (...res) => controller.handleGetList(...res));
40
- router.post("/add", toDTO(PasswordCreateSchema), (...res) => controller.handleAdd(...res));
41
- router.post("/update", toDTO(PasswordUpdateSchema), (...res) => controller.handleUpdate(...res));
42
- router.post("/delete", toDTO(PasswordDeleteSchema), (...res) => controller.handleDelete(...res));
43
- return router;
153
+ const routes = [
154
+ {
155
+ method: "get",
156
+ path: "/list/:envId",
157
+ handler: bind(controller, "handleGetList"),
158
+ },
159
+ {
160
+ method: "post",
161
+ path: "/add",
162
+ middleware: [toDTO(PasswordCreateSchema)],
163
+ handler: bind(controller, "handleAdd"),
164
+ },
165
+ {
166
+ method: "post",
167
+ path: "/update",
168
+ middleware: [toDTO(PasswordUpdateSchema)],
169
+ handler: bind(controller, "handleUpdate"),
170
+ },
171
+ {
172
+ method: "post",
173
+ path: "/delete",
174
+ middleware: [toDTO(PasswordDeleteSchema)],
175
+ handler: bind(controller, "handleDelete"),
176
+ },
177
+ ];
178
+ return registerRoutes(router, routes);
179
+ };
180
+ const createRequestLogRoutes = (controller) => {
181
+ const router = Router();
182
+ const routes = [
183
+ {
184
+ method: "get",
185
+ path: "/list",
186
+ handler: bind(controller, "handleGetLogs"),
187
+ },
188
+ ];
189
+ return registerRoutes(router, routes);
190
+ };
191
+ const createSystemSettingRoutes = (controller) => {
192
+ const router = Router();
193
+ const routes = [
194
+ {
195
+ method: "get",
196
+ path: "/",
197
+ handler: bind(controller, "handleGet"),
198
+ },
199
+ {
200
+ method: "post",
201
+ path: "/",
202
+ middleware: [toDTO(SystemSettingUpdateSchema)],
203
+ handler: bind(controller, "handleUpdate"),
204
+ },
205
+ ];
206
+ return registerRoutes(router, routes);
44
207
  };
45
208
  const createCommonRoutes = () => {
46
209
  const router = Router();
@@ -70,11 +233,16 @@ export const createRouter = () => {
70
233
  const devServerController = container.get("devServerController");
71
234
  const routeRuleController = container.get("routeRuleController");
72
235
  const passwordController = container.get("passwordController");
236
+ const requestLogController = container.get("requestLogController");
237
+ const importExportController = container.get("importExportController");
238
+ const systemSettingController = container.get("systemSettingController");
73
239
  // 挂载模块路由
74
- rootRouter.use("/env", createEnvRoutes(envController));
240
+ rootRouter.use("/env", createEnvRoutes(envController, importExportController));
75
241
  rootRouter.use("/server", createDevServerRoutes(devServerController));
76
242
  rootRouter.use("/route-rule", createRouteRuleRoutes(routeRuleController));
77
243
  rootRouter.use("/password", createPasswordRoutes(passwordController));
244
+ rootRouter.use("/request-log", createRequestLogRoutes(requestLogController));
245
+ rootRouter.use("/system-setting", createSystemSettingRoutes(systemSettingController));
78
246
  rootRouter.use("/", createCommonRoutes());
79
247
  return rootRouter;
80
248
  };
@@ -232,6 +232,64 @@ class EnvService {
232
232
  envLogger.info({ env, updatedEnv }, `环境【${env.id}】状态已更新为${updatedEnv.status}`);
233
233
  return updatedEnv;
234
234
  }
235
+ /**
236
+ * 环境切换:启动目标环境(不停止当前环境,允许多环境并行运行)
237
+ * @param currentEnvId - 当前环境ID(仅用于日志和幂等判断)
238
+ * @param targetEnvId - 目标环境ID
239
+ * @returns 目标环境信息(含端口号),供客户端重定向
240
+ * @throws {AppError} 当环境不存在或操作失败时抛出
241
+ */
242
+ async handleSwitchEnv(currentEnvId, targetEnvId) {
243
+ envLogger.info({ currentEnvId, targetEnvId }, "准备切换环境");
244
+ // 检查目标环境是否存在
245
+ const targetEnv = this.envRepo.findOneById(targetEnvId);
246
+ if (!targetEnv) {
247
+ throw new AppError(`切换失败,目标环境【${targetEnvId}】不存在`);
248
+ }
249
+ // 如果切换到同一个环境且已在运行,则无需操作
250
+ if (currentEnvId === targetEnvId && targetEnv.status === "running") {
251
+ envLogger.info("切换到相同环境且已在运行,无需操作");
252
+ return targetEnv;
253
+ }
254
+ // 启动目标环境(如果已在运行则重启以确保状态正确)
255
+ if (targetEnv.status === "running") {
256
+ await this.handleStopServer({ id: targetEnvId });
257
+ }
258
+ await this.handleStartServer({ id: targetEnvId });
259
+ // 3. 返回目标环境最新信息
260
+ const updatedTarget = this.envRepo.findOneById(targetEnvId);
261
+ if (!updatedTarget) {
262
+ throw new AppError("切换后无法获取目标环境信息");
263
+ }
264
+ envLogger.info({ updatedTarget }, "环境切换成功");
265
+ return updatedTarget;
266
+ }
267
+ /**
268
+ * 切换当前环境的 DevServer 绑定
269
+ * 更新 devServerId 后,PreProxyServer 在下个请求中动态读取,即时生效
270
+ * @param envId - 当前环境ID
271
+ * @param devServerId - 目标 DevServer ID
272
+ * @returns 更新后的环境信息
273
+ * @throws {AppError} 当环境或 DevServer 不存在时抛出
274
+ */
275
+ handleSwitchProxy(envId, devServerId) {
276
+ envLogger.info({ envId, devServerId }, "准备切换环境代理目标");
277
+ // 校验环境存在
278
+ const env = this.envRepo.findOneById(envId);
279
+ if (!env) {
280
+ throw new AppError(`切换代理失败,环境【${envId}】不存在`);
281
+ }
282
+ // 校验 DevServer 存在
283
+ const devServer = this.devServerRepo.findOneById({ id: devServerId });
284
+ if (!devServer) {
285
+ throw new AppError(`切换代理失败,DevServer【${devServerId}】不存在`);
286
+ }
287
+ // 更新 devServerId(PreProxyServer 动态读取,即时生效)
288
+ this.envRepo.update({ id: envId, devServerId });
289
+ const updatedEnv = this.envRepo.findOneById(envId);
290
+ envLogger.info({ updatedEnv }, "环境代理目标切换成功");
291
+ return updatedEnv;
292
+ }
235
293
  /**
236
294
  * 批量更新排序顺序
237
295
  * @param sortData - 排序数据
@@ -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 };