feat(warehouse): 前置仓前端配置与按域名公开拉取接口
- 新增模型 wms_warehouse_front_config 与迁移:建表、 追加 favicon_url、追加 cert_pem(可回滚) - systems/setting/warehouse.js 实现 getFrontConfig / saveFrontConfig / saveFrontCert、 域名唯一性校验、按域名缓存读取(含未登记域名的短 TTL 空缓存防穿透)与缓存清理 - systemMethods/setting/warehouse.js 开放对应 system method - 新增公共免登录接口 frontConfig.getByDomain:按域名返回公开字段 (domain/title/logo_url/login_bg_url/favicon_url/theme), 不返回 cert_path/key_path/sync_status 等内部字段;未登记域名返回 404
This commit is contained in:
parent
724f4a13c6
commit
018bbd379d
165
app/model/warehouse_front_config.js
Normal file
165
app/model/warehouse_front_config.js
Normal file
@ -0,0 +1,165 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 仓库前端个性化配置模型(仓库伪独立部署,单表)。
|
||||
* - 每仓库一行(一仓一域一证书):保存仓库前端 Logo / 标题 / 登录页图 /
|
||||
* 主题等个性化配置,以及证书元信息与证书 PEM 内容(cert_pem / cert_key,由定时
|
||||
* 任务读取后写文件部署,禁止写入日志/接口响应)。
|
||||
* - sync_status 状态机:0-待同步,1-同步成功,2-同步失败;
|
||||
* 管理后台保存后置为待同步,由定时任务同步到 nginx 后回写状态。
|
||||
* - 证书启用/停用由整行删除或 sync_status 表达;证书到期由 cert_expire_at
|
||||
* 判断,不单独保留证书 status 列。
|
||||
* - domain 唯一索引(uk_domain)为 MySQL 可空列唯一索引:允许多个 NULL,
|
||||
* 应用层在写入非空 domain 前必须做唯一性校验,不能依赖数据库约束报错。
|
||||
* - store_id 唯一索引(uk_store_id):每仓一行,由数据库层保证。
|
||||
* - 不启用 paranoid:配置为"每仓库一行"的元数据,删除语义由业务层
|
||||
* (清空/停用配置)表达,表结构不含 deleted_at 列。
|
||||
*
|
||||
* @param {Object} app Egg.js Application 实例。
|
||||
* @return {Object} Sequelize Model 定义。
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, INTEGER, TINYINT, DATE, TEXT, JSON: JSON_TYPE } = app.Sequelize;
|
||||
|
||||
const WarehouseFrontConfig = app.model.define('warehouse_front_config', {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键ID',
|
||||
},
|
||||
store_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
references: {
|
||||
model: 'store',
|
||||
key: 'id',
|
||||
},
|
||||
comment: '仓库ID,关联 wms_store.id(is_warehouse=1),每仓一行',
|
||||
},
|
||||
domain: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '仓库自持域名;可空列唯一索引允许多个 NULL,非空值唯一性需应用层校验',
|
||||
},
|
||||
title: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '站点标题',
|
||||
},
|
||||
logo_url: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: 'Logo地址',
|
||||
},
|
||||
favicon_url: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '站点 favicon 图标地址',
|
||||
},
|
||||
login_bg_url: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '登录页背景图地址',
|
||||
},
|
||||
theme: {
|
||||
type: JSON_TYPE,
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '主题配置JSON(颜色/布局等)',
|
||||
},
|
||||
cert_path: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '证书文件路径(只存路径不存内容)',
|
||||
},
|
||||
cert_pem: {
|
||||
type: TEXT,
|
||||
allowNull: true,
|
||||
comment: '证书 PEM 内容(私钥不在内);内容仅由定时任务读取,禁止写入日志/接口响应',
|
||||
},
|
||||
key_path: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '私钥文件路径(只存路径不存内容)',
|
||||
},
|
||||
cert_key: {
|
||||
type: TEXT,
|
||||
allowNull: true,
|
||||
comment: '私钥 PEM 内容;内容仅由定时任务读取,禁止写入日志/接口响应',
|
||||
},
|
||||
cert_expire_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '证书到期时间',
|
||||
},
|
||||
sync_status: {
|
||||
type: TINYINT,
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
validate: {
|
||||
isIn: {
|
||||
args: [[ 0, 1, 2 ]],
|
||||
msg: '同步状态不合法:0-待同步,1-同步成功,2-同步失败',
|
||||
},
|
||||
},
|
||||
comment: '同步状态:0-待同步,1-同步成功,2-同步失败',
|
||||
},
|
||||
sync_attempts: {
|
||||
type: INTEGER(11),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '同步尝试次数',
|
||||
},
|
||||
last_sync_error: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '最近一次同步失败原因',
|
||||
},
|
||||
last_synced_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '最近一次同步成功时间',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '更新时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_warehouse_front_config',
|
||||
freezeTableName: true,
|
||||
underscored: true,
|
||||
timestamps: true,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
paranoid: false,
|
||||
comment: '仓库前端个性化配置表(含证书内容与元信息)',
|
||||
indexes: [
|
||||
{
|
||||
name: 'uk_store_id',
|
||||
unique: true,
|
||||
fields: [ 'store_id' ],
|
||||
},
|
||||
{
|
||||
name: 'uk_domain',
|
||||
unique: true,
|
||||
fields: [ 'domain' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_sync_status',
|
||||
fields: [ 'sync_status' ],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return WarehouseFrontConfig;
|
||||
};
|
||||
46
app/service/systemMethods/frontConfig.js
Normal file
46
app/service/systemMethods/frontConfig.js
Normal file
@ -0,0 +1,46 @@
|
||||
'use strict';
|
||||
|
||||
const MainService = require('../main');
|
||||
|
||||
class FrontConfigMethodsService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
// 公共按域名拉取前端配置:免登录、免权限、免鉴权(保留系统日志,与 workbench 公共接口口径一致)
|
||||
const _noNeedLogin = 'getByDomain';
|
||||
const _noNeedRight = 'getByDomain';
|
||||
const _noNeedLog = '';
|
||||
const _noNeedAuth = 'getByDomain';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
/**
|
||||
* 按域名拉取仓库前端公开配置(公共无鉴权接口)。
|
||||
*
|
||||
* 安全红线:响应仅含公开字段(domain/title/logo_url/login_bg_url/favicon_url/theme),
|
||||
* 不含 cert_path、key_path、sync_status、sync_attempts、last_sync_error 等内部字段。
|
||||
*
|
||||
* @param {Object} [data={}] 请求参数。
|
||||
* @param {string} data.domain 待查询域名(必填,非空)。
|
||||
* @return {Promise<Object>} 统一响应结构;命中返回公开字段配置(code=200),
|
||||
* 未登记域名返回 code=404「域名未配置」。
|
||||
*/
|
||||
async getByDomain(data = {}) {
|
||||
const { domain } = data || {};
|
||||
|
||||
const targetService = this.service && this.service.systems && this.service.systems.setting && this.service.systems.setting.warehouse;
|
||||
if (!targetService || typeof targetService.getFrontConfigByDomain !== 'function') {
|
||||
return this.fail('获取前端配置失败', { code: 500 });
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await targetService.getFrontConfigByDomain(domain);
|
||||
return this.success('获取成功', { ...result, code: 200 });
|
||||
} catch (error) {
|
||||
return this.fail(error.message || '获取前端配置失败', {
|
||||
code: Number(error.code) || 500,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = FrontConfigMethodsService;
|
||||
@ -6,9 +6,9 @@ class SettingWarehouseMethodsService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'getSettings,getFieldMeta,saveSettings';
|
||||
const _noNeedRight = 'getSettings,getFieldMeta,saveSettings,getFrontConfig,saveFrontConfig,saveFrontCert';
|
||||
const _noNeedLog = '*';
|
||||
const _noNeedAuth = 'getSettings,getFieldMeta,saveSettings';
|
||||
const _noNeedAuth = 'getSettings,getFieldMeta,saveSettings,getFrontConfig,saveFrontConfig,saveFrontCert';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
@ -79,6 +79,110 @@ class SettingWarehouseMethodsService extends MainService {
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询当前仓库前端独立部署配置(settings 页回显)。
|
||||
*
|
||||
* 响应含证书原文(cert_pem)与私钥原文(key_pem)回显,
|
||||
* 仅限登录用户查询其仓库上下文绑定的配置,供仓库主体 settings 页回显;
|
||||
* 公共无鉴权接口 frontConfig.getByDomain 不经过本出口,仍只返回公开字段白名单。
|
||||
*
|
||||
* @return {Promise<Object>} 统一响应结果。
|
||||
*/
|
||||
async getFrontConfig() {
|
||||
const targetService = this.service && this.service.systems && this.service.systems.setting && this.service.systems.setting.warehouse;
|
||||
|
||||
if (!targetService || typeof targetService.getFrontConfig !== 'function') {
|
||||
return this.fail('获取仓库前端配置失败', { code: 500 });
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await targetService.getFrontConfig();
|
||||
return this.success('ok', result);
|
||||
} catch (error) {
|
||||
return this.fail(error.message || '获取仓库前端配置失败', {
|
||||
code: Number(error.code) || 500,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存当前仓库前端独立部署品牌配置(upsert,一仓一行,仅品牌字段部分更新)。
|
||||
*
|
||||
* domain 与证书字段不再受理:domain 变更必须走 saveFrontCert 重新校验证书;
|
||||
* cert_pem/key_pem/cert_path/key_path/cert_expire_at 一律被白名单过滤忽略。
|
||||
*
|
||||
* @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>} 统一响应结果。
|
||||
*/
|
||||
async saveFrontConfig(data = {}) {
|
||||
const targetService = this.service && this.service.systems && this.service.systems.setting && this.service.systems.setting.warehouse;
|
||||
|
||||
if (!targetService || typeof targetService.saveFrontConfig !== 'function') {
|
||||
return this.fail('保存仓库前端配置失败', { code: 500 });
|
||||
}
|
||||
|
||||
try {
|
||||
const source = data || {};
|
||||
const params = {};
|
||||
|
||||
// domain/cert_path/key_path/cert_pem/key_pem/cert_expire_at 均不受理:
|
||||
// domain 变更走 saveFrontCert,证书与有效期字段由后端权威维护,前端传值直接忽略
|
||||
for (const key of [ 'title', 'logo_url', 'favicon_url', 'login_bg_url', 'theme' ]) {
|
||||
if (Object.prototype.hasOwnProperty.call(source, key)) {
|
||||
params[key] = source[key];
|
||||
}
|
||||
}
|
||||
|
||||
const result = await targetService.saveFrontConfig(params);
|
||||
return this.success('ok', result);
|
||||
} catch (error) {
|
||||
return this.fail(error.message || '保存仓库前端配置失败', {
|
||||
code: Number(error.code) || 500,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传当前仓库前端独立部署证书(domain + 证书/私钥成对,需登录、仅仓库主体)。
|
||||
*
|
||||
* 后端自动写入 cert_expire_at(证书 validTo 权威值),证书/私钥内容直接入库(不落盘),
|
||||
* 保存后清理新旧 domain 的公共拉取缓存并返回完整配置输出
|
||||
* (响应含证书/私钥原文回显,口径与 getFrontConfig 一致)。
|
||||
*
|
||||
* @param {Object} data 请求参数。
|
||||
* @param {string} data.domain 仓库自持域名(必填,非空,≤100 字符,全局唯一)。
|
||||
* @param {string} data.pem 证书 PEM 文本(必填)。
|
||||
* @param {string} data.key 私钥 PEM 文本(必填,与证书成对)。
|
||||
* @return {Promise<Object>} 统一响应结果。
|
||||
*/
|
||||
async saveFrontCert(data = {}) {
|
||||
const targetService = this.service && this.service.systems && this.service.systems.setting && this.service.systems.setting.warehouse;
|
||||
|
||||
if (!targetService || typeof targetService.saveFrontCert !== 'function') {
|
||||
return this.fail('上传前端证书失败', { code: 500 });
|
||||
}
|
||||
|
||||
try {
|
||||
const source = data || {};
|
||||
const { domain, pem, key } = source;
|
||||
const result = await targetService.saveFrontCert({
|
||||
domain,
|
||||
pem,
|
||||
key,
|
||||
});
|
||||
return this.success('ok', result);
|
||||
} catch (error) {
|
||||
return this.fail(error.message || '上传前端证书失败', {
|
||||
code: Number(error.code) || 500,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = SettingWarehouseMethodsService;
|
||||
|
||||
@ -1,5 +1,7 @@
|
||||
'use strict';
|
||||
|
||||
const crypto = require('node:crypto');
|
||||
|
||||
const { Service } = require('egg');
|
||||
|
||||
const INTERNAL_WAVE_STRATEGY_VERSION_KEY = 'wave_strategy_version';
|
||||
@ -333,6 +335,33 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([
|
||||
}),
|
||||
]);
|
||||
|
||||
// 仓库前端配置品牌文本字段元信息(对应 wms_warehouse_front_config,一仓一行)。
|
||||
// 域名与证书字段不在此列:domain/cert_pem/cert_key/cert_path/key_path 只能通过证书上传接口(saveFrontCert)变更。
|
||||
const FRONT_CONFIG_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 FRONT_CONFIG_PUBLIC_FIELDS = Object.freeze([
|
||||
'domain',
|
||||
'title',
|
||||
'logo_url',
|
||||
'login_bg_url',
|
||||
'favicon_url',
|
||||
'theme',
|
||||
]);
|
||||
|
||||
// 公共按域名拉取接口缓存 TTL(秒)
|
||||
const FRONT_CONFIG_PUBLIC_CACHE_TTL_SECONDS = 600;
|
||||
// 未登记域名空缓存 TTL(秒):短缓存兜底防穿透,域名登记后由保存流程主动失效
|
||||
const FRONT_CONFIG_PUBLIC_MISS_CACHE_TTL_SECONDS = 60;
|
||||
|
||||
// 证书/私钥 PEM 文本最大长度(正常 RSA/ECC 证书远小于该值,防止异常大报文)
|
||||
const FRONT_CONFIG_PEM_MAX_LENGTH = 64 * 1024;
|
||||
|
||||
class SettingWarehouseService extends Service {
|
||||
/**
|
||||
* 读取默认快递与平台编码选项,查询失败时自动降级为空列表。
|
||||
@ -698,6 +727,658 @@ class SettingWarehouseService extends Service {
|
||||
cache_cleared_warehouse_id: cacheWarehouseId,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验并规范化仓库前端配置的字符串字段。
|
||||
*
|
||||
* @param {*} value 原始值。
|
||||
* @param {string} fieldName 字段名。
|
||||
* @param {number} maxLength 字段最大长度。
|
||||
* @return {string|null} 规范化后的字符串;空值返回 null(表示清空)。
|
||||
* @throws {Error} 超长时抛出,状态码 400。
|
||||
*/
|
||||
normalizeFrontConfigText(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。
|
||||
*/
|
||||
normalizeFrontConfigTheme(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 assertFrontConfigDomainUnique(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);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建仓库前端配置的输出对象(无记录时返回默认空配置)。
|
||||
*
|
||||
* 证书回显:输出证书原文(cert_pem)与私钥原文(key_pem,取自 cert_key 列),
|
||||
* 不再输出 cert_path/key_path 路径字段(保存时已置空,尚无真实路径)。
|
||||
* 安全说明:私钥原文回显仅限仓库主体登录后的 settings 页
|
||||
* (getFrontConfig/saveFrontConfig/saveFrontCert 三个需登录接口复用本输出);
|
||||
* 公共无鉴权接口 getFrontConfigByDomain 走 buildFrontConfigPublicOutput 白名单,
|
||||
* 不经过本方法,仍不暴露证书/私钥内容与同步状态等内部字段。
|
||||
*
|
||||
* @param {Object|null} record 配置记录实例(可为 null)。
|
||||
* @param {number} warehouseId 当前仓库 ID。
|
||||
* @return {Object} 规范化输出对象。
|
||||
*/
|
||||
buildFrontConfigOutput(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,
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询当前仓库的前端独立部署配置(settings 页回显)。
|
||||
*
|
||||
* 需登录(token 绑定仓库上下文,只能查到自己仓库的配置),
|
||||
* 响应含证书原文(cert_pem)与私钥原文(key_pem),供仓库主体 settings 页回显;
|
||||
* 公共无鉴权接口 getFrontConfigByDomain 仍只返回公开字段白名单。
|
||||
*
|
||||
* @return {Promise<Object>} 配置输出对象;无记录时返回默认空配置。
|
||||
* @throws {Error} 未识别到当前仓库时抛出,状态码 400。
|
||||
*/
|
||||
async getFrontConfig() {
|
||||
const warehouseId = this.getCurrentWarehouseId();
|
||||
|
||||
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.buildFrontConfigOutput(record, warehouseId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建前端配置公共拉取接口的缓存键(按域名)。
|
||||
*
|
||||
* @param {string} domain 域名(内部会 trim 规范化)。
|
||||
* @return {string} Redis 缓存键。
|
||||
*/
|
||||
getFrontConfigDomainCacheKey(domain) {
|
||||
return `front:config:domain:${String(domain || '').trim()}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建前端配置公共拉取接口的输出对象(仅公开字段白名单)。
|
||||
*
|
||||
* 安全红线:只输出 FRONT_CONFIG_PUBLIC_FIELDS 白名单字段,
|
||||
* 严禁输出 cert_pem/cert_key 证书与私钥内容,以及 cert_path、key_path、
|
||||
* sync_status、sync_attempts、last_sync_error 等内部字段。
|
||||
*
|
||||
* @param {Object} record 配置记录实例。
|
||||
* @return {Object} 仅含公开字段的输出对象。
|
||||
*/
|
||||
buildFrontConfigPublicOutput(record) {
|
||||
const hasRecord = !!(record && typeof record.get === 'function');
|
||||
const getValue = key => (hasRecord ? record.get(key) : null);
|
||||
|
||||
const output = {};
|
||||
for (const key of FRONT_CONFIG_PUBLIC_FIELDS) {
|
||||
const value = hasRecord ? getValue(key) : null;
|
||||
output[key] = key === 'theme' ? (value || null) : (value || '');
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理指定域名的前端配置公共拉取缓存(空域名跳过)。
|
||||
*
|
||||
* @param {string} domain 待清理的域名。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async clearFrontConfigDomainCache(domain) {
|
||||
const normalizedDomain = String(domain || '').trim();
|
||||
if (!normalizedDomain) {
|
||||
return;
|
||||
}
|
||||
|
||||
await this.deleteCacheByKey(this.getFrontConfigDomainCacheKey(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 getFrontConfigByDomain(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.getFrontConfigDomainCacheKey(normalizedDomain);
|
||||
|
||||
// 优先读缓存;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('[SettingWarehouseService.getFrontConfigByDomain] 读取缓存失败,降级查库: %s', error.message);
|
||||
}
|
||||
}
|
||||
|
||||
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: {
|
||||
domain: normalizedDomain,
|
||||
},
|
||||
});
|
||||
|
||||
if (!record) {
|
||||
// 缓存穿透兜底:未登记域名写短 TTL 空缓存,防止高频探测打穿数据库
|
||||
if (this.app && typeof this.app.setCacheAsync === 'function') {
|
||||
try {
|
||||
await this.app.setCacheAsync(cacheKey, { configured: false }, FRONT_CONFIG_PUBLIC_MISS_CACHE_TTL_SECONDS);
|
||||
} catch (error) {
|
||||
this.ctx.logger.warn('[SettingWarehouseService.getFrontConfigByDomain] 写入未命中空缓存失败: %s', error.message);
|
||||
}
|
||||
}
|
||||
throw this.createError('域名未配置', 404);
|
||||
}
|
||||
|
||||
const output = this.buildFrontConfigPublicOutput(record);
|
||||
|
||||
if (this.app && typeof this.app.setCacheAsync === 'function') {
|
||||
try {
|
||||
await this.app.setCacheAsync(cacheKey, output, FRONT_CONFIG_PUBLIC_CACHE_TTL_SECONDS);
|
||||
} catch (error) {
|
||||
this.ctx.logger.warn('[SettingWarehouseService.getFrontConfigByDomain] 写入缓存失败: %s', error.message);
|
||||
}
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化证书/私钥 PEM 文本:去首尾空白,空值返回 null(表示未提供)。
|
||||
*
|
||||
* @param {*} value 原始值(PEM 文本)。
|
||||
* @param {string} fieldName 字段名(用于错误提示)。
|
||||
* @return {string|null} 规范化后的 PEM 文本;空值返回 null。
|
||||
* @throws {Error} 内容超过长度上限时抛出,状态码 400。
|
||||
*/
|
||||
normalizeFrontConfigPem(value, fieldName) {
|
||||
if (value === undefined || value === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const normalized = String(value).trim();
|
||||
if (!normalized) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (normalized.length > FRONT_CONFIG_PEM_MAX_LENGTH) {
|
||||
throw this.createError(`${fieldName} 内容长度不能超过 ${FRONT_CONFIG_PEM_MAX_LENGTH} 字符`, 400);
|
||||
}
|
||||
|
||||
return normalized;
|
||||
}
|
||||
|
||||
/**
|
||||
* 用 Node 内置 crypto.X509Certificate 解析证书 PEM 文本。
|
||||
*
|
||||
* @param {string} certPem 证书 PEM 文本。
|
||||
* @return {Object} 解析成功后的 X509Certificate 实例。
|
||||
* @throws {Error} 证书无法解析时抛出,状态码 400,统一文案“证书不合法”。
|
||||
*/
|
||||
parseFrontConfigCertPem(certPem) {
|
||||
try {
|
||||
return new crypto.X509Certificate(certPem);
|
||||
} catch (error) {
|
||||
throw this.createError('证书不合法', 400);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验证书有效期:未生效或已过期的证书禁止提交。
|
||||
*
|
||||
* @param {Object} cert 已解析的 X509Certificate 实例。
|
||||
* @return {void} 无返回值。
|
||||
* @throws {Error} 证书未生效或已过期时抛出,状态码 400,统一文案“证书不合法”。
|
||||
*/
|
||||
assertFrontConfigCertValid(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[]} 小写域名列表。
|
||||
*/
|
||||
collectFrontConfigCertNames(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} 是否覆盖。
|
||||
*/
|
||||
frontConfigCertCoversDomain(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);
|
||||
return target.endsWith(suffix) && target.length > suffix.length;
|
||||
}
|
||||
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验私钥与证书是否成对:对比两者的 SPKI DER 公钥指纹。
|
||||
*
|
||||
* @param {string} keyPem 私钥 PEM 文本。
|
||||
* @param {Object} cert 已解析的 X509Certificate 实例。
|
||||
* @return {void} 无返回值。
|
||||
* @throws {Error} 私钥无法解析或与证书不匹配时抛出,状态码 400,统一文案“证书不合法”。
|
||||
*/
|
||||
validateFrontConfigKeyPem(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 assertFrontConfigWarehouseSubject() {
|
||||
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 变更必须走 saveFrontCert 重新校验证书;
|
||||
* 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>} 保存后的配置输出对象(同步状态已重置为待同步;证书回显口径与 getFrontConfig 一致)。
|
||||
* @throws {Error} 非仓库主体时抛出 403;参数非法时抛出 400。
|
||||
*/
|
||||
async saveFrontConfig(data = {}) {
|
||||
const warehouseId = this.getCurrentWarehouseId();
|
||||
|
||||
// 仅仓库主体管理员可配置前端独立部署(isWarehouse 判定)
|
||||
await this.assertFrontConfigWarehouseSubject();
|
||||
|
||||
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 FRONT_CONFIG_TEXT_FIELDS) {
|
||||
if (Object.prototype.hasOwnProperty.call(data, field.key)) {
|
||||
patch[field.key] = this.normalizeFrontConfigText(data[field.key], field.name, field.maxLength);
|
||||
}
|
||||
}
|
||||
|
||||
if (Object.prototype.hasOwnProperty.call(data, 'theme')) {
|
||||
patch.theme = this.normalizeFrontConfigTheme(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') {
|
||||
const conflictFields = error.fields || {};
|
||||
if (Object.prototype.hasOwnProperty.call(conflictFields, 'domain')) {
|
||||
throw this.createError(`域名 ${patch.domain || ''} 已被其他仓库使用`, 409);
|
||||
}
|
||||
throw this.createError('仓库前端配置保存冲突,请稍后重试', 409);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
// 回查一次再输出,避免实例上残留 CURRENT_TIMESTAMP 等字面量
|
||||
const savedRecord = await configModel.findByPk(record.id);
|
||||
|
||||
// 写库成功后清理公共拉取缓存(先写库后清缓存);清缓存失败仅记日志,不影响保存结果
|
||||
if (previousDomain) {
|
||||
await this.clearFrontConfigDomainCache(previousDomain)
|
||||
.catch(error => {
|
||||
this.ctx.logger.warn('[SettingWarehouseService.saveFrontConfig] 清理前端配置缓存失败: %s', error.message);
|
||||
});
|
||||
}
|
||||
|
||||
return this.buildFrontConfigOutput(savedRecord, warehouseId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传当前仓库前端独立部署证书(domain + 证书/私钥成对,upsert 该仓库行的证书与域名信息)。
|
||||
*
|
||||
* 校验链:证书可解析 → 未生效拒绝 → 已过期拒绝 → 私钥与证书成对 →
|
||||
* 证书 SAN/CN 覆盖 domain(支持 *.example.com 通配,不覆盖返回 400)→
|
||||
* domain 全局唯一(非空,409)。
|
||||
* 证书校验链任一失败均返回统一文案“证书不合法”(400),不返回细节。
|
||||
* 通过后自动写入 cert_expire_at(证书 validTo 权威值,不接受前端传值),
|
||||
* 证书/私钥 PEM 内容直接写入 cert_pem/cert_key 列(内容仅定时任务读取,
|
||||
* 不写暂存文件);cert_path/key_path 保存时置空,避免内容已换而路径陈旧,
|
||||
* 等待未来定时任务部署后回填真实路径;同时更新该仓库行的 domain/cert_expire_at
|
||||
* 并重置同步状态;写库成功后清理旧域名与新域名的公共拉取缓存(先写库后清缓存)。
|
||||
*
|
||||
* @param {Object} [data={}] 请求参数。
|
||||
* @param {string} data.domain 仓库自持域名(必填,非空,≤100 字符,全局唯一)。
|
||||
* @param {string} data.pem 证书 PEM 文本(必填)。
|
||||
* @param {string} data.key 私钥 PEM 文本(必填,与证书成对)。
|
||||
* @return {Promise<Object>} 保存后的完整配置输出对象(含证书/私钥原文回显,口径与 getFrontConfig 一致)。
|
||||
* @throws {Error} 非仓库主体时抛出 403;参数非法/证书不合法时抛出 400(证书校验失败统一文案“证书不合法”);域名重复时抛出 409。
|
||||
*/
|
||||
async saveFrontCert(data = {}) {
|
||||
const warehouseId = this.getCurrentWarehouseId();
|
||||
|
||||
// 仅仓库主体管理员可上传前端独立部署证书(isWarehouse 判定)
|
||||
await this.assertFrontConfigWarehouseSubject();
|
||||
|
||||
const configModel = this.ctx.model && this.ctx.model.WarehouseFrontConfig;
|
||||
if (!configModel || typeof configModel.findOne !== 'function') {
|
||||
throw this.createError('WarehouseFrontConfig model 不可用', 500);
|
||||
}
|
||||
|
||||
// 入参必填校验:domain 非空且 ≤100;pem/key 必填(nginx 起 HTTPS 需要成对)
|
||||
const domain = this.normalizeFrontConfigText(data.domain, 'domain', 100);
|
||||
if (!domain) {
|
||||
throw this.createError('domain 不能为空', 400);
|
||||
}
|
||||
|
||||
const certPem = this.normalizeFrontConfigPem(data.pem, 'pem');
|
||||
if (!certPem) {
|
||||
throw this.createError('pem 不能为空', 400);
|
||||
}
|
||||
|
||||
const keyPem = this.normalizeFrontConfigPem(data.key, 'key');
|
||||
if (!keyPem) {
|
||||
throw this.createError('key 不能为空', 400);
|
||||
}
|
||||
|
||||
// 校验链:证书可解析 → 未生效/已过期拒绝 → 私钥匹配 → SAN/CN 覆盖 domain → domain 全局唯一
|
||||
const cert = this.parseFrontConfigCertPem(certPem);
|
||||
this.assertFrontConfigCertValid(cert);
|
||||
this.validateFrontConfigKeyPem(keyPem, cert);
|
||||
|
||||
const certNames = this.collectFrontConfigCertNames(cert);
|
||||
if (!this.frontConfigCertCoversDomain(certNames, domain)) {
|
||||
throw this.createError('证书不合法', 400);
|
||||
}
|
||||
|
||||
await this.assertFrontConfigDomainUnique(domain, warehouseId);
|
||||
|
||||
// 证书/私钥内容直接入库(不再写暂存文件),有效期以证书 validTo 权威写入。
|
||||
// cert_path/key_path 保存时置空:内容已换而路径陈旧,避免 nginx 误读;
|
||||
// 等待未来定时任务(Egg schedule/外部 crontab)部署后回填真实路径。
|
||||
const patch = {
|
||||
domain,
|
||||
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,
|
||||
};
|
||||
|
||||
let record = await configModel.findOne({
|
||||
where: {
|
||||
store_id: warehouseId,
|
||||
},
|
||||
});
|
||||
|
||||
// 记录更新前的域名,写库成功后用于清理旧域名公共拉取缓存
|
||||
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') {
|
||||
const conflictFields = error.fields || {};
|
||||
if (Object.prototype.hasOwnProperty.call(conflictFields, 'domain')) {
|
||||
throw this.createError(`域名 ${domain} 已被其他仓库使用`, 409);
|
||||
}
|
||||
throw this.createError('仓库前端配置保存冲突,请稍后重试', 409);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
// 回查一次再输出,避免实例上残留 CURRENT_TIMESTAMP 等字面量
|
||||
const savedRecord = await configModel.findByPk(record.id);
|
||||
|
||||
// 写库成功后清理公共拉取缓存(先写库后清缓存:避免先清后写时并发读把旧值重新写回缓存)。
|
||||
// 需同时清理旧域名(更新前记录)与新域名(本次上传)两个 key;清缓存失败仅记日志,不影响保存结果。
|
||||
const affectedDomains = [ ...new Set([ previousDomain, domain ].filter(item => item)) ];
|
||||
await Promise.all(affectedDomains.map(affectedDomain => this.clearFrontConfigDomainCache(affectedDomain)
|
||||
.catch(error => {
|
||||
this.ctx.logger.warn('[SettingWarehouseService.saveFrontCert] 清理前端配置缓存失败: %s', error.message);
|
||||
})));
|
||||
|
||||
return this.buildFrontConfigOutput(savedRecord, warehouseId);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = SettingWarehouseService;
|
||||
|
||||
@ -0,0 +1,177 @@
|
||||
'use strict';
|
||||
|
||||
const FRONT_CONFIG_TABLE = 'wms_warehouse_front_config';
|
||||
|
||||
/**
|
||||
* Migration: 仓库伪独立部署专表(单表终版)。
|
||||
* - wms_warehouse_front_config:每仓库一行(一仓一域一证书),保存仓库前端
|
||||
* 个性化配置(Logo / 标题 / 登录页图 / 主题)、证书元信息(只存路径不存
|
||||
* 证书内容)与 nginx 同步状态机(pending → success/failed)。
|
||||
* - 证书启用/停用由整行删除或 sync_status 表达;证书到期由 cert_expire_at
|
||||
* 判断,不单独保留证书 status 列。
|
||||
* - domain 可空列唯一索引(uk_domain):MySQL 可空列唯一索引允许多个 NULL,
|
||||
* 非空值的唯一性需应用层校验(详见对应 Model 注释)。
|
||||
* - 演进说明:原双表方案(wms_warehouse_front_config + wms_warehouse_cert)
|
||||
* 已废弃;旧版迁移仅在开发库执行过且两表均为空,已 undo 后以本单表版本
|
||||
* 重跑。生产库从未执行过本迁移,一次发布窗口直接执行本文件即可。
|
||||
*
|
||||
* Idempotent: 表已存在时跳过创建。
|
||||
*/
|
||||
|
||||
/**
|
||||
* 判断表是否存在。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {string} tableName 表名。
|
||||
* @return {Promise<boolean>} 存在返回 true。
|
||||
*/
|
||||
async function tableExists(queryInterface, tableName) {
|
||||
const tables = await queryInterface.showAllTables();
|
||||
return tables.some(t => (typeof t === 'string' ? t : (t.tableName || t.name)) === tableName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步状态机字段(nginx 配置下发同步)。
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例。
|
||||
* @return {Object} 字段定义。
|
||||
*/
|
||||
function syncStateFields(Sequelize) {
|
||||
return {
|
||||
sync_status: {
|
||||
type: Sequelize.TINYINT,
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '同步状态:0-待同步,1-同步成功,2-同步失败',
|
||||
},
|
||||
sync_attempts: {
|
||||
type: Sequelize.INTEGER(11),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '同步尝试次数',
|
||||
},
|
||||
last_sync_error: {
|
||||
type: Sequelize.STRING(500),
|
||||
allowNull: true,
|
||||
comment: '最近一次同步失败原因',
|
||||
},
|
||||
last_synced_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: true,
|
||||
comment: '最近一次同步成功时间',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 时间戳字段(创建/更新时间),与项目既有建表迁移一致。
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例。
|
||||
* @return {Object} 字段定义。
|
||||
*/
|
||||
function timestampFields(Sequelize) {
|
||||
return {
|
||||
created_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
|
||||
comment: '更新时间',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* 执行正向迁移:创建仓库前端配置表(单表,含证书元信息)。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
up: async (queryInterface, Sequelize) => {
|
||||
if (await tableExists(queryInterface, FRONT_CONFIG_TABLE)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await queryInterface.createTable(FRONT_CONFIG_TABLE, {
|
||||
id: {
|
||||
type: Sequelize.BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键ID',
|
||||
},
|
||||
store_id: {
|
||||
type: Sequelize.BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '仓库ID,关联 wms_store.id(is_warehouse=1),每仓一行',
|
||||
},
|
||||
domain: {
|
||||
type: Sequelize.STRING(100),
|
||||
allowNull: true,
|
||||
comment: '仓库自持域名;可空列唯一索引允许多个 NULL,非空值唯一性需应用层校验',
|
||||
},
|
||||
title: {
|
||||
type: Sequelize.STRING(100),
|
||||
allowNull: true,
|
||||
comment: '站点标题',
|
||||
},
|
||||
logo_url: {
|
||||
type: Sequelize.STRING(255),
|
||||
allowNull: true,
|
||||
comment: 'Logo地址',
|
||||
},
|
||||
login_bg_url: {
|
||||
type: Sequelize.STRING(255),
|
||||
allowNull: true,
|
||||
comment: '登录页背景图地址',
|
||||
},
|
||||
theme: {
|
||||
type: Sequelize.JSON,
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '主题配置JSON(颜色/布局等)',
|
||||
},
|
||||
cert_path: {
|
||||
type: Sequelize.STRING(500),
|
||||
allowNull: true,
|
||||
comment: '证书文件路径(只存路径不存内容)',
|
||||
},
|
||||
key_path: {
|
||||
type: Sequelize.STRING(500),
|
||||
allowNull: true,
|
||||
comment: '私钥文件路径(只存路径不存内容)',
|
||||
},
|
||||
cert_expire_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: true,
|
||||
comment: '证书到期时间',
|
||||
},
|
||||
...syncStateFields(Sequelize),
|
||||
...timestampFields(Sequelize),
|
||||
});
|
||||
|
||||
await queryInterface.addIndex(FRONT_CONFIG_TABLE, [ 'store_id' ], {
|
||||
name: 'uk_store_id',
|
||||
unique: true,
|
||||
});
|
||||
await queryInterface.addIndex(FRONT_CONFIG_TABLE, [ 'domain' ], {
|
||||
name: 'uk_domain',
|
||||
unique: true,
|
||||
});
|
||||
await queryInterface.addIndex(FRONT_CONFIG_TABLE, [ 'sync_status' ], {
|
||||
name: 'idx_sync_status',
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* 回滚:删除仓库前端配置表。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
down: async queryInterface => {
|
||||
await queryInterface.dropTable(FRONT_CONFIG_TABLE);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,58 @@
|
||||
'use strict';
|
||||
|
||||
const TABLE_NAME = 'wms_warehouse_front_config';
|
||||
const COLUMN_NAME = 'favicon_url';
|
||||
|
||||
/**
|
||||
* 判断表是否存在。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {string} tableName 表名。
|
||||
* @return {Promise<boolean>} 存在返回 true。
|
||||
*/
|
||||
async function tableExists(queryInterface, tableName) {
|
||||
const tables = await queryInterface.showAllTables();
|
||||
return tables.some(t => (typeof t === 'string' ? t : (t.tableName || t.name)) === tableName);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* 执行正向迁移:为仓库前端配置表新增 favicon_url(站点 favicon 图标地址,幂等)。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async up(queryInterface, Sequelize) {
|
||||
if (!(await tableExists(queryInterface, TABLE_NAME))) {
|
||||
return;
|
||||
}
|
||||
|
||||
const columns = await queryInterface.describeTable(TABLE_NAME);
|
||||
if (columns[COLUMN_NAME]) {
|
||||
return;
|
||||
}
|
||||
|
||||
await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, {
|
||||
type: Sequelize.STRING(255),
|
||||
allowNull: true,
|
||||
comment: '站点 favicon 图标地址',
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* 回滚迁移:删除 favicon_url 字段(幂等)。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async down(queryInterface) {
|
||||
if (!(await tableExists(queryInterface, TABLE_NAME))) {
|
||||
return;
|
||||
}
|
||||
|
||||
const columns = await queryInterface.describeTable(TABLE_NAME);
|
||||
if (!columns[COLUMN_NAME]) {
|
||||
return;
|
||||
}
|
||||
|
||||
await queryInterface.removeColumn(TABLE_NAME, COLUMN_NAME);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,91 @@
|
||||
'use strict';
|
||||
|
||||
const TABLE_NAME = 'wms_warehouse_front_config';
|
||||
const CERT_PEM_COLUMN = 'cert_pem';
|
||||
const CERT_KEY_COLUMN = 'cert_key';
|
||||
|
||||
/**
|
||||
* Migration: 仓库前端配置表新增证书内容列(证书 PEM 文本直接入库)。
|
||||
*
|
||||
* 背景:
|
||||
* 原方案证书内容只存路径(cert_path/key_path),由保存接口写暂存文件后部署;
|
||||
* 现改为证书 PEM 文本直接入库,由定时任务拉取后写文件部署。
|
||||
* 证书链 fullchain PEM 一般 2~10KB,TEXT(上限 64KB)足够,且项目内长文本
|
||||
* 列惯例使用 TEXT(如 20260818190000 wms_order_items.ext_code 改 TEXT);
|
||||
* 不选 VARCHAR(16384):utf8mb4 下 16K 字符已触发 MySQL 5.7 行大小限制风险,
|
||||
* 且 PEM 长度无硬上限,TEXT 更稳。
|
||||
*
|
||||
* 列说明:
|
||||
* - cert_pem:证书 PEM 内容(私钥不在内);
|
||||
* - cert_key:私钥 PEM 内容;
|
||||
* - 均允许为 NULL(未上传证书时为空),无需索引;
|
||||
* - 敏感内容:仅由定时任务读取,禁止写入日志/接口响应。
|
||||
*
|
||||
* Idempotent: up 列已存在时跳过、down 列不存在时跳过。
|
||||
*/
|
||||
|
||||
/**
|
||||
* 判断表是否存在。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {string} tableName 表名。
|
||||
* @return {Promise<boolean>} 存在返回 true。
|
||||
*/
|
||||
async function tableExists(queryInterface, tableName) {
|
||||
const tables = await queryInterface.showAllTables();
|
||||
return tables.some(t => (typeof t === 'string' ? t : (t.tableName || t.name)) === tableName);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* 执行正向迁移:新增 cert_pem / cert_key 两列(幂等)。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async up(queryInterface, Sequelize) {
|
||||
if (!(await tableExists(queryInterface, TABLE_NAME))) {
|
||||
return;
|
||||
}
|
||||
|
||||
const columns = await queryInterface.describeTable(TABLE_NAME);
|
||||
|
||||
if (!columns[CERT_PEM_COLUMN]) {
|
||||
await queryInterface.addColumn(TABLE_NAME, CERT_PEM_COLUMN, {
|
||||
type: Sequelize.TEXT,
|
||||
allowNull: true,
|
||||
comment: '证书 PEM 内容(私钥不在内);内容仅由定时任务读取,禁止写入日志/接口响应',
|
||||
after: 'cert_path',
|
||||
});
|
||||
}
|
||||
|
||||
if (!columns[CERT_KEY_COLUMN]) {
|
||||
await queryInterface.addColumn(TABLE_NAME, CERT_KEY_COLUMN, {
|
||||
type: Sequelize.TEXT,
|
||||
allowNull: true,
|
||||
comment: '私钥 PEM 内容;内容仅由定时任务读取,禁止写入日志/接口响应',
|
||||
after: 'key_path',
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* 回滚迁移:删除 cert_pem / cert_key 两列(幂等)。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async down(queryInterface) {
|
||||
if (!(await tableExists(queryInterface, TABLE_NAME))) {
|
||||
return;
|
||||
}
|
||||
|
||||
const columns = await queryInterface.describeTable(TABLE_NAME);
|
||||
|
||||
if (columns[CERT_PEM_COLUMN]) {
|
||||
await queryInterface.removeColumn(TABLE_NAME, CERT_PEM_COLUMN);
|
||||
}
|
||||
|
||||
if (columns[CERT_KEY_COLUMN]) {
|
||||
await queryInterface.removeColumn(TABLE_NAME, CERT_KEY_COLUMN);
|
||||
}
|
||||
},
|
||||
};
|
||||
Loading…
x
Reference in New Issue
Block a user