feat: P1 보안/성능 개선 및 마이그레이션 자동화

Security fixes:
- migrate.ts: SQL/Command Injection 방지 (spawnSync 사용)
- migrate.ts: Path Traversal 검증 추가
- api-tester.ts: API 키 마스킹 (4자만 노출)
- api-tester.ts: 최소 16자 키 길이 검증
- cache.ts: ReDoS 방지 (패턴 길이/와일드카드 제한)

Performance improvements:
- cache.ts: 순차 삭제 → 병렬 배치 처리 (50개씩)
- cache.ts: KV 등록 fire-and-forget (non-blocking)
- cache.ts: 메모리 제한 (5000키)
- cache.ts: 25초 실행 시간 가드
- cache.ts: 패턴 매칭 prefix 최적화

New features:
- 마이그레이션 자동화 시스템 (scripts/migrate.ts)
- KV 기반 캐시 인덱스 (invalidatePattern, clearAll)
- 글로벌 CacheService 싱글톤

Other:
- .env.example 추가, API 키 환경변수 처리
- CACHE_TTL.RECOMMENDATIONS (10분) 분리
- e2e-tester.ts JSON 파싱 에러 핸들링 개선

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
kappa
2026-01-26 00:23:13 +09:00
parent 3a8dd705e6
commit 5a9362bf43
13 changed files with 1320 additions and 76 deletions

View File

@@ -8,7 +8,7 @@
import type { Env, ScaleType } from '../types';
import { RecommendationService } from '../services/recommendation';
import { validateStack, STACK_REQUIREMENTS } from '../services/stackConfig';
import { CacheService } from '../services/cache';
import { getGlobalCacheService } from '../services/cache';
import { logger } from '../utils/logger';
import { HTTP_STATUS, CACHE_TTL, REQUEST_LIMITS } from '../constants';
import {
@@ -33,23 +33,6 @@ interface RecommendRequestBody {
*/
const SUPPORTED_SCALES: readonly ScaleType[] = ['small', 'medium', 'large'] as const;
/**
* Cached CacheService instance for singleton pattern
*/
let cachedCacheService: CacheService | null = null;
/**
* Get or create CacheService singleton
*
* @returns CacheService instance with INSTANCES TTL
*/
function getCacheService(): CacheService {
if (!cachedCacheService) {
cachedCacheService = new CacheService(CACHE_TTL.INSTANCES);
}
return cachedCacheService;
}
/**
* Handle POST /recommend endpoint
*
@@ -174,7 +157,7 @@ export async function handleRecommend(request: Request, env: Env): Promise<Respo
// 7. Initialize cache service and generate cache key
logger.info('[Recommend] Validation passed', { stack, scale, budgetMax });
const cacheService = getCacheService();
const cacheService = getGlobalCacheService(CACHE_TTL.RECOMMENDATIONS, env.RATE_LIMIT_KV);
// Generate cache key from sorted stack, scale, and budget
// Sort stack to ensure consistent cache keys regardless of order
@@ -224,7 +207,7 @@ export async function handleRecommend(request: Request, env: Env): Promise<Respo
{
status: HTTP_STATUS.OK,
headers: {
'Cache-Control': `public, max-age=${CACHE_TTL.INSTANCES}`,
'Cache-Control': `public, max-age=${CACHE_TTL.RECOMMENDATIONS}`,
},
}
);
@@ -258,7 +241,7 @@ export async function handleRecommend(request: Request, env: Env): Promise<Respo
// 10. Store result in cache
try {
await cacheService.set(cacheKey, responseData, CACHE_TTL.INSTANCES);
await cacheService.set(cacheKey, responseData, CACHE_TTL.RECOMMENDATIONS);
} catch (error) {
// Graceful degradation: log error but don't fail the request
logger.error('[Recommend] Cache write failed',
@@ -273,7 +256,7 @@ export async function handleRecommend(request: Request, env: Env): Promise<Respo
{
status: HTTP_STATUS.OK,
headers: {
'Cache-Control': `public, max-age=${CACHE_TTL.INSTANCES}`,
'Cache-Control': `public, max-age=${CACHE_TTL.RECOMMENDATIONS}`,
},
}
);