feat: 完善安装部署与数字溯源码
This commit is contained in:
@@ -0,0 +1,211 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { createCipheriv, createHash, randomBytes } from 'crypto';
|
||||
import { existsSync, mkdirSync, readFileSync, 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 { 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));
|
||||
return {
|
||||
installed,
|
||||
configPath,
|
||||
traceCodeSalt: installed ? null : this.pendingTraceCodeSalt(),
|
||||
defaults: {
|
||||
mysqlHost: process.env.INSTALL_MYSQL_HOST || 'mysql',
|
||||
mysqlPort: Number(process.env.INSTALL_MYSQL_PORT || 3306),
|
||||
mysqlDatabase: process.env.MYSQL_DATABASE || 'artveris',
|
||||
mysqlUser: process.env.MYSQL_USER || 'artveris',
|
||||
redisHost: process.env.INSTALL_REDIS_HOST || 'redis',
|
||||
redisPort: Number(process.env.INSTALL_REDIS_PORT || 6379),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async install(dto: InstallRequestDto) {
|
||||
if (existsSync(runtimeConfigPath()) || (process.env.ARTVERIS_INSTALL_MODE !== '1' && process.env.DATABASE_URL)) {
|
||||
return { installed: true, restartRequired: false };
|
||||
}
|
||||
const traceCodeSalt = this.pendingTraceCodeSalt();
|
||||
const databaseUrl = this.buildMysqlUrl(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);
|
||||
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);
|
||||
const db = encodeURIComponent(dto.mysql.database);
|
||||
return `mysql://${user}:${password}@${dto.mysql.host}:${dto.mysql.port}/${db}`;
|
||||
}
|
||||
|
||||
private async assertMysql(databaseUrl: string): Promise<void> {
|
||||
const prisma = new PrismaClient({ datasources: { db: { url: databaseUrl } } });
|
||||
try {
|
||||
await prisma.$connect();
|
||||
await prisma.$queryRaw`SELECT 1`;
|
||||
} finally {
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
private async assertRedis(dto: InstallRequestDto): Promise<void> {
|
||||
const redis = new Redis({
|
||||
host: dto.redis.host,
|
||||
port: dto.redis.port,
|
||||
password: dto.redis.password || undefined,
|
||||
maxRetriesPerRequest: 1,
|
||||
lazyConnect: true,
|
||||
});
|
||||
try {
|
||||
await redis.connect();
|
||||
await redis.ping();
|
||||
} finally {
|
||||
redis.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
private buildRuntimeConfig(dto: InstallRequestDto, databaseUrl: string) {
|
||||
const localDir = dto.storage.localDir || resolve(process.cwd(), 'storage');
|
||||
return {
|
||||
appName: dto.appName,
|
||||
port: Number(process.env.API_PORT || 3000),
|
||||
baseUrl: dto.baseUrl.replace(/\/$/, ''),
|
||||
adminOrigin: `${dto.baseUrl.replace(/\/$/, '')}/admin`,
|
||||
clientOrigin: dto.clientBaseUrl.replace(/\/$/, ''),
|
||||
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 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, '/')}`,
|
||||
];
|
||||
writeFileSync(runtimeEnvPath(), `${envLines.join('\n')}\n`, 'utf8');
|
||||
}
|
||||
|
||||
private runPrismaMigrate(databaseUrl: string): void {
|
||||
const prismaBin = require.resolve('prisma/build/index.js');
|
||||
execFileSync(process.execPath, [prismaBin, 'migrate', 'deploy', '--schema', this.prismaSchemaPath()], {
|
||||
stdio: 'inherit',
|
||||
env: { ...process.env, DATABASE_URL: databaseUrl },
|
||||
});
|
||||
}
|
||||
|
||||
private prismaSchemaPath(): string {
|
||||
const candidates = [
|
||||
resolve(process.cwd(), 'prisma/schema.prisma'),
|
||||
resolve(process.cwd(), 'apps/api/prisma/schema.prisma'),
|
||||
resolve(__dirname, '../../prisma/schema.prisma'),
|
||||
];
|
||||
const found = candidates.find((path) => existsSync(path));
|
||||
if (!found) throw new Error(`Prisma schema not found: ${candidates.join(', ')}`);
|
||||
return found;
|
||||
}
|
||||
|
||||
private async seedInstallData(databaseUrl: string, dto: InstallRequestDto, traceCodeSalt: string, settingsEncryptionKey: string): Promise<void> {
|
||||
const prisma = new PrismaClient({ datasources: { db: { url: databaseUrl } } });
|
||||
try {
|
||||
await prisma.$connect();
|
||||
const passwordHash = await bcrypt.hash(dto.admin.password, 10);
|
||||
const realName = dto.admin.realName || dto.admin.username;
|
||||
await prisma.sysUser.upsert({
|
||||
where: { username: dto.admin.username },
|
||||
update: { passwordHash, realName, role: RoleType.SUPER_ADMIN, status: UserStatus.ACTIVE },
|
||||
create: { username: dto.admin.username, passwordHash, realName, role: RoleType.SUPER_ADMIN, status: UserStatus.ACTIVE },
|
||||
});
|
||||
const settings: Record<string, string> = {
|
||||
appName: dto.appName,
|
||||
clientBaseUrl: dto.clientBaseUrl.replace(/\/$/, ''),
|
||||
traceCodeSalt,
|
||||
settingsEncryptionKey,
|
||||
backupEnabled: String(Boolean(dto.backupEnabled)),
|
||||
storageDriver: dto.storage.driver,
|
||||
storageLocalDir: dto.storage.localDir || resolve(process.cwd(), 'storage'),
|
||||
storagePublicPrefix: '/uploads',
|
||||
cdnBaseUrl: dto.storage.cdnBaseUrl || '',
|
||||
ossEndpoint: dto.storage.ossEndpoint || '',
|
||||
ossRegion: dto.storage.ossRegion || '',
|
||||
ossBucket: dto.storage.ossBucket || '',
|
||||
ossAccessKeyId: dto.storage.ossAccessKeyId || '',
|
||||
ossAccessKeySecret: this.encryptSecret(dto.storage.ossAccessKeySecret || '', settingsEncryptionKey),
|
||||
};
|
||||
for (const [key, value] of Object.entries(settings)) {
|
||||
await prisma.systemSetting.upsert({ where: { key }, update: { value }, create: { key, value } });
|
||||
}
|
||||
} finally {
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
private encryptSecret(value: string, key: string): string {
|
||||
if (!value) return '';
|
||||
const iv = randomBytes(12);
|
||||
const cipher = createCipheriv('aes-256-gcm', createHash('sha256').update(key).digest(), 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')}`;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user