Files
Artveris/apps/api/src/settings/settings.service.ts
T

219 lines
9.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { BadRequestException, Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'crypto';
import { PrismaService } from '../prisma/prisma.service';
const EDITABLE_KEYS = [
'appName',
'appIconUrl',
'logRetentionDays',
'operationLogRetentionDays',
'watermarkText',
'filingInfo',
'carouselInterval',
'backupEnabled',
'backupSchedule',
'backupRetentionDays',
'backupRetentionCount',
'clientBaseUrl',
'storageDriver',
'storageLocalDir',
'storagePublicPrefix',
'cdnBaseUrl',
'ossEndpoint',
'ossRegion',
'ossBucket',
'ossAccessKeyId',
'ossAccessKeySecret',
'storageMigrationTarget',
'storageMigrationFingerprint',
'storageMigrationCopied',
'blockchainDriver',
'certificateEnabled',
'certificateDailyLimit',
'tianheEnv',
'tianheBaseUrl',
'tianheAppId',
'tianheAppKey',
'tianheUserId',
'tianheUserKey',
];
// 加密存储的密钥(enc:v1:)。注意:tianheUserKey 有意不加密——
// 它是全系统唯一无外部恢复途径的钱包密码,明文存库才能让备份跨重装恢复
// (加密依赖 .env 的 SETTING_ENCRYPTION_KEY,重装换密钥后密文将无法解密);
// 且单有 userKey 无 appKey(仍加密)无法操作钱包。
const SECRET_KEYS = new Set(['ossAccessKeySecret', 'tianheAppKey']);
// 展示层掩码的密钥(getAll 输出打码;明文经专用揭示接口获取)
const MASKED_KEYS = new Set(['ossAccessKeySecret', 'tianheAppKey', 'tianheUserKey']);
const ENCRYPTED_PREFIX = 'enc:v1:';
@Injectable()
export class SettingsService {
private readonly logger = new Logger(SettingsService.name);
constructor(
private readonly prisma: PrismaService,
private readonly config: ConfigService,
) {}
async getAll(): Promise<Record<string, string>> {
return this.getAllInternal(true);
}
async getAllRaw(): Promise<Record<string, string>> {
return this.getAllInternal(false);
}
private async getAllInternal(maskSecrets: boolean): Promise<Record<string, string>> {
const rows = await this.prisma.systemSetting.findMany();
const map: Record<string, string> = {
appName: this.config.get<string>('appName') || '',
appIconUrl: '',
logRetentionDays: String(this.config.get<number>('logRetentionDays') || 365),
operationLogRetentionDays: '365',
watermarkText: this.config.get<string>('watermarkText') || '仅供溯源核验使用',
filingInfo: '备案信息待补充',
carouselInterval: '3',
backupEnabled: 'false',
backupSchedule: 'daily',
backupRetentionDays: '30',
backupRetentionCount: '10',
clientBaseUrl: this.config.get<string>('clientOrigin') || 'http://localhost:5174',
storageDriver: this.config.get<string>('storage.driver') || 'local',
storageLocalDir: this.config.get<string>('storage.localDir') || './storage',
storagePublicPrefix: this.config.get<string>('storage.publicPrefix') || '/uploads',
cdnBaseUrl: this.config.get<string>('storage.cdnBaseUrl') || '',
ossEndpoint: this.config.get<string>('storage.oss.endpoint') || '',
ossRegion: this.config.get<string>('storage.oss.region') || '',
ossBucket: this.config.get<string>('storage.oss.bucket') || '',
ossAccessKeyId: this.config.get<string>('storage.oss.accessKeyId') || '',
ossAccessKeySecret: this.config.get<string>('storage.oss.accessKeySecret') || '',
settingsEncryptionKey: this.config.get<string>('settingsEncryptionKey') || '',
blockchainDriver: this.config.get<string>('blockchain.driver') || 'mock',
certificateEnabled: 'true',
certificateDailyLimit: '100',
tianheEnv: 'test',
tianheBaseUrl: this.config.get<string>('blockchain.tianhe.baseUrl') || 'https://test.api.tichain.tianhecloud.com',
tianheAppId: this.config.get<string>('blockchain.tianhe.appId') || '',
tianheAppKey: this.config.get<string>('blockchain.tianhe.appKey') || '',
tianheUserId: this.config.get<string>('blockchain.tianhe.userId') || '',
tianheUserKey: this.config.get<string>('blockchain.tianhe.userKey') || '',
};
for (const r of rows) {
// 带 enc:v1: 前缀的值统一解密(兼容历史上曾加密存储、现已改为明文的键,如 tianheUserKey)
const value = await this.decryptSecret(r.value);
map[r.key] = r.key === 'appName' && value === '艺术品可信溯源与认证平台' ? '艺术品溯源平台' : value;
}
if (map.appIconUrl === '/app-icon.svg') map.appIconUrl = '';
if (maskSecrets) {
for (const key of MASKED_KEYS) {
if (map[key]) map[key] = this.maskSecret(map[key]);
}
delete map.settingsEncryptionKey;
}
return map;
}
async get(key: string): Promise<string | null> {
const row = await this.prisma.systemSetting.findUnique({ where: { key } });
if (!row) return null;
return this.decryptSecret(row.value);
}
async getClientBaseUrl(): Promise<string> {
const fromDb = await this.get('clientBaseUrl');
return (fromDb || this.config.get<string>('clientOrigin') || 'http://localhost:5174').replace(/\/$/, '');
}
private maskSecret(value: string): string {
if (!value || value.length <= 8) return value ? '******' : '';
return `${value.slice(0, 3)}******${value.slice(-3)}`;
}
// 对外暴露的掩码工具(供控制器展示 userKey 掩码,不返回明文)
maskSecretPublic(value: string): string {
return this.maskSecret(value);
}
isMaskedSecret(value?: string | null): boolean {
return typeof value === 'string' && /^\*+$|^.{1,8}\*{3,}.{1,8}$/.test(value);
}
async update(values: Record<string, string>): Promise<Record<string, string>> {
await this.updateAtomic(values);
return this.getAll();
}
async updateAtomic(values: Record<string, string>): Promise<void> {
if (values.certificateEnabled !== undefined && !['true', 'false'].includes(String(values.certificateEnabled))) {
throw new BadRequestException('Invalid certificate switch');
}
if (values.certificateDailyLimit !== undefined &&
(!/^\d+$/.test(String(values.certificateDailyLimit)) || Number(values.certificateDailyLimit) > 10000)) {
throw new BadRequestException('Certificate daily limit must be between 0 and 10000');
}
const updates: Array<{ key: string; value: string }> = [];
for (const [key, value] of Object.entries(values)) {
if (!EDITABLE_KEYS.includes(key)) continue;
if (MASKED_KEYS.has(key) && this.isMaskedSecret(value)) continue;
const nextValue = SECRET_KEYS.has(key) ? await this.encryptSecret(String(value)) : String(value);
updates.push({ key, value: nextValue });
}
if (updates.length) {
await this.prisma.$transaction(async (tx) => {
for (const { key, value } of updates) {
await tx.systemSetting.upsert({
where: { key },
update: { value },
create: { key, value },
});
}
});
}
}
// 服务内部直写(不做白名单/加密处理),用于系统自身生成的运行时值(如天河链钱包身份)
async setRaw(key: string, value: string): Promise<void> {
await this.prisma.systemSetting.upsert({ where: { key }, update: { value }, create: { key, value } });
}
private async encryptionKey(): Promise<Buffer> {
const row = await this.prisma.systemSetting.findUnique({ where: { key: 'settingsEncryptionKey' } }).catch(() => null);
const secret =
row?.value ||
this.config.get<string>('settingsEncryptionKey') ||
process.env.SETTING_ENCRYPTION_KEY ||
this.config.get<string>('jwt.secret') ||
'artveris_dev_secret';
return createHash('sha256').update(secret).digest();
}
private async encryptSecret(value: string): Promise<string> {
if (!value || value.startsWith(ENCRYPTED_PREFIX)) return value;
const iv = randomBytes(12);
const cipher = createCipheriv('aes-256-gcm', await this.encryptionKey(), iv);
const encrypted = Buffer.concat([cipher.update(value, 'utf8'), cipher.final()]);
const tag = cipher.getAuthTag();
return `${ENCRYPTED_PREFIX}${Buffer.concat([iv, tag, encrypted]).toString('base64url')}`;
}
private async decryptSecret(value: string): Promise<string> {
if (!value?.startsWith(ENCRYPTED_PREFIX)) return value;
try {
const raw = Buffer.from(value.slice(ENCRYPTED_PREFIX.length), 'base64url');
const iv = raw.subarray(0, 12);
const tag = raw.subarray(12, 28);
const encrypted = raw.subarray(28);
const decipher = createDecipheriv('aes-256-gcm', await this.encryptionKey(), iv);
decipher.setAuthTag(tag);
return Buffer.concat([decipher.update(encrypted), decipher.final()]).toString('utf8');
} catch (e) {
// 解密失败通常意味着 SETTING_ENCRYPTION_KEY 与加密时不一致(配置损坏),
// 显式告警而非静默返回空串,避免把「配置损坏」误当成「未配置」
this.logger.warn(`密钥解密失败,可能是 SETTING_ENCRYPTION_KEY 已变更:${(e as Error).message}`);
return '';
}
}
}