@infly/libs 2.6.0 → 2.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.
@@ -1,135 +1,135 @@
1
- const fs = require("fs");
2
- const { formatReleaseResult, resolveWebhookUrl } = require("../release-result");
3
-
4
- function shouldSkipWebhook(args = process.argv, env = process.env) {
5
- return args.some((arg) => ["--nowebhook", "--noWebhook", "--no-webhook"].includes(arg))
6
- || [env.npm_config_nowebhook, env.npm_config_noWebhook, env.NO_WEBHOOK, env.DISABLE_WEBHOOK]
7
- .some((value) => ["1", "true", "yes", "on"].includes(String(value || "").toLowerCase()));
8
- }
9
-
10
- function getWebhookMessage(args = process.argv, env = process.env) {
11
- const configured = env.npm_config_m || env.npm_config_message || env.WEBHOOK_MESSAGE || env.BUILD_MESSAGE;
12
- if (configured) return String(configured).trim();
13
- for (let index = 0; index < args.length; index++) {
14
- const arg = args[index] || "";
15
- if (["-m", "--message"].includes(arg)) return String(args[index + 1] || "").trim();
16
- if (arg.startsWith("-m=")) return arg.slice(3).trim();
17
- if (arg.startsWith("--message=")) return arg.slice(10).trim();
18
- }
19
- return "";
20
- }
21
-
22
- async function sendWebhookContent(content, options = {}, dependencies = {}) {
23
- const env = dependencies.env || process.env;
24
- const logger = dependencies.logger || console;
25
- const webhookUrl = resolveWebhookUrl(options, env);
26
- if (!webhookUrl) return false;
27
- const { webhookAtUser = [], gitInfo = {} } = options;
28
- const mentions = Array.isArray(webhookAtUser) ? webhookAtUser : webhookAtUser[gitInfo.branch];
29
- try {
30
- const response = await (dependencies.httpClient || require("axios")).post(webhookUrl, {
31
- msgtype: "text", text: {
32
- content: String(content || "").replace(/%s/g, ""), mentioned_mobile_list: mentions,
33
- },
34
- }, { timeout: 15000, headers: { "Content-Type": "application/json" } });
35
- if (response.data?.errcode !== 0) throw new Error('WEBHOOK_REJECTED');
36
- return true;
37
- } catch (error) {
38
- // Axios error/config 可能包含完整凭据 URL,日志只输出受限错误码。
39
- const code = /^[A-Z0-9_]{1,40}$/.test(error.code || '') ? error.code : 'WEBHOOK_FAILED';
40
- logger.error("企业微信推送失败", code);
41
- return false;
42
- }
43
- }
44
-
45
- function getRecordContent(record, deployUrl) {
46
- if (record?.extraParams?.releaseResult) return formatReleaseResult(record.extraParams.releaseResult);
47
- const { publishText = "", extraParams = {} } = record || {};
48
- const {
49
- gitInfo = {},
50
- gitAutoPushReposBranchMap,
51
- repos,
52
- newFileName,
53
- projectName,
54
- webhookExtraText = ""
55
- } = extraParams;
56
- const { branch, author } = gitInfo || {};
57
-
58
- if (gitAutoPushReposBranchMap) {
59
- const targetBranch = gitAutoPushReposBranchMap[branch] || branch || "";
60
- return [
61
- publishText,
62
- `构建文件:已推送对应仓库【${repos || ""}】- 分支【${targetBranch}】`,
63
- `构建人:${author || ""}`,
64
- deployUrl ? `部署系统:${deployUrl}` : ""
65
- ]
66
- .filter(Boolean)
67
- .join("\n");
68
- }
69
-
70
- const gitPath =
71
- projectName && branch && newFileName
72
- ? `https://gitee.com/gdinfly_1/${projectName}/blob/${branch}/${newFileName}`
73
- : "";
74
-
75
- return [
76
- publishText,
77
- gitPath ? `构建文件下载地址:${gitPath}` : "",
78
- webhookExtraText
79
- ]
80
- .filter(Boolean)
81
- .join("\n");
82
- }
83
-
84
- async function postBatchWebhook(batchWebhookFile, extraArgs = [], mode, dependencies = {}) {
85
- if (shouldSkipWebhook(extraArgs, dependencies.env || process.env)) {
86
- console.log("\n已跳过企业微信机器人汇总推送(nowebhook)");
87
- return;
88
- }
89
-
90
- if (!fs.existsSync(batchWebhookFile)) {
91
- return;
92
- }
93
-
94
- const records = fs
95
- .readFileSync(batchWebhookFile, "utf8")
96
- .split(/\r?\n/)
97
- .filter(Boolean)
98
- .map((line) => JSON.parse(line));
99
-
100
- if (records.length === 0) {
101
- return;
102
- }
103
-
104
- const [firstRecord] = records;
105
- const { deployUrl = "" } =
106
- firstRecord.extraParams || {};
107
-
108
- let content = [
109
- records.map((record) => getRecordContent(record, deployUrl)).join("\n\n")
110
- ].join("\n");
111
- // 防御性过滤:防止运行时数据中的 %s 等格式化占位符泄露到推送内容
112
- content = (content || "").replace(/%s/g, "");
113
- if (await sendWebhookContent(content, firstRecord.extraParams, dependencies)) {
114
- console.log("\n已发送批量构建企业微信汇总推送");
115
- }
116
- }
117
-
118
- function postVersionFileAndMsg(publishText, extraParams = {}, dependencies = {}) {
119
- const env = dependencies.env || process.env;
120
- const args = dependencies.args || process.argv;
121
- if (shouldSkipWebhook(args, env)) return;
122
- let content = getRecordContent({ publishText, extraParams }, extraParams.deployUrl);
123
- const message = getWebhookMessage(args, env);
124
- if (message && !extraParams.releaseResult) content += `\n${message}`;
125
- return sendWebhookContent(content, extraParams, dependencies);
126
- }
127
-
128
- module.exports = {
129
- getRecordContent,
130
- getWebhookMessage,
131
- shouldSkipWebhook,
132
- sendWebhookContent,
133
- postVersionFileAndMsg,
134
- postBatchWebhook
135
- };
1
+ const fs = require("fs");
2
+ const { formatReleaseResult, resolveWebhookUrl } = require("../release-result");
3
+
4
+ function shouldSkipWebhook(args = process.argv, env = process.env) {
5
+ return args.some((arg) => ["--nowebhook", "--noWebhook", "--no-webhook"].includes(arg))
6
+ || [env.npm_config_nowebhook, env.npm_config_noWebhook, env.NO_WEBHOOK, env.DISABLE_WEBHOOK]
7
+ .some((value) => ["1", "true", "yes", "on"].includes(String(value || "").toLowerCase()));
8
+ }
9
+
10
+ function getWebhookMessage(args = process.argv, env = process.env) {
11
+ const configured = env.npm_config_m || env.npm_config_message || env.WEBHOOK_MESSAGE || env.BUILD_MESSAGE;
12
+ if (configured) return String(configured).trim();
13
+ for (let index = 0; index < args.length; index++) {
14
+ const arg = args[index] || "";
15
+ if (["-m", "--message"].includes(arg)) return String(args[index + 1] || "").trim();
16
+ if (arg.startsWith("-m=")) return arg.slice(3).trim();
17
+ if (arg.startsWith("--message=")) return arg.slice(10).trim();
18
+ }
19
+ return "";
20
+ }
21
+
22
+ async function sendWebhookContent(content, options = {}, dependencies = {}) {
23
+ const env = dependencies.env || process.env;
24
+ const logger = dependencies.logger || console;
25
+ const webhookUrl = resolveWebhookUrl(options, env);
26
+ if (!webhookUrl) return false;
27
+ const { webhookAtUser = [], gitInfo = {} } = options;
28
+ const mentions = Array.isArray(webhookAtUser) ? webhookAtUser : webhookAtUser[gitInfo.branch];
29
+ try {
30
+ const response = await (dependencies.httpClient || require("axios")).post(webhookUrl, {
31
+ msgtype: "text", text: {
32
+ content: String(content || "").replace(/%s/g, ""), mentioned_mobile_list: mentions,
33
+ },
34
+ }, { timeout: 15000, headers: { "Content-Type": "application/json" } });
35
+ if (response.data?.errcode !== 0) throw new Error('WEBHOOK_REJECTED');
36
+ return true;
37
+ } catch (error) {
38
+ // Axios error/config 可能包含完整凭据 URL,日志只输出受限错误码。
39
+ const code = /^[A-Z0-9_]{1,40}$/.test(error.code || '') ? error.code : 'WEBHOOK_FAILED';
40
+ logger.error("企业微信推送失败", code);
41
+ return false;
42
+ }
43
+ }
44
+
45
+ function getRecordContent(record, deployUrl) {
46
+ if (record?.extraParams?.releaseResult) return formatReleaseResult(record.extraParams.releaseResult);
47
+ const { publishText = "", extraParams = {} } = record || {};
48
+ const {
49
+ gitInfo = {},
50
+ gitAutoPushReposBranchMap,
51
+ repos,
52
+ newFileName,
53
+ projectName,
54
+ webhookExtraText = ""
55
+ } = extraParams;
56
+ const { branch, author } = gitInfo || {};
57
+
58
+ if (gitAutoPushReposBranchMap) {
59
+ const targetBranch = gitAutoPushReposBranchMap[branch] || branch || "";
60
+ return [
61
+ publishText,
62
+ `构建文件:已推送对应仓库【${repos || ""}】- 分支【${targetBranch}】`,
63
+ `构建人:${author || ""}`,
64
+ deployUrl ? `部署系统:${deployUrl}` : ""
65
+ ]
66
+ .filter(Boolean)
67
+ .join("\n");
68
+ }
69
+
70
+ const gitPath =
71
+ projectName && branch && newFileName
72
+ ? `https://gitee.com/gdinfly_1/${projectName}/blob/${branch}/${newFileName}`
73
+ : "";
74
+
75
+ return [
76
+ publishText,
77
+ gitPath ? `构建文件下载地址:${gitPath}` : "",
78
+ webhookExtraText
79
+ ]
80
+ .filter(Boolean)
81
+ .join("\n");
82
+ }
83
+
84
+ async function postBatchWebhook(batchWebhookFile, extraArgs = [], mode, dependencies = {}) {
85
+ if (shouldSkipWebhook(extraArgs, dependencies.env || process.env)) {
86
+ console.log("\n已跳过企业微信机器人汇总推送(nowebhook)");
87
+ return;
88
+ }
89
+
90
+ if (!fs.existsSync(batchWebhookFile)) {
91
+ return;
92
+ }
93
+
94
+ const records = fs
95
+ .readFileSync(batchWebhookFile, "utf8")
96
+ .split(/\r?\n/)
97
+ .filter(Boolean)
98
+ .map((line) => JSON.parse(line));
99
+
100
+ if (records.length === 0) {
101
+ return;
102
+ }
103
+
104
+ const [firstRecord] = records;
105
+ const { deployUrl = "" } =
106
+ firstRecord.extraParams || {};
107
+
108
+ let content = [
109
+ records.map((record) => getRecordContent(record, deployUrl)).join("\n\n")
110
+ ].join("\n");
111
+ // 防御性过滤:防止运行时数据中的 %s 等格式化占位符泄露到推送内容
112
+ content = (content || "").replace(/%s/g, "");
113
+ if (await sendWebhookContent(content, firstRecord.extraParams, dependencies)) {
114
+ console.log("\n已发送批量构建企业微信汇总推送");
115
+ }
116
+ }
117
+
118
+ function postVersionFileAndMsg(publishText, extraParams = {}, dependencies = {}) {
119
+ const env = dependencies.env || process.env;
120
+ const args = dependencies.args || process.argv;
121
+ if (shouldSkipWebhook(args, env)) return;
122
+ let content = getRecordContent({ publishText, extraParams }, extraParams.deployUrl);
123
+ const message = getWebhookMessage(args, env);
124
+ if (message && !extraParams.releaseResult) content += `\n${message}`;
125
+ return sendWebhookContent(content, extraParams, dependencies);
126
+ }
127
+
128
+ module.exports = {
129
+ getRecordContent,
130
+ getWebhookMessage,
131
+ shouldSkipWebhook,
132
+ sendWebhookContent,
133
+ postVersionFileAndMsg,
134
+ postBatchWebhook
135
+ };
@@ -24,5 +24,9 @@ for health_url in "${health_urls[@]}"; do
24
24
  sleep "$health_interval"
25
25
  done
26
26
  [[ "$checked" == true ]] || { echo "健康检查失败: $health_url" >&2; exit 1; }
27
- echo "健康检查通过: $health_url"
27
+ if [[ -t 1 && -z ${NO_COLOR+x} && ${FORCE_COLOR-} != 0 ]]; then
28
+ printf '\033[32m√ 健康检查通过: %s\033[0m\n' "$health_url"
29
+ else
30
+ printf '健康检查通过: %s\n' "$health_url"
31
+ fi
28
32
  done
@@ -216,4 +216,8 @@ if ! "${compose[@]}" up -d --no-deps "${selected_services[@]}"; then rollback; e
216
216
  if ! run_post_deploy "${selected_components[@]}"; then rollback; exit 1; fi
217
217
  if ! bash "$bundle_dir/health-check.sh"; then rollback; exit 1; fi
218
218
  release_complete=true
219
- echo "发布成功: $target; 上一版本记录: $project_dir/$previous_env"
219
+ if [[ -t 1 && -z ${NO_COLOR+x} && ${FORCE_COLOR-} != 0 ]]; then
220
+ printf '\033[32m√ 发布成功: %s; 上一版本记录: %s\033[0m\n' "$target" "$project_dir/$previous_env"
221
+ else
222
+ printf '发布成功: %s; 上一版本记录: %s\n' "$target" "$project_dir/$previous_env"
223
+ fi
@@ -17,6 +17,7 @@
17
17
  * [--health-check] [--health-timeout SECONDS] [--health-add-host HOST:IP]
18
18
  */
19
19
 
20
+ const { logTerminal } = require("../../cli/terminal-style");
20
21
  const { execSync, spawn } = require("child_process");
21
22
  const fs = require("fs");
22
23
  const path = require("path");
@@ -86,7 +87,7 @@ function formatCicdLink(value, deployParams) {
86
87
  .replace(/%2F/gi, "/").replace(/%26/gi, "&").replace(/%3D/gi, "=").replace(/%3A/gi, ":");
87
88
  const hyperlinkStart = `\x1b]8;;${parsedUrl.href}\x1b\\`;
88
89
  const hyperlinkEnd = "\x1b]8;;\x1b\\";
89
- return `发布系统:\n${hyperlinkStart}\x1b[34m${displayHref}\x1b[0m${hyperlinkEnd}`;
90
+ return `发布系统:\n${hyperlinkStart}${displayHref}${hyperlinkEnd}`;
90
91
  }
91
92
 
92
93
  function detectMode({ standalone = false } = {}) {
@@ -256,13 +257,13 @@ function healthCheckImage(imageTag, options = {}) {
256
257
  const addHostArg = healthAddHost ? ` --add-host ${healthAddHost}` : "";
257
258
 
258
259
  console.log("");
259
- console.log("\x1b[0;32m>>> 启动临时容器并等待镜像 HEALTHCHECK\x1b[0m");
260
+ console.log("启动临时容器并等待镜像 HEALTHCHECK");
260
261
  run(`docker run --detach --name ${containerName}${addHostArg} ${imageTag}`, { dryRun });
261
262
 
262
263
  if (dryRun) {
263
264
  run(`docker inspect --format health-status ${containerName}`, { dryRun });
264
265
  run(`docker rm --force ${containerName}`, { dryRun });
265
- console.log("\x1b[0;32m✓ [DRY RUN] 镜像健康检查计划完成\x1b[0m");
266
+ logTerminal("success", "[DRY RUN] 镜像健康检查计划完成");
266
267
  return;
267
268
  }
268
269
 
@@ -276,7 +277,7 @@ function healthCheckImage(imageTag, options = {}) {
276
277
  ).trim();
277
278
 
278
279
  if (lastStatus === "healthy") {
279
- console.log("\x1b[0;32m✓ 镜像健康检查通过\x1b[0m");
280
+ logTerminal("success", "镜像健康检查通过");
280
281
  return;
281
282
  }
282
283
  if (lastStatus === "unhealthy" || lastStatus === "missing") {
@@ -285,20 +286,20 @@ function healthCheckImage(imageTag, options = {}) {
285
286
  wait(1000);
286
287
  }
287
288
 
288
- console.error(`\x1b[0;31m镜像健康检查失败,最终状态: ${lastStatus}\x1b[0m`);
289
+ logTerminal("error", `镜像健康检查失败,最终状态: ${lastStatus}`);
289
290
  run(`docker logs ${containerName}`);
290
291
  throw new Error(`镜像 ${imageTag} 未通过健康检查,已阻止推送`);
291
292
  } finally {
292
293
  try {
293
294
  run(`docker rm --force ${containerName}`, { silent: true });
294
295
  } catch (cleanupError) {
295
- console.warn(`警告: 临时容器 ${containerName} 清理失败: ${cleanupError.message}`);
296
+ logTerminal("warning", `警告: 临时容器 ${containerName} 清理失败: ${cleanupError.message}`);
296
297
  }
297
298
  }
298
299
  }
299
300
 
300
301
  function startDockerDesktop() {
301
- console.log("\x1b[1;33mDocker Desktop 未运行,正在启动...\x1b[0m");
302
+ logTerminal("warning", "Docker Desktop 未运行,正在启动...");
302
303
  try {
303
304
  try {
304
305
  execSync(
@@ -316,7 +317,7 @@ function startDockerDesktop() {
316
317
  for (let i = 0; i < 30; i++) {
317
318
  try {
318
319
  execSync("docker info", { stdio: "ignore" });
319
- console.log("\n\x1b[0;32m✓ Docker 已就绪\x1b[0m");
320
+ logTerminal("success", "Docker 已就绪");
320
321
  return true;
321
322
  } catch {}
322
323
  process.stdout.write(".");
@@ -355,7 +356,7 @@ async function dockerBuildPush(options = {}, dependencies = {}) {
355
356
 
356
357
  const appPkgPath = path.join(cwd, "package.json");
357
358
  if (!fs.existsSync(appPkgPath)) {
358
- console.error("错误: 当前目录下缺少 package.json,请在 app 目录内执行");
359
+ logTerminal("error", "错误: 当前目录下缺少 package.json,请在 app 目录内执行");
359
360
  process.exit(1);
360
361
  }
361
362
 
@@ -365,7 +366,7 @@ async function dockerBuildPush(options = {}, dependencies = {}) {
365
366
  isStandalone,
366
367
  });
367
368
  if (!fs.existsSync(path.join(buildContext, dockerfileArg))) {
368
- console.error(`错误: 缺少 Dockerfile: ${dockerfileArg}`);
369
+ logTerminal("error", `错误: 缺少 Dockerfile: ${dockerfileArg}`);
369
370
  process.exit(1);
370
371
  }
371
372
 
@@ -392,23 +393,23 @@ async function dockerBuildPush(options = {}, dependencies = {}) {
392
393
 
393
394
  // 5. Docker Desktop 自动启动(仅本地模式)
394
395
  if (local) {
395
- console.log("\x1b[0;32m>>> 检查 Docker 运行状态\x1b[0m");
396
+ console.log("检查 Docker 运行状态");
396
397
  try {
397
398
  execSync("docker info", { stdio: "ignore" });
398
- console.log("\x1b[0;32m✓ Docker 已运行\x1b[0m");
399
+ logTerminal("success", "Docker 已运行");
399
400
  } catch {
400
401
  const ok = startDockerDesktop();
401
402
  if (!ok) {
402
- console.error("\x1b[0;31m错误: Docker Desktop 启动超时,请手动启动后重试\x1b[0m");
403
+ logTerminal("error", "Docker Desktop 启动超时,请手动启动后重试");
403
404
  process.exit(1);
404
405
  }
405
406
  }
406
407
  }
407
408
 
408
409
  // 6. 打印信息
409
- console.log("\x1b[0;34m==========================================");
410
+ console.log("==========================================");
410
411
  console.log("构建并推送 Docker 镜像");
411
- console.log("==========================================\x1b[0m");
412
+ console.log("==========================================");
412
413
  console.log(`运行模式: ${modeLabel}`);
413
414
  console.log(`镜像名称: ${imageName}`);
414
415
  console.log(`环境: ${env}`);
@@ -421,7 +422,7 @@ async function dockerBuildPush(options = {}, dependencies = {}) {
421
422
  console.log("");
422
423
 
423
424
  // 7. 构建
424
- console.log("\x1b[0;32m>>> 开始构建 Docker 镜像\x1b[0m");
425
+ console.log("开始构建 Docker 镜像");
425
426
  let effectiveBuildContext = buildContext;
426
427
  let preparedContext;
427
428
  if (!isStandalone && !dryRun) {
@@ -458,7 +459,7 @@ async function dockerBuildPush(options = {}, dependencies = {}) {
458
459
  } finally {
459
460
  if (preparedContext) fs.rmSync(preparedContext.contextRoot, { recursive: true, force: true });
460
461
  }
461
- console.log("\x1b[0;32m✓ 镜像构建完成\x1b[0m");
462
+ logTerminal("success", "镜像构建完成");
462
463
 
463
464
  // 8. 可选镜像健康门禁(失败会抛错,任何标签都不会推送)
464
465
  if (healthCheck) {
@@ -472,16 +473,14 @@ async function dockerBuildPush(options = {}, dependencies = {}) {
472
473
 
473
474
  // 9. 推送
474
475
  console.log("");
475
- console.log(`\x1b[0;32m>>> 推送镜像到 ${registry}\x1b[0m`);
476
+ console.log(`推送镜像到 ${registry}`);
476
477
  for (const tag of tags) {
477
478
  run(`docker push ${tag}`, { dryRun });
478
479
  }
479
480
 
480
481
  // 10. 结果摘要
481
482
  console.log("");
482
- console.log("\x1b[0;34m==========================================");
483
- console.log("✅ 完成");
484
- console.log("==========================================\x1b[0m");
483
+ logTerminal("success", "Docker 镜像流程已结束");
485
484
  console.log("可用标签:");
486
485
  console.log(` ${tags[0]} (commit 精确版本)`);
487
486
  if (!commitOnly) {
@@ -1,3 +1,4 @@
1
+ const { logTerminal } = require("../../cli/terminal-style");
1
2
  const fs = require("node:fs");
2
3
  const path = require("node:path");
3
4
  const { execFileSync, spawn, spawnSync } = require("node:child_process");
@@ -204,9 +205,9 @@ async function releaseDocker(options = {}) {
204
205
  }
205
206
 
206
207
  if (emergency.emergency) {
207
- console.warn("\n⚠️ 紧急构建模式:已跳过项目检查和 SonarQube");
208
- console.warn(`紧急原因: ${emergency.emergencyReason}`);
209
- console.warn(`目标 commit: ${projectVersion.fullCommit}`);
208
+ logTerminal("warning", "\n紧急构建模式:已跳过项目检查和 SonarQube");
209
+ logTerminal("warning", `紧急原因: ${emergency.emergencyReason}`);
210
+ logTerminal("warning", `目标 commit: ${projectVersion.fullCommit}`);
210
211
  } else {
211
212
  await runProjectChecks(config.checks, projectRoot);
212
213
  }
@@ -215,7 +216,7 @@ async function releaseDocker(options = {}) {
215
216
  if (!fs.existsSync(config.coverageReport) || fs.statSync(config.coverageReport).size === 0) {
216
217
  throw new Error(`覆盖率报告不存在或为空: ${config.coverageReport}`);
217
218
  }
218
- console.log(`✓ 覆盖率报告已生成: ${config.coverageReport}`);
219
+ logTerminal("success", `覆盖率报告已生成: ${config.coverageReport}`);
219
220
  }
220
221
 
221
222
  if (!emergency.emergency && config.sonar) {
@@ -1,30 +1,30 @@
1
- const fs = require("node:fs");
2
- const path = require("node:path");
3
-
4
- function inside(root, relative) {
5
- if (typeof relative !== "string" || !relative || path.isAbsolute(relative)) throw new Error(`必须配置相对路径: ${relative}`);
6
- const result = path.resolve(root, relative);
7
- const offset = path.relative(root, result);
8
- if (offset === ".." || offset.startsWith(`..${path.sep}`)) throw new Error(`路径越界: ${relative}`);
9
- return result;
10
- }
11
-
12
- function confinedPath(root, relative, io = fs) {
13
- const candidate = inside(root, relative);
14
- let existing = candidate;
15
- while (existing !== root && !io.existsSync(existing)) {
16
- if (io.lstatSync) {
17
- try {
18
- if (io.lstatSync(existing).isSymbolicLink()) throw new Error(`无法解析链接路径: ${relative}`);
19
- } catch (error) { if (error.code !== "ENOENT") throw error; }
20
- }
21
- existing = path.dirname(existing);
22
- }
23
- if (io.realpathSync && io.existsSync(existing)) {
24
- const offset = path.relative(io.realpathSync(root), io.realpathSync(existing));
25
- if (offset === ".." || offset.startsWith(`..${path.sep}`) || path.isAbsolute(offset)) throw new Error(`链接路径越界: ${relative}`);
26
- }
27
- return candidate;
28
- }
29
-
30
- module.exports = { inside, confinedPath };
1
+ const fs = require("node:fs");
2
+ const path = require("node:path");
3
+
4
+ function inside(root, relative) {
5
+ if (typeof relative !== "string" || !relative || path.isAbsolute(relative)) throw new Error(`必须配置相对路径: ${relative}`);
6
+ const result = path.resolve(root, relative);
7
+ const offset = path.relative(root, result);
8
+ if (offset === ".." || offset.startsWith(`..${path.sep}`)) throw new Error(`路径越界: ${relative}`);
9
+ return result;
10
+ }
11
+
12
+ function confinedPath(root, relative, io = fs) {
13
+ const candidate = inside(root, relative);
14
+ let existing = candidate;
15
+ while (existing !== root && !io.existsSync(existing)) {
16
+ if (io.lstatSync) {
17
+ try {
18
+ if (io.lstatSync(existing).isSymbolicLink()) throw new Error(`无法解析链接路径: ${relative}`);
19
+ } catch (error) { if (error.code !== "ENOENT") throw error; }
20
+ }
21
+ existing = path.dirname(existing);
22
+ }
23
+ if (io.realpathSync && io.existsSync(existing)) {
24
+ const offset = path.relative(io.realpathSync(root), io.realpathSync(existing));
25
+ if (offset === ".." || offset.startsWith(`..${path.sep}`) || path.isAbsolute(offset)) throw new Error(`链接路径越界: ${relative}`);
26
+ }
27
+ return candidate;
28
+ }
29
+
30
+ module.exports = { inside, confinedPath };
@@ -19,6 +19,44 @@ const SAFE_DOCKER_PLATFORM = /^[a-z0-9]+\/[a-z0-9]+(?:\/[a-z0-9._-]+)?$/;
19
19
  const SAFE_VERSION_REQUIREMENT = /^>=(\d+)(?:\.(\d+))?(?:\.(\d+))?$/;
20
20
  const PRE_BUILD_MODES = new Set(["always", "monorepo", "standalone"]);
21
21
  const BUILD_STRATEGIES = new Set(["artifact", "source"]);
22
+ const ENV_NAME = /^[A-Z_][A-Z0-9_]*$/;
23
+ const DOCKER_NAME = /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/;
24
+
25
+ function validateRepository(repository, name) {
26
+ if (typeof repository !== "string" || !/^[a-z0-9][a-z0-9._:/-]*$/.test(repository)) {
27
+ throw new Error(`${name} 必须配置有效的镜像 repository(不含标签)`);
28
+ }
29
+ if (repository.split("/").at(-1).includes(":")) throw new Error(`${name} repository 不得包含标签`);
30
+ }
31
+
32
+ function validateBuildInputs(component, name) {
33
+ const { buildSecrets, noCacheFilter, buildTimestampArg, buildArgs } = component;
34
+ if (buildSecrets != null) {
35
+ if (!Array.isArray(buildSecrets) || !buildSecrets.length || buildSecrets.some((secret) =>
36
+ !secret || typeof secret !== "object" || Object.keys(secret).some((key) => !["id", "fileEnv", "defaultFile"].includes(key))
37
+ || typeof secret.id !== "string" || !DOCKER_NAME.test(secret.id)
38
+ || typeof secret.fileEnv !== "string" || !ENV_NAME.test(secret.fileEnv)
39
+ ) || new Set(buildSecrets.map(({ id }) => id)).size !== buildSecrets.length) {
40
+ throw new Error(`${name} buildSecrets 需声明唯一 id 及保存文件路径的 fileEnv`);
41
+ }
42
+ for (const { defaultFile } of buildSecrets) {
43
+ if (defaultFile == null) continue;
44
+ if (typeof defaultFile !== "string" || !defaultFile.trim() || /[,\r\n\0"]/.test(defaultFile)) {
45
+ throw new Error(`${name} buildSecrets.defaultFile 必须是部署仓内的相对文件路径`);
46
+ }
47
+ inside("/config", defaultFile);
48
+ }
49
+ }
50
+ if (noCacheFilter != null && (!Array.isArray(noCacheFilter) || !noCacheFilter.length
51
+ || noCacheFilter.some((stage) => typeof stage !== "string" || !DOCKER_NAME.test(stage)))) {
52
+ throw new Error(`${name} noCacheFilter 必须是合法 Docker stage 列表`);
53
+ }
54
+ if (buildTimestampArg != null && (typeof buildTimestampArg !== "string"
55
+ || !ENV_NAME.test(buildTimestampArg) || Object.hasOwn(buildArgs || {}, buildTimestampArg)
56
+ || ["BUILD_MODE", "PROJECT_DIR", "REFRESH_INTERNAL"].includes(buildTimestampArg))) {
57
+ throw new Error(`${name} buildTimestampArg 必须是未被占用的构建参数名`);
58
+ }
59
+ }
22
60
 
23
61
  function normalizePreBuildCommand(value, target) {
24
62
  const entry = Array.isArray(value) ? { command: value, when: "always" } : value;
@@ -82,10 +120,14 @@ function validateReleaseProfile(profile, target) {
82
120
  }
83
121
 
84
122
  function validateComponent(component, name, guardedByProfile = false) {
85
- if (!component || !/^[a-z0-9][a-z0-9._:/-]*$/.test(component.repository || "") || component.repository.includes("@")) {
86
- throw new Error(`${name} 必须配置有效的镜像 repository(不含标签)`);
123
+ if (component?.repositoryEnv != null) {
124
+ if (typeof component.repositoryEnv !== "string" || !ENV_NAME.test(component.repositoryEnv) || component.repository != null) {
125
+ throw new Error(`${name} repositoryEnv 必须是环境变量名,且不能同时配置 repository`);
126
+ }
127
+ } else {
128
+ validateRepository(component?.repository, name);
87
129
  }
88
- if (component.repository.split("/").at(-1).includes(":")) throw new Error(`${name} repository 不得包含标签`);
130
+ validateBuildInputs(component, name);
89
131
  if (!component.expectedRef && !component.source?.branch && !guardedByProfile) {
90
132
  throw new Error(`${name} 必须配置 expectedRef、source.branch 或 target pushRef`);
91
133
  }
@@ -182,11 +224,12 @@ function validateComponent(component, name, guardedByProfile = false) {
182
224
  for (const file of component.files) { inside("/config", file.from); inside("/config", file.to); }
183
225
  }
184
226
  if (component.check) {
185
- const { entrypoint, args, addHosts = [] } = component.check;
227
+ const { entrypoint, args, addHosts = [], network } = component.check;
186
228
  if (typeof entrypoint !== "string" || !entrypoint || !Array.isArray(args)
187
229
  || !args.every((arg) => typeof arg === "string") || !Array.isArray(addHosts)
188
- || !addHosts.every((host) => typeof host === "string" && host.includes(":"))) {
189
- throw new Error(`${name} check 必须配置 entrypoint、args 数组及可选 addHosts 数组`);
230
+ || !addHosts.every((host) => typeof host === "string" && host.includes(":"))
231
+ || (network != null && network !== "none")) {
232
+ throw new Error(`${name} check 必须配置 entrypoint、args 数组及可选 addHosts 或 network: none`);
190
233
  }
191
234
  }
192
235
  if (component.health != null) {
@@ -201,4 +244,5 @@ function validateComponent(component, name, guardedByProfile = false) {
201
244
  }
202
245
  }
203
246
 
204
- module.exports = { compareVersions, normalizePreBuildCommand, resolveSourceDirectories, validateComponent, validateReleaseProfile };
247
+ module.exports = { compareVersions, normalizePreBuildCommand, resolveSourceDirectories, validateComponent,
248
+ validateReleaseProfile, validateRepository };