34 Commits

Author SHA1 Message Date
kaffa
7e793d6211 Add Gitea Actions CI workflow 2026-02-03 11:39:10 +09:00
kaffa
18e740873e Add MIT LICENSE 2026-02-03 11:20:21 +09:00
kappa
6385b5cab6 feat: add server lifecycle management and D1 logging
- Add start/stop/reboot endpoints for server power management
- Add D1-based logging system (logs table + db-logger utility)
- Add idempotency_key validation for order deduplication
- Extend VPS provider interface with lifecycle methods

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-30 08:27:34 +09:00
kappa
f62712af37 docs: update CLAUDE.md with security hardening and admin SSH key
- Add middleware directory to architecture diagram
- Document Admin SSH Key for server recovery
- Update Security Features section (origin validation, timeouts, etc.)
- Add TIMEOUTS and TECH_CATEGORY_WEIGHTS to config section
- Update secrets list with SSH key variables
- Add latest changes section for security hardening

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-29 11:39:26 +09:00
kappa
5319bf3e4c refactor: comprehensive code review fixes and security hardening
Security:
- Add CSP headers for HTML reports (style-src 'unsafe-inline')
- Restrict origin validation to specific .kappa-d8e.workers.dev domain
- Add base64 size limit (100KB) for report data parameter
- Implement rejection sampling for unbiased password generation
- Add SQL LIKE pattern escaping for tech specs query
- Add security warning for plaintext password storage (TODO: encrypt)

Performance:
- Add Telegram API timeout (10s) with AbortController
- Fix rate limiter sorting by resetTime for proper cleanup
- Use centralized TIMEOUTS config for VPS provider APIs

Features:
- Add admin SSH key support for server recovery access
  - ADMIN_SSH_PUBLIC_KEY for Linode (public key string)
  - ADMIN_SSH_KEY_ID_VULTR for Vultr (pre-registered key ID)
- Add origin validation middleware
- Add idempotency key migration

Code Quality:
- Return 404 status when no servers found
- Consolidate error logging to single JSON.stringify call
- Import TECH_CATEGORY_WEIGHTS from config.ts
- Add escapeLikePattern utility function

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-29 11:36:08 +09:00
kappa
d41f1ee841 fix: pass API URL params to ProvisioningService in all handlers
- Add env.LINODE_API_URL and env.VULTR_API_URL to all ProvisioningService
  constructor calls in provision.ts
- Fixes delete and other operations using wrong API endpoint (defaulting
  to api.linode.com instead of configured emulator URL)
- Affected handlers: handleGetOrders, handleGetOrder, handleDeleteOrder,
  handleGetBalance, handleGetOsImages

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-28 11:38:54 +09:00
kappa
f7aa571ae3 fix: correct provider lookup in deleteServer
Bug: deleteServer was using pricing.provider_name (always "Anvil")
instead of pricing.source_provider (linode/vultr).

Changes:
- provisioning-service.ts: Use source_provider for provider lookup
- provision.ts: Add user validation and better error handling

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-28 11:25:08 +09:00
kappa
1c65c02045 feat: add GET /api/provision/images endpoint
- Add handleGetOsImages handler in provision.ts
- Add getOsImages method in ProvisioningService
- Add route in index.ts
- Returns key, name, family, is_default for each OS image

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-28 10:35:16 +09:00
kappa
3c420d2841 feat: manage OS images in database instead of hardcoded values
- Add os_images table with linode_image_id and vultr_os_id columns
- Support Ubuntu (24.04, 22.04), Debian (11-13), AlmaLinux (8-9),
  Rocky Linux (8-9), and Fedora 42
- AlmaLinux and Rocky Linux added as CentOS migration alternatives
- Default OS changed from ubuntu_22_04 to ubuntu_24_04
- Fix Vultr OS IDs (1743=22.04, 2284=24.04)
- Remove hardcoded OS validation, validate against DB
- Return available OS list in error message for invalid image

Migration: migrations/003_os_images.sql

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-28 10:31:14 +09:00
kappa
7d9edc14a3 feat: add configurable VPS provider API URLs for emulator testing
- Add LINODE_API_URL and VULTR_API_URL environment variables
- Update LinodeProvider and VultrProvider to accept optional baseUrl
- Update ProvisioningService to pass API URLs to providers
- Add source_provider and source_region_code to PricingWithProvider type
- Use source_provider (linode/vultr) instead of provider_name (Anvil)
- Improve error handling for non-JSON responses in LinodeProvider

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-28 10:21:27 +09:00
kappa
006b938ad2 feat: add source_provider mapping for actual VPS provisioning
- Update PricingWithProvider type with source_provider and source_region_code
- Update getPricingWithProvider query to JOIN instance_types for actual plan_id
- Use source_provider (linode/vultr) instead of provider_name (Anvil)
- Use source_region_code for actual provider region (ap-northeast, nrt, icn)

Mapping: anvil_regions.source_provider + anvil_pricing.source_instance_id
         → instance_types.instance_id (actual Linode/Vultr plan)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-28 00:47:03 +09:00
kappa
91a6e227ed docs: add provisioning API documentation to CLAUDE.md
- Add provisioning service files to Architecture section
- Document telegram-conversations DB tables (users, user_deposits, server_orders)
- Add Server Provisioning API section with endpoints and security features
- Update Bindings with USER_DB and PROVISION_QUEUE
- Add provisioning API test examples
- Include schema-provisioning.sql for reference

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-27 17:22:36 +09:00
kappa
9b51b8d427 feat: add Queue-based async server provisioning
- Add Cloudflare Queue for async server provisioning workflow
- Implement VPS provider abstraction (Linode, Vultr)
- Add provisioning API endpoints with API key authentication
- Fix race condition in balance deduction (atomic query)
- Remove root_password from Queue for security (fetch from DB)
- Add IP assignment wait logic after server creation
- Add rollback/refund on all failure cases

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-27 17:19:19 +09:00
kappa
8c543eeaa5 feat: improve recommendation diversity and KRW rounding
- Add spec diversity: recommend Budget/Balanced/Premium tiers instead of same spec
- Add bandwidth-based filtering: prioritize servers with adequate transfer allowance
- Fix KRW rounding: server price 500원, TB cost 500원, GB cost 1원
- Add bandwidth warning to infrastructure_tips when traffic exceeds 2x included

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-27 14:44:34 +09:00
kappa
23abd0e64e feat: add CDN cache hit rate for accurate bandwidth cost estimation
- Add cdn_enabled and cdn_cache_hit_rate API parameters
- Use case별 기본 캐시 히트율 자동 적용 (video: 92%, blog: 90%, etc.)
- 원본 서버 트래픽(origin_monthly_tb)과 절감 비용(cdn_savings_cost) 계산
- 응답에 CDN breakdown 필드 추가 (bandwidth_estimate, bandwidth_info)
- 캐시 키에 CDN 옵션 포함하여 정확한 캐시 분리
- 4개 CDN 관련 테스트 추가 (총 59 tests)
- CLAUDE.md 문서 업데이트

Cost impact example (10K video streaming):
- Without CDN: $18,370 → With CDN 92%: $1,464 (92% savings)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-26 11:34:53 +09:00
kappa
ba939ceff3 docs: update CLAUDE.md with new architecture and security features
- Add test commands (npm test, npm run test:watch)
- Update architecture diagram with new directory structure
- Document security features (XSS prevention, cache validation, type safety)
- Add AI Fallback System section
- Document Major Architecture Refactoring in Recent Changes

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-26 03:30:31 +09:00
kappa
4b00c73d96 refactor: major architecture improvements and security hardening
## Security Fixes
- Fix XSS vulnerability in report.ts with escapeHtml()
- Add cache data integrity validation
- Add region_preference input validation (max 10 items, 50 chars each)
- Replace `any` types with `unknown` + type guards

## Architecture Refactoring
- Split utils.ts (801 lines) into 6 modules: http, validation, bandwidth, cache, ai, exchange-rate
- Extract AI logic to src/services/ai-service.ts (recommend.ts 49% reduction)
- Add Repository pattern: src/repositories/AnvilServerRepository.ts
- Reduce code duplication in DB queries

## New Features
- AI fallback: rule-based recommendations when OpenAI unavailable
- Vitest testing: 55 tests (utils.test.ts, bandwidth.test.ts)
- Duplicate server prevention in AI recommendations

## Files Added
- src/utils/{index,http,validation,bandwidth,cache,ai,exchange-rate}.ts
- src/services/ai-service.ts
- src/repositories/AnvilServerRepository.ts
- src/__tests__/{utils,bandwidth}.test.ts
- vitest.config.ts

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-26 03:29:12 +09:00
kappa
411cde4801 feat: add region diversity, HTML report, and transfer pricing
Region Diversity:
- No region specified → same spec from 3 different regions
- Cache key now includes region_preference
- Fixed server_id to use ap.id (pricing) instead of ai.id (instance)

HTML Report:
- New /api/recommend/report endpoint for printable reports
- Supports multi-language (en, ko, ja, zh)
- Displays bandwidth_info with proper KRW formatting

Transfer Pricing:
- bandwidth_info includes overage costs from anvil_transfer_pricing
- available_regions shows alternative regions with prices

Code Quality:
- Extracted region-utils.ts for flexible region matching
- Cleaned up AI prompt (removed obsolete provider references)
- Renamed project to cloud-orchestrator

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-26 02:49:24 +09:00
kappa
580cc1bbe2 feat: migrate pricing from legacy tables to anvil_pricing
- Replace pricing/instance_types/providers/regions with anvil_* tables
- Add real-time USD→KRW exchange rate conversion (open.er-api.com)
- Korean users (lang=ko) see KRW prices, others see USD
- Remove provider_filter parameter (now single provider: Anvil)
- Add ExchangeRateCache interface with 1-hour KV caching
- Update CLAUDE.md with new table structure and exchange rate docs

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-26 01:05:44 +09:00
kappa
f6c35067f9 feat: add available_regions to recommendations
- Add AvailableRegion interface in types.ts
- Show all regions where the same server spec is available
- Helps users see regional options (e.g., Tokyo and Osaka for japan)
- Sorted by price, excludes current region

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 19:41:42 +09:00
kappa
67d86be5d5 feat: add flexible region matching to servers API
- Add shared buildFlexibleRegionConditions() in utils.ts
- Add COUNTRY_NAME_TO_REGIONS mapping for country/city expansion
- Update servers.ts to use flexible region matching (korea, tokyo, japan, etc.)
- Update recommend.ts to use shared function (remove duplicate code)
- Fix servers GROUP BY to show all regions (it.id, r.id)
- Update CLAUDE.md with single-line curl examples

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 19:36:34 +09:00
kappa
bfaa1d73e4 docs: update CLAUDE.md with security and performance improvements
- Add Security Features section
- Add Configuration section with LIMITS
- Reorganize Recent Changes by category (Architecture, Features, Security, Performance, Code Quality)
- Document prompt injection protection
- Document rate limiting fallback
- Document O(1) VPS lookup optimization

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 19:20:16 +09:00
kappa
4bed3237fc fix: address remaining code review issues
- Apply sanitizeForAIPrompt to AI prompt (prevent prompt injection)
- Replace hardcoded provider IDs with name-based filtering
- Remove dead code (queryVPSBenchmarks function)
- Use LIMITS.MAX_REQUEST_BODY_BYTES constant
- Change parseAIResponse parameter from `any` to `unknown`

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 18:15:09 +09:00
kappa
7dfd3659ec fix: address code review issues (security, performance, quality)
Security:
- Add JSON.parse error handling (return 400 instead of 500)
- Add rate limiting fallback when KV unavailable (in-memory Map)
- Add AI prompt injection protection (sanitizeForAIPrompt)

Performance:
- Optimize VPS benchmark matching (O(1) Map lookup vs O(n*m) loop)
- Reduce AI candidates from 50 to 15 (saves ~60% API cost)
- Centralize magic numbers in LIMITS config

Code Quality:
- Remove dead code (unused queryVPSBenchmarks function)
- Extract duplicated region SQL to DEFAULT_REGION_FILTER_SQL
- Replace hardcoded provider IDs with name-based filtering
- Move magic numbers to config.ts LIMITS object

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 18:08:06 +09:00
kappa
b682abc45d refactor: modularize codebase and add DB workload multiplier
- Split monolithic index.ts (2370 lines) into modular structure:
  - src/handlers/ for route handlers
  - src/utils.ts for shared utilities
  - src/config.ts for configuration
  - src/types.ts for TypeScript definitions

- Add DB workload multiplier for smarter database resource calculation:
  - Heavy (analytics, logs): 0.3x multiplier
  - Medium-heavy (e-commerce, transactional): 0.5x
  - Medium (API, SaaS): 0.7x
  - Light (blog, portfolio): 1.0x

- Fix tech_specs with realistic vcpu_per_users values (150+ technologies)
- Fix "blog" matching "log" regex bug
- Update documentation to reflect new architecture

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 17:46:16 +09:00
kappa
0bb7296600 refactor: 남은 코드 품질/보안 이슈 개선
1. hashString 함수 수정
   - Math.abs() → >>> 0 unsigned 변환

2. CSP 보안 헤더 추가
   - Content-Security-Policy: default-src 'none'

3. 캐시 키 충돌 방지
   - URL-safe base64 인코딩으로 변경

4. CORS 보안 강화
   - Origin 없는 요청에 빈 문자열 반환 (CORS 미적용)
   - 허용 목록 기반 Origin 검증

5. estimateBandwidth 리팩토링
   - USE_CASE_CONFIGS 활용으로 중복 정규식 제거
   - switch 문으로 가독성 향상
   - getDauMultiplier, getActiveUserRatio 간소화

6. 요청 본문 크기 제한
   - 10KB 초과 요청 차단 (413 응답)
   - 대용량 payload 공격 방어

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 16:29:45 +09:00
kappa
ceb5eb7248 refactor: High/Medium 품질 이슈 개선
1. CONFIG 상수 추출
   - Rate limit, Currency, Bandwidth, AI, Cache 설정 중앙화
   - 매직 넘버 10개 → CONFIG 참조로 변경

2. 미사용 함수 제거
   - queryVPSBenchmarks 함수 삭제 (52줄)

3. 에러 타입 체크 개선
   - catch 블록에서 unknown 타입 사용
   - err.message 접근 전 instanceof 체크

4. 쿼리 병렬화
   - queryCandidateServers + queryVPSBenchmarksBatch 병렬 실행
   - 예상 15-25% 응답 시간 개선

5. Use Case 패턴 통합
   - USE_CASE_CONFIGS로 중복 제거
   - getDauMultiplier, getActiveUserRatio 간소화
   - 50줄 이상 중복 코드 제거

6. DB 성능 인덱스 추가
   - instance_types(provider_id, vcpu, memory_mb)
   - pricing(instance_type_id, region_id)
   - regions(region_code, country_code)
   - vps_benchmarks 관련 인덱스

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 16:19:31 +09:00
kappa
efb5dc70e7 fix: Critical 보안 이슈 4건 수정
1. SQL injection 취약점 수정 (currency 직접 삽입 제거)
   - SQL 쿼리에서 currency 제거, 결과 매핑에서 추가

2. 에러 메시지 정보 노출 수정
   - 클라이언트에 내부 에러 상세 숨김
   - 서버 로그에만 기록

3. API 키 로깅 제거
   - sk-*** 형식만 표시, 실제 값 노출 안함

4. Rate limit fail-closed 정책 적용
   - KV 오류 시 요청 거부 (보안 강화)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 16:11:45 +09:00
kappa
1d0cbdd7cc feat: Cloudflare AI Gateway 지원 추가
- AI_GATEWAY_URL 환경변수로 AI Gateway 활성화
- OpenAI 지역 차단(HKG 등) 우회 가능
- 403 에러 시 지역 차단 감지 및 안내 메시지 추가

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 16:03:05 +09:00
kappa
dcc8be6f5b refactor: 서버 추천 핵심 로직 개선
## vCPU 계산 로직 개선
- 카테고리 합산 → 병목 분석(Max)으로 변경
- nginx+nodejs+postgresql 조합: 16 vCPU → 10 vCPU
- 요청 흐름(web→app→db)에서 가장 느린 컴포넌트가 병목

## 메모리 계산 로직 개선
- memory_intensive 서비스: Max → 합산으로 변경
- java+elasticsearch+redis: 8GB → 11GB (실제 동시 실행 반영)

## 대역폭 추정 개선
- 사용자 활동률(activeUserRatio) 추가
- video: 30%, gaming: 50%, e-commerce: 40%
- 비디오 1000명: 257TB → ~80TB/월 (현실적)

## DAU 변환 비율 개선
- 용도별 차등 적용 (getDauMultiplier)
- gaming: 10-20배, blog: 30-50배, saas: 5-10배

## aliases 대소문자 수정
- LOWER(aliases) LIKE로 case-insensitive 매칭

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 15:11:24 +09:00
kappa
502bbd271e refactor: 타입 안전성 및 안정성 개선
- DB 결과 타입 검증용 type guard 함수 추가 (isValidServer, isValidVPSBenchmark, isValidTechSpec, isValidBenchmarkData, isValidAIRecommendation)
- 모든 DB 쿼리 결과에 타입 가드 적용하여 런타임 검증
- AI 응답 파싱에 구조 검증 추가
- OpenAI API 호출에 30초 타임아웃 추가 (AbortController)
- 타임아웃 에러 처리 개선

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 14:28:09 +09:00
kappa
f87ce77595 fix: OpenAI API 키 수정 및 에러 로깅 개선
- Vault에서 올바른 OpenAI API 키 가져와 워커 시크릿 업데이트
- 에러 응답에 details 필드 추가 (디버깅용)
- AI 응답 로깅 추가

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 10:21:34 +09:00
kappa
fd29ee7557 feat: vCPU 및 대역폭 기반 서버 필터링 추가
- minVcpu: expected_users / vcpu_per_users 기반 최소 vCPU 필터링
- 대역폭 기반 provider 필터링:
  - very_heavy (>6TB/month): Linode만 표시
  - heavy (2-6TB/month): Linode 우선 정렬
- queryCandidateServers에 minVcpu, bandwidthEstimate 파라미터 추가

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 09:52:51 +09:00
kappa
4cb9da06dc feat: 대역폭 추정 및 DAU 표시 기능 추가
- 동시접속자 기반 월간 대역폭 자동 추정
- DAU(일일활성사용자) 추정치 표시 (동접 × 10-14)
- 대역폭 기반 Linode/Vultr 자동 선택 로직
- 비용 분석에 대역폭 비용 포함
- 지역 미선택시 서울/도쿄/오사카/싱가포르 기본 표시
- 지역별 서버 분리 표시 (GROUP BY instance + region)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 09:40:36 +09:00