feat(deploy): 证书同步脚本支持站点个性化配置外置(customDir 契约)
生成的 server 块不再内联 location /,改为只含证书骨架(listen / server_name / ssl_certificate*),尾部以 include <customDir>/<domain>/*.conf 收口;站点级 location / root / 伪静态等个性化配置由运维放进该目录,脚本绝不内联、绝不覆盖。 默认目录 <confDir>/custom(生产 /www/wwwroot/nginx_config/custom、开发 D:/wms/nginx_config/custom),位于部署根上一级之外,发布回退不会触碰。 配置入口:新增 `--custom-dir` 参数、`CERT_SYNC_CUSTOM_DIR` 环境变量与配置键 customDir, 缺省即 <confDir>/custom;--help、参数解析默认值与启动日志同步补充。 目录维护(ensureCustomConf,幂等且绝不覆盖用户文件): - 递归创建 <customDir>/<domain>/(0755),保证 server 块 include 的通配符始终合法 (目录不存在 / 目录为空 / 目录有文件 三种情况 nginx -t 均通过,已在生产 nginx 1.28.0 实测); - 目录内已有其它 *.conf → 视为用户自定义配置:不写默认文件,并删除脚本自产的 00-default.conf(避免两个 location / 触发 nginx duplicate location); - 目录内无其它 *.conf → 首次原子写默认文件 00-default.conf(0644,首行带脚本标记), 已存在(无论是否被运维改过)一律不覆盖; - 只有带脚本标记的文件才可能被删除,无标记文件一律不动;dry-run 只打印计划、不落盘。 其它: - server 块内容校验放宽为「upstreamInclude 或 customGlobPath 命中即可」(upstream include 现在位于外置文件内,不再直接出现在 server 块里); - 旧域名下线仍只删 confDir 根层的 server 块,custom/<domain>/ 目录保留不删 (旧块删除后其 include 已失效,残留目录无副作用,可被运维移作他用)。
This commit is contained in:
parent
01454bb916
commit
3c252a65d3
@ -6,6 +6,9 @@
|
||||
* 职责:扫描 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 单槽位丢失而残留的旧产物;
|
||||
@ -23,6 +26,9 @@
|
||||
* - reload 策略:本批有成功条目时执行一次 nginx -s reload;
|
||||
* reload 失败时本批成功条目回退 sync_status=0(下分钟自动重试,
|
||||
* sync_attempts 达到 RELOAD_FAILURE_MAX_RETRY 后转 sync_status=2 终止重试)。
|
||||
* - 站点个性化配置外置:server 块尾部以 include <customDir>/<domain>/*.conf 收口,
|
||||
* 脚本只负责该目录存在与默认反代文件(00-default.conf)的首次生成,
|
||||
* 用户自定义 *.conf 一律保留、永不覆盖,详见「部署约定」customDir 契约。
|
||||
* - 敏感红线:任何日志/错误输出不得打印 cert_pem / cert_key 内容,
|
||||
* last_sync_error 统一做 PEM 片段脱敏 + 500 字符截断。
|
||||
* - 文件权限:私钥 0600、证书/conf 0644;写文件采用「临时文件 + rename」原子写。
|
||||
@ -43,6 +49,22 @@
|
||||
* cwd(部署根 /www/wwwroot/qimen)解析为 ../.ssl 与 ../nginx_config,
|
||||
* 目录不存在时自动递归创建;nginx 主配置由运维自行 include ../nginx_config/*.conf,
|
||||
* 本脚本不管理主配置。
|
||||
* - customDir 契约(站点个性化配置外置,运维改站点只需动这里):
|
||||
* - 一域名一目录:<customDir>/<domain>/(目录名沿用文件名清洗推导,
|
||||
* 清洗后与原域名不一致时带 _短哈希8 防碰撞);
|
||||
* - 生成块尾部 include <customDir>/<domain>/*.conf(通配符:目录不存在 /
|
||||
* 目录为空 / 目录有文件三种情况 nginx -t 均通过,已在生产 nginx 1.28.0 实测);
|
||||
* - 默认文件 <customDir>/<domain>/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 默认 <confDir>/custom(生产 /www/wwwroot/nginx_config/custom、
|
||||
* 开发 D:/wms/nginx_config/custom),位于部署根上一级之外,发布回退不会触碰;
|
||||
* - 旧域名下线只删 confDir 根层的 server 块,custom/<domain>/ 目录保留不删
|
||||
* (旧 server 块删除后其 include 已失效,残留目录无副作用,可能被运维移作他用)。
|
||||
* - 自定义命令占位符:{nginxBin} 与 {nginxPrefix}(-p 前缀目录,win32 宝塔 nginx
|
||||
* 防 cwd 劫持),替换时自动按平台加引号;覆盖命令经 shell 执行。
|
||||
* - 建议 crontab 每分钟调用一次薄 shell 包装(crontab 安装由部署 agent 负责)。
|
||||
@ -103,6 +125,10 @@ 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';
|
||||
|
||||
@ -132,6 +158,7 @@ const SERVER_NAME_PATTERN = /^[ \t]*server_name[ \t]+([^;]+);/m;
|
||||
* @property {boolean} skipNginx 跳过 nginx -t / reload。
|
||||
* @property {string} certDir 证书输出目录(绝对路径)。
|
||||
* @property {string} confDir nginx server 块目录(绝对路径)。
|
||||
* @property {string} customDir 站点个性化配置外置目录(绝对路径,默认 <confDir>/custom)。
|
||||
* @property {string} upstreamInclude upstream 配置文件 include 名。
|
||||
* @property {number} limit 单次处理条数上限。
|
||||
* @property {string} nginxBin nginx 可执行文件路径。
|
||||
@ -173,6 +200,8 @@ 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 可缺省,缺省即 <confDir>/custom)',
|
||||
'',
|
||||
'参数优先级: CLI 参数 > 环境变量 > 外部配置文件 > 内置默认',
|
||||
'',
|
||||
@ -182,7 +211,9 @@ function printUsage() {
|
||||
' --cleanup-only 只做旧域名下线与孤儿兜底清理,不做证书同步(供运维单独执行)',
|
||||
' --cert-dir <path> 证书输出目录(默认取配置文件或 ../.ssl,相对路径按 cwd 解析)',
|
||||
' --conf-dir <path> nginx server 块目录(默认取配置文件或 ../nginx_config,同样按 cwd 解析)',
|
||||
' --upstream-include <v> server 块 include 的 upstream 配置名(默认取配置文件或 nginx-upstream.conf)',
|
||||
' --custom-dir <path> 站点个性化配置外置目录(默认取配置文件或 <confDir>/custom,按 cwd 解析)',
|
||||
' --upstream-include <v> 默认站点配置(custom/<域名>/00-default.conf)include 的 upstream 配置名',
|
||||
' (默认取配置文件或 nginx-upstream.conf)',
|
||||
' --skip-nginx 跳过 nginx -t 校验与 nginx reload(开发/测试用)',
|
||||
' --nginx-bin <path> nginx 可执行文件路径(默认取配置文件或 PATH 中的 nginx)',
|
||||
' --nginx-prefix <path> nginx -p 前缀目录(win32 宝塔 nginx 防 cwd 劫持,默认取配置文件)',
|
||||
@ -194,8 +225,8 @@ function printUsage() {
|
||||
' --help, -h 打印本帮助',
|
||||
'',
|
||||
'环境变量(优先级高于配置文件、低于命令行参数):',
|
||||
' CERT_SYNC_ENV / CERT_SYNC_CERT_DIR / CERT_SYNC_CONF_DIR / CERT_SYNC_UPSTREAM_INCLUDE',
|
||||
' CERT_SYNC_LIMIT / CERT_SYNC_NGINX_BIN / CERT_SYNC_NGINX_PREFIX',
|
||||
' CERT_SYNC_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_RELOAD_CMD / CERT_SYNC_TEST_CMD',
|
||||
' WMS_DB_TARGET / DB_HOST / DB_PORT / DB_USER / DB_PASSWORD / DB_NAME(透传 database/config.js)',
|
||||
'',
|
||||
@ -245,6 +276,7 @@ function parseArgs(argv) {
|
||||
env: '',
|
||||
certDir: '',
|
||||
confDir: '',
|
||||
customDir: '',
|
||||
upstreamInclude: '',
|
||||
nginxBin: '',
|
||||
nginxPrefix: '',
|
||||
@ -288,6 +320,8 @@ 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') {
|
||||
@ -311,6 +345,7 @@ function parseArgs(argv) {
|
||||
configPath: '',
|
||||
certDir: '',
|
||||
confDir: '',
|
||||
customDir: '',
|
||||
upstreamInclude: '',
|
||||
nginxBin: '',
|
||||
nginxPrefix: '',
|
||||
@ -340,6 +375,11 @@ function parseArgs(argv) {
|
||||
return String(value).trim();
|
||||
};
|
||||
|
||||
// customDir 缺省值依赖 confDir(<confDir>/custom),故先解析 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,
|
||||
configPath,
|
||||
@ -348,7 +388,8 @@ function parseArgs(argv) {
|
||||
skipNginx: cli.skipNginx,
|
||||
help: false,
|
||||
certDir: path.resolve(pickString(cli.certDir, 'CERT_SYNC_CERT_DIR', config.certDir, DEFAULT_CERT_DIR)),
|
||||
confDir: path.resolve(pickString(cli.confDir, 'CERT_SYNC_CONF_DIR', config.confDir, DEFAULT_CONF_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, ''),
|
||||
@ -602,20 +643,42 @@ 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}} 文件路径集合。
|
||||
* @return {{baseName: string, certPath: string, keyPath: string, confPath: string,
|
||||
* customDirPath: string, customGlobPath: 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,
|
||||
};
|
||||
}
|
||||
|
||||
@ -651,28 +714,127 @@ function validateRowContent(domainRaw, certPem, keyPem) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成 server 块内容(与项目现有 nginx 风格一致)。
|
||||
* 生成 server 块内容(仅证书骨架 + 外置站点配置 include,不含任何 location)。
|
||||
* 站点级 location / root / 伪静态等个性化配置由运维放入 <customDir>/<domain>/ 下的
|
||||
* *.conf,本脚本绝不内联也不覆盖。
|
||||
* @param {string} domain 域名(已通过白名单校验)。
|
||||
* @param {string} certPath 证书文件绝对路径。
|
||||
* @param {string} keyPath 私钥文件绝对路径。
|
||||
* @param {string} upstreamInclude upstream 配置文件 include 名。
|
||||
* @param {string} customGlobPath 站点个性化配置外置目录通配路径(<customDir>/<domain>/*.conf)。
|
||||
* @return {string} server 块文本。
|
||||
*/
|
||||
function buildServerConf(domain, certPath, keyPath, upstreamInclude) {
|
||||
function buildServerConf(domain, certPath, keyPath, customGlobPath) {
|
||||
return `server {
|
||||
listen 443 ssl;
|
||||
server_name ${domain};
|
||||
ssl_certificate ${certPath};
|
||||
ssl_certificate_key ${keyPath};
|
||||
location / {
|
||||
include ${upstreamInclude};
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Warehouse-Domain $host;
|
||||
}
|
||||
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. 递归创建 <customDir>/<domain>/ 目录(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 覆盖目标;
|
||||
* 失败时清理临时文件后抛出异常。
|
||||
@ -842,8 +1004,8 @@ async function markRowReloadRetry(sequelize, row, message) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 逐条处理待同步记录:写证书/私钥文件 → 写 server 块 → 单条 nginx -t;
|
||||
* nginx -t 失败撤销本条 server 块并重新校验,保证不拖垮整体 nginx。
|
||||
* 逐条处理待同步记录:确保站点个性化配置目录(customDir 契约)→ 写证书/私钥文件 →
|
||||
* 写 server 块 → 单条 nginx -t;nginx -t 失败撤销本条 server 块并重新校验,保证不拖垮整体 nginx。
|
||||
* 返回成功条目列表(不立即回写 DB,等 reload 后再统一回写)。
|
||||
* @param {SyncContext} ctx 运行上下文。
|
||||
* @param {Object[]} rows 待同步记录数组。
|
||||
@ -862,9 +1024,13 @@ async function processRows(ctx, rows, stats) {
|
||||
|
||||
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) {
|
||||
@ -883,9 +1049,10 @@ async function processRows(ctx, rows, stats) {
|
||||
}
|
||||
|
||||
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, args.upstreamInclude), CERT_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);
|
||||
@ -1301,6 +1468,8 @@ function rollbackDeletedFiles(rollbackEntries) {
|
||||
* 2. retired_domain 与当前 domain 相同(数据异常,槽位指向生效域名);
|
||||
* 3. retired_domain 仍在生效域名集合内(可能被其它仓库使用)。
|
||||
* 文件不存在不算失败(只记 [SKIP] 日志);权限等硬失败保留槽位待下一轮重试。
|
||||
* 外置个性化配置目录 <customDir>/<domain>/ 不做下线删除:旧 server 块删除后其
|
||||
* include 已失效,残留目录无副作用且可能被运维移作他用,一律保留。
|
||||
* @param {SyncContext} ctx 运行上下文。
|
||||
* @param {Object} cleanupCtx 清理上下文(stats / effectiveDomains / handledConfPaths / rollbackEntries)。
|
||||
* @return {Promise<Array<{row: Object, retiredDomain: string}>>} 可清空槽位的行(reload 成功后统一清空)。
|
||||
@ -1503,10 +1672,15 @@ function hasCleanupFailure(stats) {
|
||||
*
|
||||
* conf 白名单识别(三条全部命中才认为是本系统生成、才允许删除):
|
||||
* 1. 文件名形态命中 CONF_FILE_NAME_PATTERN({domainSafe}{[_短哈希8]}.conf);
|
||||
* 2. 文件内容包含本系统 upstreamInclude 路径字符串(本系统 server 块的固有标记);
|
||||
* 2. 文件内容包含本系统固有标记之一(模板两代兼容):
|
||||
* - 旧模板(location 硬编码时代):包含 upstreamInclude 路径字符串;
|
||||
* - 新模板(仅证书骨架 + 外置 include):包含本脚本按该域名推导的
|
||||
* custom 通配路径(<customDir>/<domain>/*.conf);
|
||||
* 3. 文件内容可解析出 server_name <domain>,domain 通过域名白名单校验,
|
||||
* 且用该 domain 反推的 conf 文件名与实际文件名完全一致(命名可回推一致)。
|
||||
* 未命中的文件一律不动(他人手工 conf、宝塔自身文件等),只计入跳过统计;
|
||||
* 扫描范围仅 confDir 根层普通文件(readDirSafe 按 entry.isFile() 过滤),
|
||||
* custom/ 等子目录不会进入待删集合,外置站点配置目录绝不递归清理。
|
||||
* 命中白名单且 domain 不在生效集合内(按小写比较)→ 列入待删。
|
||||
*
|
||||
* 证书 / 私钥文件:仅处理文件名严格命中 CERT_FILE_NAME_PATTERN 的,且需同时满足
|
||||
@ -1525,6 +1699,8 @@ async function cleanupOrphans(ctx, cleanupCtx) {
|
||||
const { stats, effectiveDomains, knownBaseNames, handledConfPaths, removedConfPaths, rollbackEntries } = cleanupCtx;
|
||||
|
||||
// ---------- 第一遍:conf 目录扫描 + 白名单判定 ----------
|
||||
// 只扫根层:readDirSafe 以 withFileTypes + entry.isFile() 过滤,
|
||||
// custom/ 等子目录(外置站点个性化配置)不会进入待删集合,孤儿清理绝不递归到子目录。
|
||||
const confEntries = readDirSafe(args.confDir);
|
||||
const confContents = new Map();
|
||||
const orphanConfs = [];
|
||||
@ -1547,10 +1723,6 @@ async function cleanupOrphans(ctx, cleanupCtx) {
|
||||
stats.skippedOrphan++;
|
||||
continue;
|
||||
}
|
||||
if (!content.includes(args.upstreamInclude)) {
|
||||
stats.skippedOrphan++;
|
||||
continue;
|
||||
}
|
||||
const domain = parseServerName(content);
|
||||
if (!domain || domain.length > DOMAIN_MAX_LENGTH || !DOMAIN_PATTERN.test(domain)) {
|
||||
stats.skippedOrphan++;
|
||||
@ -1560,6 +1732,12 @@ async function cleanupOrphans(ctx, cleanupCtx) {
|
||||
stats.skippedOrphan++;
|
||||
continue;
|
||||
}
|
||||
// 固有标记判定(模板两代兼容):旧模板含 upstreamInclude;新模板含本脚本为该域名推导的外置通配路径
|
||||
const customGlobPath = buildCustomPaths(args, domain).customGlobPath;
|
||||
if (!content.includes(args.upstreamInclude) && !content.includes(customGlobPath)) {
|
||||
stats.skippedOrphan++;
|
||||
continue;
|
||||
}
|
||||
if (effectiveDomains.has(domain.toLowerCase())) {
|
||||
continue;
|
||||
}
|
||||
@ -1641,6 +1819,7 @@ async function main() {
|
||||
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 <customDir>/<domain>/*.conf)`);
|
||||
console.log(`[CERT-SYNC] upstream include: ${args.upstreamInclude}`);
|
||||
console.log(`[CERT-SYNC] nginx 二进制: ${args.nginxBin}`);
|
||||
if (args.nginxPrefix) {
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user