import { Injectable, Logger } from '@nestjs/common'; import { InfisicalSDK } from '@infisical/sdk'; import { ConfigService } from '@nestjs/config'; type SecretMap = Record; @Injectable() export class SecretService { private logger = new Logger(SecretService.name); private secrets: SecretMap | null = null; // null = 아직 로드 전 private loading?: Promise; // 진행 중인 로드(중복 호출 방지) private infisicalClient: InfisicalSDK; private readonly siteUrl: string; private readonly clientSecret: string; private readonly clientId: string; private readonly projectId: string; private readonly PROCESS_ENVS = [ 'COSMOSDB_ENDPOINT', 'COSMOSDB_KEY', 'NATS_ENDPOINT', 'NATS_TOKEN', 'NATS_URL', 'DAKAO_INBOUND_SUBJECT', 'DAKAO_NATS_COMMAND_CHAT_SEND_MESSAGE_SUBJECT', 'DAKAO_REPLY_SUBJECT_PREFIX', 'DAKAO_COMMAND_SOURCE', 'DAKAO_BOT_USER_ID', 'DAKAO_INSTANCE_ID', 'JWT_CLAIM_AUDIENCE', 'MICROSOFT_ENTRAID_TENANT_ID', 'MICROSOFT_ENTRAID_ALLOWED_ALGS', 'AUTH_DEV_HEADER_ENABLED', // 필요시 추가 ] as const; constructor(private readonly config: ConfigService) { this.siteUrl = this.config.get('INFISICAL_SITE_URL') ?? 'https://secret-manager.dahyeon.us/'; this.clientSecret = this.config.get( 'INFISICAL_CLIENT_SECRET', ) as string; this.clientId = this.config.get('INFISICAL_CLIENT_ID') as string; this.projectId = this.config.get('INFISICAL_PROJECT_ID') as string; // console.log(this.siteUrl, this.clientSecret, this.clientId, this.projectId) const missing = [ !this.siteUrl && 'INFISICAL_SITE_URL', !this.clientId && 'INFISICAL_CLIENT_ID', !this.clientSecret && 'INFISICAL_CLIENT_SECRET', !this.projectId && 'INFISICAL_PROJECT_ID', ].filter(Boolean); if (missing.length > 0) { throw new Error( `Missing required Infisical configuration: ${missing.join(', ')}`, ); } this.infisicalClient = new InfisicalSDK({ siteUrl: this.siteUrl }); } /** 한 번만 로그인/페치. 동시에 여러 번 호출돼도 같은 Promise를 공유 */ private async fetchSecrets(): Promise { if (this.secrets) return; // 이미 로드됨 if (this.loading) return this.loading; // 로드 중이면 그거 기다리기 this.loading = (async () => { await this.infisicalClient.auth().universalAuth.login({ clientId: this.clientId, clientSecret: this.clientSecret, }); // console.log(this.infisicalClient) const res = await this.infisicalClient.secrets().listSecrets({ environment: process.env.NODE_ENV === 'prod' ? 'prod' : process.env.NODE_ENV === 'test' ? 'staging' : 'dev', projectId: this.projectId, }); // 임시 객체에 채운 뒤 한 번에 교체(일관성 보장) const map: SecretMap = {}; for (const s of res.secrets) { map[s.secretKey] = s.secretValue; } // 필요한 값은 process.env에 반영 for (const k of this.PROCESS_ENVS) { const v = map[k as string]; if (typeof v === 'string' && v.length > 0) { process.env[k as string] = v; } } this.secrets = map; this.logger.log( `Fetched ${Object.keys(map).length} secrets from Infisical`, ); })(); try { await this.loading; } finally { this.loading = undefined; // 실패/성공 모두 끝나면 해제(실패 시 재시도 가능) } } /** lazy get: 필요할 때 처음 한번만 로드 */ public async get(key: string, fallback?: T): Promise { if (!this.secrets) { await this.fetchSecrets(); } // console.log('Secrets loaded:', this.secrets); const val = this.secrets![key]; if (val === undefined) { const cfg = this.config.get(key); if (cfg !== undefined) return cfg; if (fallback !== undefined) return fallback; throw new Error(`Secret not found for key="${key}"`); } return val as T; } /** 필요 시: 동기 접근(초기화 안됐으면 에러). constructor 등에서 강제 사용 금지 */ public getSync(key: string, fallback?: T): T { if (!this.secrets) { const cfg = this.config.get(key); if (cfg !== undefined) return cfg; if (fallback !== undefined) return fallback; throw new Error(`SecretService not initialized yet (key="${key}")`); } const val = this.secrets[key]; if (val === undefined) { const cfg = this.config.get(key); if (cfg !== undefined) return cfg; if (fallback !== undefined) return fallback; throw new Error(`Secret not found for key="${key}"`); } return val as T; } /** 선택: 사전에 강제로 로드하고 싶을 때 호출 */ public async ready(): Promise { await this.fetchSecrets(); } }