1627 lines
64 KiB
JavaScript
1627 lines
64 KiB
JavaScript
'use strict';
|
||
|
||
const crypto = require('node:crypto');
|
||
// 域名验证 TXT 记录的兜底解析使用 Node 内置 DNS(本文件为全仓首次引入 node:dns):
|
||
// DoH(ctx.curl)不可用时降级为系统解析;仅服务域名验证链路,不参与业务主链路。
|
||
const dns = require('node:dns');
|
||
|
||
const { Service } = require('egg');
|
||
|
||
// 仓库前端配置品牌文本字段元信息(对应 wms_warehouse_front_config,一仓一行)。
|
||
// 域名与证书字段不在此列:domain 只能通过 frontConfig.setDomain 设置(并先通过域名验证),
|
||
// cert_pem/cert_key/cert_path/key_path 只能通过证书上传接口(saveCert)变更。
|
||
const TEXT_FIELDS = Object.freeze([
|
||
Object.freeze({ key: 'title', name: 'title', maxLength: 100 }),
|
||
Object.freeze({ key: 'logo_url', name: 'logo_url', maxLength: 255 }),
|
||
Object.freeze({ key: 'favicon_url', name: 'favicon_url', maxLength: 255 }),
|
||
Object.freeze({ key: 'login_bg_url', name: 'login_bg_url', maxLength: 255 }),
|
||
]);
|
||
|
||
// 公共按域名拉取接口对外输出的字段白名单(安全红线:严禁输出证书/私钥内容与证书路径、同步状态等内部字段)
|
||
const PUBLIC_FIELDS = Object.freeze([
|
||
'domain',
|
||
'title',
|
||
'logo_url',
|
||
'login_bg_url',
|
||
'favicon_url',
|
||
'theme',
|
||
]);
|
||
|
||
// 公共按域名拉取接口缓存 TTL(秒)
|
||
const PUBLIC_CACHE_TTL_SECONDS = 600;
|
||
// 未登记域名空缓存 TTL(秒):短缓存兜底防穿透,域名登记后由保存流程主动失效
|
||
const PUBLIC_MISS_CACHE_TTL_SECONDS = 60;
|
||
|
||
// 证书/私钥 PEM 文本最大长度(正常 RSA/ECC 证书远小于该值,防止异常大报文)
|
||
const PEM_MAX_LENGTH = 64 * 1024;
|
||
|
||
// 域名验证状态(与 wms_warehouse_front_config.domain_status 列及模型 validate 保持一致)
|
||
const DOMAIN_STATUS_UNVERIFIED = 0;
|
||
const DOMAIN_STATUS_VERIFIED = 1;
|
||
const DOMAIN_STATUS_FAILED = 2;
|
||
|
||
// 域名形态:至少两段标签,每段 1~63 位、仅字母数字与连字符、首尾不得为连字符;
|
||
// 天然排除通配符 *、下划线、首尾点与单段主机名(长度上限由 normalizeText 的 ≤100 兜住)
|
||
const DOMAIN_PATTERN = /^(?!-)[A-Za-z0-9-]{1,63}(?<!-)(\.(?!-)[A-Za-z0-9-]{1,63}(?<!-))+$/;
|
||
|
||
// 域名验证 TXT 记录主机名前缀与随机码字节数(5 字节 → 10 位 hex)
|
||
const DOMAIN_VERIFY_HOST_PREFIX = 'wmsv-';
|
||
const DOMAIN_VERIFY_HOST_RANDOM_BYTES = 5;
|
||
// 域名验证 TXT 记录值随机字节数(16 字节 → 32 位 hex)
|
||
const DOMAIN_VERIFY_TOKEN_BYTES = 16;
|
||
|
||
// 域名验证失败原因落库长度上限(与 domain_last_error STRING(500) 列宽一致)
|
||
const DOMAIN_LAST_ERROR_MAX_LENGTH = 500;
|
||
|
||
// 单条 TXT 记录解析结果长度上限(异常超长记录截断保护)
|
||
const TXT_VALUE_MAX_LENGTH = 1024;
|
||
|
||
// checkDomain 响应回显解析值的条数与单条长度上限(排障用,避免响应被超长记录撑爆)
|
||
const DOMAIN_RESOLVED_VALUES_LIMIT = 5;
|
||
const DOMAIN_RESOLVED_VALUE_MAX_LENGTH = 255;
|
||
|
||
/**
|
||
* 前端独立部署配置服务:仓库前端品牌配置、证书上传与按域名公共拉取。
|
||
*
|
||
* 数据表:wms_warehouse_front_config(一仓一行,domain 全局唯一)。
|
||
* 公共拉取缓存键:front:config:domain:{domain}。
|
||
*/
|
||
class FrontConfigService extends Service {
|
||
createError(message, code = 500) {
|
||
const error = new Error(message);
|
||
error.code = code;
|
||
return error;
|
||
}
|
||
|
||
/**
|
||
* 从 ctx.user.store_id 获取当前仓库 ID。
|
||
*
|
||
* @return {number} 仓库 ID。
|
||
* @throws {Error} 未识别到仓库时抛出,状态码 400。
|
||
*/
|
||
getCurrentWarehouseId() {
|
||
const warehouseId = Number(this.ctx.user && this.ctx.user.store_id);
|
||
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
|
||
throw this.createError('未识别到当前仓库,无法操作仓库设置', 400);
|
||
}
|
||
return warehouseId;
|
||
}
|
||
|
||
/**
|
||
* 删除指定缓存键。
|
||
*
|
||
* @param {string} cacheKey 缓存键。
|
||
* @return {Promise<void>} 无返回值。
|
||
*/
|
||
async deleteCacheByKey(cacheKey) {
|
||
if (!cacheKey) {
|
||
return;
|
||
}
|
||
|
||
if (this.app && typeof this.app.delCacheAsync === 'function') {
|
||
await this.app.delCacheAsync(cacheKey);
|
||
return;
|
||
}
|
||
|
||
if (this.app && typeof this.app.setCacheAsync === 'function') {
|
||
await this.app.setCacheAsync(cacheKey, null, 0);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 校验并规范化仓库前端配置的字符串字段。
|
||
*
|
||
* @param {*} value 原始值。
|
||
* @param {string} fieldName 字段名。
|
||
* @param {number} maxLength 字段最大长度。
|
||
* @return {string|null} 规范化后的字符串;空值返回 null(表示清空)。
|
||
* @throws {Error} 超长时抛出,状态码 400。
|
||
*/
|
||
normalizeText(value, fieldName, maxLength) {
|
||
if (value === undefined || value === null) {
|
||
return null;
|
||
}
|
||
|
||
const normalized = String(value).trim();
|
||
if (!normalized) {
|
||
return null;
|
||
}
|
||
|
||
if (normalized.length > maxLength) {
|
||
throw this.createError(`${fieldName} 长度不能超过 ${maxLength} 字符`, 400);
|
||
}
|
||
|
||
return normalized;
|
||
}
|
||
|
||
/**
|
||
* 校验并规范化仓库前端配置的 theme 字段。
|
||
*
|
||
* @param {*} value 原始值(对象或 JSON 字符串)。
|
||
* @return {Object|null} 规范化后的主题对象;空值返回 null(表示清空)。
|
||
* @throws {Error} 非合法 JSON 对象时抛出,状态码 400。
|
||
*/
|
||
normalizeTheme(value) {
|
||
if (value === undefined || value === null || value === '') {
|
||
return null;
|
||
}
|
||
|
||
let parsed = value;
|
||
if (typeof value === 'string') {
|
||
try {
|
||
parsed = JSON.parse(value.trim());
|
||
} catch (error) {
|
||
throw this.createError('theme 必须是合法的 JSON 对象', 400);
|
||
}
|
||
}
|
||
|
||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
||
throw this.createError('theme 必须是合法的 JSON 对象', 400);
|
||
}
|
||
|
||
return parsed;
|
||
}
|
||
|
||
/**
|
||
* 校验非空 domain 的全局唯一性(可空列唯一索引允许多 NULL,数据库不兜底)。
|
||
*
|
||
* @param {string} domain 待校验域名(非空)。
|
||
* @param {number} excludeWarehouseId 排除的仓库 ID(当前仓库自身)。
|
||
* @return {Promise<void>} 无返回值。
|
||
* @throws {Error} domain 已被其他仓库使用时抛出,状态码 409。
|
||
*/
|
||
async assertDomainUnique(domain, excludeWarehouseId) {
|
||
const configModel = this.ctx.model && this.ctx.model.WarehouseFrontConfig;
|
||
if (!configModel || typeof configModel.findOne !== 'function') {
|
||
throw this.createError('WarehouseFrontConfig model 不可用', 500);
|
||
}
|
||
|
||
const { Op } = this.app.Sequelize;
|
||
const existing = await configModel.findOne({
|
||
where: {
|
||
domain,
|
||
store_id: { [Op.ne]: excludeWarehouseId },
|
||
},
|
||
attributes: [ 'store_id', 'domain' ],
|
||
});
|
||
|
||
if (existing) {
|
||
throw this.createError(`域名 ${domain} 已被其他仓库使用`, 409);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 从记录(Sequelize 实例或普通对象)读取字段值。
|
||
*
|
||
* @param {Object} record 记录实例或普通对象。
|
||
* @param {string} key 字段名。
|
||
* @return {*} 字段值;不可读时返回 null。
|
||
*/
|
||
getRecordField(record, key) {
|
||
if (!record) {
|
||
return null;
|
||
}
|
||
|
||
if (typeof record.get === 'function') {
|
||
return record.get(key);
|
||
}
|
||
|
||
return Object.prototype.hasOwnProperty.call(record, key) ? record[key] : null;
|
||
}
|
||
|
||
/**
|
||
* 脱敏并截断错误文本:去掉 PEM 块内容、压缩空白、按列宽截断。
|
||
*
|
||
* 安全红线:域名验证失败原因会写入 domain_last_error 并回显前端,
|
||
* 严禁把原始网络错误/堆栈原样落库(脱敏思路参考 script/warehouse-cert-sync.cjs 的 sanitizeErrorText)。
|
||
*
|
||
* @param {*} text 原始错误文本。
|
||
* @return {string} 脱敏截断后的文本(≤500 字符)。
|
||
*/
|
||
sanitizeErrorText(text) {
|
||
return String(text === undefined || text === null ? '' : text)
|
||
.replace(/-----BEGIN [^-]*-----[\s\S]*?-----END [^-]*-----/g, '[PEM 内容已省略]')
|
||
.replace(/\s+/g, ' ')
|
||
.trim()
|
||
.slice(0, DOMAIN_LAST_ERROR_MAX_LENGTH);
|
||
}
|
||
|
||
/**
|
||
* 读取域名验证配置(config.frontConfig.domainVerify),缺失或非法项回退默认值。
|
||
*
|
||
* 公共方法:app/schedule 下的域名验证定时任务会直接调用,签名与返回值需保持稳定。
|
||
*
|
||
* @return {Object} 域名验证配置,字段如下:
|
||
* - enable {boolean}:是否启用域名验证定时任务;
|
||
* - interval {string}:扫描间隔(Egg schedule 语法);
|
||
* - lockTtlSeconds {number}:Redis 跨进程锁 TTL(秒);
|
||
* - batchSize {number}:单轮最多处理行数;
|
||
* - dohUrl {string}:DNS-over-HTTPS 服务地址;
|
||
* - timeoutMs {number}:单次 DoH 请求超时(毫秒);
|
||
* - maxAttempts {number}:自动重试次数上限。
|
||
*/
|
||
getDomainVerifyConfig() {
|
||
const frontConfig = (this.app && this.app.config && this.app.config.frontConfig) || {};
|
||
const raw = frontConfig.domainVerify || {};
|
||
const toPositiveNumber = (value, fallback) => {
|
||
const parsed = Number(value);
|
||
return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
|
||
};
|
||
|
||
return {
|
||
enable: raw.enable !== false,
|
||
interval: String(raw.interval || '10m'),
|
||
lockTtlSeconds: toPositiveNumber(raw.lockTtlSeconds, 600),
|
||
batchSize: Math.floor(toPositiveNumber(raw.batchSize, 50)),
|
||
dohUrl: String(raw.dohUrl || 'https://doh.pub/dns-query'),
|
||
timeoutMs: toPositiveNumber(raw.timeoutMs, 5000),
|
||
maxAttempts: Math.floor(toPositiveNumber(raw.maxAttempts, 20)),
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 读取 CNAME 目标(config.frontConfig.cname)。
|
||
*
|
||
* 域名未通过验证时随 getDomain 返回给前端,提示用户把域名 CNAME 指向该目标。
|
||
*
|
||
* @return {string} CNAME 目标;未配置返回空串。
|
||
*/
|
||
getCnameTarget() {
|
||
const frontConfig = (this.app && this.app.config && this.app.config.frontConfig) || {};
|
||
return String(frontConfig.cname || '').trim();
|
||
}
|
||
|
||
/**
|
||
* 生成域名验证所需的随机码(一次性校验子域 + TXT 记录值)。
|
||
*
|
||
* 校验目标用一次性随机子域(wmsv-<10 位 hex>.<域名>)而非裸域名,
|
||
* 避免与用户主域上已有的其它 TXT 记录(SPF/DKIM/站点校验等)互相干扰。
|
||
*
|
||
* @param {string} domain 已规范化的域名。
|
||
* @return {Object} { host: 待校验 TXT 主机名, token: 待校验 TXT 记录值(32 位 hex) }。
|
||
*/
|
||
buildDomainVerifyCode(domain) {
|
||
const randomTag = crypto.randomBytes(DOMAIN_VERIFY_HOST_RANDOM_BYTES).toString('hex');
|
||
|
||
return {
|
||
host: `${DOMAIN_VERIFY_HOST_PREFIX}${randomTag}.${domain}`,
|
||
token: crypto.randomBytes(DOMAIN_VERIFY_TOKEN_BYTES).toString('hex'),
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 解析 DoH 应答中单条 TXT 记录的 data 文本(去外层引号、多段拼接、截断保护)。
|
||
*
|
||
* DoH JSON 的 Answer[].data 形如 "abc" 或 "abc" "def"(TXT 单条记录可按 255 字节分段)。
|
||
*
|
||
* @param {*} data DoH 应答中的 data 字段。
|
||
* @return {string} 解析后的 TXT 文本;无内容返回空串。
|
||
*/
|
||
parseTxtAnswerData(data) {
|
||
const text = String(data === undefined || data === null ? '' : data).trim();
|
||
if (!text) {
|
||
return '';
|
||
}
|
||
|
||
const segments = text.match(/"([^"]*)"/g);
|
||
const value = segments && segments.length > 0
|
||
? segments.map(segment => segment.slice(1, -1)).join('')
|
||
: text.replace(/"/g, '');
|
||
|
||
return value.trim().slice(0, TXT_VALUE_MAX_LENGTH);
|
||
}
|
||
|
||
/**
|
||
* 从 DoH 应答的 Answer 数组中提取 TXT 记录(type=16)。
|
||
*
|
||
* @param {Array} answers DoH 应答的 Answer 数组。
|
||
* @return {string[]} TXT 记录文本列表(已去空、截断)。
|
||
*/
|
||
extractTxtValuesFromAnswers(answers) {
|
||
const values = [];
|
||
|
||
for (const answer of Array.isArray(answers) ? answers : []) {
|
||
if (!answer || Number(answer.type) !== 16) {
|
||
continue;
|
||
}
|
||
|
||
const value = this.parseTxtAnswerData(answer.data);
|
||
if (value) {
|
||
values.push(value);
|
||
}
|
||
}
|
||
|
||
return values;
|
||
}
|
||
|
||
/**
|
||
* DoH(DNS-over-HTTPS)解析 TXT 记录。
|
||
*
|
||
* @param {string} host 待解析主机名。
|
||
* @param {Object} verifyConfig 域名验证配置(getDomainVerifyConfig 返回值)。
|
||
* @return {Promise<string[]>} TXT 记录文本列表;无记录返回空数组。
|
||
* @throws {Error} DoH 请求失败/响应异常时抛出(由 resolveTxtValues 决定是否降级)。
|
||
*/
|
||
async resolveTxtByDoh(host, verifyConfig) {
|
||
const url = `${verifyConfig.dohUrl}?name=${encodeURIComponent(host)}&type=TXT`;
|
||
const response = await this.ctx.curl(url, {
|
||
method: 'GET',
|
||
headers: { accept: 'application/dns-json' },
|
||
timeout: verifyConfig.timeoutMs,
|
||
dataType: 'json',
|
||
});
|
||
|
||
const statusCode = Number(response && response.status) || 0;
|
||
if (statusCode !== 200) {
|
||
throw new Error(`DoH 服务返回异常状态码 ${statusCode}`);
|
||
}
|
||
|
||
const body = response && response.data;
|
||
if (!body || typeof body !== 'object') {
|
||
throw new Error('DoH 响应体不是合法 JSON');
|
||
}
|
||
|
||
// Status=3(NXDOMAIN)或 Status=0 但无 Answer 均视为「未解析到记录」,
|
||
// 返回空数组交给上层判定,不降级系统 DNS 重复查询
|
||
return this.extractTxtValuesFromAnswers(body.Answer);
|
||
}
|
||
|
||
/**
|
||
* 系统 DNS(node:dns)解析 TXT 记录,作为 DoH 的兜底路径。
|
||
*
|
||
* @param {string} host 待解析主机名。
|
||
* @return {Promise<string[]>} TXT 记录文本列表(多段已拼接、去空、截断)。
|
||
* @throws {Error} 解析失败(含 NXDOMAIN/超时)时抛出。
|
||
*/
|
||
async resolveTxtBySystem(host) {
|
||
const records = await dns.promises.resolveTxt(host);
|
||
const values = [];
|
||
|
||
for (const record of Array.isArray(records) ? records : []) {
|
||
const joined = Array.isArray(record) ? record.join('') : String(record || '');
|
||
const value = joined.trim().slice(0, TXT_VALUE_MAX_LENGTH);
|
||
if (value) {
|
||
values.push(value);
|
||
}
|
||
}
|
||
|
||
return values;
|
||
}
|
||
|
||
/**
|
||
* 解析指定主机名的 TXT 记录(DoH 主路径,失败降级系统 DNS)。
|
||
*
|
||
* 公共方法:app/schedule 下的域名验证定时任务会直接调用,签名与返回值需保持稳定。
|
||
*
|
||
* @param {string} host 待解析主机名(域名验证一律传 domain_verify_host,不用裸域名)。
|
||
* @return {Promise<Object>} { values: string[], source: 'doh'|'system' }。
|
||
* @throws {Error} 两条路径均失败时抛出,状态码 500,文案已脱敏截断。
|
||
*/
|
||
async resolveTxtValues(host) {
|
||
const normalizedHost = String(host || '').trim().toLowerCase();
|
||
if (!normalizedHost) {
|
||
throw this.createError('域名解析主机名不能为空', 400);
|
||
}
|
||
|
||
const verifyConfig = this.getDomainVerifyConfig();
|
||
|
||
try {
|
||
const values = await this.resolveTxtByDoh(normalizedHost, verifyConfig);
|
||
return { values, source: 'doh' };
|
||
} catch (error) {
|
||
this.ctx.logger.warn(
|
||
'[FrontConfigService.resolveTxtValues] DoH 解析失败,降级系统 DNS: %s',
|
||
this.sanitizeErrorText(error.message)
|
||
);
|
||
}
|
||
|
||
try {
|
||
const values = await this.resolveTxtBySystem(normalizedHost);
|
||
return { values, source: 'system' };
|
||
} catch (error) {
|
||
const reason = this.sanitizeErrorText(error.message) || '未知错误';
|
||
throw this.createError(`DNS 解析失败:${reason}`, 500);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 校验单行记录的域名 TXT 归属(定时任务逐行调用,必须失败隔离、不得抛异常)。
|
||
*
|
||
* @param {Object} record 配置记录(需含 domain_verify_host / domain_verify_token)。
|
||
* @return {Promise<Object>} 校验结果,字段如下:
|
||
* - verified {boolean}:是否校验通过(解析到的 TXT 记录中包含校验值);
|
||
* - values {string[]}:实际解析到的 TXT 值;
|
||
* - source {string}:解析来源 doh/system,未解析为空串;
|
||
* - error {string|null}:失败原因(已脱敏截断),成功为 null。
|
||
*/
|
||
async verifyDomainRecord(record) {
|
||
const verifyHost = String(this.getRecordField(record, 'domain_verify_host') || '').trim();
|
||
const verifyToken = String(this.getRecordField(record, 'domain_verify_token') || '').trim();
|
||
|
||
if (!verifyHost) {
|
||
return { verified: false, values: [], source: '', error: '未生成待校验的 TXT 主机名,请重新设置域名' };
|
||
}
|
||
|
||
if (!verifyToken) {
|
||
return { verified: false, values: [], source: '', error: '未生成待校验的 TXT 记录值,请重新设置域名' };
|
||
}
|
||
|
||
try {
|
||
const { values, source } = await this.resolveTxtValues(verifyHost);
|
||
const normalizedValues = values.map(value => String(value).trim());
|
||
|
||
// 校验值为后端生成的 hex,比对时忽略大小写(DNS 记录本身大小写不敏感)
|
||
const expected = verifyToken.toLowerCase();
|
||
if (normalizedValues.some(value => value.toLowerCase() === expected)) {
|
||
return { verified: true, values: normalizedValues, source, error: null };
|
||
}
|
||
|
||
return {
|
||
verified: false,
|
||
values: normalizedValues,
|
||
source,
|
||
error: normalizedValues.length > 0 ? 'TXT 记录未包含校验值' : '未解析到 TXT 记录',
|
||
};
|
||
} catch (error) {
|
||
return {
|
||
verified: false,
|
||
values: [],
|
||
source: '',
|
||
error: this.sanitizeErrorText(error.message) || '域名解析失败',
|
||
};
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 判定错误是否为「数据库列不存在」(迁移尚未执行的典型表现)。
|
||
*
|
||
* 迁移尚未执行时查询 domain_status 等新列会报 ER_BAD_FIELD_ERROR / Unknown column,
|
||
* 这类错误必须走降级路径(而非中断定时任务、也不应让公共拉取接口直接 500)。
|
||
*
|
||
* @param {*} error 错误对象。
|
||
* @return {boolean} 是未知列错误返回 true。
|
||
*/
|
||
isUnknownColumnError(error) {
|
||
if (!error) {
|
||
return false;
|
||
}
|
||
|
||
const code = String((error.parent && error.parent.code) || error.code || '');
|
||
if (code === 'ER_BAD_FIELD_ERROR') {
|
||
return true;
|
||
}
|
||
|
||
const message = String(error.message || '');
|
||
return /unknown column/i.test(message) || message.includes('ER_BAD_FIELD_ERROR');
|
||
}
|
||
|
||
/**
|
||
* 查询「已验证」的域名配置记录(公共拉取闸门的查库入口)。
|
||
*
|
||
* 迁移容错:迁移尚未执行(domain_status 列不存在)时降级为仅按 domain 查询,
|
||
* 保持迁移前的行为,并用进程内一次性标记避免刷日志;
|
||
* 迁移完成后需重启实例,闸门才会真正生效(进程内标记与 model 定义均在重启后刷新)。
|
||
*
|
||
* @param {Object} configModel WarehouseFrontConfig model。
|
||
* @param {string} normalizedDomain 已 trim 的域名。
|
||
* @return {Promise<Object|null>} 命中返回记录实例,未命中返回 null。
|
||
* @throws {Error} 非「未知列」的数据库异常原样抛出(由调用方转 500)。
|
||
*/
|
||
async findVerifiedDomainRecord(configModel, normalizedDomain) {
|
||
try {
|
||
return await configModel.findOne({
|
||
where: {
|
||
domain: normalizedDomain,
|
||
domain_status: DOMAIN_STATUS_VERIFIED,
|
||
},
|
||
});
|
||
} catch (error) {
|
||
if (!this.isUnknownColumnError(error)) {
|
||
throw error;
|
||
}
|
||
|
||
// 一次性 WARN:迁移完成并重启实例后自动恢复闸门,避免每个请求都刷日志
|
||
if (this.app && !this.app._frontConfigDomainStatusFallbackWarned) {
|
||
this.app._frontConfigDomainStatusFallbackWarned = true;
|
||
this.ctx.logger.warn(
|
||
'[FrontConfigService.findVerifiedDomainRecord] wms_warehouse_front_config.domain_status 列不存在'
|
||
+ '(迁移尚未执行),本次降级为仅按 domain 查询;迁移完成后需重启实例才能恢复域名验证闸门'
|
||
);
|
||
}
|
||
|
||
return configModel.findOne({
|
||
where: {
|
||
domain: normalizedDomain,
|
||
},
|
||
});
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 扫描并校验待验证的域名(供定时任务与手动触发复用)。
|
||
*
|
||
* 选取条件:domain_verify_host 与 domain_verify_token 均非空、domain_status 为 0(未验证)
|
||
* 或 2(验证失败),且 domain_verify_attempts 未达 maxAttempts 上限;按 id 升序单批处理
|
||
* batchSize 行。已达尝试上限的行不再自动重试,计入 skipped(仍可由 checkDomain 手动触发)。
|
||
*
|
||
* 失败隔离:单行解析/落库失败只计入 errors,不中断整轮;onRow 回调抛错同样不影响主流程。
|
||
* fail-soft:model 不可用、或迁移尚未执行(domain_status 等列不存在)时不抛出,
|
||
* 返回零统计 + errors 中的脱敏原因,由调用方记 WARN。
|
||
*
|
||
* @param {Object} [options] 扫描选项。
|
||
* @param {number} [options.batchSize] 单轮最多处理行数(默认取 domainVerify.batchSize)。
|
||
* @param {number} [options.maxAttempts] 超过后不再自动重试(默认取 domainVerify.maxAttempts)。
|
||
* @param {Function} [options.onRow] 每行处理后的回调(参数 { id, store_id, domain, verified, error })。
|
||
* @return {Promise<{scanned:number, verified:number, failed:number, skipped:number, errors:string[]}>}
|
||
* scanned:本轮选中的待处理行数;verified:其中校验通过且落库成功的行数;
|
||
* failed:校验失败且落库成功的行数;skipped:因达到 maxAttempts 上限而未自动重试的行数;
|
||
* errors:脱敏后的错误原因列表。
|
||
*/
|
||
async verifyPendingDomains(options = {}) {
|
||
const verifyConfig = this.getDomainVerifyConfig();
|
||
const batchSize = Number(options.batchSize) > 0
|
||
? Math.floor(Number(options.batchSize))
|
||
: verifyConfig.batchSize;
|
||
const maxAttempts = Number(options.maxAttempts) > 0
|
||
? Math.floor(Number(options.maxAttempts))
|
||
: verifyConfig.maxAttempts;
|
||
const onRow = typeof options.onRow === 'function' ? options.onRow : null;
|
||
|
||
const summary = { scanned: 0, verified: 0, failed: 0, skipped: 0, errors: [] };
|
||
|
||
const configModel = this.ctx.model && this.ctx.model.WarehouseFrontConfig;
|
||
if (!configModel || typeof configModel.findAll !== 'function') {
|
||
summary.errors.push('WarehouseFrontConfig model 不可用');
|
||
return summary;
|
||
}
|
||
|
||
const { Op } = this.app.Sequelize;
|
||
const pendingWhere = {
|
||
domain_verify_host: { [Op.ne]: null },
|
||
domain_verify_token: { [Op.ne]: null },
|
||
domain_status: { [Op.in]: [ DOMAIN_STATUS_UNVERIFIED, DOMAIN_STATUS_FAILED ] },
|
||
};
|
||
|
||
let rows = [];
|
||
try {
|
||
rows = await configModel.findAll({
|
||
where: {
|
||
...pendingWhere,
|
||
domain_verify_attempts: { [Op.lt]: maxAttempts },
|
||
},
|
||
attributes: [
|
||
'id',
|
||
'store_id',
|
||
'domain',
|
||
'domain_status',
|
||
'domain_verify_host',
|
||
'domain_verify_token',
|
||
'domain_verify_attempts',
|
||
'domain_last_error',
|
||
],
|
||
order: [[ 'id', 'ASC' ]],
|
||
limit: batchSize,
|
||
raw: true,
|
||
});
|
||
} catch (error) {
|
||
const reason = this.sanitizeErrorText(error.message) || '未知错误';
|
||
this.ctx.logger.warn('[FrontConfigService.verifyPendingDomains] 查询待验证域名失败: %s', reason);
|
||
summary.errors.push('查询待验证域名失败:' + reason);
|
||
return summary;
|
||
}
|
||
|
||
// 已达上限的行不再自动重试,单独计数便于观察「自动重试已耗尽」的域名规模;
|
||
// 计数失败不影响主流程(计入 errors 即可)
|
||
try {
|
||
summary.skipped = await configModel.count({
|
||
where: {
|
||
...pendingWhere,
|
||
domain_verify_attempts: { [Op.gte]: maxAttempts },
|
||
},
|
||
});
|
||
} catch (error) {
|
||
const reason = this.sanitizeErrorText(error.message) || '未知错误';
|
||
this.ctx.logger.warn('[FrontConfigService.verifyPendingDomains] 统计已达重试上限行数失败: %s', reason);
|
||
summary.errors.push('统计已达重试上限行数失败:' + reason);
|
||
}
|
||
|
||
summary.scanned = rows.length;
|
||
|
||
for (const row of rows) {
|
||
const rowId = Number(row.id);
|
||
const rowDomain = String(row.domain || '').trim();
|
||
const currentAttempts = Number(row.domain_verify_attempts) || 0;
|
||
let result = { verified: false, error: '未解析到 TXT 记录' };
|
||
|
||
try {
|
||
// verifyDomainRecord 契约上不抛异常,此处为最后一道兜底,保证单行失败不中断整轮
|
||
result = await this.verifyDomainRecord(row);
|
||
} catch (error) {
|
||
result = { verified: false, error: this.sanitizeErrorText(error.message) || '域名校验异常' };
|
||
}
|
||
|
||
let updateValues;
|
||
if (result.verified) {
|
||
updateValues = {
|
||
domain_status: DOMAIN_STATUS_VERIFIED,
|
||
domain_verified_at: new Date(),
|
||
domain_last_error: null,
|
||
domain_verify_attempts: currentAttempts + 1,
|
||
};
|
||
} else {
|
||
updateValues = {
|
||
domain_status: DOMAIN_STATUS_FAILED,
|
||
domain_verify_attempts: currentAttempts + 1,
|
||
domain_last_error: this.sanitizeErrorText(result.error || '未解析到 TXT 记录'),
|
||
};
|
||
}
|
||
|
||
try {
|
||
// 防并发守卫:仅更新 id 与 domain 均匹配的行,避免与并发校验者互相覆盖
|
||
await configModel.update(updateValues, {
|
||
where: { id: rowId, domain: row.domain },
|
||
});
|
||
|
||
if (result.verified) {
|
||
summary.verified += 1;
|
||
// 未验证域名本不会被公共拉取放行,成功后仍主动清一次缓存更稳妥
|
||
await this.clearDomainCache(rowDomain);
|
||
} else {
|
||
summary.failed += 1;
|
||
}
|
||
} catch (error) {
|
||
const reason = this.sanitizeErrorText(error.message) || '未知错误';
|
||
summary.errors.push('更新域名验证状态失败(id=' + rowId + '):' + reason);
|
||
this.ctx.logger.warn(
|
||
'[FrontConfigService.verifyPendingDomains] 更新域名验证状态失败 id=%s: %s',
|
||
rowId,
|
||
reason
|
||
);
|
||
}
|
||
|
||
if (onRow) {
|
||
try {
|
||
await onRow({
|
||
id: rowId,
|
||
store_id: Number(row.store_id) || 0,
|
||
domain: rowDomain,
|
||
verified: !!result.verified,
|
||
error: result.verified ? null : this.sanitizeErrorText(result.error || ''),
|
||
});
|
||
} catch (error) {
|
||
// 回调异常只 WARN,绝不影响主流程
|
||
this.ctx.logger.warn(
|
||
'[FrontConfigService.verifyPendingDomains] onRow 回调执行失败 id=%s: %s',
|
||
rowId,
|
||
this.sanitizeErrorText(error.message)
|
||
);
|
||
}
|
||
}
|
||
}
|
||
|
||
return summary;
|
||
}
|
||
|
||
/**
|
||
* 构建前端配置品牌信息输出对象(settings 页回显,无记录时返回默认空值)。
|
||
*
|
||
* 安全红线:仅输出品牌与基础字段,严禁输出 cert_pem/key_pem/cert_expire_at/
|
||
* sync_status/sync_attempts/last_sync_error/last_synced_at 等证书与同步内部字段。
|
||
*
|
||
* @param {Object|null} record 配置记录实例(可为 null)。
|
||
* @param {number} warehouseId 当前仓库 ID。
|
||
* @return {Object} 品牌信息输出对象(warehouse_id/domain/title/logo_url/favicon_url/login_bg_url/theme/updated_at)。
|
||
*/
|
||
buildInfoOutput(record, warehouseId) {
|
||
const hasRecord = !!(record && typeof record.get === 'function');
|
||
const getValue = key => (hasRecord ? record.get(key) : null);
|
||
|
||
return {
|
||
warehouse_id: Number(warehouseId || 0),
|
||
domain: hasRecord ? (getValue('domain') || '') : '',
|
||
title: hasRecord ? (getValue('title') || '') : '',
|
||
logo_url: hasRecord ? (getValue('logo_url') || '') : '',
|
||
favicon_url: hasRecord ? (getValue('favicon_url') || '') : '',
|
||
login_bg_url: hasRecord ? (getValue('login_bg_url') || '') : '',
|
||
theme: hasRecord ? (getValue('theme') || null) : null,
|
||
updated_at: hasRecord ? (getValue('updated_at') || null) : null,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 构建前端配置证书输出对象(证书/私钥原文回显,无记录时返回默认空值)。
|
||
*
|
||
* 证书回显:输出证书原文(cert_pem)与私钥原文(key_pem,取自 cert_key 列),
|
||
* 不再输出 cert_path/key_path 路径字段(保存时已置空,尚无真实路径)。
|
||
* 安全说明:私钥原文回显仅限仓库主体登录后的 settings 页(getCert/saveCert
|
||
* 复用本输出);公共无鉴权接口 getByDomain 走 buildPublicOutput 白名单,不经过本方法。
|
||
*
|
||
* ⚠ 响应契约:本方法输出 13 个字段(原有 10 个 + 本次新增 3 个),文档与测试需同步。
|
||
* 原有 10 字段:warehouse_id/domain/cert_pem/key_pem/cert_expire_at/sync_status/
|
||
* sync_attempts/last_sync_error/last_synced_at/updated_at。
|
||
* 新增 3 字段(追加在末尾):
|
||
* - domain_status:域名验证状态 0-未验证/1-已验证/2-验证失败;
|
||
* - can_set_cert:域名非空且已验证(domain_status=1)才允许上传证书;
|
||
* - can_set_cert_reason:不可上传时的原因,可上传为空串。
|
||
*
|
||
* @param {Object|null} record 配置记录实例(可为 null)。
|
||
* @param {number} warehouseId 当前仓库 ID。
|
||
* @return {Object} 证书输出对象(13 字段)。
|
||
*/
|
||
buildCertOutput(record, warehouseId) {
|
||
const hasRecord = !!(record && typeof record.get === 'function');
|
||
const getValue = key => (hasRecord ? record.get(key) : null);
|
||
|
||
const domain = hasRecord ? (getValue('domain') || '') : '';
|
||
const domainStatus = hasRecord ? Number(getValue('domain_status') || 0) : DOMAIN_STATUS_UNVERIFIED;
|
||
// 上传证书的前置闸门:必须先设置域名并通过 DNS TXT 验证
|
||
const canSetCert = !!domain && domainStatus === DOMAIN_STATUS_VERIFIED;
|
||
|
||
let canSetCertReason = '';
|
||
if (!domain) {
|
||
canSetCertReason = '请先设置域名';
|
||
} else if (!canSetCert) {
|
||
canSetCertReason = this.describeDomainStatus(domainStatus);
|
||
}
|
||
|
||
return {
|
||
warehouse_id: Number(warehouseId || 0),
|
||
domain: hasRecord ? (getValue('domain') || '') : '',
|
||
cert_pem: hasRecord ? (getValue('cert_pem') || '') : '',
|
||
key_pem: hasRecord ? (getValue('cert_key') || '') : '',
|
||
cert_expire_at: hasRecord ? (getValue('cert_expire_at') || null) : null,
|
||
sync_status: hasRecord ? Number(getValue('sync_status') || 0) : 0,
|
||
sync_attempts: hasRecord ? Number(getValue('sync_attempts') || 0) : 0,
|
||
last_sync_error: hasRecord ? (getValue('last_sync_error') || '') : '',
|
||
last_synced_at: hasRecord ? (getValue('last_synced_at') || null) : null,
|
||
updated_at: hasRecord ? (getValue('updated_at') || null) : null,
|
||
can_set_cert: canSetCert,
|
||
can_set_cert_reason: canSetCertReason,
|
||
domain_status: domainStatus,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 查询当前仓库前端独立部署品牌配置(settings 页回显)。
|
||
*
|
||
* 需登录(token 绑定仓库上下文,只能查到自己仓库的配置),仅返回品牌与基础字段,
|
||
* 不含证书/私钥原文与同步状态等内部字段(证书回显走 getCert)。
|
||
*
|
||
* @return {Promise<Object>} 品牌信息输出对象;无记录时返回默认空值。
|
||
* @throws {Error} 未识别到当前仓库时抛出 400;非仓库主体时抛出 403。
|
||
*/
|
||
async getInfo() {
|
||
const warehouseId = this.getCurrentWarehouseId();
|
||
|
||
// 仅仓库主体管理员可查看前端独立部署配置(isWarehouse 判定)
|
||
await this.assertWarehouseSubject();
|
||
|
||
const configModel = this.ctx.model && this.ctx.model.WarehouseFrontConfig;
|
||
if (!configModel || typeof configModel.findOne !== 'function') {
|
||
throw this.createError('WarehouseFrontConfig model 不可用', 500);
|
||
}
|
||
|
||
const record = await configModel.findOne({
|
||
where: {
|
||
store_id: warehouseId,
|
||
},
|
||
});
|
||
|
||
return this.buildInfoOutput(record, warehouseId);
|
||
}
|
||
|
||
/**
|
||
* 查询当前仓库前端独立部署证书配置(settings 页回显)。
|
||
*
|
||
* 需登录(token 绑定仓库上下文,只能查到自己仓库的配置),
|
||
* 响应含证书原文(cert_pem)与私钥原文(key_pem),仅供仓库主体 settings 页回显;
|
||
* 公共无鉴权接口 getByDomain 仍只返回公开字段白名单。
|
||
*
|
||
* @return {Promise<Object>} 证书输出对象;无记录时返回默认空值。
|
||
* @throws {Error} 未识别到当前仓库时抛出 400;非仓库主体时抛出 403。
|
||
*/
|
||
async getCert() {
|
||
const warehouseId = this.getCurrentWarehouseId();
|
||
|
||
// 仅仓库主体管理员可查看前端独立部署证书(isWarehouse 判定)
|
||
await this.assertWarehouseSubject();
|
||
|
||
const configModel = this.ctx.model && this.ctx.model.WarehouseFrontConfig;
|
||
if (!configModel || typeof configModel.findOne !== 'function') {
|
||
throw this.createError('WarehouseFrontConfig model 不可用', 500);
|
||
}
|
||
|
||
const record = await configModel.findOne({
|
||
where: {
|
||
store_id: warehouseId,
|
||
},
|
||
});
|
||
|
||
return this.buildCertOutput(record, warehouseId);
|
||
}
|
||
|
||
/**
|
||
* 查询当前仓库域名验证状态(settings 页回显,需登录、仅仓库主体)。
|
||
*
|
||
* 需登录(token 绑定仓库上下文,只能查到自己仓库的配置);无记录时返回空值默认。
|
||
*
|
||
* @return {Promise<Object>} 域名输出对象(warehouse_id/domain/domain_status/verify_host/
|
||
* verify_value/cname/verified_at/attempts/last_error)。
|
||
* @throws {Error} 未识别到当前仓库时抛出 400;非仓库主体时抛出 403。
|
||
*/
|
||
async getDomain() {
|
||
const warehouseId = this.getCurrentWarehouseId();
|
||
|
||
// 仅仓库主体管理员可查看前端独立部署域名配置(isWarehouse 判定)
|
||
await this.assertWarehouseSubject();
|
||
|
||
const configModel = this.ctx.model && this.ctx.model.WarehouseFrontConfig;
|
||
if (!configModel || typeof configModel.findOne !== 'function') {
|
||
throw this.createError('WarehouseFrontConfig model 不可用', 500);
|
||
}
|
||
|
||
const record = await configModel.findOne({
|
||
where: {
|
||
store_id: warehouseId,
|
||
},
|
||
});
|
||
|
||
return this.buildDomainOutput(record, warehouseId);
|
||
}
|
||
|
||
/**
|
||
* 设置当前仓库自持域名并下发一次性 TXT 校验记录(需登录、仅仓库主体)。
|
||
*
|
||
* 流程:仓库主体校验 → domain 非空/长度/形态校验(统一转小写)→ 全局唯一校验(409)
|
||
* → 生成随机校验子域与校验值 → upsert 该仓库行 → 清理新旧域名公共拉取缓存。
|
||
* 域名发生变更(含从无到有)会同时清空既有证书与同步状态:旧证书 SAN/CN 不覆盖新域名,
|
||
* 保留会让 nginx 用错误证书对外服务;域名未变化时保留既有证书与验证状态。
|
||
*
|
||
* @param {Object} [data={}] 请求参数。
|
||
* @param {string} data.domain 仓库自持域名(必填,非空,≤100 字符,全局唯一)。
|
||
* @return {Promise<Object>} 域名输出对象(含待配置的 verify_host/verify_value 与 cname)。
|
||
* @throws {Error} 未识别到当前仓库时抛出 400;非仓库主体时抛出 403;
|
||
* 参数非法时抛出 400;域名被其他仓库占用时抛出 409。
|
||
*/
|
||
async setDomain(data = {}) {
|
||
const warehouseId = this.getCurrentWarehouseId();
|
||
|
||
// 仅仓库主体管理员可配置前端独立部署域名(isWarehouse 判定)
|
||
await this.assertWarehouseSubject();
|
||
|
||
const configModel = this.ctx.model && this.ctx.model.WarehouseFrontConfig;
|
||
if (!configModel || typeof configModel.findOne !== 'function') {
|
||
throw this.createError('WarehouseFrontConfig model 不可用', 500);
|
||
}
|
||
|
||
const domain = this.normalizeText(data.domain, 'domain', 100);
|
||
if (!domain) {
|
||
throw this.createError('domain 不能为空', 400);
|
||
}
|
||
|
||
// 统一转小写存储:DNS 大小写不敏感,避免同一域名靠大小写差异绕过去重校验
|
||
const normalizedDomain = domain.toLowerCase();
|
||
if (!DOMAIN_PATTERN.test(normalizedDomain)) {
|
||
throw this.createError('domain 格式不正确', 400);
|
||
}
|
||
|
||
// domain 全局唯一:可空列唯一索引不拦多个 NULL,非空值的唯一性必须应用层校验
|
||
await this.assertDomainUnique(normalizedDomain, warehouseId);
|
||
|
||
const record = await configModel.findOne({
|
||
where: {
|
||
store_id: warehouseId,
|
||
},
|
||
});
|
||
|
||
const previousDomain = record ? String(record.get('domain') || '').trim() : '';
|
||
// 仅大小写差异不算域名变更:避免单纯规范化大小写就把仍在有效期内的证书清掉
|
||
const domainChanged = previousDomain.toLowerCase() !== normalizedDomain;
|
||
|
||
// 重复设置同一已验证域名:幂等返回,不刷新校验码、不清证书、不重置验证状态
|
||
if (record && !domainChanged && Number(record.get('domain_status') || 0) === DOMAIN_STATUS_VERIFIED) {
|
||
return this.buildDomainOutput(record, warehouseId);
|
||
}
|
||
|
||
// 首次设置/域名变更/尚未验证:下发新的校验码并回到「未验证」,清零历史尝试次数与失败原因
|
||
const verifyCode = this.buildDomainVerifyCode(normalizedDomain);
|
||
const patch = {
|
||
domain: normalizedDomain,
|
||
domain_verify_host: verifyCode.host,
|
||
domain_verify_token: verifyCode.token,
|
||
domain_status: DOMAIN_STATUS_UNVERIFIED,
|
||
domain_verify_attempts: 0,
|
||
domain_verified_at: null,
|
||
domain_last_error: null,
|
||
};
|
||
|
||
if (domainChanged) {
|
||
// 域名变更:既有证书对新域名不再有效,必须一并清空并重置同步状态,
|
||
// 避免 nginx 继续用旧域名证书对外服务(证书与域名不匹配)
|
||
Object.assign(patch, {
|
||
cert_pem: null,
|
||
cert_key: null,
|
||
cert_path: null,
|
||
key_path: null,
|
||
cert_expire_at: null,
|
||
sync_status: 0,
|
||
sync_attempts: 0,
|
||
last_sync_error: null,
|
||
last_synced_at: null,
|
||
});
|
||
}
|
||
|
||
let savedRecord = record;
|
||
try {
|
||
if (record) {
|
||
await record.update(patch);
|
||
} else {
|
||
savedRecord = await configModel.create({
|
||
store_id: warehouseId,
|
||
...patch,
|
||
});
|
||
}
|
||
} catch (error) {
|
||
// 并发写入兜底:唯一索引冲突统一转为业务错误
|
||
if (error && error.name === 'SequelizeUniqueConstraintError') {
|
||
const conflictFields = error.fields || {};
|
||
if (Object.prototype.hasOwnProperty.call(conflictFields, 'domain')) {
|
||
throw this.createError(`域名 ${normalizedDomain} 已被其他仓库使用`, 409);
|
||
}
|
||
throw this.createError('仓库前端配置保存冲突,请稍后重试', 409);
|
||
}
|
||
throw error;
|
||
}
|
||
|
||
// 回查一次再输出,避免实例上残留 CURRENT_TIMESTAMP 等字面量
|
||
const refreshedRecord = await configModel.findByPk(savedRecord.id);
|
||
|
||
// 写库成功后清理公共拉取缓存(先写库后清缓存):域名变更时新旧两个 domain 都必须清,
|
||
// 否则旧域名的公开配置缓存仍会对外返回;清缓存失败仅记日志,不影响设置结果
|
||
const affectedDomains = [ ...new Set([ previousDomain, normalizedDomain ].filter(item => item)) ];
|
||
await Promise.all(affectedDomains.map(affectedDomain => this.clearDomainCache(affectedDomain)
|
||
.catch(error => {
|
||
this.ctx.logger.warn('[FrontConfigService.setDomain] 清理前端配置缓存失败: %s', error.message);
|
||
})));
|
||
|
||
return this.buildDomainOutput(refreshedRecord, warehouseId);
|
||
}
|
||
|
||
/**
|
||
* 主动执行一次域名 TXT 校验并回写结果(需登录、仅仓库主体)。
|
||
*
|
||
* 无记录或 domain 为空时返回 400 提示先设置域名;校验通过置 domain_status=1
|
||
* 并记录 domain_verified_at;失败置 domain_status=2、尝试次数 +1 并记录脱敏后的失败原因。
|
||
* 校验一律以库内 domain_verify_host 为目标(不用裸域名),避免与用户主域其它 TXT 记录冲突。
|
||
*
|
||
* @return {Promise<Object>} 域名输出对象 + verified(本次是否通过)
|
||
* + resolved_values(本次解析到的 TXT 值,最多 5 条)。
|
||
* @throws {Error} 未识别到当前仓库时抛出 400;未设置域名时抛出 400;非仓库主体时抛出 403。
|
||
*/
|
||
async checkDomain() {
|
||
const warehouseId = this.getCurrentWarehouseId();
|
||
|
||
// 仅仓库主体管理员可触发域名校验(isWarehouse 判定)
|
||
await this.assertWarehouseSubject();
|
||
|
||
const configModel = this.ctx.model && this.ctx.model.WarehouseFrontConfig;
|
||
if (!configModel || typeof configModel.findOne !== 'function') {
|
||
throw this.createError('WarehouseFrontConfig model 不可用', 500);
|
||
}
|
||
|
||
const record = await configModel.findOne({
|
||
where: {
|
||
store_id: warehouseId,
|
||
},
|
||
});
|
||
|
||
const domain = record ? String(record.get('domain') || '').trim() : '';
|
||
if (!domain) {
|
||
throw this.createError('请先设置域名', 400);
|
||
}
|
||
|
||
const domainStatus = Number(record.get('domain_status') || 0);
|
||
const currentHost = String(record.get('domain_verify_host') || '').trim();
|
||
const currentToken = String(record.get('domain_verify_token') || '').trim();
|
||
|
||
// 兼容迁移回填的历史行:域名线上已生效(直接视为已验证)但从未生成校验记录,
|
||
// 无法也无需重新校验;此处直接返回已验证,避免手动点校验把生效中的域名降级为验证失败
|
||
if (domainStatus === DOMAIN_STATUS_VERIFIED && (!currentHost || !currentToken)) {
|
||
return {
|
||
...this.buildDomainOutput(record, warehouseId),
|
||
verified: true,
|
||
resolved_values: [],
|
||
};
|
||
}
|
||
|
||
const patch = {};
|
||
let verifyHost = currentHost;
|
||
let verifyToken = currentToken;
|
||
|
||
// 未验证/验证失败且库内缺少校验码(历史脏数据):补发一份,
|
||
// 用户配置 DNS 解析后再次校验即可通过(本次校验仍会因记录未生效而失败)
|
||
if (!verifyHost || !verifyToken) {
|
||
const verifyCode = this.buildDomainVerifyCode(domain);
|
||
verifyHost = verifyCode.host;
|
||
verifyToken = verifyCode.token;
|
||
patch.domain_verify_host = verifyHost;
|
||
patch.domain_verify_token = verifyToken;
|
||
}
|
||
|
||
const verifyResult = await this.verifyDomainRecord({
|
||
domain_verify_host: verifyHost,
|
||
domain_verify_token: verifyToken,
|
||
});
|
||
|
||
if (verifyResult.verified) {
|
||
patch.domain_status = DOMAIN_STATUS_VERIFIED;
|
||
patch.domain_verified_at = new Date();
|
||
patch.domain_last_error = null;
|
||
} else {
|
||
patch.domain_status = DOMAIN_STATUS_FAILED;
|
||
patch.domain_verify_attempts = Number(record.get('domain_verify_attempts') || 0) + 1;
|
||
patch.domain_last_error = this.sanitizeErrorText(verifyResult.error) || '域名验证失败';
|
||
}
|
||
|
||
await record.update(patch);
|
||
|
||
// 回查一次再输出,避免实例上残留 CURRENT_TIMESTAMP 等字面量
|
||
const savedRecord = await configModel.findByPk(record.id);
|
||
|
||
return {
|
||
...this.buildDomainOutput(savedRecord, warehouseId),
|
||
verified: !!verifyResult.verified,
|
||
resolved_values: (Array.isArray(verifyResult.values) ? verifyResult.values : [])
|
||
.slice(0, DOMAIN_RESOLVED_VALUES_LIMIT)
|
||
.map(value => String(value).slice(0, DOMAIN_RESOLVED_VALUE_MAX_LENGTH)),
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 构建域名验证输出对象(getDomain/setDomain/checkDomain 共用)。
|
||
*
|
||
* 安全口径:domain_status === 1(已验证)时不再回显校验主机名与校验值(令牌已无用途);
|
||
* 未验证/验证失败时回显,供用户配置 DNS TXT 解析记录。
|
||
*
|
||
* @param {Object|null} record 配置记录实例(可为 null,返回空值默认)。
|
||
* @param {number} warehouseId 当前仓库 ID。
|
||
* @return {Object} 域名输出对象(warehouse_id/domain/domain_status/verify_host/verify_value/cname/verified_at/attempts/last_error)。
|
||
*/
|
||
buildDomainOutput(record, warehouseId) {
|
||
const hasRecord = !!(record && typeof record.get === 'function');
|
||
const getValue = key => (hasRecord ? record.get(key) : null);
|
||
|
||
const domain = hasRecord ? String(getValue('domain') || '').trim() : '';
|
||
const domainStatus = hasRecord ? Number(getValue('domain_status') || 0) : DOMAIN_STATUS_UNVERIFIED;
|
||
const exposeVerifyInfo = !!domain && domainStatus !== DOMAIN_STATUS_VERIFIED;
|
||
|
||
return {
|
||
warehouse_id: Number(warehouseId || 0),
|
||
domain,
|
||
domain_status: domainStatus,
|
||
verify_host: exposeVerifyInfo ? String(getValue('domain_verify_host') || '') : '',
|
||
verify_value: exposeVerifyInfo ? String(getValue('domain_verify_token') || '') : '',
|
||
cname: this.getCnameTarget(),
|
||
verified_at: hasRecord ? (getValue('domain_verified_at') || null) : null,
|
||
attempts: hasRecord ? Number(getValue('domain_verify_attempts') || 0) : 0,
|
||
last_error: hasRecord ? String(getValue('domain_last_error') || '') : '',
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 域名状态→前端可读文案(用于 can_set_cert_reason,已验证返回空串)。
|
||
*
|
||
* @param {number} domainStatus 域名验证状态。
|
||
* @return {string} 状态文案。
|
||
*/
|
||
describeDomainStatus(domainStatus) {
|
||
if (Number(domainStatus) === DOMAIN_STATUS_VERIFIED) {
|
||
return '';
|
||
}
|
||
|
||
if (Number(domainStatus) === DOMAIN_STATUS_FAILED) {
|
||
return '域名验证失败';
|
||
}
|
||
|
||
return '域名待验证';
|
||
}
|
||
|
||
/**
|
||
* 构建前端配置公共拉取接口的缓存键(按域名)。
|
||
*
|
||
* @param {string} domain 域名(内部会 trim 规范化)。
|
||
* @return {string} Redis 缓存键。
|
||
*/
|
||
getDomainCacheKey(domain) {
|
||
return `front:config:domain:${String(domain || '').trim()}`;
|
||
}
|
||
|
||
/**
|
||
* 构建前端配置公共拉取接口的输出对象(仅公开字段白名单)。
|
||
*
|
||
* 安全红线:只输出 PUBLIC_FIELDS 白名单字段,
|
||
* 严禁输出 cert_pem/cert_key 证书与私钥内容,以及 cert_path、key_path、
|
||
* sync_status、sync_attempts、last_sync_error 等内部字段。
|
||
*
|
||
* @param {Object} record 配置记录实例。
|
||
* @return {Object} 仅含公开字段的输出对象。
|
||
*/
|
||
buildPublicOutput(record) {
|
||
const hasRecord = !!(record && typeof record.get === 'function');
|
||
const getValue = key => (hasRecord ? record.get(key) : null);
|
||
|
||
const output = {};
|
||
for (const key of PUBLIC_FIELDS) {
|
||
const value = hasRecord ? getValue(key) : null;
|
||
output[key] = key === 'theme' ? (value || null) : (value || '');
|
||
}
|
||
return output;
|
||
}
|
||
|
||
/**
|
||
* 清理指定域名的前端配置公共拉取缓存(空域名跳过)。
|
||
*
|
||
* @param {string} domain 待清理的域名。
|
||
* @return {Promise<void>} 无返回值。
|
||
*/
|
||
async clearDomainCache(domain) {
|
||
const normalizedDomain = String(domain || '').trim();
|
||
if (!normalizedDomain) {
|
||
return;
|
||
}
|
||
|
||
await this.deleteCacheByKey(this.getDomainCacheKey(normalizedDomain));
|
||
}
|
||
|
||
/**
|
||
* 按域名查询前端配置(公共无鉴权接口业务实现,Redis 缓存 + 查库兜底)。
|
||
*
|
||
* 安全红线:只返回公开字段(domain/title/logo_url/login_bg_url/favicon_url/theme),
|
||
* 严禁返回 cert_pem/cert_key 证书与私钥内容,以及 cert_path/key_path/
|
||
* sync_status/sync_attempts/last_sync_error 等内部字段。
|
||
*
|
||
* @param {string} domain 待查询域名。
|
||
* @return {Promise<Object>} 仅含公开字段的配置对象。
|
||
* @throws {Error} domain 为空时抛出 400;未登记域名抛出 404;数据库异常抛出 500。
|
||
*/
|
||
async getByDomain(domain) {
|
||
const normalizedDomain = String(domain || '').trim();
|
||
|
||
if (!normalizedDomain) {
|
||
throw this.createError('domain 不能为空', 400);
|
||
}
|
||
|
||
if (normalizedDomain.length > 100) {
|
||
throw this.createError('domain 长度不能超过 100 字符', 400);
|
||
}
|
||
|
||
const cacheKey = this.getDomainCacheKey(normalizedDomain);
|
||
|
||
// 缓存取舍:命中缓存后 TTL(PUBLIC_CACHE_TTL_SECONDS = 600s)内直接返回,
|
||
// 若该行随后被置为「未验证」,理论上最长仍有 600s 会被放行;
|
||
// 但 setDomain / saveCert / 域名验证扫描成功均已调用 clearDomainCache 主动失效,
|
||
// 实际可通过缓存被放行的窗口很短,接受该取舍。
|
||
// 优先读缓存;Redis 异常时降级查库(getCacheAsync 内部已做 Redis 降级处理)
|
||
if (this.app && typeof this.app.getCacheAsync === 'function') {
|
||
try {
|
||
const cached = await this.app.getCacheAsync(cacheKey);
|
||
|
||
// 未登记域名空缓存标记:直接按未配置返回,防穿透
|
||
if (cached && typeof cached === 'object' && cached.configured === false) {
|
||
throw this.createError('域名未配置', 404);
|
||
}
|
||
|
||
if (cached && typeof cached === 'object' && typeof cached.domain === 'string' && cached.domain) {
|
||
return cached;
|
||
}
|
||
} catch (error) {
|
||
if (Number(error.code) === 404) {
|
||
throw error;
|
||
}
|
||
this.ctx.logger.warn('[FrontConfigService.getByDomain] 读取缓存失败,降级查库: %s', error.message);
|
||
}
|
||
}
|
||
|
||
const configModel = this.ctx.model && this.ctx.model.WarehouseFrontConfig;
|
||
if (!configModel || typeof configModel.findOne !== 'function') {
|
||
throw this.createError('WarehouseFrontConfig model 不可用', 500);
|
||
}
|
||
|
||
// 应用层闸门:只放行 domain_status = 1(已验证)的域名;
|
||
// 迁移尚未执行时 findVerifiedDomainRecord 内部降级为仅按 domain 查询(保持迁移前行为)
|
||
const record = await this.findVerifiedDomainRecord(configModel, normalizedDomain);
|
||
|
||
if (!record) {
|
||
// 缓存穿透兜底:未登记域名写短 TTL 空缓存,防止高频探测打穿数据库
|
||
if (this.app && typeof this.app.setCacheAsync === 'function') {
|
||
try {
|
||
await this.app.setCacheAsync(cacheKey, { configured: false }, PUBLIC_MISS_CACHE_TTL_SECONDS);
|
||
} catch (error) {
|
||
this.ctx.logger.warn('[FrontConfigService.getByDomain] 写入未命中空缓存失败: %s', error.message);
|
||
}
|
||
}
|
||
throw this.createError('域名未配置', 404);
|
||
}
|
||
|
||
const output = this.buildPublicOutput(record);
|
||
|
||
if (this.app && typeof this.app.setCacheAsync === 'function') {
|
||
try {
|
||
await this.app.setCacheAsync(cacheKey, output, PUBLIC_CACHE_TTL_SECONDS);
|
||
} catch (error) {
|
||
this.ctx.logger.warn('[FrontConfigService.getByDomain] 写入缓存失败: %s', error.message);
|
||
}
|
||
}
|
||
|
||
return output;
|
||
}
|
||
|
||
/**
|
||
* 规范化证书/私钥 PEM 文本:去首尾空白,空值返回 null(表示未提供)。
|
||
*
|
||
* @param {*} value 原始值(PEM 文本)。
|
||
* @param {string} fieldName 字段名(用于错误提示)。
|
||
* @return {string|null} 规范化后的 PEM 文本;空值返回 null。
|
||
* @throws {Error} 内容超过长度上限时抛出,状态码 400。
|
||
*/
|
||
normalizePem(value, fieldName) {
|
||
if (value === undefined || value === null) {
|
||
return null;
|
||
}
|
||
|
||
const normalized = String(value).trim();
|
||
if (!normalized) {
|
||
return null;
|
||
}
|
||
|
||
if (normalized.length > PEM_MAX_LENGTH) {
|
||
throw this.createError(`${fieldName} 内容长度不能超过 ${PEM_MAX_LENGTH} 字符`, 400);
|
||
}
|
||
|
||
return normalized;
|
||
}
|
||
|
||
/**
|
||
* 用 Node 内置 crypto.X509Certificate 解析证书 PEM 文本。
|
||
*
|
||
* @param {string} certPem 证书 PEM 文本。
|
||
* @return {Object} 解析成功后的 X509Certificate 实例。
|
||
* @throws {Error} 证书无法解析时抛出,状态码 400,统一文案“证书不合法”。
|
||
*/
|
||
parseCertPem(certPem) {
|
||
try {
|
||
return new crypto.X509Certificate(certPem);
|
||
} catch (error) {
|
||
throw this.createError('证书不合法', 400);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 校验证书有效期:未生效或已过期的证书禁止提交。
|
||
*
|
||
* @param {Object} cert 已解析的 X509Certificate 实例。
|
||
* @return {void} 无返回值。
|
||
* @throws {Error} 证书未生效或已过期时抛出,状态码 400,统一文案“证书不合法”。
|
||
*/
|
||
assertCertValid(cert) {
|
||
const now = Date.now();
|
||
const validFrom = new Date(cert.validFrom);
|
||
const validTo = new Date(cert.validTo);
|
||
|
||
if (Number.isNaN(validFrom.getTime())) {
|
||
throw this.createError('证书不合法', 400);
|
||
}
|
||
|
||
if (validFrom.getTime() > now) {
|
||
throw this.createError('证书不合法', 400);
|
||
}
|
||
|
||
if (Number.isNaN(validTo.getTime())) {
|
||
throw this.createError('证书不合法', 400);
|
||
}
|
||
|
||
if (validTo.getTime() <= now) {
|
||
throw this.createError('证书不合法', 400);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 收集证书可覆盖的域名列表:SAN 中的 DNS 项与 CN,统一转小写。
|
||
*
|
||
* @param {Object} cert 已解析的 X509Certificate 实例。
|
||
* @return {string[]} 小写域名列表。
|
||
*/
|
||
collectCertNames(cert) {
|
||
const names = [];
|
||
|
||
const sanText = cert.subjectAltName || '';
|
||
for (const part of String(sanText).split(',')) {
|
||
const entry = String(part).trim();
|
||
if (entry.startsWith('DNS:')) {
|
||
const dnsName = entry.slice(4).trim();
|
||
if (dnsName) {
|
||
names.push(dnsName.toLowerCase());
|
||
}
|
||
}
|
||
}
|
||
|
||
const subjectText = cert.subject || '';
|
||
const cnMatch = /CN\s*=\s*([^,\n]+)/i.exec(String(subjectText));
|
||
if (cnMatch && cnMatch[1]) {
|
||
names.push(cnMatch[1].trim().toLowerCase());
|
||
}
|
||
|
||
return names;
|
||
}
|
||
|
||
/**
|
||
* 判断证书域名列表是否覆盖目标域名(支持精确匹配与通配符 *.example.com)。
|
||
*
|
||
* @param {string[]} names 证书 SAN/CN 域名列表(小写)。
|
||
* @param {string} domain 待校验域名。
|
||
* @return {boolean} 是否覆盖。
|
||
*/
|
||
certCoversDomain(names, domain) {
|
||
const target = String(domain).toLowerCase();
|
||
if (!target) {
|
||
return true;
|
||
}
|
||
|
||
return names.some(name => {
|
||
const normalized = String(name).toLowerCase();
|
||
if (normalized === target) {
|
||
return true;
|
||
}
|
||
|
||
if (normalized.startsWith('*.')) {
|
||
const suffix = normalized.slice(1);
|
||
if (!target.endsWith(suffix)) {
|
||
return false;
|
||
}
|
||
const prefix = target.slice(0, target.length - suffix.length);
|
||
return prefix.length > 0 && !prefix.includes('.');
|
||
}
|
||
|
||
return false;
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 校验私钥与证书是否成对:对比两者的 SPKI DER 公钥指纹。
|
||
*
|
||
* @param {string} keyPem 私钥 PEM 文本。
|
||
* @param {Object} cert 已解析的 X509Certificate 实例。
|
||
* @return {void} 无返回值。
|
||
* @throws {Error} 私钥无法解析或与证书不匹配时抛出,状态码 400,统一文案“证书不合法”。
|
||
*/
|
||
validateKeyPem(keyPem, cert) {
|
||
let publicKey;
|
||
try {
|
||
publicKey = crypto.createPublicKey(keyPem);
|
||
} catch (error) {
|
||
throw this.createError('证书不合法', 400);
|
||
}
|
||
|
||
const keySpki = publicKey.export({ type: 'spki', format: 'der' });
|
||
const certSpki = cert.publicKey.export({ type: 'spki', format: 'der' });
|
||
if (Buffer.compare(keySpki, certSpki) !== 0) {
|
||
throw this.createError('证书不合法', 400);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 校验当前主体为仓库主体(前端独立部署配置仅仓库主体可操作)。
|
||
*
|
||
* @return {Promise<Object>} 当前主体对象(含 id/company_name/project/isWarehouse/status)。
|
||
* @throws {Error} 签约关系服务不可用时抛出 500;非仓库主体时抛出 403。
|
||
*/
|
||
async assertWarehouseSubject() {
|
||
const storeWarehouseService = this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.storeWarehouse;
|
||
if (!storeWarehouseService || typeof storeWarehouseService.getCurrentSubject !== 'function') {
|
||
throw this.createError('签约关系服务不可用', 500);
|
||
}
|
||
|
||
const currentSubject = await storeWarehouseService.getCurrentSubject();
|
||
if (!currentSubject || !currentSubject.isWarehouse) {
|
||
throw this.createError('仅仓库主体可配置前端独立部署', 403);
|
||
}
|
||
|
||
return currentSubject;
|
||
}
|
||
|
||
/**
|
||
* 保存当前仓库前端独立部署品牌配置(upsert,一仓一行,仅品牌字段部分更新)。
|
||
*
|
||
* 域名与证书不在本接口受理范围:domain 变更必须走 setDomain(并重新通过域名验证);
|
||
* cert_pem/key_pem/cert_path/key_path/cert_expire_at 一律不受理(方法层白名单过滤)。
|
||
* 保存仍视为一次配置变更:同步状态重置为待同步,写库成功后清理当前 domain 的公共拉取缓存。
|
||
*
|
||
* @param {Object} [data={}] 请求参数。
|
||
* @param {string} [data.title] 站点标题(≤100 字符,空值清空)。
|
||
* @param {string} [data.logo_url] Logo 地址(≤255 字符,空值清空)。
|
||
* @param {string} [data.favicon_url] 站点 favicon 图标地址(≤255 字符,空值清空)。
|
||
* @param {string} [data.login_bg_url] 登录页背景图地址(≤255 字符,空值清空)。
|
||
* @param {Object|string} [data.theme] 主题配置(合法 JSON 对象或 JSON 字符串,空值清空)。
|
||
* @return {Promise<Object>} 保存后的品牌信息输出对象(同步状态已重置为待同步;不含证书/私钥字段)。
|
||
* @throws {Error} 非仓库主体时抛出 403;参数非法时抛出 400。
|
||
*/
|
||
async saveInfo(data = {}) {
|
||
const warehouseId = this.getCurrentWarehouseId();
|
||
|
||
// 仅仓库主体管理员可配置前端独立部署(isWarehouse 判定)
|
||
await this.assertWarehouseSubject();
|
||
|
||
const configModel = this.ctx.model && this.ctx.model.WarehouseFrontConfig;
|
||
if (!configModel || typeof configModel.findOne !== 'function') {
|
||
throw this.createError('WarehouseFrontConfig model 不可用', 500);
|
||
}
|
||
|
||
const patch = {};
|
||
|
||
for (const field of TEXT_FIELDS) {
|
||
if (Object.prototype.hasOwnProperty.call(data, field.key)) {
|
||
patch[field.key] = this.normalizeText(data[field.key], field.name, field.maxLength);
|
||
}
|
||
}
|
||
|
||
if (Object.prototype.hasOwnProperty.call(data, 'theme')) {
|
||
patch.theme = this.normalizeTheme(data.theme);
|
||
}
|
||
|
||
// 保存即重置同步状态:本次保存待同步
|
||
patch.sync_status = 0;
|
||
patch.sync_attempts = 0;
|
||
patch.last_sync_error = null;
|
||
patch.last_synced_at = null;
|
||
|
||
let record = await configModel.findOne({
|
||
where: {
|
||
store_id: warehouseId,
|
||
},
|
||
});
|
||
|
||
// 品牌字段不改变 domain:写库成功后清理当前 domain 的公共拉取缓存即可
|
||
const previousDomain = record ? String(record.get('domain') || '').trim() : '';
|
||
|
||
try {
|
||
if (record) {
|
||
await record.update(patch);
|
||
} else {
|
||
record = await configModel.create({
|
||
store_id: warehouseId,
|
||
...patch,
|
||
});
|
||
}
|
||
} catch (error) {
|
||
// 并发写入兜底:唯一索引冲突统一转为业务错误
|
||
if (error && error.name === 'SequelizeUniqueConstraintError') {
|
||
throw this.createError('仓库前端配置保存冲突,请稍后重试', 409);
|
||
}
|
||
throw error;
|
||
}
|
||
|
||
// 回查一次再输出,避免实例上残留 CURRENT_TIMESTAMP 等字面量
|
||
const savedRecord = await configModel.findByPk(record.id);
|
||
|
||
// 写库成功后清理公共拉取缓存(先写库后清缓存);清缓存失败仅记日志,不影响保存结果
|
||
if (previousDomain) {
|
||
await this.clearDomainCache(previousDomain)
|
||
.catch(error => {
|
||
this.ctx.logger.warn('[FrontConfigService.saveInfo] 清理前端配置缓存失败: %s', error.message);
|
||
});
|
||
}
|
||
|
||
return this.buildInfoOutput(savedRecord, warehouseId);
|
||
}
|
||
|
||
/**
|
||
* 上传当前仓库前端独立部署证书(证书/私钥成对,需登录、仅仓库主体)。
|
||
*
|
||
* domain 不再作为入参受理:域名一律取库内已设置的值(前端若仍传 domain 会被忽略),
|
||
* 且必须先通过 DNS TXT 验证(domain_status=1)才允许上传。
|
||
* 校验链:库内域名非空且已验证 → 证书可解析 → 未生效拒绝 → 已过期拒绝 →
|
||
* 私钥与证书成对 → 证书 SAN/CN 覆盖库内 domain(支持 *.example.com 通配,不覆盖返回 400)。
|
||
* 证书校验链任一失败均返回统一文案“证书不合法”(400),不返回细节。
|
||
* 通过后自动写入 cert_expire_at(证书 validTo 权威值,不接受前端传值),
|
||
* 证书/私钥 PEM 内容直接写入 cert_pem/cert_key 列(内容仅定时任务读取,不写暂存文件);
|
||
* cert_path/key_path 保存时置空,避免内容已换而路径陈旧,等待定时任务部署后回填真实路径;
|
||
* 同时重置同步状态;写库成功后清理该域名的公共拉取缓存(先写库后清缓存)。
|
||
*
|
||
* @param {Object} [data={}] 请求参数。
|
||
* @param {string} data.pem 证书 PEM 文本(必填)。
|
||
* @param {string} data.key 私钥 PEM 文本(必填,与证书成对)。
|
||
* @return {Promise<Object>} 保存后的证书输出对象(13 字段,含证书/私钥原文回显)。
|
||
* @throws {Error} 非仓库主体时抛出 403;未设置/未验证域名、参数非法或证书不合法时抛出 400。
|
||
*/
|
||
async saveCert(data = {}) {
|
||
const warehouseId = this.getCurrentWarehouseId();
|
||
|
||
// 仅仓库主体管理员可上传前端独立部署证书(isWarehouse 判定)
|
||
await this.assertWarehouseSubject();
|
||
|
||
const configModel = this.ctx.model && this.ctx.model.WarehouseFrontConfig;
|
||
if (!configModel || typeof configModel.findOne !== 'function') {
|
||
throw this.createError('WarehouseFrontConfig model 不可用', 500);
|
||
}
|
||
|
||
// 入参必填校验:pem/key 必填(nginx 起 HTTPS 需要成对);data.domain 一律忽略不受理
|
||
const certPem = this.normalizePem(data.pem, 'pem');
|
||
if (!certPem) {
|
||
throw this.createError('pem 不能为空', 400);
|
||
}
|
||
|
||
const keyPem = this.normalizePem(data.key, 'key');
|
||
if (!keyPem) {
|
||
throw this.createError('key 不能为空', 400);
|
||
}
|
||
|
||
const record = await configModel.findOne({
|
||
where: {
|
||
store_id: warehouseId,
|
||
},
|
||
});
|
||
|
||
// 前置闸门:证书必须挂在当前仓库已设置并验证通过的域名上
|
||
const domain = record ? String(record.get('domain') || '').trim() : '';
|
||
if (!domain) {
|
||
throw this.createError('请先设置并验证域名', 400);
|
||
}
|
||
|
||
if (Number(record.get('domain_status') || 0) !== DOMAIN_STATUS_VERIFIED) {
|
||
throw this.createError('域名未通过验证,暂时无法上传证书', 400);
|
||
}
|
||
|
||
// 校验链:证书可解析 → 未生效/已过期拒绝 → 私钥匹配 → SAN/CN 覆盖库内域名
|
||
const cert = this.parseCertPem(certPem);
|
||
this.assertCertValid(cert);
|
||
this.validateKeyPem(keyPem, cert);
|
||
|
||
const certNames = this.collectCertNames(cert);
|
||
if (!this.certCoversDomain(certNames, domain)) {
|
||
throw this.createError('证书不合法', 400);
|
||
}
|
||
|
||
// 证书/私钥内容直接入库(不再写暂存文件),有效期以证书 validTo 权威写入。
|
||
// cert_path/key_path 保存时置空:内容已换而路径陈旧,避免 nginx 误读;
|
||
// 等待定时任务(Egg schedule/外部 crontab)部署后回填真实路径。
|
||
// patch 内不再含 domain:本接口已不受理域名变更,域名唯一性由 setDomain 保证,无需重复校验。
|
||
const patch = {
|
||
cert_pem: certPem,
|
||
cert_key: keyPem,
|
||
cert_path: null,
|
||
key_path: null,
|
||
cert_expire_at: new Date(cert.validTo),
|
||
// 保存即重置同步状态:本次上传待同步
|
||
sync_status: 0,
|
||
sync_attempts: 0,
|
||
last_sync_error: null,
|
||
last_synced_at: null,
|
||
};
|
||
|
||
try {
|
||
await record.update(patch);
|
||
} catch (error) {
|
||
// 并发写入兜底:唯一索引冲突统一转为业务错误
|
||
if (error && error.name === 'SequelizeUniqueConstraintError') {
|
||
throw this.createError('仓库前端配置保存冲突,请稍后重试', 409);
|
||
}
|
||
throw error;
|
||
}
|
||
|
||
// 回查一次再输出,避免实例上残留 CURRENT_TIMESTAMP 等字面量
|
||
const savedRecord = await configModel.findByPk(record.id);
|
||
|
||
// 写库成功后清理公共拉取缓存(先写库后清缓存:避免先清后写时并发读把旧值重新写回缓存)。
|
||
// 域名已不能在本接口变更,「旧域名/新域名」必然相同,因此只需清当前域名一个 key;
|
||
// 清缓存失败仅记日志,不影响保存结果。
|
||
await this.clearDomainCache(domain)
|
||
.catch(error => {
|
||
this.ctx.logger.warn('[FrontConfigService.saveCert] 清理前端配置缓存失败: %s', error.message);
|
||
});
|
||
|
||
return this.buildCertOutput(savedRecord, warehouseId);
|
||
}
|
||
}
|
||
|
||
module.exports = FrontConfigService;
|