refactor: 配置收敛为运行目录单一带注释 .env,移除 config 目录与 JSON 运行时配置
This commit is contained in:
@@ -1,27 +1,22 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { createCipheriv, createHash, randomBytes } from 'crypto';
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
|
||||
import { existsSync, mkdirSync, writeFileSync } from 'fs';
|
||||
import { dirname, resolve } from 'path';
|
||||
import { execFileSync } from 'child_process';
|
||||
import * as bcrypt from 'bcryptjs';
|
||||
import { PrismaClient, RoleType, UserStatus } from '@prisma/client';
|
||||
import Redis from 'ioredis';
|
||||
import { runtimeConfigPath, runtimeEnvPath, runtimeRoot } from '../config/runtime-config';
|
||||
import { envFilePath, isInstallMode } from '../config/runtime-config';
|
||||
import { InstallRequestDto } from './dto/install.dto';
|
||||
|
||||
const INSTALL_STATE_FILE = 'install-state.json';
|
||||
const ENCRYPTED_PREFIX = 'enc:v1:';
|
||||
|
||||
@Injectable()
|
||||
export class InstallService {
|
||||
status() {
|
||||
const configPath = runtimeConfigPath();
|
||||
const installed = existsSync(configPath) || (process.env.ARTVERIS_INSTALL_MODE !== '1' && Boolean(process.env.DATABASE_URL));
|
||||
const prefillSecrets = process.env.INSTALL_PREFILL_SECRETS === '1';
|
||||
return {
|
||||
installed,
|
||||
configPath,
|
||||
traceCodeSalt: installed ? null : this.pendingTraceCodeSalt(),
|
||||
installed: !isInstallMode(),
|
||||
defaults: {
|
||||
mysqlHost: process.env.INSTALL_MYSQL_HOST || '127.0.0.1',
|
||||
mysqlPort: Number(process.env.INSTALL_MYSQL_PORT || 3306),
|
||||
@@ -37,38 +32,22 @@ export class InstallService {
|
||||
}
|
||||
|
||||
async install(dto: InstallRequestDto) {
|
||||
if (existsSync(runtimeConfigPath()) || (process.env.ARTVERIS_INSTALL_MODE !== '1' && process.env.DATABASE_URL)) {
|
||||
if (!isInstallMode()) {
|
||||
return { installed: true, restartRequired: false };
|
||||
}
|
||||
const traceCodeSalt = this.pendingTraceCodeSalt();
|
||||
const traceCodeSalt = randomBytes(32).toString('hex');
|
||||
const settingsEncryptionKey = randomBytes(32).toString('hex');
|
||||
const databaseUrl = this.buildMysqlUrl(dto);
|
||||
await this.ensureDatabase(dto);
|
||||
await this.assertMysql(databaseUrl);
|
||||
await this.assertRedis(dto);
|
||||
const config = this.buildRuntimeConfig(dto, databaseUrl);
|
||||
this.runPrismaMigrate(databaseUrl);
|
||||
await this.seedInstallData(databaseUrl, dto, traceCodeSalt, String(config.settingsEncryptionKey || ''));
|
||||
this.writeRuntimeConfig(config, traceCodeSalt);
|
||||
await this.seedInstallData(databaseUrl, dto, traceCodeSalt, settingsEncryptionKey);
|
||||
this.writeEnvFile(dto, databaseUrl, traceCodeSalt, settingsEncryptionKey);
|
||||
setTimeout(() => process.exit(0), 600);
|
||||
return { installed: true, restartRequired: true };
|
||||
}
|
||||
|
||||
private pendingTraceCodeSalt(): string {
|
||||
const path = resolve(runtimeRoot(), INSTALL_STATE_FILE);
|
||||
try {
|
||||
if (existsSync(path)) {
|
||||
const state = JSON.parse(readFileSync(path, 'utf8')) as { traceCodeSalt?: string };
|
||||
if (state.traceCodeSalt) return state.traceCodeSalt;
|
||||
}
|
||||
} catch {
|
||||
// Regenerate below when the pending state file is malformed.
|
||||
}
|
||||
const traceCodeSalt = randomBytes(32).toString('hex');
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
writeFileSync(path, JSON.stringify({ traceCodeSalt }, null, 2), 'utf8');
|
||||
return traceCodeSalt;
|
||||
}
|
||||
|
||||
private buildMysqlUrl(dto: InstallRequestDto): string {
|
||||
const user = encodeURIComponent(dto.mysql.username);
|
||||
const password = encodeURIComponent(dto.mysql.password);
|
||||
@@ -137,54 +116,79 @@ export class InstallService {
|
||||
}
|
||||
}
|
||||
|
||||
private buildRuntimeConfig(dto: InstallRequestDto, databaseUrl: string) {
|
||||
const localDir = dto.storage.localDir || resolve(process.cwd(), 'storage');
|
||||
const baseUrl = dto.baseUrl.replace(/\/$/, '');
|
||||
return {
|
||||
appName: dto.appName,
|
||||
port: Number(dto.port || process.env.API_PORT || 3000),
|
||||
baseUrl,
|
||||
adminOrigin: `${baseUrl}/admin`,
|
||||
clientOrigin: `${baseUrl}/trace`,
|
||||
databaseUrl,
|
||||
redis: {
|
||||
host: dto.redis.host,
|
||||
port: dto.redis.port,
|
||||
password: dto.redis.password || '',
|
||||
},
|
||||
jwt: {
|
||||
secret: dto.jwtSecret || randomBytes(32).toString('hex'),
|
||||
expiresIn: dto.jwtExpiresIn || '7d',
|
||||
},
|
||||
settingsEncryptionKey: randomBytes(32).toString('hex'),
|
||||
storage: {
|
||||
driver: dto.storage.driver,
|
||||
localDir,
|
||||
publicPrefix: '/uploads',
|
||||
cdnBaseUrl: dto.storage.cdnBaseUrl || '',
|
||||
oss: {
|
||||
endpoint: dto.storage.ossEndpoint || '',
|
||||
region: dto.storage.ossRegion || '',
|
||||
bucket: dto.storage.ossBucket || '',
|
||||
accessKeyId: dto.storage.ossAccessKeyId || '',
|
||||
accessKeySecret: '',
|
||||
},
|
||||
},
|
||||
backupDir: resolve(process.cwd(), 'backups'),
|
||||
blockchain: { driver: 'mock', tianhe: {} },
|
||||
};
|
||||
private envValue(value: string): string {
|
||||
// 统一用双引号包裹(安装输入不含双引号;DATABASE_URL 中的凭据已 URL 编码)
|
||||
return `"${String(value ?? '')}"`;
|
||||
}
|
||||
|
||||
private writeRuntimeConfig(config: Record<string, unknown>, traceCodeSalt: string): void {
|
||||
const path = runtimeConfigPath();
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
writeFileSync(path, JSON.stringify(config, null, 2), 'utf8');
|
||||
const envLines = [
|
||||
`DATABASE_URL="${config.databaseUrl}"`,
|
||||
`TRACE_CODE_SALT=${traceCodeSalt}`,
|
||||
`ARTVERIS_CONFIG_PATH=${path.replace(/\\/g, '/')}`,
|
||||
// 安装向导把配置落盘为运行目录下的单一 .env(带注释)。升级不会覆盖本文件。
|
||||
private writeEnvFile(
|
||||
dto: InstallRequestDto,
|
||||
databaseUrl: string,
|
||||
traceCodeSalt: string,
|
||||
settingsEncryptionKey: string,
|
||||
): void {
|
||||
const baseUrl = dto.baseUrl.replace(/\/$/, '');
|
||||
const clientOrigin = `${baseUrl}/trace`;
|
||||
const localDir = dto.storage.localDir || resolve(process.cwd(), 'storage');
|
||||
const jwtSecret = dto.jwtSecret || randomBytes(32).toString('hex');
|
||||
const q = (v: string) => this.envValue(v);
|
||||
const lines = [
|
||||
'# Artveris 运行配置(安装向导生成)。升级不会覆盖本文件。',
|
||||
'# 改配置:可直接编辑本文件后重启服务;平台名/存储/区块链等也可在后台「系统设置」在线修改。',
|
||||
'',
|
||||
'# ===== 应用 =====',
|
||||
`APP_NAME=${q(dto.appName)}`,
|
||||
'NODE_ENV=production',
|
||||
'# 服务监听端口(由前置 Nginx/宝塔反代指向此端口)',
|
||||
`API_PORT=${q(String(dto.port || 3000))}`,
|
||||
'# 对外访问地址:三端共用,客户端在 /trace、后台 /admin、接口 /api、短链 /t',
|
||||
`BASE_URL=${q(baseUrl)}`,
|
||||
'PUBLIC_TRACE_PATH=/t',
|
||||
`ADMIN_ORIGIN=${q(baseUrl)}`,
|
||||
`CLIENT_ORIGIN=${q(clientOrigin)}`,
|
||||
`TRACE_URL_TEMPLATE=${q(`${clientOrigin}/#/trace/{code}`)}`,
|
||||
'',
|
||||
'# ===== 数据库(Prisma 直接读取 DATABASE_URL)=====',
|
||||
`DATABASE_URL=${q(databaseUrl)}`,
|
||||
'',
|
||||
'# ===== Redis =====',
|
||||
`REDIS_HOST=${q(dto.redis.host)}`,
|
||||
`REDIS_PORT=${q(String(dto.redis.port))}`,
|
||||
`REDIS_PASSWORD=${q(dto.redis.password || '')}`,
|
||||
'',
|
||||
'# ===== 安全密钥(务必保密,勿随意更改)=====',
|
||||
'# 登录令牌密钥;更改会使已签发登录失效',
|
||||
`JWT_SECRET=${q(jwtSecret)}`,
|
||||
`JWT_EXPIRES_IN=${q(dto.jwtExpiresIn || '7d')}`,
|
||||
'# 设置项加密密钥(加密 OSS/天河链等密钥);更改会导致已加密数据无法解密',
|
||||
`SETTING_ENCRYPTION_KEY=${q(settingsEncryptionKey)}`,
|
||||
'# 溯源码盐(决定 12 位码生成),勿更改',
|
||||
`TRACE_CODE_SALT=${q(traceCodeSalt)}`,
|
||||
'',
|
||||
'# ===== 文件存储:local | oss =====',
|
||||
`STORAGE_DRIVER=${q(dto.storage.driver)}`,
|
||||
`STORAGE_LOCAL_DIR=${q(localDir)}`,
|
||||
'STORAGE_PUBLIC_PREFIX=/uploads',
|
||||
`CDN_BASE_URL=${q(dto.storage.cdnBaseUrl || '')}`,
|
||||
`OSS_ENDPOINT=${q(dto.storage.ossEndpoint || '')}`,
|
||||
`OSS_REGION=${q(dto.storage.ossRegion || '')}`,
|
||||
`OSS_BUCKET=${q(dto.storage.ossBucket || '')}`,
|
||||
`OSS_ACCESS_KEY_ID=${q(dto.storage.ossAccessKeyId || '')}`,
|
||||
'# OSS 密钥的加密副本存于数据库;此处留空,需要时在后台系统设置维护',
|
||||
'OSS_ACCESS_KEY_SECRET=',
|
||||
'',
|
||||
'# ===== 区块链存证(默认 mock,可后台切天河链)=====',
|
||||
'BLOCKCHAIN_DRIVER=mock',
|
||||
'',
|
||||
'# ===== 其它 =====',
|
||||
`BACKUP_DIR=${q(resolve(process.cwd(), 'backups'))}`,
|
||||
'LOG_RETENTION_DAYS=365',
|
||||
'',
|
||||
];
|
||||
writeFileSync(runtimeEnvPath(), `${envLines.join('\n')}\n`, 'utf8');
|
||||
const path = envFilePath();
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
writeFileSync(path, `${lines.join('\n')}\n`, 'utf8');
|
||||
}
|
||||
|
||||
private runPrismaMigrate(databaseUrl: string): void {
|
||||
|
||||
Reference in New Issue
Block a user