'use strict'; /** * 仓库前端证书同步脚本(nginx 部署器)。 * * 职责:每轮以「声明式对账 + 自愈」模式运行——从 wms_warehouse_front_config 读取 * 「期望集合」(domain 非空且 domain_status=1 的行,列缺失时降级),逐行核对磁盘上的 * 证书 / 私钥 / server 块与库内内容,缺失或内容不一致时原子重写自愈,并按需清理 * 过期命名的 server 块;一轮最多执行一次 nginx -t + reload(仅当本轮确有写入或删除时), * 最后回写部署状态。 * 生成的 server 块 = 证书骨架 + 一行 include ;站点内容 * (root / 伪静态 或 反代)统一由 upstreamInclude 指向的片段文件提供, * 由运维维护、本脚本绝不覆盖;前端个性化在运行时由配置接口按域名完成, * nginx 侧无需按域名区分站点内容。 * conf 命名版本(ver)契约: * - server 块文件名 = -.conf * (例:web.wms.gztbyc.com-1.conf;suffix 仍是「清洗后与原名不一致时的 _短哈希8」); * - 证书 / 私钥文件名不变({store_id}_{domainSafe}{suffix}.pem|.key), * DB 里 cert_path 的既有语义不动; * - 命名推导单点收敛在 computeDomainNameParts + buildConfFileName(domain, ver), * 写入、过期清理、孤儿清理、下线删除全部走同一推导,禁止别处重拼字符串; * - ver 优先级:CLI --ver > 环境变量 CERT_SYNC_VER > 配置文件 ver > 内置默认 '1'(DEFAULT_VER); * - 安全校验:ver 必须匹配 ^[A-Za-z0-9][A-Za-z0-9._-]{0,31}$,非法直接致命退出(exit 1), * 保证 ver 参与路径拼接时不可能产生 .. / /; * - nginx 主配置 include /*.conf 与新命名兼容,无需改 nginx。 * * 对账自愈语义: * - 期望内容:证书 = String(cert_pem)、私钥 = String(cert_key)、 * server 块 = buildServerConf(...)(模板不变,仍 include , * 不内联任何 location); * - 内容比较前统一 trimEnd()(库文本可能带尾部换行,不因尾部空白差异反复重写); * 内容一致时绝不重写(不改 mtime、不触发 reload),保证每分钟对账零抖动; * - 自愈写入日志前缀 [CERT-SYNC][HEAL],计入 stats.healed; * - 原 sync_status=0 的行走既有同步路径(写文件 + 成功后置 1); * 原 sync_status=1 的行发生自愈写入 → 保持 1,回写 last_synced_at=NOW()、 * last_sync_error=NULL(markRowHealed); * - **sync_status=2 不是「终态豁免」**:失败行同样参与文件层对账(声明式收敛)—— * 盘上证书 / 私钥 / server 块缺失或不一致,就按库内容重建,重建(或盘面已一致) * 且本轮 nginx 校验通过后回写 markRowRecovered(sync_status=1 + cert_path/key_path + * last_synced_at + 清 last_sync_error + sync_attempts 归零):因此「删掉 .ssl / * nginx_config」、「早期遗留的失败行」都能自动恢复,无需人工重传证书; * 唯一不进对账的情况是「证书未配置 / 证书非法」(由 loadDesiredRows 前置拦下): * 未配置 → 不写盘、回写 sync_status=0 待同步(上传证书后自动恢复); * 非法 → 记行级失败(sync_status=2),需在后台重新上传证书。 * - 失败分两类: * ① 行级失败(证书非法 / 写盘失败)→ markRowFailed(sync_status=2 + last_sync_error), * 避免「假装成功」; * ② 全局失败(nginx -t / reload 等环境问题,与单行数据无关)→ 待同步条目回退 * sync_status=0、已同步条目保持 1、失败态条目保持 2,只落 last_sync_error, * 下一轮自动重试(若失败即告别对账会让该行永久卡死,修好 nginx 也不恢复)。 * * 过期 conf 清理(confDir 根层 *.conf,任何子目录一律不动): * - 「本系统产物」判定沿用既有闸门(文件名形态 / server_name 回推域名且合法 / * 文件名可由该域名按命名规则推导 / 固有标记 upstreamInclude); * - 版本闸门:文件名必须等于 buildConfFileName(domain, args.ver),否则判过期 → * 优先删除(deleteFileGuarded 通道名 staleConf、日志前缀 [CERT-SYNC][STALE]、 * 纳入 rollbackEntries 与 --dry-run 只打印); * - 生效域名且当前版本 conf 未就绪(本轮无法生成)时保留过期文件延后删除 * (先写新、再删旧,避免 443 断档);同一域名当前版本 conf 若同时存在, * 保留当前版本、只删过期文件。 * * 另外承担「域名下线」,不需要两阶段切换的额外机制,纯配置差集驱动: * - 期望集合 = 库内已配置且证书就绪的行(domain 非空 + domain_status=1 + cert_pem/cert_key * 为合法 PEM),每仓只取一条(同 store_id 多行按 id 最小者,其余 WARN 忽略); * - 下线 = 盘上有「本系统产物」但配置里没有该域名:confDir / certDir 中按命名白名单 * 识别出的 conf / 证书,其域名不在期望集合内就删除(通道名 orphan,日志前缀 * [CERT-SYNC][PLAN] DELETE ... 原因=);无需消费 retired_domain:域名提升后旧域名 * 已不是该行的 domain,立即落入差集被清理(该列仅作应用侧审计留痕); * - 无证书 / 证书非法的行不写入、也不作为保留依据:其遗留 conf 与证书会被差集清掉 * (conf 引用不存在的证书会直接让 nginx -t 全局失败);无证书的行回写 sync_status=0 待同步; * - 统计口径:汇总的「待删 / 已删文件数」按绝对路径去重后输出;通道命中数 * (orphan / staleConf)单独列示,通道命中之和大于去重数属预期 * (dry-run 不落盘,多条通道都会看到同一文件); * - 下线 / 过期 conf 的删除与自愈写入合并在同一轮,统一收敛为最多一次 * nginx -t + reload;-t 失败用 rollbackEntries 回滚本轮删除与写入 * (本轮新写入且原本不存在的文件按删除回滚),行状态降级重试不卡死。 * * 设计要点: * - 每分钟被服务器侧 root crontab 调用(薄 shell 包装由部署 agent 适配), * 必须幂等、可重入:内容一致时零写入、零 reload。 * - 逐条失败隔离:单条写文件失败只回写该条 * sync_status=2 + last_sync_error + sync_attempts+1,不影响其他条目; * nginx -t 失败时回滚本轮全部变更,保证不拖垮整体 nginx。 * - reload 策略:仅当本轮确有写入或删除时执行一次 nginx -t + reload; * reload 失败时待同步条目回退 sync_status=0(下分钟自动重试, * sync_attempts 达到 RELOAD_FAILURE_MAX_RETRY 后转 sync_status=2 终止重试), * 自愈条目磁盘内容与库一致,仅告警 + 退出码 2。 * - 站点内容单一片段:server 块尾部以 include 收口, * 片段文件(root / 伪静态 或 反代)由运维维护、脚本绝不覆盖。 * - 敏感红线:任何日志/错误输出不得打印 cert_pem / cert_key 内容, * last_sync_error 统一做 PEM 片段脱敏 + 500 字符截断。 * - 文件权限:私钥 0600、证书/conf 0644;写文件采用「临时文件 + rename」原子写。 * - DB 读写全部参数化(sequelize replacements),禁止字符串拼接 SQL。 * - 数据库目标显式处理:--env 决定 WMS_DB_TARGET,先于 require 设置, * 覆盖终端残留的 NODE_ENV,避免误连生产库。 * * 部署约定(供部署 agent): * - 脚本以部署根目录为 cwd 运行(薄 shell 包装中先 cd 到部署根目录)。 * - 双环境外部配置文件(随代码 git 提交,发布时严禁覆盖/删除/改写): * script/warehouse-cert-sync.config.dev.json 开发环境(本机宝塔 Windows nginx) * script/warehouse-cert-sync.config.prod.json 生产环境(服务器宝塔构建 nginx,systemd) * 按 --env 自动选择;所选配置缺失或 JSON 非法一律致命退出(exit 1), * 生产环境宁可不跑也不猜,开发环境同样显式报错而非静默回退。 * - 参数优先级:CLI 参数 > 环境变量 > 外部配置文件 > 内置默认。 * - 证书目录 / nginx server 块目录 / upstream include / nginx 二进制 / * reload 与 -t 命令默认全部来自配置文件;**目录名是硬约定**:证书 → * <部署根>/.ssl,nginx server 块 → <部署根>/nginx_config(与开发环境仓库根的 * .ssl / nginx_config 同构),即生产配置里写作 certDir="./.ssl" / * confDir="./nginx_config"(相对 cwd=部署根解析,目录不存在时自动递归创建)。 * 改名/搬迁必须同步改:① nginx 主配置的 include;② 本配置的 certDir/confDir; * ③ 库里的 cert_path/key_path(触发一次重同步刷新),详见 README「发布与运维」。 * - 这三个目录都在部署根一级(非版本目录 v1|v2),发布/回退只清版本目录,不碰它们。 * - nginx 主配置由运维自行 include <部署根>/nginx_config/*.conf,本脚本不管理主配置。 * - 站点内容片段:server 块尾部 include 指向运维维护的片段文件, * 站点内容(root / 伪静态 或 反代)统一由此片段提供;脚本只生成证书骨架、 * 绝不覆盖该片段,前端个性化在运行时由配置接口按域名完成。 * **upstreamInclude 必须是绝对路径且文件已存在**(脚本启动即校验,不满足直接 exit 1): * nginx 解析相对 include 的基准是 nginx prefix(如 /www/server/nginx/conf), * 不是脚本 cwd;写相对路径会让生成的 server 块 include 到不存在的文件, * nginx -t 失败 → 整轮变更回滚(连证书一起被当孤儿回收)。 * - 自定义命令占位符:{nginxBin} 与 {nginxPrefix}(-p 前缀目录,win32 宝塔 nginx * 防 cwd 劫持),替换时自动按平台加引号;覆盖命令经 shell 执行。 * - 建议 crontab 每分钟调用一次薄 shell 包装(crontab 安装由部署 agent 负责)。 * * 用法: * node script/warehouse-cert-sync.cjs --env development --skip-nginx --dry-run * node script/warehouse-cert-sync.cjs --env development \ * --cert-dir <临时目录> --conf-dir <临时目录> --skip-nginx \ * --nginx-bin --reload-cmd <覆盖命令> * node script/warehouse-cert-sync.cjs --env production * node script/warehouse-cert-sync.cjs --env production --dry-run * node script/warehouse-cert-sync.cjs --env production --cleanup-only * node script/warehouse-cert-sync.cjs --env production --cleanup-only --dry-run * node script/warehouse-cert-sync.cjs --env production --ver 2 # conf 轮转到 -2 命名 * * 退出码约定(供 crontab 告警): * 0 正常:无变更、本批全部成功、dry-run 完成; * 1 致命:参数非法(含 ver 非法)/ DB 连接失败 / 目录不可建 / 生产环境 nginx 缺失; * 2 业务级失败:本批存在条目处理失败或 nginx -t / reload 失败(详情已回写 DB)。 */ const fs = require('node:fs'); const path = require('node:path'); const crypto = require('node:crypto'); const { spawnSync } = require('node:child_process'); const Sequelize = require('sequelize'); const PROJECT_ROOT = path.resolve(__dirname, '..'); const DB_CONFIG_PATH = path.join(PROJECT_ROOT, 'database', 'config.js'); // 部署约定默认目录:相对脚本运行时 cwd(部署根目录)的上一级, // path.resolve(process.cwd(), ...) 在运行时解析为绝对路径; // nginx 主配置由运维自行 include 该 conf 目录,本脚本不管理主配置。 const DEFAULT_CERT_DIR = path.resolve(process.cwd(), '..', '.ssl'); const DEFAULT_CONF_DIR = path.resolve(process.cwd(), '..', 'nginx_config'); const DEFAULT_UPSTREAM_INCLUDE = 'nginx-upstream.conf'; const DEFAULT_NGINX_BIN = 'nginx'; const DEFAULT_LIMIT = 50; // conf 命名版本默认值:server 块文件名为 -.conf const DEFAULT_VER = '1'; // 双环境外部配置文件:按 --env 选择(文件随代码 git 提交,发布时不得覆盖删除)。 // development → 本机宝塔 Windows nginx(nginx.exe + -p 前缀);production → 服务器宝塔构建 nginx(systemd)。 const ENV_CONFIG_FILE = { development: path.join(__dirname, 'warehouse-cert-sync.config.dev.json'), production: path.join(__dirname, 'warehouse-cert-sync.config.prod.json'), }; const NGINX_CMD_TIMEOUT_MS = 30 * 1000; const LAST_SYNC_ERROR_MAX_LENGTH = 500; const RELOAD_FAILURE_MAX_RETRY = 5; const DOMAIN_MAX_LENGTH = 253; const DOMAIN_PATTERN = /^[A-Za-z0-9*._-]+$/; // ver 白名单:首字符字母数字,其余仅字母数字 . _ -,最长 32;从规则上杜绝 .. / 路径注入 const VER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,31}$/; const PEM_CERT_MARK = 'BEGIN CERTIFICATE'; const PEM_KEY_MARK = 'PRIVATE KEY'; const EXIT_OK = 0; const EXIT_FATAL = 1; const EXIT_BUSINESS_FAILURE = 2; const CERT_FILE_MODE = 0o644; const KEY_FILE_MODE = 0o600; const TABLE_NAME = 'wms_warehouse_front_config'; // ---- 域名下线(配置差集)与清理相关常量 ---- // conf 文件名形态:{domainSafe}{[_短哈希8]}{[-]}.conf(与 buildConfFileName 产物一致,仅作第一道形态闸门) const CONF_FILE_NAME_PATTERN = /^[A-Za-z0-9._-]+?(?:_[0-9a-f]{8})?\.conf$/; // 证书 / 私钥文件名形态:{store_id}_{domainSafe}{[_短哈希8]}.pem|.key const CERT_FILE_NAME_PATTERN = /^[A-Za-z0-9]+_[A-Za-z0-9._-]+?(?:_[0-9a-f]{8})?\.(?:pem|key)$/; // server_name 指令解析(取第一条 server_name 的域名) const SERVER_NAME_PATTERN = /^[ \t]*server_name[ \t]+([^;]+);/m; /** * 单条处理结果统计。 * @typedef {Object} SyncStats * @property {number} total 本批扫描到的期望集合条数(0/1/2 全部参与文件层对账)。 * @property {number} success 待同步(sync_status=0)成功条数。 * @property {number} failed 行级失败条数(PEM 非法 / 写盘失败)。 * @property {number} healed 自愈条数(sync_status=1 发生写入)。 * @property {number} recovered 失败态(sync_status=2)恢复条数(重建或状态收口)。 * @property {number} awaitingCert 已配置域名但未上传证书的条数(回写 sync_status=0 待同步)。 * @property {number} invalidCert 证书/域名内容非法的条数(行级失败)。 */ /** * 命令行参数集合。 * @typedef {Object} SyncArgs * @property {string} env 数据库环境标记:development | production。 * @property {string} configPath 生效的外部配置文件绝对路径。 * @property {boolean} dryRun 仅扫描与输出计划,不写文件、不改库。 * @property {boolean} cleanupOnly 只做域名下线差集与过期 conf 清理,不做证书同步(--cleanup-only)。 * @property {boolean} skipNginx 跳过 nginx -t / reload。 * @property {string} certDir 证书输出目录(绝对路径)。 * @property {string} confDir nginx server 块目录(绝对路径)。 * @property {string} upstreamInclude upstream 配置文件 include 名。 * @property {number} limit 单次处理条数上限。 * @property {string} ver conf 命名版本(-.conf 的 - 片段,已通过白名单校验)。 * @property {string} nginxBin nginx 可执行文件路径。 * @property {string} nginxPrefix nginx -p 前缀目录(空串表示不启用)。 * @property {string} reloadCmd nginx reload 命令覆盖(空串按系统类型推导)。 * @property {string} testCmd nginx -t 校验命令覆盖(空串按系统类型推导)。 * @property {boolean} help 是否打印帮助。 */ /** * nginx 命令执行描述(由 buildNginxCommand 统一产出)。 * @typedef {Object} NginxCommandDesc * @property {string} command 命令字符串(shell 模式)或可执行文件路径(直连模式)。 * @property {string[]} args 直连模式的参数数组(shell 模式为空数组)。 * @property {boolean} shell 是否经 shell 执行(true 时 command 为完整命令字符串)。 */ /** * 脚本运行上下文(参数、DB 连接、nginx 可用性等)。 * @typedef {Object} SyncContext * @property {SyncArgs} args 解析后的命令行参数。 * @property {import('sequelize').Sequelize} sequelize Sequelize 实例。 * @property {boolean} nginxMissing nginx 二进制缺失(开发环境自动降级)。 * @property {NginxCommandDesc} testCommand nginx -t 校验命令执行描述。 * @property {NginxCommandDesc} reloadCommand nginx reload 命令执行描述。 */ /** * 打印帮助信息(stdout)。 * @return {void} */ function printUsage() { const text = [ '仓库前端证书同步脚本(nginx 部署器)', '', '用法: node script/warehouse-cert-sync.cjs --env [选项]', '', '环境配置文件(按 --env 自动加载,随代码提交,发布时不得覆盖删除):', ' script/warehouse-cert-sync.config.dev.json 开发环境(本机宝塔 Windows nginx)', ' script/warehouse-cert-sync.config.prod.json 生产环境(服务器宝塔构建 nginx,systemd)', ' 所选配置缺失或 JSON 非法将致命退出(exit 1),生产环境宁可不跑也不猜。', ' 支持键: nginxBin / nginxPrefix / certDir / confDir / upstreamInclude / testCmd / reloadCmd / ver', '', '参数优先级: CLI 参数 > 环境变量 > 外部配置文件 > 内置默认', '', '选项:', ' --env 运行环境(必填,显式指定,不受终端 NODE_ENV 残留影响,同时决定数据库与配置文件)', ' --dry-run 仅扫描并输出计划,不写文件、不改库(含下线差集待删清单)', ' --cleanup-only 只做域名下线差集与过期 conf 清理,不做证书同步(供运维单独执行)', ' --cert-dir 证书输出目录(默认取配置文件或 ../.ssl,相对路径按 cwd 解析)', ' --conf-dir nginx server 块目录(默认取配置文件或 ../nginx_config,同样按 cwd 解析)', ' --upstream-include 站点内容片段 include 路径(root / 伪静态 或 反代统一由该片段提供,', ' 由运维维护、脚本不覆盖;默认取配置文件或 nginx-upstream.conf)', ' --skip-nginx 跳过 nginx -t 校验与 nginx reload(开发/测试用)', ' --nginx-bin nginx 可执行文件路径(默认取配置文件或 PATH 中的 nginx)', ' --nginx-prefix nginx -p 前缀目录(win32 宝塔 nginx 防 cwd 劫持,默认取配置文件)', ' --reload-cmd reload 命令覆盖(默认按系统类型推导 "{nginxBin} -s reload";', ' 支持 {nginxBin} / {nginxPrefix} 占位符且自动按平台加引号;', ' linux 可传 "systemctl reload nginx")', ' --test-cmd nginx -t 校验命令覆盖(默认按系统类型推导 "{nginxBin} -t",语义同上)', ' --limit 单次处理条数上限(默认 50)', ' --ver conf 命名版本(-.conf,默认 1;', ' 须匹配 ^[A-Za-z0-9][A-Za-z0-9._-]{0,31}$,非法致命退出)', ' --help, -h 打印本帮助', '', '环境变量(优先级高于配置文件、低于命令行参数):', ' CERT_SYNC_ENV / CERT_SYNC_CERT_DIR / CERT_SYNC_CONF_DIR', ' CERT_SYNC_UPSTREAM_INCLUDE / CERT_SYNC_LIMIT / CERT_SYNC_NGINX_BIN / CERT_SYNC_NGINX_PREFIX / CERT_SYNC_VER', ' CERT_SYNC_RELOAD_CMD / CERT_SYNC_TEST_CMD', ' WMS_DB_TARGET / DB_HOST / DB_PORT / DB_USER / DB_PASSWORD / DB_NAME(透传 database/config.js)', '', '退出码: 0 正常;1 致命错误;2 业务级失败(条目失败或 reload 失败,供 cron 告警)', ].join('\n'); console.log(text); } /** * 加载 --env 对应的外部配置文件(双环境外部配置文件机制)。 * 文件随代码 git 提交;所选配置缺失或 JSON 非法一律视为致命错误, * 生产环境宁可不跑也不猜,开发环境同样显式报错而非静默回退内置默认。 * @param {string} env 数据库环境标记:development | production。 * @return {{configPath: string, config: Object}} 配置文件绝对路径与解析后的配置对象。 * @throws {Error} 配置文件缺失、JSON 非法或顶层结构非对象时抛出异常(触发退出码 1)。 */ function loadEnvConfig(env) { const configPath = ENV_CONFIG_FILE[env]; let rawText = ''; try { rawText = fs.readFileSync(configPath, 'utf8'); } catch (error) { throw new Error(`环境配置文件缺失: ${configPath}(--env=${env} 必须搭配对应配置文件;生产环境宁可不跑也不猜,请恢复该文件或改用显式 CLI 参数覆盖)`); } let config = null; try { config = JSON.parse(rawText); } catch (error) { throw new Error(`环境配置文件 JSON 非法: ${configPath} - ${error.message}`); } if (!config || typeof config !== 'object' || Array.isArray(config)) { throw new Error(`环境配置文件结构非法: ${configPath}(顶层必须是 JSON 对象)`); } return { configPath, config }; } /** * 解析命令行参数:CLI 参数 > 环境变量 > 外部配置文件 > 内置默认(优先级从高到低)。 * 先解析 CLI 原始值,再按 --env 加载外部配置文件作为默认值来源, * 最后统一应用优先级回填缺省字段(目录类值经 path.resolve 解析为绝对路径)。 * @param {string[]} argv process.argv.slice(2) 结果。 * @return {SyncArgs} 解析后的参数集合。 * @throws {Error} 参数非法或配置文件缺失/非法时抛出异常(触发退出码 1)。 */ function parseArgs(argv) { const cli = { env: '', certDir: '', confDir: '', upstreamInclude: '', nginxBin: '', nginxPrefix: '', reloadCmd: '', testCmd: '', limit: null, dryRun: false, cleanupOnly: false, skipNginx: false, help: false, }; for (let index = 0; index < argv.length; index++) { const item = argv[index]; const eqIndex = item.indexOf('='); const key = eqIndex >= 0 ? item.slice(0, eqIndex) : item; const inlineValue = eqIndex >= 0 ? item.slice(eqIndex + 1) : null; const readValue = () => { if (inlineValue !== null) { return inlineValue; } if (index + 1 >= argv.length) { throw new Error(`参数 ${key} 缺少值`); } index++; return argv[index]; }; if (key === '--help' || key === '-h') { cli.help = true; } else if (key === '--dry-run') { cli.dryRun = true; } else if (key === '--cleanup-only') { cli.cleanupOnly = true; } else if (key === '--skip-nginx') { cli.skipNginx = true; } else if (key === '--env') { cli.env = String(readValue() || '').trim(); } else if (key === '--cert-dir') { cli.certDir = String(readValue() || '').trim(); } else if (key === '--conf-dir') { cli.confDir = String(readValue() || '').trim(); } else if (key === '--upstream-include') { cli.upstreamInclude = String(readValue() || '').trim(); } else if (key === '--nginx-bin') { cli.nginxBin = String(readValue() || '').trim(); } else if (key === '--nginx-prefix') { cli.nginxPrefix = String(readValue() || '').trim(); } else if (key === '--reload-cmd') { cli.reloadCmd = String(readValue() || '').trim(); } else if (key === '--test-cmd') { cli.testCmd = String(readValue() || '').trim(); } else if (key === '--limit') { cli.limit = Number(readValue()); } else if (key === '--ver') { cli.ver = String(readValue() || '').trim(); } else { throw new Error(`未知参数: ${item}`); } } if (cli.help) { return { env: cli.env || String(process.env.CERT_SYNC_ENV || '').trim(), configPath: '', certDir: '', confDir: '', upstreamInclude: '', nginxBin: '', nginxPrefix: '', reloadCmd: '', testCmd: '', limit: DEFAULT_LIMIT, ver: cli.ver || String(process.env.CERT_SYNC_VER || '').trim() || DEFAULT_VER, dryRun: cli.dryRun, cleanupOnly: cli.cleanupOnly, skipNginx: cli.skipNginx, help: true, }; } const env = cli.env || String(process.env.CERT_SYNC_ENV || '').trim(); if (env !== 'development' && env !== 'production') { throw new Error('必须通过 --env 显式指定运行环境:development | production'); } // 外部配置文件作为默认值来源(优先级低于 CLI 参数与环境变量) const { configPath, config } = loadEnvConfig(env); // 优先级:CLI 参数 > 环境变量 > 外部配置文件 > 内置默认 const pickString = (cliValue, envName, configValue, fallback) => { const envValue = String(process.env[envName] || '').trim(); const configString = configValue === undefined || configValue === null ? '' : String(configValue).trim(); const value = cliValue || envValue || configString || fallback; return String(value).trim(); }; // confDir 统一解析为绝对路径(目录不存在时在运行阶段递归创建) const confDir = path.resolve(pickString(cli.confDir, 'CERT_SYNC_CONF_DIR', config.confDir, DEFAULT_CONF_DIR)); const args = { env, configPath, dryRun: cli.dryRun, cleanupOnly: cli.cleanupOnly, skipNginx: cli.skipNginx, help: false, certDir: path.resolve(pickString(cli.certDir, 'CERT_SYNC_CERT_DIR', config.certDir, DEFAULT_CERT_DIR)), confDir, upstreamInclude: pickString(cli.upstreamInclude, 'CERT_SYNC_UPSTREAM_INCLUDE', config.upstreamInclude, DEFAULT_UPSTREAM_INCLUDE), nginxBin: pickString(cli.nginxBin, 'CERT_SYNC_NGINX_BIN', config.nginxBin, DEFAULT_NGINX_BIN), nginxPrefix: pickString(cli.nginxPrefix, 'CERT_SYNC_NGINX_PREFIX', config.nginxPrefix, ''), reloadCmd: pickString(cli.reloadCmd, 'CERT_SYNC_RELOAD_CMD', config.reloadCmd, ''), testCmd: pickString(cli.testCmd, 'CERT_SYNC_TEST_CMD', config.testCmd, ''), limit: cli.limit !== null ? cli.limit : (Number(process.env.CERT_SYNC_LIMIT) || DEFAULT_LIMIT), ver: pickString(cli.ver, 'CERT_SYNC_VER', config.ver, DEFAULT_VER), }; if (!Number.isInteger(args.limit) || args.limit <= 0) { throw new Error(`--limit 必须是正整数,当前值: ${args.limit}`); } if (!args.upstreamInclude) { throw new Error('--upstream-include 不能为空'); } assertUpstreamIncludeUsable(args.upstreamInclude, args.dryRun); if (!args.nginxBin) { throw new Error('--nginx-bin 不能为空'); } if (!VER_PATTERN.test(args.ver)) { throw new Error(`--ver 非法: "${args.ver}"(必须匹配 ^[A-Za-z0-9][A-Za-z0-9._-]{0,31}$,禁止出现 / 或 .. 等路径片段)`); } return args; } /** * 站点内容片段(upstreamInclude)可用性前置校验:必须是「绝对路径」且文件存在。 * * 红线背景:nginx 解析 include 相对路径的基准是 nginx prefix(编译期 --prefix, * 宝塔构包为 /www/server/nginx/conf),**不是脚本 cwd(部署根)**。写相对路径会让 * 生成的 server 块 include 到不存在的文件 → nginx -t 失败 → 本轮写入与删除全部回滚 * (新写入的证书还会被孤儿清理当垃圾回收),该行被置 sync_status=2 后不再对账, * 现场表现为「脚本装了、目录却一直是空的」。因此在任何写盘 / 连库之前直接致命退出。 * @param {string} upstreamInclude 配置生效的 include 路径(已 trim)。 * @param {boolean} dryRun 是否 dry-run(不写盘、不改库,允许在看不到目标机器文件的场景下继续)。 * @return {void} * @throws {Error} 非绝对路径,或(非 dry-run 时)目标文件不存在时抛出异常。 */ function assertUpstreamIncludeUsable(upstreamInclude, dryRun) { // 绝对路径判定需跨平台:生产配置写的是 POSIX 绝对路径(/www/wwwroot/qimen/front.conf), // 在 Windows 开发机上用同一份配置做 dry-run 时 path.isAbsolute 会误判为 false, // 因此 POSIX / Windows 两种绝对路径形态都接受,只拦 "x.conf" / "./x.conf" / "../x"。 if (!path.posix.isAbsolute(upstreamInclude) && !path.win32.isAbsolute(upstreamInclude)) { throw new Error( `upstreamInclude 必须是绝对路径,当前值: "${upstreamInclude}"。` + 'nginx 解析相对 include 的基准是 nginx prefix(如 /www/server/nginx/conf),不是脚本 cwd,' + '相对路径会导致 nginx -t 失败并回滚整轮变更(生产建议绝对值 /www/wwwroot/qimen/front.conf)' ); } if (!fs.existsSync(upstreamInclude)) { const message = `upstreamInclude 指向的站点内容片段不存在: "${upstreamInclude}"。` + '请先创建该片段文件(root / 伪静态 或 反代),否则 nginx include 会 open() failed 让整轮 -t 失败'; if (dryRun) { console.warn(`[CERT-SYNC][WARN] ${message}(dry-run 继续;真实运行时将致命退出)`); return; } throw new Error(message); } } /** * 按 --env 显式设置数据库连接目标,覆盖终端残留的 NODE_ENV。 * WMS_DB_TARGET 优先级高于 NODE_ENV(database/config.js 约定), * 在 require database/config.js 之前调用本函数即可消除残留风险。 * @param {SyncArgs} args 解析后的参数集合。 * @return {void} */ function applyDbTarget(args) { const target = args.env === 'production' ? 'production' : 'development'; process.env.WMS_DB_TARGET = target; const residue = process.env.NODE_ENV; if (residue && String(residue).trim().toLowerCase() !== String(target).toLowerCase()) { console.warn(`[CERT-SYNC] 检测到终端残留 NODE_ENV=${residue},已由 --env=${args.env} 显式覆盖(WMS_DB_TARGET=${target})`); } } /** * 加载 database/config.js 并创建 Sequelize 实例。 * @param {SyncArgs} args 解析后的参数集合。 * @return {import('sequelize').Sequelize} Sequelize 实例。 * @throws {Error} 配置加载失败时抛出异常。 */ function connectDb(args) { const dbConfigAll = require(DB_CONFIG_PATH); const cfg = dbConfigAll[args.env] || dbConfigAll.production; if (!cfg || !cfg.host) { throw new Error('数据库配置解析失败,请检查 --env 与 config 文件'); } const sequelize = new Sequelize(cfg.database, cfg.username, cfg.password, { host: cfg.host, port: cfg.port, dialect: cfg.dialect || 'mysql', logging: false, define: cfg.define, pool: cfg.pool, }); console.log(`[CERT-SYNC] 数据库目标: ${args.env} -> ${cfg.host}:${cfg.port}/${cfg.database}`); return sequelize; } /** * 统一构造 nginx 命令执行描述(系统类型分支集中在唯一入口)。 * * 分支策略: * - 自定义命令(reloadCmd / testCmd 覆盖)非空:优先采用覆盖命令字符串, * 经 shell 执行(win32 由 cmd.exe 包装、POSIX 由 /bin/sh 包装), * 覆盖 systemctl 等非标准 reload 场景;{nginxBin} / {nginxPrefix} 占位符 * 替换时自动按平台加引号(win32 双引号、POSIX 单引号), * 避免路径被 shell 按空白/斜杠二次切分。 * - win32:nginx 二进制为 .cmd/.bat 批处理时不能被 spawnSync 直接执行, * 保持经 shell 包装整条命令(参数做引号转义)的执行方式。 * - linux / darwin / 其他 POSIX:spawnSync(nginxBin, args, shell=false) * 原样执行,避免 shell 注入与引号歧义。 * @param {string} nginxBin nginx 可执行文件路径。 * @param {string} nginxPrefix nginx -p 前缀目录(空串表示不启用,供 {nginxPrefix} 占位符使用)。 * @param {string[]} args nginx 参数数组(默认推导场景)。 * @param {string} overrideCommand 自定义覆盖命令(空串表示使用默认推导)。 * @return {NginxCommandDesc} 命令执行描述。 * @throws {Error} 自定义命令含 {nginxPrefix} 占位符但未提供 nginxPrefix 时抛出异常。 */ function buildNginxCommand(nginxBin, nginxPrefix, args, overrideCommand) { if (overrideCommand) { if (String(overrideCommand).includes('{nginxPrefix}') && !nginxPrefix) { throw new Error('自定义命令包含 {nginxPrefix} 占位符,但未配置 nginx prefix(--nginx-prefix / CERT_SYNC_NGINX_PREFIX / 配置文件 nginxPrefix)'); } // 占位符替换时自动按平台加引号,防止路径被 shell 按空白/斜杠二次切分 const quoteShellValue = value => (process.platform === 'win32' ? `"${String(value).replace(/"/g, '')}"` : `'${String(value).replace(/'/g, '')}'`); return { command: String(overrideCommand) .split('{nginxBin}') .join(quoteShellValue(nginxBin)) .split('{nginxPrefix}') .join(quoteShellValue(nginxPrefix)), args: [], shell: true, }; } const isWindowsBatch = process.platform === 'win32' && /\.(cmd|bat)$/i.test(nginxBin); if (isWindowsBatch) { const quote = value => `"${String(value).replace(/"/g, '')}"`; return { command: `${quote(nginxBin)} ${args.map(quote).join(' ')}`, args: [], shell: true, }; } return { command: nginxBin, args, shell: false, }; } /** * 执行 nginx 命令的底层 spawnSync 封装。 * 仅消费 buildNginxCommand 产出的执行描述,不做任何平台判断。 * @param {NginxCommandDesc} commandDesc nginx 命令执行描述。 * @return {import('node:child_process').SpawnSyncReturns} spawnSync 原始结果。 */ function spawnNginxRaw(commandDesc) { if (commandDesc.shell) { return spawnSync(commandDesc.command, { encoding: 'utf8', timeout: NGINX_CMD_TIMEOUT_MS, shell: true, }); } return spawnSync(commandDesc.command, commandDesc.args, { encoding: 'utf8', timeout: NGINX_CMD_TIMEOUT_MS, }); } /** * 探测 nginx 二进制是否可用(ENOENT 判定缺失)。 * @param {string} nginxBin nginx 可执行文件路径。 * @param {string} nginxPrefix nginx -p 前缀目录(空串表示不启用)。 * @return {boolean} 可用返回 true,缺失返回 false。 */ function nginxBinExists(nginxBin, nginxPrefix) { const result = spawnNginxRaw(buildNginxCommand(nginxBin, nginxPrefix, [ '-v' ], '')); return !(result.error && result.error.code === 'ENOENT'); } /** * 探测 wms_warehouse_front_config 是否已有 domain_status 列。 * * 域名验证闸门依赖该列;脚本部署早于迁移时该列不存在,需降级为不按验证状态过滤, * 保证脚本可在迁移前先行部署(与 app/service/systems/frontConfig.js 的降级策略一致)。 * @param {import('sequelize').Sequelize} sequelize Sequelize 实例。 * @return {Promise} 存在返回 true;探测失败返回 false。 */ async function hasDomainStatusColumn(sequelize) { try { const rows = await sequelize.query( `SELECT COUNT(*) AS c FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = ? AND column_name = 'domain_status'`, { replacements: [ TABLE_NAME ], type: Sequelize.QueryTypes.SELECT } ); return Number(rows && rows[0] && rows[0].c) > 0; } catch (error) { console.warn(`[CERT-SYNC] domain_status 列探测失败(按无该列降级): ${sanitizeErrorText(error.message)}`); return false; } } /** * 将域名清洗为安全的文件名片段(非法字符替换为下划线)。 * @param {string} input 原始域名。 * @return {string} 清洗后的片段,空结果返回 'unknown'。 */ function sanitizeFileNameSegment(input) { const cleaned = String(input || '').replace(/[^A-Za-z0-9._-]+/g, '_').replace(/^_+|_+$/g, ''); return cleaned || 'unknown'; } /** * 计算域名的 8 位短哈希(仅当域名被清洗后与原名不一致时用于防碰撞)。 * @param {string} domain 原始域名。 * @return {string} 8 位十六进制哈希。 */ function shortHash(domain) { return crypto.createHash('md5') .update(String(domain)) .digest('hex') .slice(0, 8); } /** * 域名命名推导(写盘与下线清理共用的唯一入口)。 * 命名规则:domain 做非法字符清洗得到 domainSafe;清洗后与原名不一致时 * 追加 _短哈希8 防不同域名清洗后碰撞(如 *.a.com 会被清洗为 .a.com)。 * @param {string} domainRaw 原始域名(已 trim)。 * @return {{domainSafe: string, suffix: string}} 命名片段(suffix 为空串或 _短哈希8)。 */ function computeDomainNameParts(domainRaw) { const domainSafe = sanitizeFileNameSegment(domainRaw); const changed = domainSafe !== domainRaw; return { domainSafe, suffix: changed ? `_${shortHash(domainRaw)}` : '', }; } /** * 推导域名对应的 server 块文件名({domainSafe}{suffix}-{ver}.conf,命名推导单点收敛)。 * 写入(buildFileNames)、过期 conf 清理、下线差集删除共用本推导, * 保证「按名删除」与「按名写入」严格一致。 * @param {string} domainRaw 原始域名(已 trim)。 * @param {string} ver conf 命名版本(已通过 VER_PATTERN 白名单校验)。 * @return {string} conf 文件名(不含目录)。 */ function buildConfFileName(domainRaw, ver) { const parts = computeDomainNameParts(domainRaw); return `${parts.domainSafe}${parts.suffix}-${ver}.conf`; } /** * 判定 conf 文件名是否能由该域名按命名规则推导(兼容无 ver 旧命名与 -ver 新命名)。 * 仅作「文件名 ↔ 域名」可回推闸门(过期 conf 清理 / 孤儿清理共用); * 是否过期由调用方叠加 buildConfFileName(domain, ver) 精确比较。 * 推导与写入同源(computeDomainNameParts),不做正则转义拼接。 * @param {string} fileName conf 文件名(不含目录)。 * @param {string} domainRaw 原始域名(已 trim)。 * @return {boolean} 可由该域名推导返回 true。 */ function isConfNameDerivableFromDomain(fileName, domainRaw) { const parts = computeDomainNameParts(domainRaw); const base = `${parts.domainSafe}${parts.suffix}`; if (fileName === `${base}.conf`) { return true; } if (fileName.startsWith(`${base}-`) && fileName.endsWith('.conf')) { const verPart = fileName.slice(base.length + 1, -'.conf'.length); return VER_PATTERN.test(verPart); } return false; } /** * 推导证书 / 私钥文件名前缀({store_id}_{domainSafe}{suffix})。 * @param {number|string} storeId 仓库 ID。 * @param {string} domainRaw 原始域名(已 trim)。 * @return {string} baseName(不含扩展名与目录)。 */ function buildCertBaseName(storeId, domainRaw) { const parts = computeDomainNameParts(domainRaw); return `${storeId}_${parts.domainSafe}${parts.suffix}`; } /** * 生成一条记录的文件名与落盘路径(命名推导见 computeDomainNameParts)。 * @param {SyncArgs} args 解析后的参数集合。 * @param {number} storeId 仓库 ID。 * @param {string} domainRaw 原始域名(已 trim)。 * @return {{baseName: string, certPath: string, keyPath: string, confPath: string}} 文件路径集合。 */ function buildFileNames(args, storeId, domainRaw) { const baseName = buildCertBaseName(storeId, domainRaw); return { baseName, certPath: path.join(args.certDir, `${baseName}.pem`), keyPath: path.join(args.certDir, `${baseName}.key`), confPath: path.join(args.confDir, buildConfFileName(domainRaw, args.ver)), }; } /** * 校验单条记录的 domain 与证书/私钥内容(不做加密学解析,仅做安全与形态校验)。 * @param {string} domainRaw 原始域名。 * @param {*} certPem 证书 PEM 内容。 * @param {*} keyPem 私钥 PEM 内容。 * @return {string|null} 校验失败返回错误描述,通过返回 null。 */ function validateRowContent(domainRaw, certPem, keyPem) { if (!domainRaw) { return 'domain 为空,无法生成文件名与 server 块'; } if (domainRaw.length > DOMAIN_MAX_LENGTH || !DOMAIN_PATTERN.test(domainRaw)) { return `domain 含非法字符或超长(${domainRaw.length} 字符)`; } const cert = String(certPem || '').trim(); const key = String(keyPem || '').trim(); if (!cert) { return 'cert_pem 内容为空'; } if (!key) { return 'cert_key 内容为空'; } if (!cert.includes(PEM_CERT_MARK)) { return `cert_pem 缺少 ${PEM_CERT_MARK} 标记,不是合法证书 PEM`; } if (!key.includes(PEM_KEY_MARK)) { return `cert_key 缺少 ${PEM_KEY_MARK} 标记,不是合法私钥 PEM`; } return null; } /** * 生成 server 块内容(证书骨架 + 一行 include ,不含任何 location)。 * 站点内容(root / 伪静态 或 反代)统一由 upstreamInclude 指向的片段文件提供, * 由运维维护、本脚本绝不覆盖;前端个性化在运行时由配置接口按域名完成, * nginx 侧无需按域名区分站点内容。 * @param {string} domain 域名(已通过白名单校验)。 * @param {string} certPath 证书文件绝对路径。 * @param {string} keyPath 私钥文件绝对路径。 * @param {string} upstreamInclude upstream 站点内容片段 include 路径(运维维护)。 * @return {string} server 块文本。 */ function buildServerConf(domain, certPath, keyPath, upstreamInclude) { return `server { listen 443 ssl; server_name ${domain}; ssl_certificate ${certPath}; ssl_certificate_key ${keyPath}; include ${upstreamInclude}; } `; } /** * 原子写文件:先写同目录临时文件(指定权限),rename 覆盖目标; * 失败时清理临时文件后抛出异常。 * @param {string} filePath 目标文件绝对路径。 * @param {string} content 文件内容。 * @param {number} mode 文件权限(八进制)。 * @return {void} * @throws {Error} 写文件失败时抛出异常。 */ function writeFileAtomic(filePath, content, mode) { const dir = path.dirname(filePath); const tmpPath = path.join(dir, `.${path.basename(filePath)}.tmp-${process.pid}-${Date.now()}`); try { fs.writeFileSync(tmpPath, content, { encoding: 'utf8', mode }); fs.chmodSync(tmpPath, mode); fs.renameSync(tmpPath, filePath); } catch (error) { try { fs.unlinkSync(tmpPath); } catch (cleanupError) { // 清理临时文件失败可忽略,不影响主错误 } throw error; } } /** * 静默删除文件(不存在时忽略)。 * @param {string} filePath 文件绝对路径。 * @return {void} */ function removeFileQuiet(filePath) { try { fs.unlinkSync(filePath); } catch (error) { if (error && error.code !== 'ENOENT') { console.warn(`[CERT-SYNC] 删除文件失败: ${filePath} - ${error.message}`); } } } /** * 执行 nginx 命令(同步,带超时),返回状态与输出。 * @param {NginxCommandDesc} commandDesc nginx 命令执行描述。 * @return {{ok: boolean, stdout: string, stderr: string}} 执行结果。 */ function runNginxCommand(commandDesc) { const result = spawnNginxRaw(commandDesc); const label = commandDesc.shell ? commandDesc.command : `${commandDesc.command} ${commandDesc.args.join(' ')}`; if (result.error) { return { ok: false, stdout: '', stderr: `${label} 执行失败: ${result.error.message}`, }; } return { ok: result.status === 0, stdout: String(result.stdout || ''), stderr: String(result.stderr || ''), }; } /** * 脱敏并截断错误文本:去掉 PEM 块内容、压缩空白、截断到列上限。 * @param {string} text 原始错误文本。 * @return {string} 脱敏截断后的文本(≤500 字符)。 */ function sanitizeErrorText(text) { return String(text || '') .replace(/-----BEGIN [^-]*-----[\s\S]*?-----END [^-]*-----/g, '[PEM 内容已省略]') .replace(/\s+/g, ' ') .trim() .slice(0, LAST_SYNC_ERROR_MAX_LENGTH); } async function markRowFailed(sequelize, row, message, priorStatus = 0) { await sequelize.query( `UPDATE ${TABLE_NAME} SET sync_status = 2, last_sync_error = :error, sync_attempts = sync_attempts + 1, cert_path = NULL, key_path = NULL, updated_at = NOW() WHERE id = :id AND sync_status = :priorStatus AND domain <=> :domain`, { replacements: { error: sanitizeErrorText(message), id: row.id, priorStatus, domain: row.domain, }, } ); } /** * nginx -t 校验失败(**全局环境级失败**)后对待同步条目的回写:保持 sync_status=0 * 待同步、只落 last_sync_error,下一轮自动重试,**绝不置 2**。 * 不递增 sync_attempts:本路径是自动重试(环境修好即自愈),递增会在长期异常下无上限增长。 * * 为什么与 markRowFailed 不同:-t 失败源于 nginx 主配置 / 站点片段 include / 目录 * 等全局问题,与单行证书数据无关,不应写成「行失败」——否则现场会看到「配置已修好、 * 行状态却仍为 2」的错位(脚本后来改为失败态也参与文件层收敛,已能兜底,但仍不该把 * 环境问题记成行失败)。 * 本轮文件已随 rollbackEntries 回滚删除,故同时清空 cert_path / key_path。 * WHERE 带 sync_status=0 与 domain(NULL-safe `<=>`)守卫,避免覆盖并发重新保存的结果。 * @param {import('sequelize').Sequelize} sequelize Sequelize 实例。 * @param {Object} row 记录对象(含 id、domain)。 * @param {string} message 失败原因。 * @return {Promise} 无返回值。 */ async function markRowTestRetry(sequelize, row, message) { await sequelize.query( `UPDATE ${TABLE_NAME} SET sync_status = 0, last_sync_error = :error, cert_path = NULL, key_path = NULL, updated_at = NOW() WHERE id = :id AND sync_status = 0 AND domain <=> :domain`, { replacements: { error: sanitizeErrorText(message), id: row.id, domain: row.domain, }, } ); } /** * nginx -t 校验失败后对自愈条目的回写:保持 sync_status=1(不降级、不置 2), * 只落 last_sync_error 供页面提示;下一轮内容仍不一致会自动重试自愈。 * @param {import('sequelize').Sequelize} sequelize Sequelize 实例。 * @param {Object} row 记录对象(含 id、domain)。 * @param {string} message 失败原因。 * @return {Promise} 无返回值。 */ async function markRowHealFailed(sequelize, row, message) { await sequelize.query( `UPDATE ${TABLE_NAME} SET last_sync_error = :error, updated_at = NOW() WHERE id = :id AND sync_status = 1 AND domain <=> :domain`, { replacements: { error: sanitizeErrorText(message), id: row.id, domain: row.domain, }, } ); } /** * 失败态(sync_status=2)恢复回写:本轮文件层已按库内容重建(或盘面已与库一致) * 且 nginx -t / reload 收口通过后调用——置 sync_status=1、回填 cert_path/key_path、 * last_synced_at=NOW()、清空 last_sync_error、sync_attempts 归零。 * WHERE 带 sync_status=2 与 domain(NULL-safe `<=>`)守卫, * 避免覆盖并发重新保存证书(应用侧会把状态改回 0)的结果。 * @param {import('sequelize').Sequelize} sequelize Sequelize 实例。 * @param {Object} row 记录对象(含 id、domain)。 * @param {string} certPath 证书文件绝对路径。 * @param {string} keyPath 私钥文件绝对路径。 * @return {Promise} 无返回值。 */ async function markRowRecovered(sequelize, row, certPath, keyPath) { await sequelize.query( `UPDATE ${TABLE_NAME} SET sync_status = 1, cert_path = :certPath, key_path = :keyPath, last_synced_at = NOW(), last_sync_error = NULL, sync_attempts = 0, updated_at = NOW() WHERE id = :id AND sync_status = 2 AND domain <=> :domain`, { replacements: { certPath, keyPath, id: row.id, domain: row.domain, }, } ); } /** * 失败态(sync_status=2)本轮全局校验(nginx -t / reload)未通过时的回写: * 保持 2、只更新 last_sync_error(不递增 attempts——下一轮仍会重新尝试收敛, * 环境修好即自动恢复,同属自动重试路径)。 * @param {import('sequelize').Sequelize} sequelize Sequelize 实例。 * @param {Object} row 记录对象(含 id、domain)。 * @param {string} message 失败原因。 * @return {Promise} 无返回值。 */ async function markRowRecoverRetry(sequelize, row, message) { await sequelize.query( `UPDATE ${TABLE_NAME} SET last_sync_error = :error, updated_at = NOW() WHERE id = :id AND sync_status = 2 AND domain <=> :domain`, { replacements: { error: sanitizeErrorText(message), id: row.id, domain: row.domain, }, } ); } /** * 「证书未配置」行的状态收敛:回写 sync_status=0(待同步)+ attempts 归零 + 清错误。 * 语义:证书还没上传不是失败,而是等下一次保存证书时再同步;不清空 cert_path/key_path * (无证书时本来就为空;由下线差集负责回收遗留文件)。 * WHERE 带 sync_status<>0 与 domain(NULL-safe `<=>`)守卫 + cert_pem 仍为空的复核, * 避免覆盖并发重新保存证书(应用侧会置 sync_status=0 并写入 PEM)的结果。 * @param {import('sequelize').Sequelize} sequelize Sequelize 实例。 * @param {Object} row 记录对象(含 id、domain)。 * @return {Promise} 无返回值。 */ async function markRowAwaitingCert(sequelize, row) { await sequelize.query( `UPDATE ${TABLE_NAME} SET sync_status = 0, sync_attempts = 0, last_sync_error = NULL, updated_at = NOW() WHERE id = :id AND domain <=> :domain AND sync_status <> 0 AND (cert_pem IS NULL OR cert_pem = '' OR cert_key IS NULL OR cert_key = '')`, { replacements: { id: row.id, domain: row.domain, }, } ); } /** * 回写单条成功状态:sync_status=1、回填 cert_path/key_path 实际全路径、 * last_synced_at=NOW()、last_sync_error 清空。 * WHERE 带 sync_status=0 与 domain 守卫,避免覆盖并发重新保存的结果。 * @param {import('sequelize').Sequelize} sequelize Sequelize 实例。 * @param {Object} row 记录对象(含 id、domain)。 * @param {string} certPath 证书文件绝对路径。 * @param {string} keyPath 私钥文件绝对路径。 * @return {Promise} 无返回值。 */ async function markRowSuccess(sequelize, row, certPath, keyPath) { await sequelize.query( `UPDATE ${TABLE_NAME} SET sync_status = 1, cert_path = :certPath, key_path = :keyPath, last_synced_at = NOW(), last_sync_error = NULL, updated_at = NOW() WHERE id = :id AND sync_status = 0 AND domain <=> :domain`, { replacements: { certPath, keyPath, id: row.id, domain: row.domain, }, } ); } /** * 回写自愈成功状态(保持 sync_status=1):last_synced_at=NOW()、last_sync_error 清空。 * WHERE 带 sync_status=1 与 domain 守卫(NULL-safe:`<=>`), * 避免覆盖并发重新保存(重新上传证书会把状态改回 0)的结果。 * @param {import('sequelize').Sequelize} sequelize Sequelize 实例。 * @param {Object} row 记录对象(含 id、domain)。 * @return {Promise} 无返回值。 */ async function markRowHealed(sequelize, row) { await sequelize.query( `UPDATE ${TABLE_NAME} SET last_synced_at = NOW(), last_sync_error = NULL, updated_at = NOW() WHERE id = :id AND sync_status = 1 AND domain <=> :domain`, { replacements: { id: row.id, domain: row.domain, }, } ); } /** * reload 失败后的重试回写:sync_attempts+1;未达重试上限时回退 * sync_status=0(下分钟自动重试),达到上限转 sync_status=2 终止重试。 * @param {import('sequelize').Sequelize} sequelize Sequelize 实例。 * @param {Object} row 记录对象(含 id、domain、sync_attempts)。 * @param {string} message 失败原因。 * @return {Promise} 回写后的同步状态(0 重试 / 2 终止)。 */ async function markRowReloadRetry(sequelize, row, message) { const attempts = Number(row.sync_attempts || 0) + 1; const nextStatus = attempts >= RELOAD_FAILURE_MAX_RETRY ? 2 : 0; await sequelize.query( `UPDATE ${TABLE_NAME} SET sync_status = :status, last_sync_error = :error, sync_attempts = sync_attempts + 1, updated_at = NOW() WHERE id = :id AND sync_status = 0 AND domain <=> :domain`, { replacements: { status: nextStatus, error: sanitizeErrorText(message), id: row.id, domain: row.domain, }, } ); return nextStatus; } /** * 声明式对账(期望集合逐行核对 → 缺失/不一致自愈)。 * * 处理规则(每行按 sync_status 分流,但**文件层对账对 0/1/2 一律生效**): * - sync_status=0(待同步):走既有同步路径,无条件写入证书 / 私钥 / server 块, * 成功后统一回写 markRowSuccess(保持原有回写语义); * - sync_status=1(已同步):逐文件对账(比较前统一 trimEnd),内容一致绝不重写; * 缺失 / 不一致 → 原子重写自愈([CERT-SYNC][HEAL] 前缀,计入 stats.healed), * 回写 markRowHealed(保持 sync_status=1 + last_synced_at=NOW() + 清空错误); * - sync_status=2(失败):**同样参与文件层对账**(缺失 / 不一致就重建,前缀 * [CERT-SYNC][RECOVER],计入 stats.recovered),本轮 nginx 校验通过后回写 * markRowRecovered(2 → 1,恢复同步态);盘面已与库一致时也收口为 1。 * 入参已由 loadDesiredRows 保证「域名形态合法 + PEM 就绪 + 每仓一条」,本函数不再做 * 内容预校验(无证书 / 证书 / 域名非法的行由 settleCertPendingRows 收敛状态); * 行级失败仅剩写盘失败 → markRowFailed(按原状态守卫); * 全局失败(nginx -t / reload)由 finalizeUnifiedCycle 统一降级重试,不置 2 卡死。 * 每次写入前登记该路径本轮开始前的原状态(recordPriorState),供 nginx -t 失败时回滚。 * @param {SyncContext} ctx 运行上下文。 * @param {Object[]} rows 期望集合记录数组。 * @param {SyncStats} stats 统计对象(就地累加)。 * @param {Array<{path: string, content: Buffer|null, mode: number}>} rollbackEntries 回滚素材集合(就地累加)。 * @return {Promise<{pendingSuccess: Array<{row: Object, names: Object}>, healedRows: Array<{row: Object, names: Object}>, recoveredRows: Array<{row: Object, names: Object}>, currentConfPaths: Set}>} 本批结果。 */ async function reconcileDesiredRows(ctx, rows, stats, rollbackEntries) { const { args } = ctx; const pendingSuccess = []; const healedRows = []; const recoveredRows = []; const currentConfPaths = new Set(); for (const row of rows) { const domainRaw = String(row.domain || '').trim(); const priorStatus = Number(row.sync_status); const rowLabel = `#${row.id} store=${row.store_id} domain=${domainRaw || '(空)'} status=${priorStatus}`; const names = buildFileNames(args, row.store_id, domainRaw); if (args.dryRun) { console.log(`[CERT-SYNC][PLAN] ${rowLabel}`); if (priorStatus === 0) { console.log(`[CERT-SYNC][PLAN] 待同步: cert_pem ${String(row.cert_pem || '').length} 字节 / cert_key ${String(row.cert_key || '').length} 字节 -> ${names.confPath}`); stats.success++; } else { const plan = []; if (!fileContentMatches(names.certPath, String(row.cert_pem || ''))) { plan.push('cert_pem'); } if (!fileContentMatches(names.keyPath, String(row.cert_key || ''))) { plan.push('cert_key'); } if (!fileContentMatches(names.confPath, buildServerConf(domainRaw, names.certPath, names.keyPath, args.upstreamInclude))) { plan.push('server 块'); } if (plan.length > 0) { console.log(`[CERT-SYNC][PLAN][${priorStatus === 2 ? 'RECOVER' : 'HEAL'}] 将自愈 ${plan.join('/')} -> ${names.confPath}`); if (priorStatus === 2) { stats.recovered++; } else { stats.healed++; } } else if (priorStatus === 2) { console.log('[CERT-SYNC][PLAN][RECOVER] 盘面与库一致,将收口恢复 sync_status=1(需一次 nginx -t/reload)'); stats.recovered++; } else { console.log('[CERT-SYNC][PLAN] 对账一致,不写入'); } } currentConfPaths.add(names.confPath); continue; } // 站点内容由 upstreamInclude 指向的片段文件提供(运维维护),本脚本不写、不校验该片段 if (priorStatus === 0) { // 待同步:既有同步路径,无条件写入(写前登记原状态供 nginx -t 失败回滚) try { recordPriorState(rollbackEntries, names.certPath); writeFileAtomic(names.certPath, String(row.cert_pem), CERT_FILE_MODE); recordPriorState(rollbackEntries, names.keyPath); writeFileAtomic(names.keyPath, String(row.cert_key), KEY_FILE_MODE); recordPriorState(rollbackEntries, names.confPath); writeFileAtomic(names.confPath, buildServerConf(domainRaw, names.certPath, names.keyPath, args.upstreamInclude), CERT_FILE_MODE); console.log(`[CERT-SYNC][OK] ${rowLabel} 文件与 server 块已写入`); pendingSuccess.push({ row, names }); currentConfPaths.add(names.confPath); stats.success++; } catch (error) { // 清理本条已落盘的文件(幂等:下次重试重新写入) removeFileQuiet(names.certPath); removeFileQuiet(names.keyPath); removeFileQuiet(names.confPath); const message = error && error.message ? error.message : String(error); console.error(`[CERT-SYNC][FAIL] ${rowLabel} - ${message}`); await markRowFailed(ctx.sequelize, row, message, priorStatus); stats.failed++; } continue; } // sync_status=1/2:对账 + 自愈(内容一致绝不重写,不改 mtime、不触发 reload; // 失败态 2 的写入日志前缀为 [RECOVER],成功后回写 markRowRecovered 恢复为已同步) const desiredConf = buildServerConf(domainRaw, names.certPath, names.keyPath, args.upstreamInclude); const heals = []; if (!fileContentMatches(names.certPath, String(row.cert_pem || ''))) { heals.push({ path: names.certPath, content: String(row.cert_pem), mode: CERT_FILE_MODE, kind: 'cert_pem' }); } if (!fileContentMatches(names.keyPath, String(row.cert_key || ''))) { heals.push({ path: names.keyPath, content: String(row.cert_key), mode: KEY_FILE_MODE, kind: 'cert_key' }); } if (!fileContentMatches(names.confPath, desiredConf)) { heals.push({ path: names.confPath, content: desiredConf, mode: CERT_FILE_MODE, kind: 'server 块' }); } if (heals.length === 0) { if (priorStatus === 2) { // 盘面已与库一致:上一轮失败残留的状态位,交给 finalize 做一次 nginx -t/reload 后收口为 1 console.log(`[CERT-SYNC][RECOVER] ${rowLabel} 盘面与库一致,待 nginx 校验通过后恢复 sync_status=1`); recoveredRows.push({ row, names }); currentConfPaths.add(names.confPath); stats.recovered++; } continue; } const localPrior = []; try { for (const heal of heals) { localPrior.push(capturePriorState(heal.path)); recordPriorState(rollbackEntries, heal.path); writeFileAtomic(heal.path, heal.content, heal.mode); console.log(`[CERT-SYNC][${priorStatus === 2 ? 'RECOVER' : 'HEAL'}] ${rowLabel} ${heal.kind} 缺失或内容不一致,已原子重写 -> ${heal.path}`); } if (priorStatus === 2) { recoveredRows.push({ row, names }); stats.recovered++; } else { healedRows.push({ row, names }); stats.healed++; } currentConfPaths.add(names.confPath); } catch (error) { // 恢复本条写入前的原状态(保持磁盘原状,避免半写),行转失败态等待人工处理 restorePriorStates(localPrior); const message = error && error.message ? error.message : String(error); console.error(`[CERT-SYNC][FAIL] ${rowLabel} 自愈写入失败 - ${message}`); await markRowFailed(ctx.sequelize, row, message, priorStatus); stats.failed++; } } return { pendingSuccess, healedRows, recoveredRows, currentConfPaths }; } // ===================================================================== // 域名下线(配置差集驱动)与孤儿清理 // // 模型(不需要两阶段切换的额外机制): // - 期望集合 = 库内**已配置且证书就绪**的行:domain 非空 + domain_status=1 + // cert_pem/cert_key 均为合法 PEM;每仓只取一条(同 store_id 多行按 id 最小者, // 其余行 WARN 后忽略 —— 保证每个仓库只生效一个域名)。 // - 下线 = 盘上有「本系统产物」但配置里没有该域名:confDir / certDir 中按命名白名单 // 识别出的 conf / 证书(见 cleanupOrphans 与 cleanupStaleConfs),其域名不在期望集合 // 内就删除 → 与自愈写入合并在同一轮,最多一次 nginx -t + reload。 // - 无证书 / 证书非法的行不写入、也不作为保留依据:其遗留 conf 与证书会被差集清掉 // (conf 引用不存在的证书会让 nginx -t 全局失败);无证书的行回写 sync_status=0 待同步。 // - 旧域名无需专门通道:域名提升后旧域名已不是该行的 domain,立刻落入差集被清理; // 库表 retired_domain / retired_at 仅作应用侧审计留痕,本脚本不读取、不写回。 // // 红线: // 1. 只允许删除 confDir / certDir 内的文件,删除前统一做目录前缀校验; // 2. 只允许删除「本系统按命名规则生成」的文件(白名单识别,见 cleanupOrphans); // 3. --dry-run 只打印待删清单,绝不删除文件、不写库、不 reload; // 4. 删除失败(权限等)不中断整轮,只计入统计并 WARN。 // ===================================================================== /** * 读取「期望集合」:库内已配置且证书就绪的行(每仓一条)。 * * 过滤与去重规则(写入 / 保留 / 保集合同源,避免「写了不保 / 保了不写」的错位): * 1. domain 非空且形态合法(白名单校验);domain_status 列存在时要求 domain_status=1 * (未验证域名不生成 server 块); * 2. cert_pem / cert_key 必须是合法 PEM(validateRowContent 通过)—— * 证书没配置就不写 conf,也不作为文件保留依据; * 3. 同一 store_id 只保留 id 最小的一条(每个仓库只生效一个域名),多余行计入 duplicates。 * 同时把「证书未就绪」的行分类返回,供调用方收敛行状态: * - awaitingCertRows:证书为空(未配置)→ 回写 sync_status=0 待同步; * - invalidCertRows:证书非空但非法、或域名形态非法 → 行级失败(markRowFailed)。 * @param {import('sequelize').Sequelize} sequelize Sequelize 实例。 * @param {boolean} domainStatusReady 是否存在 domain_status 列。 * @return {Promise<{rows: Object[], awaitingCertRows: Object[], invalidCertRows: Object[], duplicates: Array<{storeId: string, keptId: number, ignoredIds: number[]}>}>} 期望集合与分类结果。 */ async function loadDesiredRows(sequelize, domainStatusReady) { const verifiedFilter = domainStatusReady ? ' AND domain_status = 1' : ''; const records = await sequelize.query( `SELECT id, store_id, domain, cert_pem, cert_key, sync_status, sync_attempts FROM ${TABLE_NAME} WHERE domain IS NOT NULL AND domain <> ''${verifiedFilter} ORDER BY id ASC`, { type: Sequelize.QueryTypes.SELECT } ); const rows = []; const awaitingCertRows = []; const invalidCertRows = []; const duplicateEntries = []; const keptByStore = new Map(); for (const record of records || []) { const domainRaw = String(record.domain || '').trim(); if (!domainRaw || domainRaw.length > DOMAIN_MAX_LENGTH || !DOMAIN_PATTERN.test(domainRaw)) { invalidCertRows.push({ ...record, domain: domainRaw, reason: `域名形态非法: "${domainRaw}"` }); continue; } const validateError = validateRowContent(domainRaw, record.cert_pem, record.cert_key); if (validateError) { if (isCertBlank(record.cert_pem, record.cert_key)) { awaitingCertRows.push({ ...record, domain: domainRaw }); } else { invalidCertRows.push({ ...record, domain: domainRaw, reason: validateError }); } continue; } const storeKey = String(record.store_id); const kept = keptByStore.get(storeKey); if (kept) { kept.ignoredIds.push(record.id); continue; } const entry = { storeId: storeKey, keptId: record.id, ignoredIds: [] }; keptByStore.set(storeKey, entry); duplicateEntries.push(entry); rows.push({ ...record, domain: domainRaw }); } return { rows, awaitingCertRows, invalidCertRows, duplicates: duplicateEntries.filter(entry => entry.ignoredIds.length > 0), }; } /** * 判定证书字段是否「未配置」(NULL / 空串 / 纯空白)。 * 未配置与「配置了但内容非法」是两种状态:前者是正常待办(等上传),后者是行级失败。 * @param {*} certPem cert_pem 列值。 * @param {*} certKey cert_key 列值。 * @return {boolean} 未配置返回 true。 */ function isCertBlank(certPem, certKey) { const cert = String(certPem === null || certPem === undefined ? '' : certPem).trim(); const key = String(certKey === null || certKey === undefined ? '' : certKey).trim(); return cert === '' || key === ''; } /** * 收敛「证书未就绪」行的状态(在文件对账之前 / 之后均可,与文件变更无关): * - 证书未配置(awaitingCertRows)→ 回写 sync_status=0 待同步(上传证书后下一轮自动写入); * - 证书非法 / 域名非法(invalidCertRows)→ markRowFailed(sync_status=2 + 错误)。 * --dry-run 只打印计划,不写库。 * @param {SyncContext} ctx 运行上下文。 * @param {Object} desired loadDesiredRows 的返回值。 * @param {SyncStats} stats 统计对象(就地累加)。 * @return {Promise} 无返回值。 */ async function settleCertPendingRows(ctx, desired, stats) { const { args } = ctx; for (const row of desired.invalidCertRows) { const label = `#${row.id} store=${row.store_id} domain=${row.domain || '(空)'} status=${row.sync_status}`; if (args.dryRun) { console.log(`[CERT-SYNC][PLAN] ${label} 预校验: 将失败(${row.reason})`); stats.failed++; continue; } console.error(`[CERT-SYNC][FAIL] ${label} - ${row.reason}`); await markRowFailed(ctx.sequelize, row, row.reason, Number(row.sync_status)); stats.failed++; } for (const row of desired.awaitingCertRows) { if (Number(row.sync_status) === 0) { continue; } const label = `#${row.id} store=${row.store_id} domain=${row.domain}`; console.log(`[CERT-SYNC][PENDING] ${label} 未配置证书,回写 sync_status=0 待同步(上传证书后下一轮自动写入)`); if (!args.dryRun) { await markRowAwaitingCert(ctx.sequelize, row); } stats.awaitingCert++; } } /** * 生成去重台账的路径键:win32 下路径大小写不敏感(D:/ 与 d:/ 指向同一文件),统一小写, * 避免同一文件在去重台账里被算成两个文件。 * @param {string} filePath 文件绝对路径。 * @return {string} 去重键。 */ function cleanupPathKey(filePath) { const resolved = path.resolve(filePath); return process.platform === 'win32' ? resolved.toLowerCase() : resolved; } /** * 创建下线 / 清理统计对象(就地累加,供汇总打印与退出码判定使用)。 * * 两套口径不可混用: * - 通道命中数(orphanConfs/orphanCerts/staleConfs):按「谁动的手」累加, * 同一文件被两条通道各处理一次就计两次(dry-run 不落盘 → 会真实出现;真实运行不会); * - 去重后文件数(cleanedPaths.size):按绝对路径去重,是「本轮待删 / 已删文件数」的唯一权威口径。 * @return {Object} 统计对象。 */ function createCleanupStats() { return { orphanConfs: 0, // 孤儿通道命中的 conf 个数(不去重) orphanCerts: 0, // 孤儿通道命中的证书文件个数(不去重) staleConfs: 0, // 过期 conf 通道命中的 conf 个数(不去重) staleSkipped: 0, // 过期 conf 清理跳过数(闸门未命中 / 当前版本未就绪 / 超单轮上限) planned: 0, // dry-run 计划行数(含通道重复列出;去重后文件数见 cleanedPaths.size) cleanedPaths: new Map(), // 去重台账:路径键 → 首次列出/删除该路径的通道名(dry-run 与真实运行共用) duplicateListings: 0, // dry-run 下被第二条通道重复列表的次数(解释「通道命中数之和 > 去重数」) skippedOrphan: 0, // 孤儿清理跳过的文件数(白名单未命中 / 超单轮上限 / 不可判定) deleteFailed: 0, // 删除失败文件数(权限等,非致命) refusedPaths: 0, // 路径前缀校验拒绝数(红线护栏命中) cleanupFailed: 0, // 清理阶段失败计数(nginx -t 或 reload 失败,用于退出码) }; } /** * 格式化「去重后」口径摘要:`N 个文件(去重后;通道命中 orphan=X, staleConf=Y)`。 * * 去重后文件数取 cleanedPaths 规模;通道命中数之和大于 N 属于预期: * dry-run 不落盘,先列出的通道不会真的删掉文件,后一条通道仍会看到同一文件。 * @param {Object} stats 统计对象。 * @return {string} 摘要文本。 */ function formatCleanupDedupDetail(stats) { const orphanHits = stats.orphanConfs + stats.orphanCerts; return `${stats.cleanedPaths.size} 个文件(去重后;通道命中 orphan=${orphanHits}, staleConf=${stats.staleConfs})`; } /** * 路径前缀校验:解析后必须严格位于允许目录内(红线:禁止删除配置目录之外的路径)。 * win32 下 path.relative 不区分大小写,POSIX 下区分。 * @param {string} allowedDir 允许删除的目录(绝对路径)。 * @param {string} filePath 待删除文件路径。 * @return {boolean} 位于目录内返回 true。 */ function isPathInsideDir(allowedDir, filePath) { const rel = path.relative(path.resolve(allowedDir), path.resolve(filePath)); if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) { return false; } return true; } /** * 读取文本文件;不存在或不可读返回 null(调用方按「不可判定」处理,不删除)。 * @param {string} filePath 文件绝对路径。 * @return {string|null} 文件内容或 null。 */ function readTextFileOrNull(filePath) { try { return fs.readFileSync(filePath, 'utf8'); } catch (error) { if (error && error.code !== 'ENOENT') { console.warn(`[CERT-SYNC][WARN] 读取文件失败(按不可判定处理,不删除): ${filePath} - ${sanitizeErrorText(error.message)}`); } return null; } } /** * 判断磁盘文件内容是否与期望内容一致(比较前双方统一 trimEnd, * 库文本尾部换行差异不触发重写;文件缺失 / 不可读一律按不一致处理)。 * @param {string} filePath 文件绝对路径。 * @param {string} desiredContent 期望内容。 * @return {boolean} 一致返回 true,否则 false。 */ function fileContentMatches(filePath, desiredContent) { const current = readTextFileOrNull(filePath); if (current === null) { return false; } return current.trimEnd() === String(desiredContent || '').trimEnd(); } /** * 读取目录下的普通文件列表(目录不存在 / 不可读返回空数组并 WARN)。 * @param {string} dirPath 目录绝对路径。 * @return {Array<{name: string, fullPath: string}>} 文件列表。 */ function readDirSafe(dirPath) { let entries = []; try { entries = fs.readdirSync(dirPath, { withFileTypes: true }); } catch (error) { console.warn(`[CERT-SYNC][WARN] 目录不可读(本轮跳过该目录扫描): ${dirPath} - ${sanitizeErrorText(error.message)}`); return []; } const files = []; for (const entry of entries) { if (!entry.isFile()) { continue; } files.push({ name: entry.name, fullPath: path.join(dirPath, entry.name) }); } return files; } /** * 从 conf 内容解析首个 server_name 的域名。 * @param {string} content conf 文件内容。 * @return {string|null} 域名(去引号与空白),解析不到返回 null。 */ function parseServerName(content) { const matched = SERVER_NAME_PATTERN.exec(String(content || '')); if (!matched) { return null; } const firstToken = String(matched[1] || '').trim().split(/\s+/)[0] || ''; const domain = firstToken.replace(/^["']|["']$/g, '').trim(); return domain || null; } /** * 采集 conf 内容中引用的证书 / 私钥文件名前缀({store_id}_{domainSafe}{suffix})。 * 用于在「删除后的 conf 集合」上判定证书文件是否仍被引用。 * @param {string} content conf 文件内容。 * @param {Set} target 采集结果集合(就地累加)。 * @return {void} */ function collectCertBaseNames(content, target) { const pattern = /([A-Za-z0-9]+_[A-Za-z0-9._-]+?)\.(?:pem|key)/g; const text = String(content || ''); let matched = pattern.exec(text); while (matched) { target.add(matched[1]); matched = pattern.exec(text); } } /** * 受控删除(下线与孤儿清理的唯一删除入口)。 * * 行为约定: * 1. 目标必须位于 allowedDir 内(前缀校验),否则拒绝并 WARN(红线); * 2. dry-run 只打印 [PLAN] DELETE,绝不落盘; * 3. 文件不存在不算失败,只记 [SKIP] 日志; * 4. 删除前缓存文件内容,供本轮 nginx -t 失败时回滚(尽量恢复磁盘原状); * 5. 删除失败不抛异常,计入统计并 WARN,不中断整轮; * 6. 计划 / 删除成功的路径登记入去重台账(cleanedPaths),供汇总输出去重口径。 * @param {SyncContext} ctx 运行上下文。 * @param {string} allowedDir 允许删除的目录(confDir 或 certDir)。 * @param {string} filePath 目标文件绝对路径。 * @param {'orphan'|'staleConf'} reason 删除原因(审计日志用)。 * @param {Object} stats 统计对象(就地累加)。 * @param {Array<{path: string, content: Buffer|null, mode: number}>} rollbackEntries 回滚素材集合(就地累加)。 * @return {'deleted'|'planned'|'missing'|'refused'|'failed'} 处理结果。 */ function deleteFileGuarded(ctx, allowedDir, filePath, reason, stats, rollbackEntries) { if (!isPathInsideDir(allowedDir, filePath)) { console.warn(`[CERT-SYNC][WARN] 拒绝删除配置目录之外的路径: ${filePath}(原因=${reason},允许目录=${allowedDir})`); stats.refusedPaths++; return 'refused'; } let stat = null; try { stat = fs.statSync(filePath); } catch (error) { if (error && error.code === 'ENOENT') { console.log(`[CERT-SYNC][SKIP] 待删文件不存在: ${filePath} 原因=${reason}`); return 'missing'; } console.warn(`[CERT-SYNC][WARN] 读取待删文件属性失败: ${filePath} - ${sanitizeErrorText(error.message)}`); stats.deleteFailed++; return 'failed'; } if (!stat.isFile()) { console.warn(`[CERT-SYNC][WARN] 待删目标不是普通文件,已跳过: ${filePath}`); return 'missing'; } const dedupKey = cleanupPathKey(filePath); if (ctx.args.dryRun) { // dry-run 绝不落盘 → 同一路径可能被后一条通道再次列出: // 第二次列出时追加去重标注,避免运维按日志行数误判待删文件规模 const listedBy = stats.cleanedPaths.get(dedupKey); if (listedBy) { stats.duplicateListings++; console.log(`[CERT-SYNC][PLAN] DELETE ${filePath} 原因=${reason} [已由 ${listedBy} 通道列出,去重]`); } else { stats.cleanedPaths.set(dedupKey, reason); console.log(`[CERT-SYNC][PLAN] DELETE ${filePath} 原因=${reason}`); } stats.planned++; return 'planned'; } try { // 回滚素材:删除前登记本轮开始前的原状态(私钥内容只在内存中流转,绝不打印) recordPriorState(rollbackEntries, filePath); fs.unlinkSync(filePath); } catch (error) { console.warn(`[CERT-SYNC][WARN] 删除失败(不中断本轮): ${filePath} - ${sanitizeErrorText(error.message)}`); stats.deleteFailed++; return 'failed'; } // 去重台账只登记首次成功的删除(真实运行下第二条通道只会命中 [SKIP] 待删文件不存在) if (!stats.cleanedPaths.has(dedupKey)) { stats.cleanedPaths.set(dedupKey, reason); } console.log(`[CERT-SYNC] DELETE ${filePath} 原因=${reason}`); return 'deleted'; } /** * 采集文件当前内容与权限(登记「本轮开始前的原状态」;文件不存在时 content=null)。 * @param {string} filePath 文件绝对路径。 * @return {{path: string, content: Buffer|null, mode: number}} 原状态描述。 * @throws {Error} stat 失败(非 ENOENT)或读取失败时抛出异常。 */ function capturePriorState(filePath) { try { const stat = fs.statSync(filePath); // mode 只取低 9 位权限位(0o777),避免把文件类型位带进回滚写入 // eslint-disable-next-line no-bitwise return { path: filePath, content: fs.readFileSync(filePath), mode: stat.mode & 0o777 }; } catch (error) { if (error && error.code === 'ENOENT') { return { path: filePath, content: null, mode: 0 }; } throw error; } } /** * 向本轮回滚台账登记路径原状态(首见胜出:同一路径只保留本轮第一次采集的原状态)。 * 删除 / 写入前调用,保证 nginx -t 失败时能把磁盘恢复到本轮开始前的状态。 * @param {Array<{path: string, content: Buffer|null, mode: number}>} rollbackEntries 回滚素材集合(就地累加)。 * @param {string} filePath 文件绝对路径。 * @return {void} */ function recordPriorState(rollbackEntries, filePath) { const key = cleanupPathKey(filePath); for (const entry of rollbackEntries) { if (cleanupPathKey(entry.path) === key) { return; } } rollbackEntries.push(capturePriorState(filePath)); } /** * 恢复一组「写入前原状态」(单行自愈写入失败时回滚本行,不抛异常、不中断整轮)。 * 原状态为 null(文件原本不存在)时删除该文件,否则原子写回原内容与权限。 * @param {Array<{path: string, content: Buffer|null, mode: number}>} entries 原状态集合。 * @return {void} */ function restorePriorStates(entries) { for (const entry of entries) { try { if (entry.content === null || entry.content === undefined) { removeFileQuiet(entry.path); } else { writeFileAtomic(entry.path, entry.content, entry.mode); } } catch (error) { console.warn(`[CERT-SYNC][WARN] 本行回滚失败,需人工恢复: ${entry.path} - ${sanitizeErrorText(error.message)}`); } } } /** * 回滚本轮全部文件变更(nginx -t 失败时把磁盘恢复到本轮开始前的状态)。 * 台账内每条记录都是「本轮开始前」的原状态:原文件存在则原子写回, * content=null 表示原本不存在(本轮新写入),按删除回滚;同一路径首见胜出。 * @param {Array<{path: string, content: Buffer|null, mode: number}>} rollbackEntries 回滚素材集合。 * @return {number} 成功恢复(或回删)的文件数。 */ function rollbackFileChanges(rollbackEntries) { let restored = 0; const seen = new Set(); for (const entry of rollbackEntries) { const key = cleanupPathKey(entry.path); if (seen.has(key)) { continue; } seen.add(key); try { if (entry.content === null || entry.content === undefined) { removeFileQuiet(entry.path); } else { writeFileAtomic(entry.path, entry.content, entry.mode); } restored++; } catch (error) { console.error(`[CERT-SYNC][WARN] 回滚失败,需人工恢复: ${entry.path} - ${sanitizeErrorText(error.message)}`); } } return restored; } /** * 收集清理阶段的删除动作(配置差集驱动的域名下线 + 孤儿清理),不做 nginx -t / reload。 * nginx 校验与 reload 由 finalizeUnifiedCycle 统一收敛(每轮最多一次), * 避免一轮里「下线清理一次 reload、证书同步又一次 reload」。 * @param {SyncContext} ctx 运行上下文。 * @param {Object} cleanupCtx 清理上下文(stats / effectiveDomains / knownBaseNames / handledConfPaths / removedConfPaths / rollbackEntries)。 * @return {Promise} 无返回值。 */ async function runCleanup(ctx, cleanupCtx) { const { args } = ctx; const { effectiveDomains, knownBaseNames } = cleanupCtx; console.log(`[CERT-SYNC] 下线清理开始: 期望域名 ${effectiveDomains.size} 个(已配置且证书就绪), 库内证书命名 ${knownBaseNames.size} 个, dry-run=${args.dryRun}`); await cleanupOrphans(ctx, cleanupCtx); } /** * 过期 conf 清理(confDir 根层 *.conf;任何子目录一律不动,绝不递归)。 * * 「本系统产物」判定(保守,四道闸门全过才进入版本分流): * 1. 文件名形态命中 CONF_FILE_NAME_PATTERN; * 2. 内容可解析出 server_name ,且 domain 通过白名单校验; * 3. 文件名可由该 domain 按命名规则推导(isConfNameDerivableFromDomain, * 兼容无 ver 旧命名与 -ver 新命名); * 4. 内容含本系统固有标记(upstreamInclude)。 * 版本闸门:文件名必须等于 buildConfFileName(domain, args.ver): * - 相等且 domain 在生效集合 → 当前版本,保留(非生效域名的交给孤儿通道); * - 不等 → 过期(旧无后缀命名 / 旧 ver / 手工改成可推导形态),优先删除 * (deleteFileGuarded 通道名 staleConf,日志前缀 [CERT-SYNC][STALE], * 纳入 rollbackEntries 与 --dry-run 只打印)。 * 防断档:过期文件所属 domain 仍在生效集合时,必须先确认当前版本 conf 已存在 * (本轮对账已生成或磁盘已有),否则保留过期文件延后到下一轮(先写新、再删旧)。 * 单轮删除数量上限为 --limit,超出部分下一轮继续(cron 每分钟一次,可自然收敛)。 * @param {SyncContext} ctx 运行上下文。 * @param {Object} cleanupCtx 清理上下文(stats / effectiveDomains / handledConfPaths / removedConfPaths / rollbackEntries)。 * @param {Set} currentConfPaths 本轮已写入 / 计划写入的当前版本 conf 绝对路径集合。 * @return {Promise} 无返回值。 */ async function cleanupStaleConfs(ctx, cleanupCtx, currentConfPaths) { const { args } = ctx; const { stats, effectiveDomains, handledConfPaths, removedConfPaths, rollbackEntries } = cleanupCtx; let staleCount = 0; for (const entry of readDirSafe(args.confDir)) { if (!/\.conf$/i.test(entry.name)) { continue; } if (handledConfPaths.has(entry.fullPath)) { continue; } const content = readTextFileOrNull(entry.fullPath); if (content === null) { stats.staleSkipped++; continue; } if (!CONF_FILE_NAME_PATTERN.test(entry.name)) { stats.staleSkipped++; continue; } const domain = parseServerName(content); if (!domain || domain.length > DOMAIN_MAX_LENGTH || !DOMAIN_PATTERN.test(domain)) { stats.staleSkipped++; continue; } if (!isConfNameDerivableFromDomain(entry.name, domain)) { stats.staleSkipped++; continue; } if (!content.includes(args.upstreamInclude)) { stats.staleSkipped++; continue; } if (entry.name === buildConfFileName(domain, args.ver)) { // 当前版本命名:生效域名保留(孤儿通道负责非生效域名) continue; } // 过期命名:生效域名须先确认当前版本就绪,否则延后(先写新、再删旧,避免 443 断档) if (effectiveDomains.has(domain.toLowerCase())) { const currentPath = path.join(args.confDir, buildConfFileName(domain, args.ver)); const currentReady = currentConfPaths.has(currentPath) || fs.existsSync(currentPath); if (!currentReady) { console.warn(`[CERT-SYNC][STALE][WARN] ${entry.name}(domain=${domain})命名过期,但当前版本 conf 未就绪,保留待下一轮: ${entry.fullPath}`); stats.staleSkipped++; continue; } } if (staleCount >= args.limit) { stats.staleSkipped++; continue; } console.log(`[CERT-SYNC][STALE] 过期 conf 判定(命名不符合 ver=${args.ver}): ${entry.name}(domain=${domain})`); const result = deleteFileGuarded(ctx, args.confDir, entry.fullPath, 'staleConf', stats, rollbackEntries); handledConfPaths.add(entry.fullPath); if (result === 'deleted' || result === 'planned') { stats.staleConfs++; staleCount++; removedConfPaths.add(entry.fullPath); } } } /** * 统一 nginx 校验 + reload + 回写(每轮最多一次)。 * * 执行顺序(有变更时):nginx -t → reload(-t 通过且不 skip)→ 回写 DB: * - -t 失败:用 rollbackEntries 回滚本轮全部删除与写入(新写入的文件按删除回滚), * 待同步条目回退 sync_status=0(markRowTestRetry,下分钟自动重试)、自愈条目 * 保持 sync_status=1 只落错误(markRowHealFailed)、失败态恢复条目保持 2 只落错误 * (markRowRecoverRetry):-t 失败是全局环境问题,降级重试而非永久卡死; * - reload 失败:待同步条目按 markRowReloadRetry 回退重试(达上限转 2 终止), * 自愈条目磁盘内容与库一致(-t 已通过),按 markRowHealed 回写并告警; * - 成功(或 skip-nginx / nginx 缺失):待同步条目 markRowSuccess、自愈条目 * markRowHealed、失败态恢复条目 markRowRecovered(2 → 1)。 * @param {SyncContext} ctx 运行上下文。 * @param {Object} finalizeCtx 本轮结果集合。 * @param {Array<{row: Object, names: Object}>} finalizeCtx.pendingSuccess 待同步成功条目。 * @param {Array<{row: Object, names: Object}>} finalizeCtx.healedRows 自愈条目。 * @param {Array<{row: Object, names: Object}>} finalizeCtx.recoveredRows 失败态恢复条目。 * @param {Object} finalizeCtx.cleanupCtx 清理上下文。 * @param {SyncStats} finalizeCtx.syncStats 同步统计对象(就地累加)。 * @return {Promise} 无返回值。 */ async function finalizeUnifiedCycle(ctx, finalizeCtx) { const { args } = ctx; const { pendingSuccess, healedRows, recoveredRows, cleanupCtx, syncStats } = finalizeCtx; const { stats: cleanupStats, rollbackEntries } = cleanupCtx; const nginxEnabled = !args.skipNginx && !ctx.nginxMissing; if (nginxEnabled) { const testResult = runNginxCommand(ctx.testCommand); if (!testResult.ok) { const testError = sanitizeErrorText(testResult.stderr || testResult.stdout); console.error(`[CERT-SYNC][RELOAD-FAIL] 本轮变更后 nginx -t 失败: ${testError}`); const restored = rollbackFileChanges(rollbackEntries); if (rollbackEntries.length > 0) { const retest = runNginxCommand(ctx.testCommand); const retestTip = retest.ok ? '(回滚后 nginx -t 已恢复)' : `(回滚后 nginx -t 仍失败,请检查其它配置: ${sanitizeErrorText(retest.stderr || retest.stdout)})`; console.error(`[CERT-SYNC][RELOAD-FAIL] 已回滚 ${restored}/${rollbackEntries.length} 个文件${retestTip}`); } const failMessage = `nginx -t 校验失败: ${testError}`; for (const { row } of pendingSuccess) { await markRowTestRetry(ctx.sequelize, row, failMessage); console.error(`[CERT-SYNC][TEST-RETRY] #${row.id} 保持 sync_status=0(下分钟自动重试,修好 nginx 配置后自愈,无需人工重传证书)`); } for (const { row } of healedRows) { await markRowHealFailed(ctx.sequelize, row, failMessage); } for (const { row } of recoveredRows) { await markRowRecoverRetry(ctx.sequelize, row, failMessage); console.error(`[CERT-SYNC][RECOVER-RETRY] #${row.id} 保持 sync_status=2 等待下轮重试(nginx -t 未通过)`); } syncStats.failed += pendingSuccess.length + healedRows.length + recoveredRows.length; syncStats.success = Math.max(0, syncStats.success - pendingSuccess.length); syncStats.healed = Math.max(0, syncStats.healed - healedRows.length); syncStats.recovered = Math.max(0, syncStats.recovered - recoveredRows.length); cleanupStats.cleanupFailed++; return; } const reloadResult = runNginxCommand(ctx.reloadCommand); if (!reloadResult.ok) { const reloadError = sanitizeErrorText(reloadResult.stderr || reloadResult.stdout); console.error(`[CERT-SYNC][RELOAD-FAIL] nginx -s reload 失败: ${reloadError}`); for (const { row } of pendingSuccess) { const retriedStatus = await markRowReloadRetry(ctx.sequelize, row, `nginx reload 失败: ${reloadError}`); console.error(`[CERT-SYNC][RELOAD-RETRY] #${row.id} 回写 sync_status=${retriedStatus}(${retriedStatus === 0 ? '下分钟自动重试' : '已达重试上限,需人工介入'})`); } for (const { row } of healedRows) { await markRowHealed(ctx.sequelize, row); } for (const { row } of recoveredRows) { await markRowRecoverRetry(ctx.sequelize, row, `nginx reload 失败: ${reloadError}`); console.error(`[CERT-SYNC][RECOVER-RETRY] #${row.id} 保持 sync_status=2 等待下轮重试(nginx reload 未成功)`); } syncStats.failed += pendingSuccess.length + recoveredRows.length; syncStats.success = Math.max(0, syncStats.success - pendingSuccess.length); syncStats.recovered = Math.max(0, syncStats.recovered - recoveredRows.length); cleanupStats.cleanupFailed++; return; } console.log('[CERT-SYNC] nginx -t 通过 + nginx -s reload 成功'); } else { console.warn(`[CERT-SYNC] 已跳过 nginx -t / reload(${args.skipNginx ? '--skip-nginx' : '本机未检测到 nginx'}),文件变更已生效,回写继续`); } // 成功回写 for (const { row, names } of pendingSuccess) { await markRowSuccess(ctx.sequelize, row, names.certPath, names.keyPath); } for (const { row } of healedRows) { await markRowHealed(ctx.sequelize, row); } for (const { row, names } of recoveredRows) { await markRowRecovered(ctx.sequelize, row, names.certPath, names.keyPath); console.log(`[CERT-SYNC][RECOVERED] #${row.id} sync_status 2 -> 1(文件已按库内容收敛,证书与 server 块就绪)`); } } /** * 打印下线 / 清理统计(dry-run 时以待删口径输出)。 * @param {Object} stats 统计对象。 * @param {SyncArgs} args 参数集合。 * @return {void} */ function printCleanupSummary(stats, args) { const prefix = args.dryRun ? '[CERT-SYNC][PLAN] ' : '[CERT-SYNC] '; const verb = args.dryRun ? '待删除' : '删除'; console.log(`${prefix}下线差集清理(配置里没有该域名 → 删产物): ${verb} conf ${stats.orphanConfs} 个, 证书文件 ${stats.orphanCerts} 个, 白名单未命中/超上限跳过 ${stats.skippedOrphan} 个`); console.log(`${prefix}过期 conf 清理: ${verb} ${stats.staleConfs} 个, 跳过/延后 ${stats.staleSkipped} 个(只扫根层 *.conf,绝不递归子目录)`); console.log(`${prefix}下线清理汇总: ${verb} ${formatCleanupDedupDetail(stats)}(其中通道重复列出 ${stats.duplicateListings} 行), 删除失败 ${stats.deleteFailed} 个, 路径越界拒绝 ${stats.refusedPaths} 个, 清理阶段失败 ${stats.cleanupFailed}`); } /** * 判定清理阶段是否存在需要告警的失败(统一退出码口径:删除失败 / 路径越界 / -t 或 reload 失败)。 * @param {Object} stats 清理统计对象。 * @return {boolean} 存在失败返回 true。 */ function hasCleanupFailure(stats) { return stats.deleteFailed > 0 || stats.refusedPaths > 0 || stats.cleanupFailed > 0; } /** * 下线差集清理:以库内「期望集合」(已配置 + 证书就绪 + 每仓一条)为唯一基准, * 把 confDir / certDir 中「本系统生成但配置里已没有该域名」的产物删掉。 * * conf 白名单识别(全部命中才认为是本系统生成、才允许删除): * 1. 文件名形态命中 CONF_FILE_NAME_PATTERN({domainSafe}{[_短哈希8]}{[-]}.conf); * 2. 文件内容包含本系统固有标记(upstreamInclude 路径字符串); * 3. 文件内容可解析出 server_name ,domain 通过域名白名单校验, * 且文件名可由该 domain 按命名规则推导(isConfNameDerivableFromDomain, * 兼容无 ver 旧命名与 -ver 新命名;无 ver 旧命名还由过期 conf 清理负责)。 * 未命中的文件一律不动(他人手工 conf、宝塔自身文件等),只计入跳过统计; * 扫描范围仅 confDir 根层普通文件(readDirSafe 按 entry.isFile() 过滤), * 子目录不会进入待删集合,绝不递归清理。 * 命中白名单且 domain 不在生效集合内(按小写比较)→ 列入待删。 * * 证书 / 私钥文件:仅处理文件名严格命中 CERT_FILE_NAME_PATTERN 的,且需同时满足 * - 在「删除后的 conf 集合」上不被任何存活 conf 引用(引用判定覆盖全部 conf, * 含未通过白名单的文件,避免删掉他人 conf 仍在使用的证书); * - 不是库内任意一行 (store_id, domain) 的命名推导产物(可能只是 conf 尚未写出)。 * 存在不可读 conf 时本轮整体跳过证书清理(无法证明「未被引用」,宁可不删)。 * * 单轮删除数量上限为 --limit,超出部分下一轮继续(cron 每分钟一次,可自然收敛)。 * @param {SyncContext} ctx 运行上下文。 * @param {Object} cleanupCtx 清理上下文(stats / effectiveDomains / knownBaseNames / handledConfPaths / rollbackEntries)。 * @return {Promise} 无返回值。 */ async function cleanupOrphans(ctx, cleanupCtx) { const { args } = ctx; const { stats, effectiveDomains, knownBaseNames, handledConfPaths, removedConfPaths, rollbackEntries } = cleanupCtx; // ---------- 第一遍:conf 目录扫描 + 白名单判定 ---------- // 只扫根层:readDirSafe 以 withFileTypes + entry.isFile() 过滤, // 子目录不会进入待删集合,孤儿清理绝不递归到子目录。 const confEntries = readDirSafe(args.confDir); const confContents = new Map(); const orphanConfs = []; let unreadableConf = false; for (const entry of confEntries) { if (!/\.conf$/i.test(entry.name)) { continue; } if (handledConfPaths.has(entry.fullPath)) { continue; } const content = readTextFileOrNull(entry.fullPath); if (content === null) { unreadableConf = true; continue; } confContents.set(entry.fullPath, content); if (!CONF_FILE_NAME_PATTERN.test(entry.name)) { stats.skippedOrphan++; continue; } const domain = parseServerName(content); if (!domain || domain.length > DOMAIN_MAX_LENGTH || !DOMAIN_PATTERN.test(domain)) { stats.skippedOrphan++; continue; } if (!isConfNameDerivableFromDomain(entry.name, domain)) { stats.skippedOrphan++; continue; } // 固有标记判定:内容必须包含 upstreamInclude(本系统模板的唯一固有标记) if (!content.includes(args.upstreamInclude)) { stats.skippedOrphan++; continue; } if (effectiveDomains.has(domain.toLowerCase())) { continue; } if (orphanConfs.length >= args.limit) { stats.skippedOrphan++; continue; } orphanConfs.push({ fullPath: entry.fullPath, domain }); } // ---------- 第二遍:删除孤儿 conf ---------- for (const item of orphanConfs) { const result = deleteFileGuarded(ctx, args.confDir, item.fullPath, 'orphan', stats, rollbackEntries); handledConfPaths.add(item.fullPath); if (result === 'deleted' || result === 'planned') { stats.orphanConfs++; removedConfPaths.add(item.fullPath); } } // ---------- 第三遍:证书引用判定(在删除后的 conf 集合上判断) ---------- if (unreadableConf) { console.warn('[CERT-SYNC][WARN] conf 目录存在不可读文件,无法证明证书未被引用,本轮跳过证书孤儿清理'); stats.skippedOrphan++; return; } const referencedBaseNames = new Set(); for (const entry of confEntries) { if (!/\.conf$/i.test(entry.name)) { continue; } if (removedConfPaths.has(entry.fullPath) || !fs.existsSync(entry.fullPath)) { continue; } const content = confContents.has(entry.fullPath) ? confContents.get(entry.fullPath) : readTextFileOrNull(entry.fullPath); if (content === null) { continue; } collectCertBaseNames(content, referencedBaseNames); } // ---------- 第四遍:证书 / 私钥文件差集删除 ---------- let orphanCertCount = 0; for (const entry of readDirSafe(args.certDir)) { if (!CERT_FILE_NAME_PATTERN.test(entry.name)) { continue; } const baseName = entry.name.replace(/\.(pem|key)$/i, ''); if (referencedBaseNames.has(baseName)) { continue; } if (knownBaseNames.has(baseName)) { continue; } if (orphanCertCount >= args.limit) { stats.skippedOrphan++; continue; } const result = deleteFileGuarded(ctx, args.certDir, entry.fullPath, 'orphan', stats, rollbackEntries); if (result === 'deleted' || result === 'planned') { stats.orphanCerts++; orphanCertCount++; } } } /** * 主流程:解析参数(含 ver 校验)→ 连接数据库 → 期望集合对账自愈 → * 清理(下线 / 孤儿 / 过期 conf)→ 统一 nginx -t + reload(有变更时最多一次)→ 回写状态。 * @return {Promise} 无返回值,通过 process.exitCode 表达执行结果。 */ async function main() { const args = parseArgs(process.argv.slice(2)); if (args.help) { printUsage(); return; } console.log(`[CERT-SYNC] 开始: env=${args.env} dry-run=${args.dryRun} cleanup-only=${args.cleanupOnly} skip-nginx=${args.skipNginx} limit=${args.limit} ver=${args.ver}`); console.log(`[CERT-SYNC] conf 命名: -.conf(ver=${args.ver},示例 web.wms.gztbyc.com-${args.ver}.conf;suffix 仅当清洗后与原域名不一致时出现)`); console.log(`[CERT-SYNC] 外部配置文件: ${args.configPath}`); console.log(`[CERT-SYNC] 证书目录: ${args.certDir}`); console.log(`[CERT-SYNC] server 块目录: ${args.confDir}`); console.log(`[CERT-SYNC] upstream include: ${args.upstreamInclude}`); console.log(`[CERT-SYNC] nginx 二进制: ${args.nginxBin}`); if (args.nginxPrefix) { console.log(`[CERT-SYNC] nginx -p 前缀: ${args.nginxPrefix}`); } applyDbTarget(args); const testCommand = buildNginxCommand(args.nginxBin, args.nginxPrefix, [ '-t' ], args.testCmd); const reloadCommand = buildNginxCommand(args.nginxBin, args.nginxPrefix, [ '-s', 'reload' ], args.reloadCmd); const commandLabel = desc => (desc.shell ? desc.command : `${desc.command} ${desc.args.join(' ')}`); console.log(`[CERT-SYNC] nginx -t 命令: ${commandLabel(testCommand)}(${args.testCmd ? '自定义命令' : '按系统类型推导'})`); console.log(`[CERT-SYNC] nginx reload 命令: ${commandLabel(reloadCommand)}(${args.reloadCmd ? '自定义命令' : '按系统类型推导'})`); const sequelize = connectDb(args); const ctx = { args, sequelize, nginxMissing: false, testCommand, reloadCommand }; try { try { await sequelize.authenticate(); } catch (error) { throw new Error(`数据库连接失败: ${error.message}`); } // 目录准备:不存在则递归创建(创建失败视为致命错误,避免逐条全部失败) try { fs.mkdirSync(args.certDir, { recursive: true }); fs.mkdirSync(args.confDir, { recursive: true }); } catch (error) { throw new Error(`目录创建失败: ${error.message}`); } // nginx 可用性探测:生产环境缺失视为致命;开发环境缺失自动降级为跳过 if (!args.skipNginx && !nginxBinExists(args.nginxBin, args.nginxPrefix)) { if (args.env === 'development') { console.warn(`[CERT-SYNC] 开发环境未检测到 nginx(${args.nginxBin}),自动跳过 nginx -t / reload`); ctx.nginxMissing = true; } else { throw new Error(`nginx 二进制不可用: ${args.nginxBin}(生产环境必须可用,或显式 --skip-nginx)`); } } // 域名验证闸门:迁移尚未执行(无 domain_status 列)时降级为不按验证状态过滤, // 保证脚本可先行部署;迁移执行后自动生效 const domainStatusReady = await hasDomainStatusColumn(sequelize); if (!domainStatusReady) { console.warn('[CERT-SYNC] 未检测到 wms_warehouse_front_config.domain_status 列(迁移尚未执行),本轮降级为不按域名验证状态过滤'); } // 清理上下文(下线 / 孤儿 / 过期 conf 共用):删除与写入统一登记 rollbackEntries, // 供 nginx -t 失败时一次性回滚;nginx -t / reload 由 finalizeUnifiedCycle 统一收敛(每轮最多一次) const cleanupStats = createCleanupStats(); // 期望集合:库内「已配置且证书就绪」的行(每仓只取一条)。 // 同一个集合同时充当写入集合与下线差集的保留集合,避免「写了不保 / 保了不写」的错位 const desired = await loadDesiredRows(sequelize, domainStatusReady); for (const dup of desired.duplicates) { console.warn(`[CERT-SYNC][WARN] 仓库 ${dup.storeId} 配置了多个域名:保留 id=${dup.keptId},忽略 id=${dup.ignoredIds.join('/')}(每个仓库只生效一个域名,请清理多余行)`); } const effectiveDomains = new Set(desired.rows.map(row => String(row.domain).trim().toLowerCase())); const knownBaseNames = new Set(desired.rows.map(row => buildCertBaseName(row.store_id, String(row.domain).trim()))); const rollbackEntries = []; const handledConfPaths = new Set(); const removedConfPaths = new Set(); const cleanupCtx = { stats: cleanupStats, effectiveDomains, knownBaseNames, handledConfPaths, removedConfPaths, rollbackEntries }; // 阶段 1:配置差集驱动的下线清理(配置里没有该域名 → 删其 conf / 证书;只收集删除动作,不做 nginx) await runCleanup(ctx, cleanupCtx); const syncStats = { total: 0, success: 0, failed: 0, healed: 0, recovered: 0, awaitingCert: 0, invalidCert: 0 }; let pendingSuccess = []; let healedRows = []; let recoveredRows = []; let currentConfPaths = new Set(); if (args.cleanupOnly) { // --cleanup-only:只做清理,不做证书同步 / 对账自愈(过期 conf 清理仍执行, // 当前版本就绪判定退化为磁盘存在性检查) console.log('[CERT-SYNC] --cleanup-only:跳过期望集合对账自愈'); await cleanupStaleConfs(ctx, cleanupCtx, currentConfPaths); } else { // 阶段 2:期望集合对账自愈(先写新,保证过期 conf 清理时当前版本已就绪) const rows = desired.rows.slice(0, args.limit); syncStats.total = rows.length; const batch = await reconcileDesiredRows(ctx, rows, syncStats, rollbackEntries); pendingSuccess = batch.pendingSuccess; healedRows = batch.healedRows; recoveredRows = batch.recoveredRows; currentConfPaths = batch.currentConfPaths; // 阶段 3:过期 conf 清理(confDir 根层;子目录不动) await cleanupStaleConfs(ctx, cleanupCtx, currentConfPaths); // 阶段 4:无证书 / 证书非法的行收敛状态(与文件变更无关) await settleCertPendingRows(ctx, desired, syncStats); } // 有文件写入/删除,或存在「盘面已一致、只缺状态收口」的失败态恢复条,就需走 nginx -t/reload const hadMutations = rollbackEntries.length > 0 || recoveredRows.length > 0; if (args.dryRun) { printCleanupSummary(cleanupStats, args); console.log(`[CERT-SYNC][SUMMARY] dry-run 完成: total=${syncStats.total} 可成功=${syncStats.success} 将失败=${syncStats.failed} 将自愈=${syncStats.healed} 将恢复失败态=${syncStats.recovered} 未配置证书=${syncStats.awaitingCert} 证书/域名非法=${syncStats.invalidCert} 将删过期 conf=${cleanupStats.staleConfs}(延后 ${cleanupStats.staleSkipped} 个)`); console.log('[CERT-SYNC][PLAN] dry-run:不写文件、不改库、不删文件、不执行 nginx -t / reload'); return; } if (!hadMutations) { console.log('[CERT-SYNC] 本轮无文件变更(对账一致 / 无待处理),静默退出'); if (syncStats.awaitingCert > 0) { console.log(`[CERT-SYNC] ${syncStats.awaitingCert} 条已配置域名等待上传证书(sync_status=0,上传后下一轮自动写入)`); } if (syncStats.failed > 0 || hasCleanupFailure(cleanupStats)) { process.exitCode = EXIT_BUSINESS_FAILURE; } return; } await finalizeUnifiedCycle(ctx, { pendingSuccess, healedRows, recoveredRows, cleanupCtx, syncStats }); printCleanupSummary(cleanupStats, args); console.log(`[CERT-SYNC][SUMMARY] total=${syncStats.total} success=${syncStats.success} failed=${syncStats.failed} healed=${syncStats.healed} recovered=${syncStats.recovered} awaitingCert=${syncStats.awaitingCert} invalidCert=${syncStats.invalidCert} staleRemoved=${cleanupStats.staleConfs}`); if (syncStats.failed > 0 || hasCleanupFailure(cleanupStats)) { process.exitCode = EXIT_BUSINESS_FAILURE; } else { process.exitCode = EXIT_OK; } } finally { await sequelize.close(); } } // 顶层错误兜底:致命错误退出码 1(cron 可据 1/2 区分告警级别) main().catch(error => { console.error(`[CERT-SYNC][FATAL] ${error && error.message ? error.message : String(error)}`); process.exitCode = EXIT_FATAL; });