From 0918f2d572c1d8ffe22b714bdfadfcb0ae846a2a Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 28 Sep 2026 01:02:23 +0800 Subject: [PATCH] =?UTF-8?q?feat(deploy):=20=E8=AF=81=E4=B9=A6=E5=90=8C?= =?UTF-8?q?=E6=AD=A5=E6=94=B9=E4=B8=BA=E5=8D=95=E7=89=87=E6=AE=B5=20includ?= =?UTF-8?q?e=20+=20ver=20=E5=91=BD=E5=90=8D=20+=20=E5=A3=B0=E6=98=8E?= =?UTF-8?q?=E5=BC=8F=E8=87=AA=E6=84=88=E4=B8=8E=E5=B7=AE=E9=9B=86=E4=B8=8B?= =?UTF-8?q?=E7=BA=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 站点内容外置为单一片段(upstreamInclude,运维维护):生成的 server 块 = 证书骨架 + 一行 include <片段>,撤掉此前的 customDir 多片段方案;并强制 include 必须是绝对路径 且文件已存在(nginx 解析相对 include 的基准是 nginx prefix,不是脚本 cwd,写相对路径 会让 nginx -t 失败并回滚整轮变更),不满足直接 exit 1(dry-run 下仅告警) - conf 命名加版本位 -.conf:轮转只改配置的 ver,旧命名自动清理并 reload - 声明式对账自愈:证书 / 私钥 / server 块缺失或被改坏,按库内内容原子重建后统一 nginx -t + reload(内容一致时零写入、零 reload);失败态(sync_status=2)同样参与 收敛并在校验通过后回到 1;nginx -t / reload 属全局失败,只落 last_sync_error 下轮 重试,不再把行写成 2 卡死 - 域名下线改为配置差集驱动:以「已配置 + 已验证 + 证书就绪」的期望集合为准(同一仓库 只取 id 最小的一条),目录中属于本系统命名规则但配置里已无该域名的 conf / 证书直接 删除并 reload;不再消费 retired_domain(该列仅作应用侧审计留痕) - 证书未配置的行不写 conf 也不作为文件保留依据(遗留产物由差集回收,避免 conf 引用 不存在的证书导致 nginx -t 全局失败),行状态回写 sync_status=0 待同步;证书非空但 非法、域名形态非法才记行级失败(2) - cert-sync 部署命令瘦身为 install / uninstall;新增 watchdog 部署命令(precheck / install / status / dry-run / run),安装路径统一到 script/;deploy-lib 保护生产运行时 配置不被发布覆盖;README 补「发布与运维」章节(目录硬约定 / 定时任务 / 命令清单) --- README.md | 69 + package.json | 13 +- script/deploy-cert-sync.cjs | 526 +++--- script/deploy-lib.cjs | 10 +- script/deploy-watchdog.cjs | 292 ++++ script/qimen-watchdog.sh | 8 +- script/warehouse-cert-sync.cjs | 1605 +++++++++++-------- script/warehouse-cert-sync.config.dev.json | 3 +- script/warehouse-cert-sync.config.prod.json | 9 +- 9 files changed, 1652 insertions(+), 883 deletions(-) create mode 100644 script/deploy-watchdog.cjs diff --git a/README.md b/README.md index 2ecfed1..e823b09 100644 --- a/README.md +++ b/README.md @@ -123,6 +123,75 @@ npm run doc:api:update -- --spec=temp/api-doc-update.json --dry-run - 数据库、Redis、平台配置在对应配置文件中维护 - 敏感信息不要提交到仓库 +## 发布与运维(deploy / 证书同步 / 看门狗) + +### 部署根布局(生产 `deployRoot` 默认 `/www/wwwroot/qimen`) + +```text +/ +├── current.md # 当前活跃版本(v1 | v2) +├── nginx-upstream.conf # 发布时改写:proxy_pass 指向活跃版本端口(v1:6061 / v2:6062) +├── front.conf # 站点内容片段(root / 伪静态),运维维护、脚本绝不覆盖 +├── .ssl/ # 证书目录(cron 写入 {store_id}_{domain}.pem|.key,私钥 0600) +├── nginx_config/ # nginx server 块目录(cron 写入 {domain}-.conf,如 web.wms.gztbyc.com-1.conf) +├── script/ +│ ├── warehouse-cert-sync.sh # 证书同步薄包装(cron 每分钟入口) +│ ├── warehouse-cert-sync.cjs # 证书同步主脚本(读库→写证书/conf→nginx -t+reload→回写状态) +│ ├── warehouse-cert-sync.config.prod.json # 生产运行时配置(服务器自管:仅首次放置,永不覆盖) +│ └── qimen-watchdog.sh # 接口服务看门狗(/etc/cron.d 每 5 分钟) +├── database/config.js # 上述脚本自用的 DB 配置(install 时上传) +├── .deploy/ # 发布状态 / 暂存 / 备份 +└── v1/ v2/ # 版本实例目录(发布与回退只清理这里) +``` + +### 目录约定(**硬约定**:只随 `deployRoot` 变,不随版本切换变) + +| 用途 | 路径 | 配置来源 | +|------|------|----------| +| 证书 | `/.ssl` | `script/warehouse-cert-sync.config.prod.json` → `"certDir": "./.ssl"`(开发 `D:/wms/.ssl`) | +| nginx server 块 | `/nginx_config` | 同上 → `"confDir": "./nginx_config"`(开发 `D:/wms/nginx_config`) | +| 站点内容片段 | `upstreamInclude` 指向的片段文件(生产 `/front.conf`) | 同上 → `"upstreamInclude"`(**绝对路径**,**运维维护**) | + +- 相对路径按 **cwd=部署根** 解析(薄包装先 `cd `),目录不存在时脚本自动递归创建。 +- 这两个目录都在**部署根一级**(非版本目录):发布/回退只清理 `v1|v2`,不会触碰它们。 +- **server 块命名含 `-`**:文件名为 `-.conf`(suffix 仅当域名清洗后与原名不一致时出现),版本键 `ver` 在运行时配置里(`"ver": "1"`),可用 CLI `--ver` / 环境变量 `CERT_SYNC_VER` 临时覆盖;nginx 主配置 `include /nginx_config/*.conf;` 与新命名兼容,无需改 nginx。 +- **每轮声明式对账 + 自愈**:cron 每分钟把库内「期望集合」(domain 非空且已验证)逐行与磁盘核对,证书 / 私钥 / server 块缺失、被改坏或**命名过期**(旧的无后缀命名、旧 `-`、手工改名)都会自动重建 / 清理后 reload;内容一致时零写入、零 reload。不再只依赖后台“重新上传证书”触发同步。 +- **失败态(`sync_status=2`)同样收敛,不是「终态豁免」**:失败行也参与文件层对账——盘上证书 / 私钥 / server 块缺失或与库不一致就按库内容重建,本轮 `nginx -t`/reload 通过后自动回写 `sync_status=1`(日志 `[RECOVER]` / `[RECOVERED]`)。所以「手工删掉 `.ssl`、`nginx_config`」「早期遗留的失败行」都能自动恢复,**无需人工重传证书**。唯一需要人工的情形:库内 `cert_pem`/`cert_key` 为空或非法(无内容可写,日志 `[BLOCKED]`,需在后台上传证书)。 +- **nginx 全局失败不写行失败**:`nginx -t` / reload 失败属环境问题(主配置、片段 include、目录),此时待同步行保持 `sync_status=0`、已同步行保持 `1`、失败行保持 `2`,只落 `last_sync_error` 并下一轮自动重试,避免「运维修好配置后行却卡死在 2、必须人工重传证书」。 +- **下线 = 配置差集(不需要两阶段切换的额外机制)**:期望集合 = 库内「已配置 + 已验证 + 证书就绪」的行,且**每个仓库只取一条**(同一 `store_id` 多行时按 id 最小者生效,其余行 WARN 后忽略)。`nginx_config/`、`.ssl/` 中属于本系统命名规则、但域名已不在期望集合内的文件会被删除并 reload(日志 `DELETE … 原因=orphan`)。所以**换域名不需要人工下线**:旧域名在提升后已不是该行的 `domain`,下一轮即被清掉;`retired_domain` / `retired_at` 仅作应用侧审计留痕,脚本不读取、不写回。 +- **证书没配置就不写配置**:`cert_pem` / `cert_key` 为空的行**不生成** server 块,也不作为文件保留依据(其遗留 conf / 证书会被差集回收——conf 引用不存在的证书会让 `nginx -t` 全局失败),行状态回写 `sync_status=0` 待同步;证书非空但非法(或域名形态非法)才记行级失败(`sync_status=2`)。 +- **ver 轮转步骤**:改服务器 `warehouse-cert-sync.config.prod.json` 的 `"ver"`(或临时 `--ver`)→ 下一轮 cron 自动生成新命名 `-<新ver>.conf`、删除旧命名并 reload;无需清空库、无需重传证书(证书文件名不含 ver,不受影响)。 +- **站点内容单一片段**:生成的 server 块 = 证书骨架 + `include ;`;站点内容(root / 伪静态 或 反代)统一由 `upstreamInclude` 指向的片段文件提供(生产 `/www/wwwroot/qimen/front.conf`),**由运维维护、脚本绝不覆盖**;前端个性化在运行时由配置接口按域名完成,nginx 侧无需按域名区分站点内容。 + - ⚠️ **`upstreamInclude` 必须写绝对路径,且片段文件必须先存在**:nginx 解析 `include` 相对路径的基准是 **nginx prefix**(宝塔为 `/www/server/nginx/conf`),**不是脚本 cwd(部署根)**;写相对路径会让生成的 server 块 include 到不存在的文件 → `nginx -t` 失败 → 整轮变更回滚(连本轮写入的证书一起被当孤儿回收)。脚本启动即校验,不满足直接 `exit 1`(致命退出、不写盘、不改库)。 +- **改名/搬迁必须同步三处**:① nginx 主配置的 `include /nginx_config/*.conf;`;② 服务器上的 `warehouse-cert-sync.config.prod.json`;③ 库表 `wms_warehouse_front_config.cert_path/key_path`(触发一次重同步即可刷新)。 +- 安全:`.ssl/` 与 `nginx_config/` 已在 `.gitignore` 忽略,且列入发布默认排除(`deploy-lib.cjs` 的 `DEFAULT_EXCLUDE_PATHS`),私钥不会进仓库或发布包。 + +### 定时任务 + +| 任务 | 载体 | 频率 | 入口与日志 | +|------|------|------|-----------| +| 证书/站点配置同步 | root crontab(**宝塔「计划任务」里看不到**,它是直接写入 crontab 的裸命令) | 每分钟(`flock` 锁 `/var/lock/warehouse-cert-sync.lock`) | `/script/warehouse-cert-sync.sh` → `/var/log/warehouse-cert-sync.log` | +| 接口服务看门狗 | `/etc/cron.d/qimen-watchdog`(**刻意不放 root crontab**:宝塔面板会整体重写 root crontab) | 每 5 分钟 | `/script/qimen-watchdog.sh` → `/www/wwwlogs/wms/qimen-watchdog.log` | + +### 运维命令 + +```bash +npm run deploy:precheck / deploy:authcheck / deploy:inspect / deploy:smoke / deploy:verify +npm run deploy:version / deploy:version:history / deploy:cleanup-backups / deploy:gateway-probe +npm run deploy # 发布(= deploy:prod);npm run rollback # 回退 +npm run deploy:cert-sync:install / npm run deploy:cert-sync:uninstall +npm run deploy:watchdog:precheck | :install | :status | :dry-run | :run +``` + +- **部署配置**:`config/deploy.config.local.cjs`(**本地文件、已被 `.gitignore` 忽略**;模板 `config/deploy.config.example.cjs`)。键:`host / port / username / privateKeyPath / deployRoot / sharedDirs / preserveDirs / keepBackups / preDeployCommands / postDeployCommands / healthCheckUrl / deployIncludePaths / deployExcludePaths / sshOptions`;缺省值在 `script/deploy-lib.cjs`。查看归一化后的生效配置: + ```bash + node -e "console.log(JSON.stringify(require('./script/deploy-lib.cjs').loadDeployConfig('production'),null,2))" + ``` +- **证书同步运行时配置**:`script/warehouse-cert-sync.config.prod.json`(生产)/ `.dev.json`(开发)。生产那份是**服务器自管**(`deploy:cert-sync:install` 仅首次放置,之后永不覆盖)——改生产运行参数请在**服务器上**直接改它,改本地仓库无效。 +- **安装位置**:`deploy:cert-sync:install` 与 `deploy:watchdog:install` 都装到 `/script/`;覆盖前会留 `.prev-<时间戳>` 备份,历史根目录副本会被一次性挪成 `<名>.legacy-<时间戳>`。 +- **卸载**(`deploy:cert-sync:uninstall`):先备份再删除——备份到服务器 `/tmp/wms-cert-sync-uninstall-<时间戳>/`(`cp -a` 保留权限/时间),删除包装脚本、主脚本、双环境配置、`database/config.js`、历史位置与 `.prev-*`/`.legacy-*` 备份、crontab 中 `warehouse-cert-sync` 行;支持 `--dry-run` 只打印计划。**不删**证书与生成的 server 块(nginx 仍在 include,删了会立断 443,由运维自行决定)、不删 `/var/log/warehouse-cert-sync.log`(默认保留作排查线索)、不碰任何 watchdog 相关文件/任务。 +- **运行期手动排查**:仍可直接执行服务器上的 `/script/warehouse-cert-sync.sh --dry-run`(主脚本 CLI 不变:`--cleanup-only --dry-run` / `--cleanup-only` / `--env production`)。 + ## 功能模块 - 多快递平台对接(快手/PolyAPI 等) diff --git a/package.json b/package.json index c1b7454..0f7bfac 100644 --- a/package.json +++ b/package.json @@ -59,14 +59,13 @@ "deploy:smoke": "node ./script/deploy-ops.cjs production smoke", "deploy:verify": "node ./script/deploy-ops.cjs production verify", "deploy:cleanup-backups": "node ./script/deploy-ops.cjs production cleanup-backups", - "deploy:cert-sync:precheck": "node ./script/deploy-cert-sync.cjs production precheck", "deploy:cert-sync:install": "node ./script/deploy-cert-sync.cjs production install", - "deploy:cert-sync:dry-run": "node ./script/deploy-cert-sync.cjs production dry-run", - "deploy:cert-sync:run": "node ./script/deploy-cert-sync.cjs production run", - "deploy:cert-sync:status": "node ./script/deploy-cert-sync.cjs production status", - "deploy:cert-sync:config-check": "node ./script/deploy-cert-sync.cjs production config-check", - "deploy:cert-sync:cleanup-dry-run": "node ./script/deploy-cert-sync.cjs production cleanup-dry-run", - "deploy:cert-sync:cleanup": "node ./script/deploy-cert-sync.cjs production cleanup", + "deploy:cert-sync:uninstall": "node ./script/deploy-cert-sync.cjs production uninstall", + "deploy:watchdog:precheck": "node ./script/deploy-watchdog.cjs production precheck", + "deploy:watchdog:install": "node ./script/deploy-watchdog.cjs production install", + "deploy:watchdog:status": "node ./script/deploy-watchdog.cjs production status", + "deploy:watchdog:dry-run": "node ./script/deploy-watchdog.cjs production dry-run", + "deploy:watchdog:run": "node ./script/deploy-watchdog.cjs production run", "deploy:gateway-probe": "node ./script/deploy-ops.cjs production gateway-probe", "ops:check-root-logs": "node ./script/check-root-logs.cjs", diff --git a/script/deploy-cert-sync.cjs b/script/deploy-cert-sync.cjs index 3c5f83f..2a2043e 100644 --- a/script/deploy-cert-sync.cjs +++ b/script/deploy-cert-sync.cjs @@ -1,3 +1,18 @@ +/** + * cert-sync 部署工具(npm 命令仅 install / uninstall 两条)。 + * + * - install:校验并上传主脚本 / DB 配置;prod 配置按「首次放置一次、永不覆盖」约定处理; + * 生成薄包装 /script/warehouse-cert-sync.sh 并注册 root crontab(每分钟 flock)。 + * - uninstall:先备份再删除工具自身(包装脚本 / 主脚本 / 双环境配置 / database/config.js / + * 历史位置与 .prev-* / .legacy-* 备份 / crontab 行);支持 --dry-run 只打印计划。 + * 证书、nginx server 块、日志、watchdog 相关一律不删(原因见输出)。 + * + * 运行期手动操作仍可直接调用服务器上的包装脚本(这是主脚本 CLI 的能力,不属于本工具 npm 命令): + * /script/warehouse-cert-sync.sh --dry-run + * /script/warehouse-cert-sync.sh --cleanup-only --dry-run + * /script/warehouse-cert-sync.sh --cleanup-only + * /script/warehouse-cert-sync.sh --env production + */ 'use strict'; const fs = require('node:fs'); @@ -11,26 +26,52 @@ const { runSsh, } = require('./deploy-lib.cjs'); -const COMMANDS = new Set([ 'precheck', 'install', 'dry-run', 'run', 'status', 'config-check', 'cleanup-dry-run', 'cleanup' ]); +const COMMANDS = new Set([ 'install', 'uninstall' ]); const LOCAL_SYNC_SCRIPT = path.join(ROOT, 'script', 'warehouse-cert-sync.cjs'); const LOCAL_DB_CONFIG = path.join(ROOT, 'database', 'config.js'); const LOCAL_PROD_CONFIG = path.join(ROOT, 'script', 'warehouse-cert-sync.config.prod.json'); +/** + * 打印本工具用法(仅 install / uninstall 两条 npm 命令)。 + */ +function printUsage() { + console.error([ + 'usage: node script/deploy-cert-sync.cjs [env] [--dry-run]', + ' env: production | development(默认 production)', + ' command: install 上传脚本/配置、生成薄包装、注册 crontab', + ' uninstall 备份并删除工具自身(脚本/配置/crontab),支持 --dry-run', + '运行期手动操作请直接调用服务器上的包装脚本(主脚本 CLI 能力,非本工具命令):', + ' /script/warehouse-cert-sync.sh --dry-run', + ' /script/warehouse-cert-sync.sh --cleanup-only --dry-run', + ' /script/warehouse-cert-sync.sh --cleanup-only', + ' /script/warehouse-cert-sync.sh --env production', + ].join('\n')); +} + +/** + * 解析命令行参数。 + * @param {string[]} argv 原始参数数组(不含 node / 脚本名)。 + * @return {{ envName: string, command: string, dryRun: boolean }} 解析结果。 + */ function parseArgs(argv) { - const options = { envName: 'production', command: '' }; + const options = { envName: 'production', command: '', dryRun: false }; const tokens = [ ...argv ]; - if (tokens.length === 0) { - throw new Error('missing command: precheck | install | dry-run | run | status | config-check | cleanup-dry-run | cleanup'); + options.dryRun = tokens.includes('--dry-run'); + const positional = tokens.filter(token => token !== '--dry-run'); + if (positional.length === 0) { + printUsage(); + throw new Error('missing command: install | uninstall'); } - if (!COMMANDS.has(tokens[0])) { - options.envName = tokens[0]; - tokens.shift(); + if (!COMMANDS.has(positional[0])) { + options.envName = positional[0]; + positional.shift(); } - if (tokens.length === 0 || !COMMANDS.has(tokens[0])) { - throw new Error('missing command: precheck | install | dry-run | run | status | config-check | cleanup-dry-run | cleanup'); + if (positional.length === 0 || !COMMANDS.has(positional[0])) { + printUsage(); + throw new Error('missing command: install | uninstall'); } - options.command = tokens[0]; + options.command = positional[0]; return options; } @@ -142,132 +183,6 @@ exit $STATUS `; } -/** Read-only DB probe JS (never prints credentials). */ -const DB_PROBE_JS = ` -const path = require("node:path"); -const Sequelize = require("sequelize"); -const appDir = process.argv[1]; -function load(p) { - try { - const f = require(p); - const c = typeof f === "function" ? f({ name: "cert-sync-precheck", baseDir: appDir }) : f; - return c && typeof c === "object" ? c : {}; - } catch (e) { return {}; } -} -let src = "none"; let client = null; -const def = load(path.join(appDir, "config", "config.default.js")); -if (def.sequelize && def.sequelize.host) { src = "config.default.js#sequelize"; client = def.sequelize; } -else if (def.mysql && def.mysql.clients && def.mysql.clients.wms && def.mysql.clients.wms.host) { src = "config.default.js#mysql.clients.wms"; client = def.mysql.clients.wms; } -else if (def.mysql && def.mysql.host) { src = "config.default.js#mysql"; client = def.mysql; } -if (!client) { - const loc = load(path.join(appDir, "config", "config.local.js")); - if (loc.sequelize && loc.sequelize.host) { src = "config.local.js#sequelize"; client = loc.sequelize; } - else if (loc.mysql && loc.mysql.host) { src = "config.local.js#mysql"; client = loc.mysql; } -} -if (!client) { console.log("[DB_PROBE] cannot resolve db config from active instance"); process.exit(0); } -console.log("[DB_PROBE] config source: " + src + " database=" + String(client.database || "")); -const seq = new Sequelize(client.database, client.username || client.user, client.password, { - host: client.host, port: client.port || 3306, dialect: "mysql", logging: false, -}); -(async () => { - try { - await seq.authenticate(); - console.log("[DB_PROBE] prod db connect OK"); - const [t] = await seq.query("SELECT COUNT(*) AS c FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = 'wms_warehouse_front_config'"); - const exists = Number(t[0].c) > 0; - console.log("[DB_PROBE] wms_warehouse_front_config exists: " + (exists ? "YES" : "NO")); - if (exists) { - const [cols] = await seq.query("SELECT column_name AS cn FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = 'wms_warehouse_front_config'"); - console.log("[DB_PROBE] columns: " + cols.map(r => r.cn).join(",")); - const hasDomainStatus = cols.some(r => r.cn === "domain_status"); - console.log("[DB_PROBE] domain_status column: " + (hasDomainStatus ? "YES" : "NO")); - const [total] = await seq.query("SELECT COUNT(*) AS c FROM wms_warehouse_front_config"); - console.log("[DB_PROBE] total rows: " + total[0].c); - const [dist] = await seq.query("SELECT sync_status AS s, COUNT(*) AS c FROM wms_warehouse_front_config GROUP BY sync_status ORDER BY sync_status"); - console.log("[DB_PROBE] sync_status distribution: " + (dist.length ? dist.map(r => r.s + "=" + r.c).join(" ") : "(empty)")); - if (hasDomainStatus) { - const [ddist] = await seq.query("SELECT domain_status AS s, COUNT(*) AS c FROM wms_warehouse_front_config GROUP BY domain_status ORDER BY domain_status"); - console.log("[DB_PROBE] domain_status distribution: " + (ddist.length ? ddist.map(r => (r.s === null ? "null" : r.s) + "=" + r.c).join(" ") : "(empty)")); - const sumStatus = want => ddist.filter(r => Number(r.s) === want).reduce((n, r) => n + Number(r.c), 0); - console.log("[DB_PROBE] domain_status counts: 0_unverified=" + sumStatus(0) + " 1_verified=" + sumStatus(1) + " 2_failed=" + sumStatus(2)); - console.log("[DB_PROBE] gated-out rows (domain_status 0/2, no nginx server block after gate): " + (sumStatus(0) + sumStatus(2))); - } else { - console.log("[DB_PROBE] domain_status distribution: (column missing, migration not applied; cert-sync falls back to no filter)"); - } - const hasRetiredDomain = cols.some(r => r.cn === "retired_domain"); - console.log("[DB_PROBE] retired_domain column: " + (hasRetiredDomain ? "YES" : "NO")); - if (hasRetiredDomain) { - const [rCount] = await seq.query("SELECT COUNT(*) AS c FROM wms_warehouse_front_config WHERE retired_domain IS NOT NULL AND retired_domain <> ''"); - const [rPreview] = await seq.query("SELECT retired_domain AS d FROM wms_warehouse_front_config WHERE retired_domain IS NOT NULL AND retired_domain <> '' ORDER BY id ASC LIMIT 20"); - const names = rPreview.map(r => String(r.d)).join(","); - console.log("[DB_PROBE] retired_domain pending: retired=" + rCount[0].c + (names ? ": " + names : "")); - } else { - console.log("[DB_PROBE] retired_domain pending: (column missing, migration not applied; cleanup flow skipped)"); - } - - } - } catch (e) { - console.log("[DB_PROBE] failed: " + e.message); - } - await seq.close(); -})(); -`; - -/** - * Read-only remote precheck. - * @param {Object} config deploy 配置对象。 - */ -function runPrecheck(config) { - const deployRoot = config.deployRoot; - const remoteScript = [ - 'set -uo pipefail', - `DEPLOY_ROOT=${quoteForBash(deployRoot)}`, - 'echo "[WHOAMI] $(id -un)"', - 'echo "[UNAME] $(uname -a)"', - `echo "[CURRENT_MD] $(cat ${quoteForBash(`${deployRoot}/current.md`)} 2>/dev/null || echo MISSING)"`, - `echo "[DEPLOY_ROOT_LS]"; ls -la ${quoteForBash(deployRoot)} | awk '{print $1, $3, $4, $9}'`, - 'echo "[NGINX_BIN]"; command -v nginx || echo "nginx not in PATH"', - 'echo "[NGINX_V]"; nginx -v 2>&1 || true', - 'echo "[NGINX_V_PREFIX]"; nginx -V 2>&1 | grep -E "configure arguments|--prefix" | head -2 || true', - 'echo "[NGINX_T_NOW]"; nginx -t 2>&1 || true', - 'echo "[NGINX_PROCESS]"; ps -eo pid=,args= | grep "[n]ginx" | head -6 || true', - 'echo "[SYSTEMD_NGINX]"; systemctl is-active nginx 2>&1 || true; systemctl is-enabled nginx 2>&1 || true', - 'echo "[FLOCK]"; command -v flock || echo "flock missing"', - 'echo "[MAIN_CONF_INCLUDES]"; for f in /etc/nginx/nginx.conf /www/server/nginx/conf/nginx.conf /usr/local/nginx/conf/nginx.conf; do if [ -f "$f" ]; then echo "-- $f"; grep -n "include" "$f" | grep -v "^[[:space:]]*#" | head -20; fi; done', - 'echo "[CONF_DIR_PROBE]"; for d in /etc/nginx/conf.d /www/server/nginx/conf/conf.d; do if [ -d "$d" ]; then echo "-- $d EXISTS"; ls -1 "$d" | head -20; fi; done', - 'echo "[SSL_DIR] /www/wwwroot/.ssl"; if [ -d /www/wwwroot/.ssl ]; then echo EXISTS; ls -la /www/wwwroot/.ssl | head -20; else echo MISSING; fi', - 'echo "[CERT_CONF_DIR] /www/wwwroot/nginx_config"; if [ -d /www/wwwroot/nginx_config ]; then echo EXISTS; ls -la /www/wwwroot/nginx_config | head -30; else echo MISSING; fi', - 'echo "[PARENT_WRITABLE]"; if [ -w /www/wwwroot ]; then echo YES; else echo NO; fi', - 'echo "[DEPLOY_ROOT_META]"; for p in script database config node_modules; do if [ -e "$DEPLOY_ROOT/$p" ]; then echo "$p EXISTS"; else echo "$p MISSING"; fi; done', - 'echo "[V1_CONFIG_LS]"; ls -la "$DEPLOY_ROOT/v1/config" 2>/dev/null | head -20 || echo "v1/config missing"', - 'echo "[V2_CONFIG_LS]"; ls -la "$DEPLOY_ROOT/v2/config" 2>/dev/null | head -20 || echo "v2/config missing"', - 'echo "[V1_SEQUELIZE]"; if [ -d "$DEPLOY_ROOT/v1/node_modules/sequelize" ]; then echo YES; else echo NO; fi', - 'echo "[V2_SEQUELIZE]"; if [ -d "$DEPLOY_ROOT/v2/node_modules/sequelize" ]; then echo YES; else echo NO; fi', - 'echo "[EXISTING_CRON_CERT]"; crontab -l 2>/dev/null | grep -i "cert" || echo NONE', - 'echo "[CRON_LINE_COUNT]"; crontab -l 2>/dev/null | grep -cv "^#" || echo 0', - 'echo "[CERT_LOG_TAIL]"; tail -20 /var/log/warehouse-cert-sync.log 2>/dev/null || echo "log not exists"', - ].join('\n'); - - console.log('[PRECHECK] remote env check (read-only)'); - console.log(runSsh(config, remoteScript, { stdio: 'pipe' }).trim()); - - const dbProbeScript = [ - 'set -uo pipefail', - `DEPLOY_ROOT=${quoteForBash(deployRoot)}`, - 'ACTIVE=$(cat "$DEPLOY_ROOT/current.md" 2>/dev/null | tr -d "[:space:]" || true)', - 'APP_DIR=""', - 'if [ -n "$ACTIVE" ] && [ -d "$DEPLOY_ROOT/$ACTIVE/config" ]; then APP_DIR="$DEPLOY_ROOT/$ACTIVE"; fi', - 'if [ -z "$APP_DIR" ]; then for CAND in v1 v2; do if [ -d "$DEPLOY_ROOT/$CAND/config" ]; then APP_DIR="$DEPLOY_ROOT/$CAND"; break; fi; done; fi', - 'if [ -z "$APP_DIR" ]; then echo "[DB_PROBE] no active instance dir found"; exit 0; fi', - 'export NODE_PATH="$APP_DIR/node_modules"', - `node -e ${quoteForBash(DB_PROBE_JS)} "$APP_DIR"`, - ].join('\n'); - - console.log(''); - console.log('[PRECHECK] prod db probe (read-only, no credentials printed)'); - console.log(runSsh(config, dbProbeScript, { stdio: 'pipe' }).trim()); -} - /** * Install: upload files, create thin shell wrapper, register root crontab. * @param {Object} config deploy 配置对象。 @@ -288,11 +203,14 @@ function runInstall(config) { `DEPLOY_ROOT=${quoteForBash(deployRoot)}`, `STAMP=${quoteForBash(getNowStamp())}`, 'mkdir -p "$DEPLOY_ROOT/script" "$DEPLOY_ROOT/database"', - 'for p in "$DEPLOY_ROOT/warehouse-cert-sync.sh" "$DEPLOY_ROOT/script/warehouse-cert-sync.cjs" "$DEPLOY_ROOT/database/config.js"; do', + 'for p in "$DEPLOY_ROOT/script/warehouse-cert-sync.sh" "$DEPLOY_ROOT/script/warehouse-cert-sync.cjs" "$DEPLOY_ROOT/database/config.js"; do', ' if [ -f "$p" ]; then cp -a "$p" "$p.prev-$STAMP" && echo "BACKED_UP $p -> $p.prev-$STAMP"; fi', 'done', + '# 历史位置(部署根)一次性迁移:旧 wrapper 挪进 script/ 留作回滚备份,避免根目录残留孤儿', + 'LEGACY="$DEPLOY_ROOT/warehouse-cert-sync.sh"', + 'if [ -f "$LEGACY" ]; then mv "$LEGACY" "$DEPLOY_ROOT/script/warehouse-cert-sync.sh.legacy-$STAMP" && echo "LEGACY_MOVED $LEGACY -> $DEPLOY_ROOT/script/warehouse-cert-sync.sh.legacy-$STAMP"; fi', ].join('\n'); - console.log('[INSTALL] remote dir prep + backup of existing files'); + console.log('[INSTALL] remote dir prep + backup of existing files (wrapper installs under script/)'); console.log(runSsh(config, remoteDirScript, { stdio: 'pipe' }).trim()); const remoteScriptPath = `${deployRoot}/script/warehouse-cert-sync.cjs`; @@ -340,7 +258,7 @@ function runInstall(config) { } console.log('[INSTALL] dev config NOT uploaded (development-only)'); - const wrapperPath = `${deployRoot}/warehouse-cert-sync.sh`; + const wrapperPath = `${deployRoot}/script/warehouse-cert-sync.sh`; const installScript = [ 'set -euo pipefail', `DEPLOY_ROOT=${quoteForBash(deployRoot)}`, @@ -366,119 +284,281 @@ function runInstall(config) { } /** - * Run the remote wrapper with optional extra args; returns output + exit code. - * useFlock=true 时用与 crontab 相同的锁文件串行化(手工清理与每分钟定时任务互斥), - * flock 不可用时只告警并降级为不加锁执行(不阻断运维操作)。 - * @param {Object} config deploy 配置对象(含 deployRoot)。 - * @param {string[]} extraArgs 透传给远端包装脚本的额外参数。 - * @param {boolean} useFlock 是否用 flock 串行化执行,默认 false。 - * @return {string} 远端输出(已 trim)。 + * 把远端配置里的目录值(如 ./.ssl)按部署根解析成绝对路径。 + * @param {string} deployRoot 部署根目录。 + * @param {string} value 配置值(相对或绝对)。 + * @param {string} fallback 解析失败时的默认值。 + * @return {string} 远端绝对路径。 */ -function runRemoteWrapper(config, extraArgs = [], useFlock = false) { - const wrapperPath = `${config.deployRoot}/warehouse-cert-sync.sh`; - const runLine = useFlock - ? 'FLOCK_BIN=$(command -v flock || true); if [ -n "$FLOCK_BIN" ]; then "$FLOCK_BIN" -w 30 /var/lock/warehouse-cert-sync.lock bash "$WRAPPER" $ARGS; else echo "WARN: flock not found, run without lock"; bash "$WRAPPER" $ARGS; fi' - : 'bash "$WRAPPER" $ARGS'; - const remoteScript = [ - 'set -uo pipefail', - `WRAPPER=${quoteForBash(wrapperPath)}`, - `ARGS=${quoteForBash(extraArgs.join(' '))}`, - 'if [ ! -f "$WRAPPER" ]; then echo "FATAL: wrapper missing: $WRAPPER"; exit 1; fi', - runLine, - 'echo "CERT_SYNC_EXIT=$?"', - ].join('\n'); - return runSsh(config, remoteScript, { stdio: 'pipe' }).trim(); +function resolveRemotePath(deployRoot, value, fallback) { + const v = String(value || '').trim(); + if (!v) return fallback; + if (v.startsWith('/')) return v; + return `${String(deployRoot).replace(/\/+$/, '')}/${v.replace(/^\.\//, '')}`; } /** - * Status: crontab line, remote file list, log tail. + * 只读解析服务器 prod 配置中的 certDir / confDir(用于「未触碰」清单展示)。 + * 配置缺失或解析失败时回退默认值(/.ssl、/nginx_config),不阻断卸载流程。 * @param {Object} config deploy 配置对象。 + * @return {{ certDir: string, confDir: string }} 解析出的远端绝对目录。 */ -function runStatus(config) { +function resolveServerDirs(config) { const deployRoot = config.deployRoot; - const remoteScript = [ + const defaultCertDir = `${deployRoot}/.ssl`; + const defaultConfDir = `${deployRoot}/nginx_config`; + const result = { certDir: defaultCertDir, confDir: defaultConfDir }; + const cfgPath = `${deployRoot}/script/warehouse-cert-sync.config.prod.json`; + const probeScript = [ 'set -uo pipefail', - 'echo "[CRONTAB_CERT_LINES]"', - 'crontab -l 2>/dev/null | grep -n "warehouse-cert-sync" || echo NONE', - 'echo "[REMOTE_FILES]"', - `ls -la ${quoteForBash(`${deployRoot}/warehouse-cert-sync.sh`)} ${quoteForBash(`${deployRoot}/script/warehouse-cert-sync.cjs`)} ${quoteForBash(`${deployRoot}/script/warehouse-cert-sync.config.prod.json`)} ${quoteForBash(`${deployRoot}/script/warehouse-cert-sync.config.dev.json`)} ${quoteForBash(`${deployRoot}/database/config.js`)} 2>&1`, - 'echo "[WRAPPER_HEAD]"', - `head -12 ${quoteForBash(`${deployRoot}/warehouse-cert-sync.sh`)} 2>/dev/null`, - 'echo "[CERT_LOG_TAIL]"', - 'tail -30 /var/log/warehouse-cert-sync.log 2>/dev/null || echo "log not exists"', + `CFG=${quoteForBash(cfgPath)}`, + 'if [ -f "$CFG" ]; then', + ` node -e ${quoteForBash('const c=JSON.parse(require("node:fs").readFileSync(process.argv[1],"utf8")); console.log("CERT_DIR="+(c.certDir||"./.ssl")); console.log("CONF_DIR="+(c.confDir||"./nginx_config"));')} "$CFG"`, + 'else', + ' echo "CERT_DIR=./.ssl"', + ' echo "CONF_DIR=./nginx_config"', + 'fi', ].join('\n'); - console.log(runSsh(config, remoteScript, { stdio: 'pipe' }).trim()); + try { + const output = String(runSsh(config, probeScript, { stdio: 'pipe' }) || ''); + for (const line of output.split('\n')) { + if (line.startsWith('CERT_DIR=')) { + result.certDir = resolveRemotePath(deployRoot, line.slice(9), defaultCertDir); + } + if (line.startsWith('CONF_DIR=')) { + result.confDir = resolveRemotePath(deployRoot, line.slice(9), defaultConfDir); + } + } + } catch (err) { + console.warn(`[UNINSTALL] 服务器目录探测失败,回退默认值:${err.message}`); + } + return result; } /** - * 只读核对服务器 prod 配置文件:存在性 + JSON 合法性 + 内容展示(无凭据,可安全输出)。 - * @param {Object} config deploy 配置对象。 + * 生成卸载目标清单:精确路径 + 历史备份 glob(.prev-* / .legacy-*)。 + * @param {string} deployRoot 部署根目录。 + * @return {{ exactPaths: string[], globPatterns: string[] }} 目标清单。 */ -function runConfigCheck(config) { - const deployRoot = config.deployRoot; - const remoteScript = [ +function buildUninstallTargets(deployRoot) { + const exactPaths = [ + `${deployRoot}/script/warehouse-cert-sync.sh`, + `${deployRoot}/warehouse-cert-sync.sh`, + `${deployRoot}/script/warehouse-cert-sync.cjs`, + `${deployRoot}/script/warehouse-cert-sync.config.prod.json`, + `${deployRoot}/script/warehouse-cert-sync.config.dev.json`, + `${deployRoot}/database/config.js`, + ]; + const globPatterns = []; + for (const base of [ + `${deployRoot}/script/warehouse-cert-sync.sh`, + `${deployRoot}/warehouse-cert-sync.sh`, + `${deployRoot}/script/warehouse-cert-sync.cjs`, + `${deployRoot}/script/warehouse-cert-sync.config.prod.json`, + `${deployRoot}/script/warehouse-cert-sync.config.dev.json`, + `${deployRoot}/database/config.js`, + ]) { + globPatterns.push(`${base}.prev-*`, `${base}.legacy-*`); + } + return { exactPaths, globPatterns }; +} + +/** + * 生成 dry-run 计划脚本(只读:只打印将备份/将删除的目标与将清理的 crontab 行)。 + * @param {Object} config deploy 配置对象。 + * @param {string} backupDir 计划使用的备份目录(dry-run 不创建)。 + * @return {string} 远端 bash 脚本。 + */ +function buildUninstallDryRunScript(config, backupDir) { + const { exactPaths, globPatterns } = buildUninstallTargets(config.deployRoot); + return [ 'set -uo pipefail', - `DEPLOY_ROOT=${quoteForBash(deployRoot)}`, - 'PROD="$DEPLOY_ROOT/script/warehouse-cert-sync.config.prod.json"', - 'DEV="$DEPLOY_ROOT/script/warehouse-cert-sync.config.dev.json"', - 'for f in "$PROD" "$DEV"; do', - ' if [ -f "$f" ]; then', - ' echo "[CONFIG_EXISTS] $f"', - ' if node -e \'JSON.parse(require("node:fs").readFileSync(process.argv[1], "utf8"))\' "$f" >/dev/null 2>&1; then', - ' echo "[CONFIG_JSON] $f VALID"', + `B_DIR=${quoteForBash(backupDir)}`, + 'echo "PLAN_BACKUP_DIR=$B_DIR"', + `for T in ${exactPaths.map(quoteForBash).join(' ')}; do`, + ' if [ -f "$T" ]; then echo "WOULD_BACKUP_AND_DELETE $T"; else echo "MISSING_SKIP $T"; fi', + 'done', + `for G in ${globPatterns.map(quoteForBash).join(' ')}; do`, + ' for F in $G; do', + ' [ -f "$F" ] || continue', + ' echo "WOULD_BACKUP_AND_DELETE $F"', + ' done', + 'done', + 'CRON_BEFORE=$(crontab -l 2>/dev/null | wc -l)', + 'CRON_CERT=$(crontab -l 2>/dev/null | grep -c "warehouse-cert-sync" || true)', + 'if [ "$CRON_CERT" -gt 0 ]; then', + ' crontab -l 2>/dev/null | grep "warehouse-cert-sync" | sed "s|^|WOULD_REMOVE_CRON_LINE |" || true', + ' echo "CRONTAB_WOULD_GO before=$CRON_BEFORE after=$((CRON_BEFORE - CRON_CERT))"', + 'else', + ' echo "CRONTAB_UNTOUCHED_NO_MATCH"', + 'fi', + ].join('\n'); +} + +/** + * 生成真实卸载脚本:先备份(cp -a 保留权限/时间)再删除,清理 crontab 行。 + * 单项失败不中断(HAD_ERRORS 标记),证书/server 块/日志/watchdog 一律不触碰。 + * @param {Object} config deploy 配置对象。 + * @param {string} backupDir 备份目录(/tmp/wms-cert-sync-uninstall-<时间戳>/)。 + * @return {string} 远端 bash 脚本。 + */ +function buildUninstallScript(config, backupDir) { + const { exactPaths, globPatterns } = buildUninstallTargets(config.deployRoot); + return [ + 'set -u', + `BACKUP_DIR=${quoteForBash(backupDir)}`, + 'HAD_ERRORS=0', + 'mkdir -p "$BACKUP_DIR" && echo "BACKUP_DIR=$BACKUP_DIR" || { echo "BACKUP_DIR_CREATE_FAILED $BACKUP_DIR"; HAD_ERRORS=1; }', + `for T in ${exactPaths.map(quoteForBash).join(' ')}; do`, + ' if [ -f "$T" ]; then', + ' BASE=$(basename "$T")', + ' if cp -a "$T" "$BACKUP_DIR/$BASE"; then', + ' echo "BACKED_UP $T -> $BACKUP_DIR/$BASE"', ' else', - ' echo "[CONFIG_JSON] $f INVALID"', + ' echo "BACKUP_FAILED $T (保留未删)"', + ' HAD_ERRORS=1', + ' continue', ' fi', - ' else', - ' echo "[CONFIG_MISSING] $f"', + ' if rm -f "$T"; then echo "DELETED $T"; else echo "DELETE_FAILED $T"; HAD_ERRORS=1; fi', ' fi', 'done', - 'echo "[PROD_CONFIG_CONTENT]"', - 'cat "$PROD" 2>/dev/null || echo "(missing)"', - 'echo "[DEV_CONFIG_ON_SERVER]"', - 'if [ -f "$DEV" ]; then echo YES; else echo NO; fi', + `for G in ${globPatterns.map(quoteForBash).join(' ')}; do`, + ' for F in $G; do', + ' [ -f "$F" ] || continue', + ' BASE=$(basename "$F")', + ' if cp -a "$F" "$BACKUP_DIR/$BASE"; then', + ' echo "BACKED_UP $F -> $BACKUP_DIR/$BASE"', + ' else', + ' echo "BACKUP_FAILED $F (保留未删)"', + ' HAD_ERRORS=1', + ' continue', + ' fi', + ' if rm -f "$F"; then echo "DELETED $F"; else echo "DELETE_FAILED $F"; HAD_ERRORS=1; fi', + ' done', + 'done', + 'CRON_BEFORE=$(crontab -l 2>/dev/null | wc -l)', + 'CRON_CERT=$(crontab -l 2>/dev/null | grep -c "warehouse-cert-sync" || true)', + 'if [ "$CRON_CERT" -gt 0 ]; then', + ' crontab -l 2>/dev/null | grep "warehouse-cert-sync" | sed "s|^|CRON_REMOVED_LINE |" || true', + ' if ( crontab -l 2>/dev/null | grep -v "warehouse-cert-sync" || true ) | crontab -; then', + ' echo "CRONTAB_REWRITTEN before=$CRON_BEFORE after=$(crontab -l 2>/dev/null | wc -l)"', + ' else', + ' echo "CRONTAB_REWRITE_FAILED"', + ' HAD_ERRORS=1', + ' fi', + 'else', + ' echo "CRONTAB_UNTOUCHED_NO_MATCH"', + 'fi', + 'echo "HAD_ERRORS=$HAD_ERRORS"', ].join('\n'); - console.log(runSsh(config, remoteScript, { stdio: 'pipe' }).trim()); } +/** + * 按三段结构打印卸载输出:[UNINSTALL] 备份 / [UNINSTALL] 已删除 / [UNINSTALL] 未触碰(原因)。 + * @param {string} output 远端脚本输出。 + * @param {boolean} dryRun 是否 dry-run(只打印计划)。 + * @param {string} backupDir 备份目录路径。 + * @param {{ certDir: string, confDir: string }} dirs 证书/server 块目录解析结果。 + * @param {string} deployRoot 部署根目录。 + */ +function printUninstallReport(output, dryRun, backupDir, dirs, deployRoot) { + const lines = String(output || '').split(/\r?\n/); + const planNote = dryRun ? '(计划,未执行)' : ''; + const backupLines = []; + const deletedLines = []; + for (const line of lines) { + if (line.startsWith('PLAN_BACKUP_DIR=')) { + backupLines.push(`BACKUP_DIR=${line.slice('PLAN_BACKUP_DIR='.length)}${dryRun ? '(计划,不创建)' : ''}`); + } else if (line.startsWith('WOULD_BACKUP_AND_DELETE ')) { + const src = line.slice('WOULD_BACKUP_AND_DELETE '.length); + backupLines.push(`BACKED_UP ${src} -> ${backupDir}${src.split('/').pop()}${planNote}`); + deletedLines.push(`DELETED ${src}${planNote}`); + } else if (line.startsWith('MISSING_SKIP ')) { + backupLines.push(`SKIP ${line.slice('MISSING_SKIP '.length)}(不存在)`); + } else if (line.startsWith('BACKUP_DIR=')) { + backupLines.push(line); + } else if (line.startsWith('BACKUP_DIR_CREATE_FAILED ')) { + backupLines.push(line); + } else if (line.startsWith('BACKED_UP ')) { + backupLines.push(line); + } else if (line.startsWith('BACKUP_FAILED ')) { + backupLines.push(line); + } else if (line.startsWith('DELETED ')) { + deletedLines.push(line); + } else if (line.startsWith('DELETE_FAILED ')) { + deletedLines.push(line); + } else if (line.startsWith('WOULD_REMOVE_CRON_LINE ')) { + deletedLines.push(`CRON_REMOVED_LINE ${line.slice('WOULD_REMOVE_CRON_LINE '.length)}${planNote}`); + } else if (line.startsWith('CRON_REMOVED_LINE ')) { + deletedLines.push(line); + } else if (line.startsWith('CRONTAB_REWRITTEN ')) { + deletedLines.push(line); + } else if (line.startsWith('CRONTAB_WOULD_GO ')) { + deletedLines.push(`${line}${dryRun ? '(计划,未执行)' : ''}`); + } else if (line.startsWith('CRONTAB_UNTOUCHED_NO_MATCH')) { + deletedLines.push('crontab 无 warehouse-cert-sync 行,未改写'); + } + } + + console.log(`[UNINSTALL] 备份${dryRun ? '(计划)' : ''}`); + for (const line of backupLines) console.log(` ${line}`); + console.log(`[UNINSTALL] 已删除${dryRun ? '(计划)' : ''}`); + for (const line of deletedLines) console.log(` ${line}`); + console.log('[UNINSTALL] 未触碰(原因)'); + console.log(` CERT_DIR_KEPT ${dirs.certDir}(运行产物:证书/私钥,nginx 仍在 include,删除会立断 443;由运维自行决定,如先切走 include 再手工删)`); + console.log(` CONF_DIR_KEPT ${dirs.confDir}(运行产物:-.conf server 块,nginx 仍在 include,同上)`); + console.log(' LOG_KEPT /var/log/warehouse-cert-sync.log(默认保留作排查线索)'); + console.log(` UPSTREAM_KEPT ${deployRoot}/nginx-upstream.conf(非本工具文件,不删)`); + console.log(` WATCHDOG_KEPT ${deployRoot}/script/qimen-watchdog.*、/etc/cron.d/qimen-watchdog(看门狗相关,不属于 cert-sync 工具)`); + if (dryRun) { + console.log(`[UNINSTALL] dry-run 结束(未做任何变更)。实际执行时备份目录:${backupDir}`); + console.log('如需回滚(实际执行后):把备份目录里的文件 cp -a 回原路径并重跑 install'); + return; + } + console.log(`备份目录:${backupDir}`); + console.log('如需回滚:把备份目录里的文件 cp -a 回原路径并重跑 install'); + if (lines.some(line => line === 'HAD_ERRORS=1')) { + console.error('[UNINSTALL] 存在失败项(见上),可从备份目录恢复'); + process.exitCode = 1; + } +} + +/** + * 卸载 cert-sync 工具自身:先备份再删除(包装脚本 / 主脚本 / 双环境配置 / + * database/config.js / 历史位置与 .prev-* / .legacy-* 备份 / crontab 行)。 + * 证书、nginx server 块、日志、watchdog 相关一律不删(原因见输出)。 + * --dry-run 时只打印计划,不备份、不删除、不改 crontab。 + * @param {Object} config deploy 配置对象。 + * @param {Object} options 命令选项(dryRun)。 + */ +function runUninstall(config, options) { + const backupDir = `/tmp/wms-cert-sync-uninstall-${getNowStamp()}/`; + const dirs = resolveServerDirs(config); + const remoteScript = options.dryRun + ? buildUninstallDryRunScript(config, backupDir) + : buildUninstallScript(config, backupDir); + if (options.dryRun) { + console.log('[UNINSTALL] dry-run(只读:只打印计划,不备份、不删除、不改 crontab)'); + } else { + console.log('[UNINSTALL] 开始卸载(先备份再删除)'); + } + const output = String(runSsh(config, remoteScript, { stdio: 'pipe' }) || ''); + printUninstallReport(output, options.dryRun, backupDir, dirs, config.deployRoot); +} + +/** + * 入口:解析命令行参数并执行 install / uninstall。 + */ function main() { const options = parseArgs(process.argv.slice(2)); const config = loadDeployConfig(options.envName); - if (options.command === 'precheck') { - runPrecheck(config); - return; - } if (options.command === 'install') { runInstall(config); return; } - if (options.command === 'dry-run') { - console.log('[DRY-RUN] remote dry-run (read-only, no file writes, no db updates)'); - console.log(runRemoteWrapper(config, [ '--dry-run' ])); - return; - } - if (options.command === 'run') { - console.log('[RUN] remote real execution'); - console.log(runRemoteWrapper(config, [])); - return; - } - if (options.command === 'cleanup-dry-run') { - console.log('[CLEANUP-DRY-RUN] remote retired-domain cleanup dry-run (read-only: no file deletes, no db updates, no reload)'); - console.log(runRemoteWrapper(config, [ '--cleanup-only', '--dry-run' ], true)); - return; - } - if (options.command === 'cleanup') { - console.log('[CLEANUP] remote retired-domain cleanup (real execution: deletes retired conf/cert files, then nginx -t + reload)'); - console.log(runRemoteWrapper(config, [ '--cleanup-only' ], true)); - return; - } - if (options.command === 'status') { - runStatus(config); - return; - } - if (options.command === 'config-check') { - runConfigCheck(config); + if (options.command === 'uninstall') { + runUninstall(config, options); return; } throw new Error(`unsupported command: ${options.command}`); diff --git a/script/deploy-lib.cjs b/script/deploy-lib.cjs index e32a12e..4518a3d 100644 --- a/script/deploy-lib.cjs +++ b/script/deploy-lib.cjs @@ -22,6 +22,12 @@ const DEFAULT_POST_DEPLOY_COMMANDS = [ 'npm run stop || true', 'npm start', ]; +/** + * 默认发布排除路径:应用配置 + 工程内的证书/nginx 产物目录。 + * `.ssl/` 与 `nginx_config/` 同在部署根一级(工程目录内),虽已被 .gitignore 忽略, + * 这里再排一次做防御,避免将来 include 规则放宽时把私钥打进发布包。 + */ +const DEFAULT_EXCLUDE_PATHS = [ 'config/**', '.ssl/**', 'nginx_config/**' ]; /** * 发布包固定排除文件(与 config.deployExcludePaths 叠加,防御性兜底)。 @@ -183,7 +189,7 @@ function normalizeDeployConfig(config, envName) { deployIncludePaths: Array.isArray(config.deployIncludePaths) && config.deployIncludePaths.length > 0 ? config.deployIncludePaths : DEFAULT_EGG_MINIMAL_INCLUDE_PATHS, - deployExcludePaths: Array.isArray(config.deployExcludePaths) ? config.deployExcludePaths : [ 'config/**' ], + deployExcludePaths: Array.isArray(config.deployExcludePaths) ? config.deployExcludePaths : [ ...DEFAULT_EXCLUDE_PATHS ], sshOptions, }; } @@ -275,7 +281,7 @@ function pathMatchesRule(filePath, rule) { function listDeployableFiles(config) { const output = runCommand('git', [ 'ls-files', '--cached', '--others', '--exclude-standard' ]); const includeRules = Array.isArray(config && config.deployIncludePaths) ? config.deployIncludePaths : DEFAULT_EGG_MINIMAL_INCLUDE_PATHS; - const excludeRules = Array.isArray(config && config.deployExcludePaths) ? config.deployExcludePaths : [ 'config/**' ]; + const excludeRules = Array.isArray(config && config.deployExcludePaths) ? config.deployExcludePaths : DEFAULT_EXCLUDE_PATHS; const allExcludeRules = [ ...excludeRules, ...RELEASE_PINNED_EXCLUDE_PATHS ]; return Array.from(new Set( diff --git a/script/deploy-watchdog.cjs b/script/deploy-watchdog.cjs new file mode 100644 index 0000000..39b5ed8 --- /dev/null +++ b/script/deploy-watchdog.cjs @@ -0,0 +1,292 @@ +'use strict'; + +/** + * qimen 接口服务看门狗(keep-alive)的安装与运维工具。 + * + * 与 script/deploy-cert-sync.cjs 同源思路,但对象完全不同: + * - 安装对象:script/qimen-watchdog.sh(仓库源)→ <部署根>/script/qimen-watchdog.sh(服务器稳定副本) + * - 调度载体:/etc/cron.d/qimen-watchdog(系统级 cron.d) + * **刻意不放 root crontab**:宝塔面板会整体重写 root crontab,放那儿会被冲掉。 + * - 日志:/www/wwwlogs/wms/qimen-watchdog.log + * + * 为什么副本放部署根下的 script/ 目录而不是 v1/v2: + * 与证书同步脚本同理——不受版本切换与发布清理影响,版本目录里没有它的位置; + * 同时与 warehouse-cert-sync.sh / warehouse-cert-sync.cjs 收口在同一目录,运维只需看一处。 + * install 会把历史位置(部署根)的同名副本一次性挪成 script/.legacy-<时间戳> 备份。 + * + * 设计要点: + * 1. 幂等:可重复 install;cron.d 文件用「临时文件 + mv」原子覆盖,不会出现半截配置; + * 2. 备份:覆盖前把既有副本 cp -a 成 .prev-<时间戳>,保留回滚余地; + * 3. 去重:若 root crontab 里存在历史 watchdog 行(早期手工装的),install 会删掉, + * 避免与 cron.d 条目双跑——看门狗双跑会并发 kill/start 同一实例,风险很高; + * 4. 校验三连:bash -n 语法校验 + sha256 与本地源比对(不一致直接失败)+ + * 远端 --dry-run 冒烟(只探活、绝不启动/杀进程); + * 5. 不碰服务:install 不重启 qimen、不 reload nginx、不动任何数据库。 + * + * 用法: + * node script/deploy-watchdog.cjs production precheck + * node script/deploy-watchdog.cjs production install + * node script/deploy-watchdog.cjs production status + * node script/deploy-watchdog.cjs production dry-run # 远端执行 --dry-run(只探活并报告) + * node script/deploy-watchdog.cjs production run # 远端真实保活(探活失败才会拉起服务) + * + * 退出码:0 成功;非 0 失败(参数非法 / 本地文件缺失 / sha 不一致 / 远端命令失败)。 + */ + +const fs = require('node:fs'); +const path = require('node:path'); +const crypto = require('node:crypto'); +const { + ROOT, + getNowStamp, + loadDeployConfig, + quoteForBash, + runScp, + runSsh, +} = require('./deploy-lib.cjs'); + +const COMMANDS = new Set([ 'precheck', 'install', 'status', 'dry-run', 'run' ]); +const COMMAND_HINT = 'precheck | install | status | dry-run | run'; + +/** 仓库源文件(脚本本体)。 */ +const LOCAL_WATCHDOG = path.join(ROOT, 'script', 'qimen-watchdog.sh'); + +/** 服务器副本文件名(落在部署根的 script/ 目录下,与 cert-sync 脚本同目录)。 */ +const REMOTE_FILENAME = 'qimen-watchdog.sh'; +/** 服务器副本相对部署根的路径。 */ +const REMOTE_RELATIVE = `script/${REMOTE_FILENAME}`; +/** cron.d 文件名 / 路径(名称不含点,避免被 cron 忽略)。 */ +const CRON_D_NAME = 'qimen-watchdog'; +const CRON_D_PATH = `/etc/cron.d/${CRON_D_NAME}`; +const LOG_PATH = '/www/wwwlogs/wms/qimen-watchdog.log'; +const LOCK_PATH = '/var/lock/qimen-watchdog.lock'; +const CRON_SCHEDULE = '*/5 * * * *'; +const CRON_USER = 'root'; + +/** + * 解析命令行参数。 + * @param {string[]} argv process.argv.slice(2)。 + * @return {{envName: string, command: string}} 解析结果。 + * @throws {Error} 缺少/非法命令时抛出。 + */ +function parseArgs(argv) { + const options = { envName: 'production', command: '' }; + const tokens = [ ...argv ]; + if (tokens.length === 0) { + throw new Error(`missing command: ${COMMAND_HINT}`); + } + if (!COMMANDS.has(tokens[0])) { + options.envName = tokens[0]; + tokens.shift(); + } + if (tokens.length === 0 || !COMMANDS.has(tokens[0])) { + throw new Error(`missing command: ${COMMAND_HINT}`); + } + options.command = tokens[0]; + return options; +} + +/** + * 计算本地文件 sha256(十六进制,小写)。 + * @param {string} filePath 文件绝对路径。 + * @return {string} sha256 摘要。 + */ +function localSha256(filePath) { + return crypto.createHash('sha256').update(fs.readFileSync(filePath)).digest('hex'); +} + +/** + * 目标服务器上的看门狗脚本绝对路径。 + * @param {Object} config deploy 配置对象。 + * @return {string} 绝对路径。 + */ +function remoteWatchdogPath(config) { + return `${config.deployRoot}/${REMOTE_RELATIVE}`; +} + +/** + * 生成 /etc/cron.d/qimen-watchdog 的完整内容。 + * @param {string} watchdogPath 服务器上的看门狗脚本绝对路径。 + * @return {string} cron.d 文件内容(含首部注释与 env 声明)。 + */ +function buildCronFileContent(watchdogPath) { + return [ + '# qimen 接口服务看门狗(保活)', + '# 由 npm run deploy:watchdog:install 维护,请勿手工编辑(会被下次安装覆盖)。', + '# 仓库源:script/qimen-watchdog.sh;服务器稳定副本:<部署根>/script/qimen-watchdog.sh', + '# 放在 /etc/cron.d 而非 root crontab:宝塔面板会整体重写 root crontab,会把它冲掉。', + '# 手动验证:bash <部署根>/script/qimen-watchdog.sh --dry-run', + 'SHELL=/bin/bash', + 'PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + `${CRON_SCHEDULE} ${CRON_USER} ${watchdogPath} >> ${LOG_PATH} 2>&1`, + '', + ].join('\n'); +} + +/** + * 只读预检:确认目标机具备安装条件。 + * @param {Object} config deploy 配置对象。 + * @return {void} + */ +function runPrecheck(config) { + const deployRoot = config.deployRoot; + const remoteScript = [ + 'set -uo pipefail', + `DEPLOY_ROOT=${quoteForBash(deployRoot)}`, + `TARGET="$DEPLOY_ROOT/${REMOTE_FILENAME}"`, + 'echo "[WHOAMI] $(id -un)"', + 'echo "[UNAME] $(uname -a)"', + 'echo "[DEPLOY_ROOT_LS]"; ls -la "$DEPLOY_ROOT" | awk \'{print $1, $3, $4, $9}\'', + 'echo "[CURRENT_MD] $(cat "$DEPLOY_ROOT/current.md" 2>/dev/null | tr -d "[:space:]" || echo MISSING)"', + 'echo "[UPSTREAM_CONF]"; cat "$DEPLOY_ROOT/nginx-upstream.conf" 2>/dev/null || echo "(missing)"', + 'echo "[WATCHDOG_FILE]"; if [ -f "$TARGET" ]; then ls -l --time-style=full-iso "$TARGET"; sha256sum "$TARGET"; else echo "MISSING"; fi', + 'echo "[CRON_D]"; if [ -f ' + quoteForBash(CRON_D_PATH) + ' ]; then cat ' + quoteForBash(CRON_D_PATH) + '; else echo "MISSING"; fi', + 'echo "[CRON_SERVICE]"; systemctl is-active cron 2>/dev/null || (service cron status 2>/dev/null | head -1) || echo unknown', + 'echo "[ROOT_CRONTAB_MATCH]"; crontab -l 2>/dev/null | grep -n "qimen-watchdog" || echo NONE', + 'echo "[LOG]"; ls -l ' + quoteForBash(LOG_PATH) + ' 2>/dev/null || echo "log missing"; tail -5 ' + quoteForBash(LOG_PATH) + ' 2>/dev/null', + 'echo "[LOCK]"; ls -l ' + quoteForBash(LOCK_PATH) + ' 2>/dev/null || echo "lock not created yet"', + 'echo "[INSTANCES]"; ps -eo pid=,etime=,args= | grep "[e]gg-scripts start" | head -6 || true', + 'echo "[PORTS]"; ss -lntp 2>/dev/null | grep -E ":6061|:6062" || echo "no 6061/6062 listener"', + ].join('\n'); + + console.log('[PRECHECK] watchdog remote env check (read-only, no service start/kill)'); + console.log(String(runSsh(config, remoteScript, { stdio: 'pipe' }) || '').trim()); +} + +/** + * 安装:备份旧副本 → 上传脚本 → 写 cron.d → 清理历史 root crontab 行 → 语法/哈希/冒烟校验。 + * @param {Object} config deploy 配置对象。 + * @return {void} + */ +function runInstall(config) { + const deployRoot = config.deployRoot; + if (!fs.existsSync(LOCAL_WATCHDOG)) { + throw new Error(`local file missing: ${LOCAL_WATCHDOG} (script/qimen-watchdog.sh)`); + } + const localSha = localSha256(LOCAL_WATCHDOG); + const target = remoteWatchdogPath(config); + + console.log(`[INSTALL] local source: ${LOCAL_WATCHDOG} sha256=${localSha}`); + + const remoteDirScript = [ + 'set -euo pipefail', + `DEPLOY_ROOT=${quoteForBash(deployRoot)}`, + `TARGET="$DEPLOY_ROOT/${REMOTE_RELATIVE}"`, + `STAMP=${quoteForBash(getNowStamp())}`, + 'mkdir -p "$DEPLOY_ROOT/script" /www/wwwlogs/wms', + '# 历史位置(部署根)一次性迁移:旧副本挪进 script/ 留作回滚备份,避免根目录残留孤儿', + 'LEGACY="$DEPLOY_ROOT/qimen-watchdog.sh"', + 'if [ -f "$LEGACY" ]; then mv "$LEGACY" "$DEPLOY_ROOT/script/qimen-watchdog.sh.legacy-$STAMP" && echo "LEGACY_MOVED $LEGACY -> $DEPLOY_ROOT/script/qimen-watchdog.sh.legacy-$STAMP"; fi', + 'if [ -f "$TARGET" ]; then cp -a "$TARGET" "$TARGET.prev-$STAMP" && echo "BACKED_UP $TARGET -> $TARGET.prev-$STAMP"; else echo "NO_EXISTING_COPY"; fi', + `touch ${quoteForBash(LOG_PATH)} && chmod 644 ${quoteForBash(LOG_PATH)} && echo "LOG_FILE_OK"`, + ].join('\n'); + console.log('[INSTALL] remote dir prep + backup of existing copy'); + console.log(String(runSsh(config, remoteDirScript, { stdio: 'pipe' }) || '').trim()); + + runScp(config, LOCAL_WATCHDOG, target); + console.log(`[INSTALL] uploaded -> ${target}`); + + const finalizeScript = [ + 'set -euo pipefail', + `TARGET=${quoteForBash(target)}`, + `CRON_D=${quoteForBash(CRON_D_PATH)}`, + 'chmod 755 "$TARGET" && echo "CHMOD_OK"', + 'bash -n "$TARGET" && echo "WATCHDOG_SYNTAX_OK"', + `LOCAL_SHA=${quoteForBash(localSha)}`, + 'REMOTE_SHA_LINE=$(sha256sum "$TARGET")', + 'REMOTE_SHA=${REMOTE_SHA_LINE%% *}', + 'if [ "$REMOTE_SHA" = "$LOCAL_SHA" ]; then echo "SHA_MATCH $REMOTE_SHA"; else echo "SHA_MISMATCH local=$LOCAL_SHA remote=$REMOTE_SHA"; exit 1; fi', + 'TMP=$(mktemp /tmp/qimen-watchdog.cron.XXXXXX)', + 'cat > "$TMP" <<\'QIMEN_WATCHDOG_CRON_EOF\'', + buildCronFileContent(target).replace(/\n+$/, ''), + 'QIMEN_WATCHDOG_CRON_EOF', + 'chown root:root "$TMP" && chmod 644 "$TMP"', + 'mv "$TMP" "$CRON_D" && echo "CRON_D_WRITTEN $CRON_D"', + 'echo "[CRON_D_CONTENT]"', + 'cat "$CRON_D"', + 'if crontab -l 2>/dev/null | grep -q "qimen-watchdog"; then', + ' crontab -l 2>/dev/null | grep -v "qimen-watchdog" | crontab -', + ' echo "ROOT_CRONTAB_DEDUPED (legacy watchdog line removed)"', + 'else', + ' echo "ROOT_CRONTAB_CLEAN"', + 'fi', + 'echo "[CRON_SERVICE] $(systemctl is-active cron 2>/dev/null || echo unknown)"', + 'echo "[SMOKE] bash $TARGET --dry-run (probe only, never starts/kills)"', + 'bash "$TARGET" --dry-run 2>&1 | tail -15 || true', + ].join('\n'); + + console.log('[INSTALL] write cron.d + verify (syntax / sha256 / dry-run smoke)'); + console.log(String(runSsh(config, finalizeScript, { stdio: 'pipe' }) || '').trim()); +} + +/** + * 状态:只读查看副本、cron.d、日志、锁、探活结果,并与本地源比对哈希。 + * @param {Object} config deploy 配置对象。 + * @return {void} + */ +function runStatus(config) { + const target = remoteWatchdogPath(config); + const localSha = fs.existsSync(LOCAL_WATCHDOG) ? localSha256(LOCAL_WATCHDOG) : '(local file missing)'; + + const remoteScript = [ + 'set -uo pipefail', + `TARGET=${quoteForBash(target)}`, + `CRON_D=${quoteForBash(CRON_D_PATH)}`, + 'echo "[WATCHDOG_FILE]"; if [ -f "$TARGET" ]; then ls -l --time-style=full-iso "$TARGET"; else echo "MISSING"; fi', + 'echo "[SHA_REMOTE]"; sha256sum "$TARGET" 2>/dev/null || echo "(missing)"', + 'echo "[CRON_D]"; cat "$CRON_D" 2>/dev/null || echo "MISSING"', + 'echo "[CRON_SERVICE]"; systemctl is-active cron 2>/dev/null || echo unknown', + 'echo "[ROOT_CRONTAB_MATCH]"; crontab -l 2>/dev/null | grep -n "qimen-watchdog" || echo NONE', + 'echo "[LOCK]"; ls -l ' + quoteForBash(LOCK_PATH) + ' 2>/dev/null || echo "lock not created yet"', + 'echo "[LOG_TAIL]"; tail -10 ' + quoteForBash(LOG_PATH) + ' 2>/dev/null || echo "log missing"', + 'echo "[INSTANCES]"; ps -eo pid=,etime=,args= | grep "[e]gg-scripts start" | head -6 || true', + 'echo "[PORTS]"; ss -lntp 2>/dev/null | grep -E ":6061|:6062" || echo "no 6061/6062 listener"', + 'echo "[PROBE_DRY_RUN]"; bash "$TARGET" --dry-run 2>&1 | tail -12 || true', + ].join('\n'); + + console.log('[STATUS] watchdog (read-only; probe uses --dry-run)'); + console.log(`[STATUS] local source sha256 = ${localSha}`); + console.log(String(runSsh(config, remoteScript, { stdio: 'pipe' }) || '').trim()); +} + +/** + * 远端执行看门狗脚本(转发参数)。 + * @param {Object} config deploy 配置对象。 + * @param {string[]} extraArgs 追加参数(如 --dry-run)。 + * @return {string} 远端输出。 + */ +function runRemoteWatchdog(config, extraArgs = []) { + const script = `bash ${quoteForBash(remoteWatchdogPath(config))}${extraArgs.map(arg => ` ${arg}`).join('')}`; + return String(runSsh(config, script) || ''); +} + +function main() { + const options = parseArgs(process.argv.slice(2)); + const config = loadDeployConfig(options.envName); + + if (options.command === 'precheck') { + runPrecheck(config); + return; + } + if (options.command === 'install') { + runInstall(config); + return; + } + if (options.command === 'status') { + runStatus(config); + return; + } + if (options.command === 'dry-run') { + console.log('[DRY-RUN] remote watchdog --dry-run (probe only, never starts/kills)'); + console.log(runRemoteWatchdog(config, [ '--dry-run' ])); + return; + } + if (options.command === 'run') { + console.log('[RUN] remote watchdog real execution (starts the instance only when probe fails)'); + console.log(runRemoteWatchdog(config, [])); + return; + } + throw new Error(`unsupported command: ${options.command}`); +} + +main(); diff --git a/script/qimen-watchdog.sh b/script/qimen-watchdog.sh index 73cf2fb..de4b821 100644 --- a/script/qimen-watchdog.sh +++ b/script/qimen-watchdog.sh @@ -29,10 +29,14 @@ # # cron(系统级,不放在 root crontab —— 宝塔面板会整体重写 root crontab,会把它冲掉): # /etc/cron.d/qimen-watchdog -# */5 * * * * root /www/wwwroot/qimen/qimen-watchdog.sh >> /www/wwwlogs/wms/qimen-watchdog.log 2>&1 +# */5 * * * * root /www/wwwroot/qimen/script/qimen-watchdog.sh >> /www/wwwlogs/wms/qimen-watchdog.log 2>&1 # # 仓库源文件:script/qimen-watchdog.sh(本文件是它在服务器上的稳定副本,更新后需重新安装; -# 放 deploy 根目录而非 v1/v2 内,是为了不受版本切换与发布清理影响)。 +# 放 deploy 根下的 script/ 目录而非 v1/v2 内,是为了不受版本切换与发布清理影响, +# 并与 warehouse-cert-sync.sh / warehouse-cert-sync.cjs 收口在同一目录)。 +# +# 安装/更新:npm run deploy:watchdog:install(script/deploy-watchdog.cjs; +# 会把历史位置 <部署根>/qimen-watchdog.sh 挪成 script/<名>.legacy-<时间戳> 备份)。 # set -u diff --git a/script/warehouse-cert-sync.cjs b/script/warehouse-cert-sync.cjs index a9220aa..95a2bf8 100644 --- a/script/warehouse-cert-sync.cjs +++ b/script/warehouse-cert-sync.cjs @@ -3,32 +3,90 @@ /** * 仓库前端证书同步脚本(nginx 部署器)。 * - * 职责:扫描 wms_warehouse_front_config 中 sync_status=0(待同步)的记录, - * 将 cert_pem / cert_key 内容写为证书文件,生成对应域名 server 块, - * 逐条 nginx -t 校验后统一 reload,并回写部署状态。 - * 生成的 server 块只含证书骨架(listen / server_name / ssl_certificate*), - * 站点级个性化配置(location / root / 伪静态等)全部外置到 customDir 契约目录, - * 本脚本不在生成的 server 块内内联任何 location 指令。 - * 另外承担「旧域名下线」(两阶段域名切换的应用侧配套,应用不碰 nginx 文件): - * - 消费 retired_domain:删除旧域名残留的 server 块与证书文件,删干净后才清空该槽位; - * - 孤儿兜底清理:以目录实际文件为准做差集,回收因 retired_domain 单槽位丢失而残留的旧产物; - * - 统计口径:汇总的「待删 / 已删文件数」按绝对路径去重后输出;通道命中数(retired_domain / orphan) - * 单独列示,两者之和大于去重数属预期(dry-run 不落盘,两条通道都会看到同一文件); - * - 只要本轮删过文件,就先 nginx -t 再 reload;-t 失败回滚本轮删除并保留 retired_domain 待下轮重试。 - + * 职责:每轮以「声明式对账 + 自愈」模式运行——从 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 适配), - * 必须幂等、可重入:重复执行会覆盖同名文件与 conf,无副作用。 - * - 逐条失败隔离:单条写文件失败 / nginx -t 失败只回写该条 + * 必须幂等、可重入:内容一致时零写入、零 reload。 + * - 逐条失败隔离:单条写文件失败只回写该条 * sync_status=2 + last_sync_error + sync_attempts+1,不影响其他条目; - * nginx -t 失败时撤销本条 server 块,保证不拖垮整体 nginx。 - * - reload 策略:本批有成功条目时执行一次 nginx -s reload; - * reload 失败时本批成功条目回退 sync_status=0(下分钟自动重试, - * sync_attempts 达到 RELOAD_FAILURE_MAX_RETRY 后转 sync_status=2 终止重试)。 - * - 站点个性化配置外置:server 块尾部以 include //*.conf 收口, - * 脚本只负责该目录存在与默认反代文件(00-default.conf)的首次生成, - * 用户自定义 *.conf 一律保留、永不覆盖,详见「部署约定」customDir 契约。 + * 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」原子写。 @@ -45,26 +103,21 @@ * 生产环境宁可不跑也不猜,开发环境同样显式报错而非静默回退。 * - 参数优先级:CLI 参数 > 环境变量 > 外部配置文件 > 内置默认。 * - 证书目录 / nginx server 块目录 / upstream include / nginx 二进制 / - * reload 与 -t 命令默认全部来自配置文件;生产配置中 certDir/confDir 相对 - * cwd(部署根 /www/wwwroot/qimen)解析为 ../.ssl 与 ../nginx_config, - * 目录不存在时自动递归创建;nginx 主配置由运维自行 include ../nginx_config/*.conf, - * 本脚本不管理主配置。 - * - customDir 契约(站点个性化配置外置,运维改站点只需动这里): - * - 一域名一目录://(目录名沿用文件名清洗推导, - * 清洗后与原域名不一致时带 _短哈希8 防碰撞); - * - 生成块尾部 include //*.conf(通配符:目录不存在 / - * 目录为空 / 目录有文件三种情况 nginx -t 均通过,已在生产 nginx 1.28.0 实测); - * - 默认文件 //00-default.conf(0644 原子写):仅当目录内 - * 没有其它 *.conf 时由脚本写入一次,之后永不覆盖;内容为默认反代 - * (include upstream + Host / X-Warehouse-Domain 头),首行带脚本标记; - * - 放自定义文件(实现 root + 伪静态等):把任意命名的 *.conf 放进该域名目录; - * 一旦存在自定义 *.conf,脚本不再写默认文件,并自动删除脚本自产的 - * 00-default.conf(避免两个 location / 触发 nginx duplicate location); - * 只有带脚本标记的 00-default.conf 才会被删除,无标记文件一律不动; - * - customDir 默认 /custom(生产 /www/wwwroot/nginx_config/custom、 - * 开发 D:/wms/nginx_config/custom),位于部署根上一级之外,发布回退不会触碰; - * - 旧域名下线只删 confDir 根层的 server 块,custom// 目录保留不删 - * (旧 server 块删除后其 include 已失效,残留目录无副作用,可能被运维移作他用)。 + * 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 负责)。 @@ -78,11 +131,12 @@ * 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 致命:参数非法 / DB 连接失败 / 目录不可建 / 生产环境 nginx 缺失; - * 2 业务级失败:本批存在条目处理失败或 nginx reload 失败(详情已回写 DB)。 + * 0 正常:无变更、本批全部成功、dry-run 完成; + * 1 致命:参数非法(含 ver 非法)/ DB 连接失败 / 目录不可建 / 生产环境 nginx 缺失; + * 2 业务级失败:本批存在条目处理失败或 nginx -t / reload 失败(详情已回写 DB)。 */ const fs = require('node:fs'); @@ -103,6 +157,8 @@ 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)。 @@ -116,6 +172,8 @@ 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'; @@ -125,15 +183,11 @@ const EXIT_BUSINESS_FAILURE = 2; const CERT_FILE_MODE = 0o644; const KEY_FILE_MODE = 0o600; -const CUSTOM_DIR_MODE = 0o755; -const CUSTOM_CONF_FILE_MODE = 0o644; -const DEFAULT_CUSTOM_CONF_NAME = '00-default.conf'; -const DEFAULT_CUSTOM_CONF_MARKER = '由 warehouse-cert-sync 生成的默认站点配置'; const TABLE_NAME = 'wms_warehouse_front_config'; -// ---- 旧域名下线 / 孤儿兜底清理相关常量 ---- -// conf 文件名形态:{domainSafe}{[_短哈希8]}.conf(与 buildConfFileName 产物一致,仅作第一道形态闸门) +// ---- 域名下线(配置差集)与清理相关常量 ---- +// 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)$/; @@ -143,9 +197,13 @@ const SERVER_NAME_PATTERN = /^[ \t]*server_name[ \t]+([^;]+);/m; /** * 单条处理结果统计。 * @typedef {Object} SyncStats - * @property {number} total 本批扫描到的待同步条数。 - * @property {number} success 成功条数。 - * @property {number} failed 失败条数。 + * @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 证书/域名内容非法的条数(行级失败)。 */ /** @@ -154,13 +212,13 @@ const SERVER_NAME_PATTERN = /^[ \t]*server_name[ \t]+([^;]+);/m; * @property {string} env 数据库环境标记:development | production。 * @property {string} configPath 生效的外部配置文件绝对路径。 * @property {boolean} dryRun 仅扫描与输出计划,不写文件、不改库。 - * @property {boolean} cleanupOnly 只做旧域名下线与孤儿兜底清理,不做证书同步(--cleanup-only)。 + * @property {boolean} cleanupOnly 只做域名下线差集与过期 conf 清理,不做证书同步(--cleanup-only)。 * @property {boolean} skipNginx 跳过 nginx -t / reload。 * @property {string} certDir 证书输出目录(绝对路径)。 * @property {string} confDir nginx server 块目录(绝对路径)。 - * @property {string} customDir 站点个性化配置外置目录(绝对路径,默认 /custom)。 * @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 命令覆盖(空串按系统类型推导)。 @@ -200,20 +258,18 @@ function printUsage() { ' 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 / customDir / upstreamInclude / testCmd / reloadCmd', - ' (customDir 可缺省,缺省即 /custom)', + ' 支持键: nginxBin / nginxPrefix / certDir / confDir / upstreamInclude / testCmd / reloadCmd / ver', '', '参数优先级: CLI 参数 > 环境变量 > 外部配置文件 > 内置默认', '', '选项:', ' --env 运行环境(必填,显式指定,不受终端 NODE_ENV 残留影响,同时决定数据库与配置文件)', - ' --dry-run 仅扫描并输出计划,不写文件、不改库(含旧域名下线/孤儿清理的待删清单)', - ' --cleanup-only 只做旧域名下线与孤儿兜底清理,不做证书同步(供运维单独执行)', + ' --dry-run 仅扫描并输出计划,不写文件、不改库(含下线差集待删清单)', + ' --cleanup-only 只做域名下线差集与过期 conf 清理,不做证书同步(供运维单独执行)', ' --cert-dir 证书输出目录(默认取配置文件或 ../.ssl,相对路径按 cwd 解析)', ' --conf-dir nginx server 块目录(默认取配置文件或 ../nginx_config,同样按 cwd 解析)', - ' --custom-dir 站点个性化配置外置目录(默认取配置文件或 /custom,按 cwd 解析)', - ' --upstream-include 默认站点配置(custom/<域名>/00-default.conf)include 的 upstream 配置名', - ' (默认取配置文件或 nginx-upstream.conf)', + ' --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 劫持,默认取配置文件)', @@ -222,11 +278,13 @@ function printUsage() { ' 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_CUSTOM_DIR', - ' CERT_SYNC_UPSTREAM_INCLUDE / CERT_SYNC_LIMIT / CERT_SYNC_NGINX_BIN / CERT_SYNC_NGINX_PREFIX', + ' 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)', '', @@ -276,7 +334,6 @@ function parseArgs(argv) { env: '', certDir: '', confDir: '', - customDir: '', upstreamInclude: '', nginxBin: '', nginxPrefix: '', @@ -320,8 +377,6 @@ function parseArgs(argv) { cli.certDir = String(readValue() || '').trim(); } else if (key === '--conf-dir') { cli.confDir = String(readValue() || '').trim(); - } else if (key === '--custom-dir') { - cli.customDir = String(readValue() || '').trim(); } else if (key === '--upstream-include') { cli.upstreamInclude = String(readValue() || '').trim(); } else if (key === '--nginx-bin') { @@ -334,6 +389,8 @@ function parseArgs(argv) { 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}`); } @@ -345,13 +402,13 @@ function parseArgs(argv) { configPath: '', certDir: '', confDir: '', - customDir: '', 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, @@ -375,10 +432,8 @@ function parseArgs(argv) { return String(value).trim(); }; - // customDir 缺省值依赖 confDir(/custom),故先解析 confDir 再回填 + // confDir 统一解析为绝对路径(目录不存在时在运行阶段递归创建) const confDir = path.resolve(pickString(cli.confDir, 'CERT_SYNC_CONF_DIR', config.confDir, DEFAULT_CONF_DIR)); - const customDirRaw = pickString(cli.customDir, 'CERT_SYNC_CUSTOM_DIR', config.customDir, ''); - const customDir = customDirRaw ? path.resolve(customDirRaw) : path.join(confDir, 'custom'); const args = { env, @@ -389,13 +444,13 @@ function parseArgs(argv) { help: false, certDir: path.resolve(pickString(cli.certDir, 'CERT_SYNC_CERT_DIR', config.certDir, DEFAULT_CERT_DIR)), confDir, - customDir, 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) { @@ -404,13 +459,52 @@ function parseArgs(argv) { 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 约定), @@ -468,13 +562,13 @@ function connectDb(args) { * @param {string} nginxBin nginx 可执行文件路径。 * @param {string} nginxPrefix nginx -p 前缀目录(空串表示不启用,供 {nginxPrefix} 占位符使用)。 * @param {string[]} args nginx 参数数组(默认推导场景)。 - * @param {string} customCommand 自定义覆盖命令(空串表示使用默认推导)。 + * @param {string} overrideCommand 自定义覆盖命令(空串表示使用默认推导)。 * @return {NginxCommandDesc} 命令执行描述。 * @throws {Error} 自定义命令含 {nginxPrefix} 占位符但未提供 nginxPrefix 时抛出异常。 */ -function buildNginxCommand(nginxBin, nginxPrefix, args, customCommand) { - if (customCommand) { - if (String(customCommand).includes('{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 按空白/斜杠二次切分 @@ -482,7 +576,7 @@ function buildNginxCommand(nginxBin, nginxPrefix, args, customCommand) { ? `"${String(value).replace(/"/g, '')}"` : `'${String(value).replace(/'/g, '')}'`); return { - command: String(customCommand) + command: String(overrideCommand) .split('{nginxBin}') .join(quoteShellValue(nginxBin)) .split('{nginxPrefix}') @@ -560,28 +654,6 @@ async function hasDomainStatusColumn(sequelize) { } } -/** - * 扫描待同步记录(sync_status=0、且域名已验证 domain_status=1,按 id 升序,limit 条)。 - * - * 域名验证闸门:未通过验证(domain_status 为 0/2)的域名不生成 nginx server 块; - * filterVerifiedDomain 为 false 时(迁移尚未执行、无 domain_status 列)降级为不过滤。 - * @param {import('sequelize').Sequelize} sequelize Sequelize 实例。 - * @param {number} limit 单次处理条数上限。 - * @param {boolean} [filterVerifiedDomain] 是否只取已验证域名,默认 true。 - * @return {Promise} 待同步记录数组。 - */ -async function scanPendingRows(sequelize, limit, filterVerifiedDomain = true) { - const verifiedFilter = filterVerifiedDomain ? ' AND domain_status = 1' : ''; - return sequelize.query( - `SELECT id, store_id, domain, cert_pem, cert_key, cert_expire_at, sync_attempts - FROM ${TABLE_NAME} - WHERE sync_status = 0${verifiedFilter} - ORDER BY id ASC - LIMIT ?`, - { replacements: [ limit ], type: Sequelize.QueryTypes.SELECT } - ); -} - /** * 将域名清洗为安全的文件名片段(非法字符替换为下划线)。 * @param {string} input 原始域名。 @@ -621,15 +693,38 @@ function computeDomainNameParts(domainRaw) { } /** - * 推导域名对应的 server 块文件名({domainSafe}{suffix}.conf)。 - * 写入(buildFileNames)与删除(旧域名下线 / 孤儿兜底清理)共用本推导, + * 推导域名对应的 server 块文件名({domainSafe}{suffix}-{ver}.conf,命名推导单点收敛)。 + * 写入(buildFileNames)、过期 conf 清理、下线差集删除共用本推导, * 保证「按名删除」与「按名写入」严格一致。 * @param {string} domainRaw 原始域名(已 trim)。 + * @param {string} ver conf 命名版本(已通过 VER_PATTERN 白名单校验)。 * @return {string} conf 文件名(不含目录)。 */ -function buildConfFileName(domainRaw) { +function buildConfFileName(domainRaw, ver) { const parts = computeDomainNameParts(domainRaw); - return `${parts.domainSafe}${parts.suffix}.conf`; + 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; } /** @@ -643,42 +738,20 @@ function buildCertBaseName(storeId, domainRaw) { return `${storeId}_${parts.domainSafe}${parts.suffix}`; } -/** - * 推导域名的站点个性化配置外置路径(customDir 契约,一域名一目录)。 - * 目录名与 server 块 / 证书文件共用同一套命名推导(computeDomainNameParts), - * 保证「生成块 include 的目录」与「脚本维护的目录」严格一致。 - * @param {SyncArgs} args 解析后的参数集合。 - * @param {string} domainRaw 原始域名(已 trim)。 - * @return {{customDirPath: string, customGlobPath: string, defaultPath: string}} 外置配置路径集合。 - */ -function buildCustomPaths(args, domainRaw) { - const parts = computeDomainNameParts(domainRaw); - const customDirPath = path.join(args.customDir, `${parts.domainSafe}${parts.suffix}`); - return { - customDirPath, - customGlobPath: path.join(customDirPath, '*.conf'), - defaultPath: path.join(customDirPath, DEFAULT_CUSTOM_CONF_NAME), - }; -} - /** * 生成一条记录的文件名与落盘路径(命名推导见 computeDomainNameParts)。 * @param {SyncArgs} args 解析后的参数集合。 * @param {number} storeId 仓库 ID。 * @param {string} domainRaw 原始域名(已 trim)。 - * @return {{baseName: string, certPath: string, keyPath: string, confPath: string, - * customDirPath: string, customGlobPath: string}} 文件路径集合。 + * @return {{baseName: string, certPath: string, keyPath: string, confPath: string}} 文件路径集合。 */ function buildFileNames(args, storeId, domainRaw) { const baseName = buildCertBaseName(storeId, domainRaw); - const customPaths = buildCustomPaths(args, domainRaw); return { baseName, certPath: path.join(args.certDir, `${baseName}.pem`), keyPath: path.join(args.certDir, `${baseName}.key`), - confPath: path.join(args.confDir, buildConfFileName(domainRaw)), - customDirPath: customPaths.customDirPath, - customGlobPath: customPaths.customGlobPath, + confPath: path.join(args.confDir, buildConfFileName(domainRaw, args.ver)), }; } @@ -714,126 +787,27 @@ function validateRowContent(domainRaw, certPem, keyPem) { } /** - * 生成 server 块内容(仅证书骨架 + 外置站点配置 include,不含任何 location)。 - * 站点级 location / root / 伪静态等个性化配置由运维放入 // 下的 - * *.conf,本脚本绝不内联也不覆盖。 + * 生成 server 块内容(证书骨架 + 一行 include ,不含任何 location)。 + * 站点内容(root / 伪静态 或 反代)统一由 upstreamInclude 指向的片段文件提供, + * 由运维维护、本脚本绝不覆盖;前端个性化在运行时由配置接口按域名完成, + * nginx 侧无需按域名区分站点内容。 * @param {string} domain 域名(已通过白名单校验)。 * @param {string} certPath 证书文件绝对路径。 * @param {string} keyPath 私钥文件绝对路径。 - * @param {string} customGlobPath 站点个性化配置外置目录通配路径(//*.conf)。 + * @param {string} upstreamInclude upstream 站点内容片段 include 路径(运维维护)。 * @return {string} server 块文本。 */ -function buildServerConf(domain, certPath, keyPath, customGlobPath) { +function buildServerConf(domain, certPath, keyPath, upstreamInclude) { return `server { listen 443 ssl; server_name ${domain}; ssl_certificate ${certPath}; ssl_certificate_key ${keyPath}; - include ${customGlobPath}; -} -`; -} - -/** - * 生成默认站点配置内容(customDir 契约的 00-default.conf)。 - * 仅在目录内没有其它 *.conf 时由脚本写入一次,之后不再覆盖; - * 首行标记同时用作「脚本自产」判定,确保清理时不会误删用户文件。 - * @param {string} upstreamInclude upstream 配置文件 include 名。 - * @return {string} 默认站点配置文本。 - */ -function buildDefaultCustomConf(upstreamInclude) { - return `# ${DEFAULT_CUSTOM_CONF_MARKER}:仅在目录内无其它 *.conf 时写入,之后不再覆盖。 -location / { include ${upstreamInclude}; - proxy_set_header Host $host; - proxy_set_header X-Warehouse-Domain $host; } `; } -/** - * 确保域名的站点个性化配置外置目录与默认文件就绪(customDir 契约)。 - * - * 规则(幂等、绝不覆盖用户配置): - * 1. 递归创建 // 目录(0755),保证生成块的 include 通配符合法; - * dry-run 不建目录,只打印计划; - * 2. 目录内已有其它 *.conf(默认文件除外)→ 视为用户自定义配置,一律保留: - * - 不写入默认文件; - * - 若存在「脚本自产」的 00-default.conf(内容含脚本标记),删除之, - * 避免两个 location / 触发 nginx duplicate location;无标记的 00-default.conf - * 视为用户文件,不删不动(只有脚本自产默认文件允许被本函数删除); - * 3. 目录内无其它 *.conf → 确保默认文件存在:不存在则原子写 00-default.conf(0644), - * 已存在(无论是否被修改过)一律不覆盖。 - * @param {SyncArgs} args 解析后的参数集合。 - * @param {string} domainRaw 原始域名(已 trim)。 - * @return {{dirPath: string, defaultPath: string, hasCustom: boolean}} 目录 / 默认文件 / 是否已存在用户自定义配置。 - */ -function ensureCustomConf(args, domainRaw) { - const paths = buildCustomPaths(args, domainRaw); - - if (args.dryRun) { - console.log(`[CERT-SYNC][CUSTOM] 计划: 确保目录存在(mkdir -p 0755)-> ${paths.customDirPath}`); - } else { - try { - fs.mkdirSync(paths.customDirPath, { recursive: true, mode: CUSTOM_DIR_MODE }); - } catch (error) { - throw new Error(`创建站点个性化配置目录失败: ${paths.customDirPath} - ${error.message}`); - } - } - - // 扫描目录内现有 *.conf;dry-run 未建目录(ENOENT)按空目录处理 - let confNames = []; - try { - confNames = fs.readdirSync(paths.customDirPath, { withFileTypes: true }) - .filter(entry => entry.isFile() && /\.conf$/i.test(entry.name)) - .map(entry => entry.name); - } catch (error) { - if (!args.dryRun || !error || error.code !== 'ENOENT') { - throw error; - } - } - - const otherNames = confNames.filter(name => name !== DEFAULT_CUSTOM_CONF_NAME); - const hasDefaultFile = confNames.includes(DEFAULT_CUSTOM_CONF_NAME); - - // 已有用户自定义 *.conf:保留;顺带清掉脚本自产的默认文件(避免 duplicate location) - if (otherNames.length > 0) { - console.log(`[CERT-SYNC][CUSTOM] 已存在用户自定义配置 ${otherNames.length} 个(${otherNames.slice(0, 3).join(', ')}${otherNames.length > 3 ? ' …' : ''}),保留,不写入默认文件: ${paths.customDirPath}`); - if (hasDefaultFile) { - const defaultContent = readTextFileOrNull(paths.defaultPath); - if (defaultContent !== null && defaultContent.includes(DEFAULT_CUSTOM_CONF_MARKER)) { - if (args.dryRun) { - console.log(`[CERT-SYNC][CUSTOM] 计划: 删除脚本自产的默认文件(已有用户自定义配置,避免 duplicate location)-> ${paths.defaultPath}`); - } else { - removeFileQuiet(paths.defaultPath); - console.log(`[CERT-SYNC][CUSTOM] 已删除脚本自产的默认文件(已有用户自定义配置,避免 nginx duplicate location): ${paths.defaultPath}`); - } - } else { - console.warn(`[CERT-SYNC][CUSTOM][WARN] 默认文件存在但无脚本标记(非脚本自产),不删不动,请自行确认是否与用户配置冲突: ${paths.defaultPath}`); - } - } - return { dirPath: paths.customDirPath, defaultPath: paths.defaultPath, hasCustom: true }; - } - - // 目录内没有用户自定义:确保默认文件存在(已存在一律不覆盖) - if (hasDefaultFile) { - const defaultContent = readTextFileOrNull(paths.defaultPath); - if (defaultContent !== null && defaultContent.includes(DEFAULT_CUSTOM_CONF_MARKER)) { - console.log(`[CERT-SYNC][CUSTOM] 默认站点配置已存在(脚本自产),保持不变: ${paths.defaultPath}`); - } else { - console.warn(`[CERT-SYNC][CUSTOM][WARN] 默认文件已存在但无脚本标记(可能被运维修改),不覆盖不删除: ${paths.defaultPath}`); - } - return { dirPath: paths.customDirPath, defaultPath: paths.defaultPath, hasCustom: false }; - } - - if (args.dryRun) { - console.log(`[CERT-SYNC][CUSTOM] 计划: 目录内无自定义配置,将写入默认文件(仅首次)-> ${paths.defaultPath}`); - } else { - writeFileAtomic(paths.defaultPath, buildDefaultCustomConf(args.upstreamInclude), CUSTOM_CONF_FILE_MODE); - console.log(`[CERT-SYNC][CUSTOM] 已写入默认站点配置(仅首次生成,之后不再覆盖): ${paths.defaultPath}`); - } - return { dirPath: paths.customDirPath, defaultPath: paths.defaultPath, hasCustom: false }; -} /** * 原子写文件:先写同目录临时文件(指定权限),rename 覆盖目标; @@ -913,16 +887,7 @@ function sanitizeErrorText(text) { .slice(0, LAST_SYNC_ERROR_MAX_LENGTH); } -/** - * 回写单条失败状态:sync_status=2、last_sync_error、sync_attempts+1、 - * cert_path/key_path 置空(内容已换路径未知)。 - * WHERE 带 sync_status=0 与 domain 守卫,避免覆盖并发重新保存的结果。 - * @param {import('sequelize').Sequelize} sequelize Sequelize 实例。 - * @param {Object} row 记录对象(含 id、domain)。 - * @param {string} message 失败原因(原样日志,回写前会脱敏截断)。 - * @return {Promise} 无返回值。 - */ -async function markRowFailed(sequelize, row, message) { +async function markRowFailed(sequelize, row, message, priorStatus = 0) { await sequelize.query( `UPDATE ${TABLE_NAME} SET sync_status = 2, @@ -931,10 +896,158 @@ async function markRowFailed(sequelize, row, message) { cert_path = NULL, key_path = NULL, updated_at = NOW() - WHERE id = :id AND sync_status = 0 AND domain = :domain`, + 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, }, @@ -961,7 +1074,7 @@ async function markRowSuccess(sequelize, row, certPath, keyPath) { last_synced_at = NOW(), last_sync_error = NULL, updated_at = NOW() - WHERE id = :id AND sync_status = 0 AND domain = :domain`, + WHERE id = :id AND sync_status = 0 AND domain <=> :domain`, { replacements: { certPath, @@ -973,6 +1086,30 @@ async function markRowSuccess(sequelize, row, certPath, keyPath) { ); } +/** + * 回写自愈成功状态(保持 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 终止重试。 @@ -990,7 +1127,7 @@ async function markRowReloadRetry(sequelize, row, message) { last_sync_error = :error, sync_attempts = sync_attempts + 1, updated_at = NOW() - WHERE id = :id AND sync_status = 0 AND domain = :domain`, + WHERE id = :id AND sync_status = 0 AND domain <=> :domain`, { replacements: { status: nextStatus, @@ -1004,122 +1141,169 @@ async function markRowReloadRetry(sequelize, row, message) { } /** - * 逐条处理待同步记录:确保站点个性化配置目录(customDir 契约)→ 写证书/私钥文件 → - * 写 server 块 → 单条 nginx -t;nginx -t 失败撤销本条 server 块并重新校验,保证不拖垮整体 nginx。 - * 返回成功条目列表(不立即回写 DB,等 reload 后再统一回写)。 + * 声明式对账(期望集合逐行核对 → 缺失/不一致自愈)。 + * + * 处理规则(每行按 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 统计对象(就地更新)。 - * @return {Promise>} 成功条目数组。 + * @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 processRows(ctx, rows, stats) { - const successRows = []; +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 rowLabel = `#${row.id} store=${row.store_id} domain=${domainRaw || '(空)'}`; - const validateError = validateRowContent(domainRaw, row.cert_pem, row.cert_key); + 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}`); - const custom = ensureCustomConf(args, domainRaw); - console.log(`[CERT-SYNC][PLAN] cert_pem ${String(row.cert_pem || '').length} 字节 -> ${names.certPath}`); - console.log(`[CERT-SYNC][PLAN] cert_key ${String(row.cert_key || '').length} 字节 -> ${names.keyPath}`); - console.log(`[CERT-SYNC][PLAN] server 块 -> ${names.confPath}`); - console.log(`[CERT-SYNC][PLAN] custom 目录 -> ${custom.dirPath}${custom.hasCustom ? '(已有自定义配置,保留)' : ''}`); - console.log(`[CERT-SYNC][PLAN] custom include -> ${names.customGlobPath}`); - console.log(`[CERT-SYNC][PLAN] 默认文件 -> ${custom.defaultPath}(${custom.hasCustom ? '不写入' : '将写入'})`); - console.log(`[CERT-SYNC][PLAN] nginx -t=${!args.skipNginx && !ctx.nginxMissing} reload=${!args.skipNginx && !ctx.nginxMissing}`); - console.log(`[CERT-SYNC][PLAN] 预校验: ${validateError ? `将失败(${validateError})` : '通过'}`); - if (!validateError) { + 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; } - if (validateError) { - console.error(`[CERT-SYNC][FAIL] ${rowLabel} - ${validateError}`); - await markRowFailed(ctx.sequelize, row, validateError); - stats.failed++; + // 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 { - ensureCustomConf(args, domainRaw); - writeFileAtomic(names.certPath, String(row.cert_pem), CERT_FILE_MODE); - writeFileAtomic(names.keyPath, String(row.cert_key), KEY_FILE_MODE); - writeFileAtomic(names.confPath, buildServerConf(domainRaw, names.certPath, names.keyPath, names.customGlobPath), CERT_FILE_MODE); - - if (!args.skipNginx && !ctx.nginxMissing) { - const testResult = runNginxCommand(ctx.testCommand); - if (!testResult.ok) { - // 撤销本条 server 块,避免拖垮整体 nginx,并复验恢复 - removeFileQuiet(names.confPath); - const restoreResult = runNginxCommand(ctx.testCommand); - const restoreTip = restoreResult.ok - ? '' - : `(撤销本条后 nginx -t 仍失败,请检查其他配置: ${sanitizeErrorText(restoreResult.stderr || restoreResult.stdout)})`; - const errorText = `nginx -t 校验失败: ${sanitizeErrorText(testResult.stderr || testResult.stdout)}${restoreTip}`; - throw new Error(errorText); - } + 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}`); } - - console.log(`[CERT-SYNC][OK] ${rowLabel} 文件与 server 块已写入`); - successRows.push({ row, names }); - stats.success++; + if (priorStatus === 2) { + recoveredRows.push({ row, names }); + stats.recovered++; + } else { + healedRows.push({ row, names }); + stats.healed++; + } + currentConfPaths.add(names.confPath); } catch (error) { - // 清理本条已落盘的文件(幂等:下次重试重新写入) - removeFileQuiet(names.certPath); - removeFileQuiet(names.keyPath); - removeFileQuiet(names.confPath); + // 恢复本条写入前的原状态(保持磁盘原状,避免半写),行转失败态等待人工处理 + restorePriorStates(localPrior); const message = error && error.message ? error.message : String(error); - console.error(`[CERT-SYNC][FAIL] ${rowLabel} - ${message}`); - await markRowFailed(ctx.sequelize, row, message); + console.error(`[CERT-SYNC][FAIL] ${rowLabel} 自愈写入失败 - ${message}`); + await markRowFailed(ctx.sequelize, row, message, priorStatus); stats.failed++; } } - return successRows; -} - -/** - * 回写本批成功条目(在 reload 成功或 skip-nginx 之后调用)。 - * @param {SyncContext} ctx 运行上下文。 - * @param {Array<{row: Object, names: Object}>} successRows 成功条目数组。 - * @return {Promise} 无返回值。 - */ -async function writeBackSuccessRows(ctx, successRows) { - for (const { row, names } of successRows) { - await markRowSuccess(ctx.sequelize, row, names.certPath, names.keyPath); - } -} - -/** - * reload 失败处理:本批成功条目按重试策略回写(回退待同步或转失败)。 - * @param {SyncContext} ctx 运行上下文。 - * @param {Array<{row: Object, names: Object}>} successRows 本批成功条目数组。 - * @param {string} reloadError reload 失败原因(脱敏后)。 - * @return {Promise} 无返回值。 - */ -async function handleReloadFailure(ctx, successRows, reloadError) { - console.error(`[CERT-SYNC][RELOAD-FAIL] nginx -s reload 失败: ${reloadError}`); - for (const { row } of successRows) { - const retriedStatus = await markRowReloadRetry(ctx.sequelize, row, `nginx reload 失败: ${reloadError}`); - console.error(`[CERT-SYNC][RELOAD-RETRY] #${row.id} 回写 sync_status=${retriedStatus}(${retriedStatus === 0 ? '下分钟自动重试' : '已达重试上限,需人工介入'})`); - } + return { pendingSuccess, healedRows, recoveredRows, currentConfPaths }; } // ===================================================================== -// 旧域名下线(retired_domain 消费)与孤儿兜底清理 +// 域名下线(配置差集驱动)与孤儿清理 // -// 背景:前端独立部署改为两阶段域名切换后,应用侧只登记 pending,并在 TXT 校验 -// 通过后「提升」为新域名(domain 换成新域名、清空证书并重置同步状态),同时把 -// 旧域名写入 retired_domain(仅保留最近一个)。应用不碰 nginx 文件,因此旧域名的 -// server 块与证书文件必须由本脚本下线。 +// 模型(不需要两阶段切换的额外机制): +// - 期望集合 = 库内**已配置且证书就绪**的行: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 内的文件,删除前统一做目录前缀校验; @@ -1129,92 +1313,119 @@ async function handleReloadFailure(ctx, successRows, reloadError) { // ===================================================================== /** - * 探测 wms_warehouse_front_config 是否已有 retired_domain 列(两阶段域名切换新增)。 + * 读取「期望集合」:库内已配置且证书就绪的行(每仓一条)。 * - * 脚本可能先于迁移部署:该列不存在时整段跳过下线 / 清理流程并 WARN, - * 与 domain_status 的降级策略同源(宁可不做,也不猜)。 - * @param {import('sequelize').Sequelize} sequelize Sequelize 实例。 - * @return {Promise} 存在返回 true;探测失败返回 false。 - */ -async function hasRetiredDomainColumn(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 = 'retired_domain'`, - { replacements: [ TABLE_NAME ], type: Sequelize.QueryTypes.SELECT } - ); - return Number(rows && rows[0] && rows[0].c) > 0; - } catch (error) { - console.warn(`[CERT-SYNC] retired_domain 列探测失败(按无该列降级,跳过下线与孤儿清理): ${sanitizeErrorText(error.message)}`); - return false; - } -} - -/** - * 扫描待下线的旧域名记录(retired_domain 非空,按 id 升序,limit 条)。 - * @param {import('sequelize').Sequelize} sequelize Sequelize 实例。 - * @param {number} limit 单轮处理条数上限。 - * @return {Promise} 待下线记录数组(id / store_id / domain / retired_domain / retired_at)。 - */ -async function scanRetiredRows(sequelize, limit) { - return sequelize.query( - `SELECT id, store_id, domain, retired_domain, retired_at - FROM ${TABLE_NAME} - WHERE retired_domain IS NOT NULL AND retired_domain <> '' - ORDER BY id ASC - LIMIT ?`, - { replacements: [ limit ], type: Sequelize.QueryTypes.SELECT } - ); -} - -/** - * 读取「生效域名集合」= 允许存在 nginx server 块的域名。 - * domain_status 列缺失(迁移未执行)时降级为不按验证状态过滤。 - * 集合统一小写化:DNS 与 nginx server_name 匹配均不区分大小写, - * 避免 A.com / a.com 的大小写差异被误判为孤儿。 + * 过滤与去重规则(写入 / 保留 / 保集合同源,避免「写了不保 / 保了不写」的错位): + * 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>} 小写化生效域名集合。 + * @return {Promise<{rows: Object[], awaitingCertRows: Object[], invalidCertRows: Object[], duplicates: Array<{storeId: string, keptId: number, ignoredIds: number[]}>}>} 期望集合与分类结果。 */ -async function loadEffectiveDomains(sequelize, domainStatusReady) { +async function loadDesiredRows(sequelize, domainStatusReady) { const verifiedFilter = domainStatusReady ? ' AND domain_status = 1' : ''; - const rows = await sequelize.query( - `SELECT DISTINCT domain FROM ${TABLE_NAME} - WHERE domain IS NOT NULL AND domain <> ''${verifiedFilter}`, + 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 domains = new Set(); - for (const row of rows || []) { - const domain = String(row.domain || '').trim().toLowerCase(); - if (domain) { - domains.add(domain); + + 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 domains; + + return { + rows, + awaitingCertRows, + invalidCertRows, + duplicates: duplicateEntries.filter(entry => entry.ignoredIds.length > 0), + }; } /** - * 读取「库内仍存在的证书文件名前缀集合」(不限域名验证状态)。 - * 孤儿证书兜底的安全闸门:只要某证书文件仍能对应表内任意一行的 - * (store_id, domain) 命名推导结果,就一律不删(可能只是 conf 尚未写出)。 - * @param {import('sequelize').Sequelize} sequelize Sequelize 实例。 - * @return {Promise>} baseName 集合({store_id}_{domainSafe}{suffix})。 + * 判定证书字段是否「未配置」(NULL / 空串 / 纯空白)。 + * 未配置与「配置了但内容非法」是两种状态:前者是正常待办(等上传),后者是行级失败。 + * @param {*} certPem cert_pem 列值。 + * @param {*} certKey cert_key 列值。 + * @return {boolean} 未配置返回 true。 */ -async function loadKnownCertBaseNames(sequelize) { - const rows = await sequelize.query( - `SELECT DISTINCT store_id, domain FROM ${TABLE_NAME} - WHERE domain IS NOT NULL AND domain <> ''`, - { type: Sequelize.QueryTypes.SELECT } - ); - const baseNames = new Set(); - for (const row of rows || []) { - const domain = String(row.domain || '').trim(); - if (!domain) { +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; } - baseNames.add(buildCertBaseName(row.store_id, domain)); + 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++; } - return baseNames; } /** @@ -1232,33 +1443,29 @@ function cleanupPathKey(filePath) { * 创建下线 / 清理统计对象(就地累加,供汇总打印与退出码判定使用)。 * * 两套口径不可混用: - * - 通道命中数(retiredConfs/retiredCerts/orphanConfs/orphanCerts):按「谁动的手」累加, + * - 通道命中数(orphanConfs/orphanCerts/staleConfs):按「谁动的手」累加, * 同一文件被两条通道各处理一次就计两次(dry-run 不落盘 → 会真实出现;真实运行不会); * - 去重后文件数(cleanedPaths.size):按绝对路径去重,是「本轮待删 / 已删文件数」的唯一权威口径。 * @return {Object} 统计对象。 */ function createCleanupStats() { return { - scannedRetired: 0, // 扫描到的待下线行数 - clearedRows: 0, // 已清空 retired_domain 的行数 - retiredConfs: 0, // 下线通道命中的 conf 个数(不去重) - retiredCerts: 0, // 下线通道命中的证书文件个数(不去重) 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 下被第二条通道重复列表的次数(解释「通道命中数之和 > 去重数」) - skippedRetired: 0, // 跳过的待下线条数(形态非法 / 数据冲突) skippedOrphan: 0, // 孤儿清理跳过的文件数(白名单未命中 / 超单轮上限 / 不可判定) deleteFailed: 0, // 删除失败文件数(权限等,非致命) refusedPaths: 0, // 路径前缀校验拒绝数(红线护栏命中) - clearedDeferred: 0, // 因 nginx -t / reload 失败而延后清空的行数 cleanupFailed: 0, // 清理阶段失败计数(nginx -t 或 reload 失败,用于退出码) }; } /** - * 格式化「去重后」口径摘要:`N 个文件(去重后;通道命中 retired_domain=X, orphan=Y)`。 + * 格式化「去重后」口径摘要:`N 个文件(去重后;通道命中 orphan=X, staleConf=Y)`。 * * 去重后文件数取 cleanedPaths 规模;通道命中数之和大于 N 属于预期: * dry-run 不落盘,先列出的通道不会真的删掉文件,后一条通道仍会看到同一文件。 @@ -1266,9 +1473,8 @@ function createCleanupStats() { * @return {string} 摘要文本。 */ function formatCleanupDedupDetail(stats) { - const retiredHits = stats.retiredConfs + stats.retiredCerts; const orphanHits = stats.orphanConfs + stats.orphanCerts; - return `${stats.cleanedPaths.size} 个文件(去重后;通道命中 retired_domain=${retiredHits}, orphan=${orphanHits})`; + return `${stats.cleanedPaths.size} 个文件(去重后;通道命中 orphan=${orphanHits}, staleConf=${stats.staleConfs})`; } /** @@ -1302,6 +1508,21 @@ function readTextFileOrNull(filePath) { } } +/** + * 判断磁盘文件内容是否与期望内容一致(比较前双方统一 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 目录绝对路径。 @@ -1370,9 +1591,9 @@ function collectCertBaseNames(content, target) { * @param {SyncContext} ctx 运行上下文。 * @param {string} allowedDir 允许删除的目录(confDir 或 certDir)。 * @param {string} filePath 目标文件绝对路径。 - * @param {'retired_domain'|'orphan'} reason 删除原因(审计日志用)。 + * @param {'orphan'|'staleConf'} reason 删除原因(审计日志用)。 * @param {Object} stats 统计对象(就地累加)。 - * @param {Array<{path: string, content: Buffer, mode: number}>} rollbackEntries 回滚素材集合(就地累加)。 + * @param {Array<{path: string, content: Buffer|null, mode: number}>} rollbackEntries 回滚素材集合(就地累加)。 * @return {'deleted'|'planned'|'missing'|'refused'|'failed'} 处理结果。 */ function deleteFileGuarded(ctx, allowedDir, filePath, reason, stats, rollbackEntries) { @@ -1416,11 +1637,8 @@ function deleteFileGuarded(ctx, allowedDir, filePath, reason, stats, rollbackEnt } try { - // 回滚素材:删除前缓存内容与权限(私钥内容只在内存中流转,绝不打印) - const content = fs.readFileSync(filePath); - // mode 只取低 9 位权限位(0o777),避免把文件类型位带进回滚写入 - // eslint-disable-next-line no-bitwise - rollbackEntries.push({ path: filePath, content, mode: stat.mode & 0o777 }); + // 回滚素材:删除前登记本轮开始前的原状态(私钥内容只在内存中流转,绝不打印) + recordPriorState(rollbackEntries, filePath); fs.unlinkSync(filePath); } catch (error) { @@ -1437,15 +1655,84 @@ function deleteFileGuarded(ctx, allowedDir, filePath, reason, stats, rollbackEnt } /** - * 回滚本轮已删除的文件(nginx -t 失败时把磁盘尽量恢复成本轮开始前的状态)。 - * @param {Array<{path: string, content: Buffer, mode: number}>} rollbackEntries 回滚素材集合。 - * @return {number} 成功恢复的文件数。 + * 采集文件当前内容与权限(登记「本轮开始前的原状态」;文件不存在时 content=null)。 + * @param {string} filePath 文件绝对路径。 + * @return {{path: string, content: Buffer|null, mode: number}} 原状态描述。 + * @throws {Error} stat 失败(非 ENOENT)或读取失败时抛出异常。 */ -function rollbackDeletedFiles(rollbackEntries) { - let restored = 0; +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 { - writeFileAtomic(entry.path, entry.content, entry.mode); + 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)}`); @@ -1455,159 +1742,139 @@ function rollbackDeletedFiles(rollbackEntries) { } /** - * 消费 retired_domain(下线主线):删除旧域名残留的 server 块与证书文件。 - * - * 产物路径完全按写入时的命名推导推算(与 buildFileNames 同源): - * - server 块:{confDir}/{domainSafe}{suffix}.conf - * - 证书文件:{certDir}/{store_id}_{domainSafe}{suffix}.pem 与 .key - * suffix 仅在「域名被清洗后与原名不一致」时出现(下划线 + 域名 md5 前 8 位), - * 例如 *.a.com 会被清洗为 .a.com,必须带 _短哈希8 才不会与 .a.com 的产物冲突。 - * - * 安全闸门(任一命中即整条跳过:不删文件、不清空槽位): - * 1. retired_domain 形态非法(空 / 超长 / 含非法字符); - * 2. retired_domain 与当前 domain 相同(数据异常,槽位指向生效域名); - * 3. retired_domain 仍在生效域名集合内(可能被其它仓库使用)。 - * 文件不存在不算失败(只记 [SKIP] 日志);权限等硬失败保留槽位待下一轮重试。 - * 外置个性化配置目录 // 不做下线删除:旧 server 块删除后其 - * include 已失效,残留目录无副作用且可能被运维移作他用,一律保留。 + * 收集清理阶段的删除动作(配置差集驱动的域名下线 + 孤儿清理),不做 nginx -t / reload。 + * nginx 校验与 reload 由 finalizeUnifiedCycle 统一收敛(每轮最多一次), + * 避免一轮里「下线清理一次 reload、证书同步又一次 reload」。 * @param {SyncContext} ctx 运行上下文。 - * @param {Object} cleanupCtx 清理上下文(stats / effectiveDomains / handledConfPaths / rollbackEntries)。 - * @return {Promise>} 可清空槽位的行(reload 成功后统一清空)。 - */ -async function consumeRetiredDomains(ctx, cleanupCtx) { - const { args } = ctx; - const { stats, effectiveDomains, handledConfPaths, removedConfPaths, rollbackEntries } = cleanupCtx; - const rows = await scanRetiredRows(ctx.sequelize, args.limit); - stats.scannedRetired = rows.length; - const clearableRows = []; - - for (const row of rows) { - const currentDomain = String(row.domain || '').trim(); - const retiredRaw = String(row.retired_domain || '').trim(); - const rowLabel = `#${row.id} store=${row.store_id} retired=${retiredRaw || '(空)'}`; - - if (!retiredRaw || retiredRaw.length > DOMAIN_MAX_LENGTH || !DOMAIN_PATTERN.test(retiredRaw)) { - console.warn(`[CERT-SYNC][WARN] ${rowLabel} retired_domain 形态非法,跳过(不删文件、不清空槽位)`); - stats.skippedRetired++; - continue; - } - if (retiredRaw.toLowerCase() === currentDomain.toLowerCase()) { - console.warn(`[CERT-SYNC][WARN] ${rowLabel} retired_domain 与当前 domain 相同(数据异常),跳过以免误删生效产物`); - stats.skippedRetired++; - continue; - } - if (effectiveDomains.has(retiredRaw.toLowerCase())) { - console.warn(`[CERT-SYNC][WARN] ${rowLabel} retired_domain 仍在生效域名集合内(可能被其它仓库使用),跳过以免误删`); - stats.skippedRetired++; - continue; - } - - const confPath = path.join(args.confDir, buildConfFileName(retiredRaw)); - const certBaseName = buildCertBaseName(row.store_id, retiredRaw); - // 无论删除结果如何都登记为「本轮已处理」,避免孤儿清理对同一文件重复动作与重复日志 - handledConfPaths.add(confPath); - - const targets = [ - { dir: args.confDir, filePath: confPath, kind: 'conf' }, - { dir: args.certDir, filePath: path.join(args.certDir, `${certBaseName}.pem`), kind: 'cert' }, - { dir: args.certDir, filePath: path.join(args.certDir, `${certBaseName}.key`), kind: 'cert' }, - ]; - - let hardFailed = false; - for (const target of targets) { - const result = deleteFileGuarded(ctx, target.dir, target.filePath, 'retired_domain', stats, rollbackEntries); - if (result === 'failed') { - hardFailed = true; - continue; - } - if (result === 'deleted' || result === 'planned') { - if (target.kind === 'conf') { - stats.retiredConfs++; - removedConfPaths.add(target.filePath); - } else { - stats.retiredCerts++; - } - } - } - - if (hardFailed) { - console.warn(`[CERT-SYNC][WARN] ${rowLabel} 存在删除失败,保留 retired_domain 待下一轮重试`); - continue; - } - clearableRows.push({ row, retiredDomain: retiredRaw }); - } - - return clearableRows; -} - -/** - * 清空 retired_domain 槽位(retired_at 保留作审计)。 - * 防并发守卫:WHERE 带 id + retired_domain 双条件(与 markRowSuccess 同风格), - * 避免覆盖并发写入的新值(应用可能刚好又发生一次域名切换)。 - * @param {import('sequelize').Sequelize} sequelize Sequelize 实例。 - * @param {Object} row 记录对象(含 id)。 - * @param {string} retiredDomain 本轮消费的旧域名原值(并发守卫条件)。 - * @return {Promise} 受影响行数(0 表示已被并发修改,未清空)。 - */ -async function clearRetiredDomainSlot(sequelize, row, retiredDomain) { - const queryResult = await sequelize.query( - - `UPDATE ${TABLE_NAME} - SET retired_domain = NULL, - updated_at = NOW() - WHERE id = :id AND retired_domain = :retiredDomain`, - { replacements: { id: row.id, retiredDomain } } - ); - const metadata = Array.isArray(queryResult) ? queryResult[1] : null; - const affected = metadata && typeof metadata.affectedRows === 'number' ? Number(metadata.affectedRows) : null; - - return affected === null ? 1 : affected; -} - -/** - * 执行旧域名下线 + 孤儿兜底清理。 - * - * 执行顺序(关键:避免 reload 失败时误清空 retired_domain): - * 1. 删除旧域名 conf / 证书 + 孤儿差集删除(只删白名单命中的文件); - * 2. 只要本轮删过任何文件,就在删除后的配置树上执行 nginx -t,通过后再 reload; - * 3. nginx -t 失败 → 回滚本轮删除的文件并告警;reload 失败 → 直接告警; - * -t / reload 任一失败都不清空 retired_domain(槽位保留即待办标记,下一分钟自动重试, - * 等价于证书同步的 markRowReloadRetry「回退待处理 + 下一轮重试」策略); - * 4. 只有「本轮无文件变更」或「-t 通过且 reload 成功」才清空槽位。 - * @param {SyncContext} ctx 运行上下文。 - * @param {boolean} domainStatusReady 是否存在 domain_status 列。 - * @param {Object} stats 统计对象(就地累加)。 + * @param {Object} cleanupCtx 清理上下文(stats / effectiveDomains / knownBaseNames / handledConfPaths / removedConfPaths / rollbackEntries)。 * @return {Promise} 无返回值。 */ -async function runCleanup(ctx, domainStatusReady, stats) { +async function runCleanup(ctx, cleanupCtx) { const { args } = ctx; - const rollbackEntries = []; - const handledConfPaths = new Set(); - const removedConfPaths = new Set(); - const effectiveDomains = await loadEffectiveDomains(ctx.sequelize, domainStatusReady); - const knownBaseNames = await loadKnownCertBaseNames(ctx.sequelize); - const cleanupCtx = { stats, effectiveDomains, knownBaseNames, handledConfPaths, removedConfPaths, rollbackEntries }; + const { effectiveDomains, knownBaseNames } = cleanupCtx; - console.log(`[CERT-SYNC] 下线清理开始: 生效域名 ${effectiveDomains.size} 个, 库内证书命名 ${knownBaseNames.size} 个, dry-run=${args.dryRun}`); - const clearableRows = await consumeRetiredDomains(ctx, cleanupCtx); + console.log(`[CERT-SYNC] 下线清理开始: 期望域名 ${effectiveDomains.size} 个(已配置且证书就绪), 库内证书命名 ${knownBaseNames.size} 个, dry-run=${args.dryRun}`); await cleanupOrphans(ctx, cleanupCtx); +} - // 汇总统一改为「去重后」口径:dry-run 下同一文件可能被下线通道与孤儿通道各列一次, - // 直接相加各通道计数会虚增待删规模(发布前核对待删清单的关键输出) - const dedupedFiles = stats.cleanedPaths.size; - if (dedupedFiles === 0) { - console.log('[CERT-SYNC] 下线清理: 本轮无文件变更,跳过 nginx -t / reload'); - } else if (args.dryRun) { - console.log(`[CERT-SYNC][PLAN] 下线清理: 待删 ${formatCleanupDedupDetail(stats)}、不执行 nginx -t / reload、不写库`); - return; - } else if (args.skipNginx || ctx.nginxMissing) { - console.warn(`[CERT-SYNC] 下线清理: 已跳过 nginx -t / reload(${args.skipNginx ? '--skip-nginx' : '本机未检测到 nginx'}),文件删除已生效,清库继续`); - console.log(`[CERT-SYNC] 下线清理: 删除 ${formatCleanupDedupDetail(stats)}`); - } else { +/** + * 过期 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) { - console.error(`[CERT-SYNC][RELOAD-FAIL] 下线清理后 nginx -t 失败: ${sanitizeErrorText(testResult.stderr || testResult.stdout)}`); - const restored = rollbackDeletedFiles(rollbackEntries); + 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 @@ -1615,31 +1882,62 @@ async function runCleanup(ctx, domainStatusReady, stats) { : `(回滚后 nginx -t 仍失败,请检查其它配置: ${sanitizeErrorText(retest.stderr || retest.stdout)})`; console.error(`[CERT-SYNC][RELOAD-FAIL] 已回滚 ${restored}/${rollbackEntries.length} 个文件${retestTip}`); } - stats.cleanupFailed++; - stats.clearedDeferred += clearableRows.length; - console.warn(`[CERT-SYNC][WARN] 本轮不清空 retired_domain(${clearableRows.length} 条保留,下一轮自动重试)`); + 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) { - console.error(`[CERT-SYNC][RELOAD-FAIL] nginx -s reload 失败: ${sanitizeErrorText(reloadResult.stderr || reloadResult.stdout)}`); - stats.cleanupFailed++; - stats.clearedDeferred += clearableRows.length; - console.warn(`[CERT-SYNC][WARN] 本轮不清空 retired_domain(${clearableRows.length} 条保留,下一轮自动重试;文件已删除,重试幂等)`); + 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] 下线清理: 删除 ${formatCleanupDedupDetail(stats)}`); - console.log('[CERT-SYNC] 下线清理: nginx -t 通过 + nginx -s reload 成功'); + console.log('[CERT-SYNC] nginx -t 通过 + nginx -s reload 成功'); + } else { + console.warn(`[CERT-SYNC] 已跳过 nginx -t / reload(${args.skipNginx ? '--skip-nginx' : '本机未检测到 nginx'}),文件变更已生效,回写继续`); } - for (const item of clearableRows) { - const affected = await clearRetiredDomainSlot(ctx.sequelize, item.row, item.retiredDomain); - if (affected === 0) { - console.warn(`[CERT-SYNC][WARN] #${item.row.id} retired_domain 已被并发修改,本轮跳过清空(下一轮按新值处理)`); - stats.skippedRetired++; - continue; - } - stats.clearedRows++; + // 成功回写 + 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 块就绪)`); } } @@ -1652,9 +1950,9 @@ async function runCleanup(ctx, domainStatusReady, stats) { function printCleanupSummary(stats, args) { const prefix = args.dryRun ? '[CERT-SYNC][PLAN] ' : '[CERT-SYNC] '; const verb = args.dryRun ? '待删除' : '删除'; - console.log(`${prefix}旧域名下线: 处理 ${stats.scannedRetired} 条, ${verb} conf ${stats.retiredConfs} 个, 证书文件 ${stats.retiredCerts} 个, 跳过 ${stats.skippedRetired} 条`); - console.log(`${prefix}孤儿兜底清理: ${verb} conf ${stats.orphanConfs} 个, 证书文件 ${stats.orphanCerts} 个, 白名单未命中/超上限跳过 ${stats.skippedOrphan} 个`); - console.log(`${prefix}下线清理汇总: ${verb} ${formatCleanupDedupDetail(stats)}(其中通道重复列出 ${stats.duplicateListings} 行), 清空 retired_domain ${stats.clearedRows} 条(延后 ${stats.clearedDeferred} 条), 删除失败 ${stats.deleteFailed} 个, 路径越界拒绝 ${stats.refusedPaths} 个, 清理阶段失败 ${stats.cleanupFailed}`); + 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}`); } /** @@ -1667,20 +1965,18 @@ function hasCleanupFailure(stats) { } /** - * 孤儿兜底清理:以目录实际文件为准做差集,回收 retired_domain 单槽位(只记最近一个) - * 丢失中间域名后残留的产物。 + * 下线差集清理:以库内「期望集合」(已配置 + 证书就绪 + 每仓一条)为唯一基准, + * 把 confDir / certDir 中「本系统生成但配置里已没有该域名」的产物删掉。 * - * conf 白名单识别(三条全部命中才认为是本系统生成、才允许删除): - * 1. 文件名形态命中 CONF_FILE_NAME_PATTERN({domainSafe}{[_短哈希8]}.conf); - * 2. 文件内容包含本系统固有标记之一(模板两代兼容): - * - 旧模板(location 硬编码时代):包含 upstreamInclude 路径字符串; - * - 新模板(仅证书骨架 + 外置 include):包含本脚本按该域名推导的 - * custom 通配路径(//*.conf); + * conf 白名单识别(全部命中才认为是本系统生成、才允许删除): + * 1. 文件名形态命中 CONF_FILE_NAME_PATTERN({domainSafe}{[_短哈希8]}{[-]}.conf); + * 2. 文件内容包含本系统固有标记(upstreamInclude 路径字符串); * 3. 文件内容可解析出 server_name ,domain 通过域名白名单校验, - * 且用该 domain 反推的 conf 文件名与实际文件名完全一致(命名可回推一致)。 + * 且文件名可由该 domain 按命名规则推导(isConfNameDerivableFromDomain, + * 兼容无 ver 旧命名与 -ver 新命名;无 ver 旧命名还由过期 conf 清理负责)。 * 未命中的文件一律不动(他人手工 conf、宝塔自身文件等),只计入跳过统计; * 扫描范围仅 confDir 根层普通文件(readDirSafe 按 entry.isFile() 过滤), - * custom/ 等子目录不会进入待删集合,外置站点配置目录绝不递归清理。 + * 子目录不会进入待删集合,绝不递归清理。 * 命中白名单且 domain 不在生效集合内(按小写比较)→ 列入待删。 * * 证书 / 私钥文件:仅处理文件名严格命中 CERT_FILE_NAME_PATTERN 的,且需同时满足 @@ -1700,7 +1996,7 @@ async function cleanupOrphans(ctx, cleanupCtx) { // ---------- 第一遍:conf 目录扫描 + 白名单判定 ---------- // 只扫根层:readDirSafe 以 withFileTypes + entry.isFile() 过滤, - // custom/ 等子目录(外置站点个性化配置)不会进入待删集合,孤儿清理绝不递归到子目录。 + // 子目录不会进入待删集合,孤儿清理绝不递归到子目录。 const confEntries = readDirSafe(args.confDir); const confContents = new Map(); const orphanConfs = []; @@ -1728,13 +2024,12 @@ async function cleanupOrphans(ctx, cleanupCtx) { stats.skippedOrphan++; continue; } - if (buildConfFileName(domain) !== entry.name) { + if (!isConfNameDerivableFromDomain(entry.name, domain)) { stats.skippedOrphan++; continue; } - // 固有标记判定(模板两代兼容):旧模板含 upstreamInclude;新模板含本脚本为该域名推导的外置通配路径 - const customGlobPath = buildCustomPaths(args, domain).customGlobPath; - if (!content.includes(args.upstreamInclude) && !content.includes(customGlobPath)) { + // 固有标记判定:内容必须包含 upstreamInclude(本系统模板的唯一固有标记) + if (!content.includes(args.upstreamInclude)) { stats.skippedOrphan++; continue; } @@ -1805,7 +2100,8 @@ async function cleanupOrphans(ctx, cleanupCtx) { } /** - * 主流程:解析参数 → 连接数据库 → 扫描 → 逐条处理 → reload → 回写状态。 + * 主流程:解析参数(含 ver 校验)→ 连接数据库 → 期望集合对账自愈 → + * 清理(下线 / 孤儿 / 过期 conf)→ 统一 nginx -t + reload(有变更时最多一次)→ 回写状态。 * @return {Promise} 无返回值,通过 process.exitCode 表达执行结果。 */ async function main() { @@ -1815,11 +2111,11 @@ async function main() { return; } - console.log(`[CERT-SYNC] 开始: env=${args.env} dry-run=${args.dryRun} cleanup-only=${args.cleanupOnly} skip-nginx=${args.skipNginx} limit=${args.limit}`); + 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] 站点个性化配置目录(custom): ${args.customDir}(server 块 include //*.conf)`); console.log(`[CERT-SYNC] upstream include: ${args.upstreamInclude}`); console.log(`[CERT-SYNC] nginx 二进制: ${args.nginxBin}`); if (args.nginxPrefix) { @@ -1869,58 +2165,79 @@ async function main() { console.warn('[CERT-SYNC] 未检测到 wms_warehouse_front_config.domain_status 列(迁移尚未执行),本轮降级为不按域名验证状态过滤'); } - // 旧域名下线 + 孤儿兜底清理(两阶段域名切换的 nginx 侧配套): - // 放在证书同步之前执行,避免同一轮内「写新 conf」与「删旧 conf」互相干扰; - // 本流程自带一次 nginx -t / reload(仅在本轮确实删过文件时),与下面的同步流程互不耦合。 + // 清理上下文(下线 / 孤儿 / 过期 conf 共用):删除与写入统一登记 rollbackEntries, + // 供 nginx -t 失败时一次性回滚;nginx -t / reload 由 finalizeUnifiedCycle 统一收敛(每轮最多一次) const cleanupStats = createCleanupStats(); - const retiredDomainReady = await hasRetiredDomainColumn(sequelize); - if (!retiredDomainReady) { - console.warn('[CERT-SYNC] 未检测到 wms_warehouse_front_config.retired_domain 列(迁移尚未执行),本轮跳过旧域名下线与孤儿兜底清理'); + // 期望集合:库内「已配置且证书就绪」的行(每仓只取一条)。 + // 同一个集合同时充当写入集合与下线差集的保留集合,避免「写了不保 / 保了不写」的错位 + 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 { - await runCleanup(ctx, domainStatusReady, cleanupStats); - printCleanupSummary(cleanupStats, args); + // 阶段 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); } - // --cleanup-only:只做下线 / 清理,不做证书同步(供运维单独执行) - if (args.cleanupOnly) { - console.log(`[CERT-SYNC][SUMMARY] --cleanup-only 完成: 清空 retired_domain ${cleanupStats.clearedRows} 条, ${args.dryRun ? '待删' : '删除'} ${formatCleanupDedupDetail(cleanupStats)}, 通道命中明细(不去重)conf ${cleanupStats.retiredConfs + cleanupStats.orphanConfs} 个 / 证书文件 ${cleanupStats.retiredCerts + cleanupStats.orphanCerts} 个, 删除失败 ${cleanupStats.deleteFailed} 个`); - process.exitCode = hasCleanupFailure(cleanupStats) ? EXIT_BUSINESS_FAILURE : EXIT_OK; + // 有文件写入/删除,或存在「盘面已一致、只缺状态收口」的失败态恢复条,就需走 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; } - const rows = await scanPendingRows(sequelize, args.limit, domainStatusReady); - if (!rows || rows.length === 0) { - console.log('[CERT-SYNC] 无待同步记录,静默退出'); - if (hasCleanupFailure(cleanupStats)) { + 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; } - const stats = { total: rows.length, success: 0, failed: 0 }; - const successRows = await processRows(ctx, rows, stats); + await finalizeUnifiedCycle(ctx, { pendingSuccess, healedRows, recoveredRows, cleanupCtx, syncStats }); + printCleanupSummary(cleanupStats, args); - if (args.dryRun) { - console.log(`[CERT-SYNC][SUMMARY] dry-run 完成: total=${stats.total} 可成功=${stats.success} 将失败=${stats.failed}`); - return; - } - - if (successRows.length > 0 && !args.skipNginx && !ctx.nginxMissing) { - const reloadResult = runNginxCommand(ctx.reloadCommand); - if (reloadResult.ok) { - console.log('[CERT-SYNC] nginx -s reload 成功'); - await writeBackSuccessRows(ctx, successRows); - } else { - await handleReloadFailure(ctx, successRows, sanitizeErrorText(reloadResult.stderr || reloadResult.stdout)); - stats.failed += successRows.length; - stats.success -= successRows.length; - } - } else if (successRows.length > 0) { - await writeBackSuccessRows(ctx, successRows); - } - - console.log(`[CERT-SYNC][SUMMARY] total=${stats.total} success=${stats.success} failed=${stats.failed}`); - if (stats.failed > 0 || hasCleanupFailure(cleanupStats)) { + 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; diff --git a/script/warehouse-cert-sync.config.dev.json b/script/warehouse-cert-sync.config.dev.json index 6be1605..a71ef26 100644 --- a/script/warehouse-cert-sync.config.dev.json +++ b/script/warehouse-cert-sync.config.dev.json @@ -1,9 +1,10 @@ { - "description": "开发环境配置(Windows 本机 / 宝塔 Windows 版 nginx,nginx.exe)。nginx.exe 从任意 cwd 启动时会把启动目录当作前缀,导致读不到 conf/nginx.conf,因此 test/reload 命令必须带 -p 前缀指向 D:/BtSoft/nginx/;-p 的值使用正斜杠形式,经 win 版 nginx -t 实测可用。", + "description": "开发环境配置(Windows 本机 / 宝塔 Windows 版 nginx,nginx.exe)。证书与 nginx 配置目录同样在【工程目录内】(仓库根 D:/wms/.ssl 与 D:/wms/nginx_config),与生产 <部署根>/.ssl、<部署根>/nginx_config 同构。nginx.exe 从任意 cwd 启动时会把启动目录当作前缀,导致读不到 conf/nginx.conf,因此 test/reload 命令必须带 -p 前缀指向 D:/BtSoft/nginx/;-p 的值使用正斜杠形式,经 win 版 nginx -t 实测可用。ver 为 conf 命名版本:生成的 server 块文件名为 -.conf(如 web.wms.gztbyc.com-1.conf);证书/私钥文件名不变。站点内容片段路径 = upstreamInclude(开发为 D:/wms/nginx-upstream-local.conf,运维维护):生成的 server 块 = 证书骨架 + 一行 include ,站点 root / 伪静态 或 反代统一由该片段提供,脚本绝不覆盖,前端个性化在运行时由配置接口按域名完成。", "nginxBin": "D:/BtSoft/nginx/nginx.exe", "nginxPrefix": "D:/BtSoft/nginx/", "certDir": "D:/wms/.ssl", "confDir": "D:/wms/nginx_config", + "ver": "1", "upstreamInclude": "D:/wms/nginx-upstream-local.conf", "testCmd": "{nginxBin} -p {nginxPrefix} -t", "reloadCmd": "{nginxBin} -p {nginxPrefix} -s reload" diff --git a/script/warehouse-cert-sync.config.prod.json b/script/warehouse-cert-sync.config.prod.json index 1ac73d2..45786c0 100644 --- a/script/warehouse-cert-sync.config.prod.json +++ b/script/warehouse-cert-sync.config.prod.json @@ -1,10 +1,11 @@ { - "description": "生产环境配置(Linux 服务器 / 宝塔构建 nginx,systemd 管理)。脚本以部署根 /www/wwwroot/qimen 为 cwd 运行,certDir/confDir 相对 cwd 解析到上一级;reload 走 systemctl reload nginx,test 直接调 /usr/bin/nginx -t。", + "description": "生产环境配置(Linux 服务器 / 宝塔构建 nginx,systemd 管理)。脚本以部署根 /www/wwwroot/qimen 为 cwd 运行;证书与生成的 server 块固定放在【工程目录内】:certDir=<部署根>/.ssl、confDir=<部署根>/nginx_config(相对 cwd 解析,目录不存在时自动递归创建),与开发环境仓库根的 .ssl / nginx_config 同构。目录名是【硬约定】,改名必须同步改:① nginx 主配置的 include;② 本文件;③ 库表 wms_warehouse_front_config.cert_path/key_path(触发重同步刷新),详见 README「发布与运维」。ver 为 conf 命名版本:生成的 server 块文件名为 -.conf(如 web.wms.gztbyc.com-1.conf);证书/私钥文件名不变。轮转时改本键(或传 --ver / CERT_SYNC_VER),下一轮脚本自动删除旧命名并生成新命名后 reload。站点内容片段路径 = upstreamInclude(生产为 /www/wwwroot/qimen/front.conf,运维维护):生成的 server 块 = 证书骨架 + 一行 include ,站点 root / 伪静态 或 反代统一由该片段提供,脚本绝不覆盖,前端个性化在运行时由配置接口按域名完成。【红线】upstreamInclude 必须写绝对路径且片段文件必须先存在(nginx 解析相对 include 的基准是 nginx prefix,如 /www/server/nginx/conf,不是脚本 cwd;写相对路径会让 nginx -t 失败并回滚整轮变更);脚本启动即校验,不满足直接 exit 1。reload 走 systemctl reload nginx,test 直接调 /usr/bin/nginx -t。", "nginxBin": "/usr/bin/nginx", "nginxPrefix": "", - "certDir": "../.ssl", - "confDir": "../nginx_config", - "upstreamInclude": "/www/wwwroot/qimen/nginx-upstream.conf", + "certDir": "./.ssl", + "confDir": "./nginx_config", + "ver": "1", + "upstreamInclude": "/www/wwwroot/qimen/front.conf", "testCmd": "{nginxBin} -t", "reloadCmd": "systemctl reload nginx" }