From 7897f2de2055dfda40ce5ab33e9b12126d004b89 Mon Sep 17 00:00:00 2001 From: TtiPo Date: Sun, 8 Nov 2026 00:06:02 +0900 Subject: [PATCH] =?UTF-8?q?fix:=20=ED=85=9C=ED=94=8C=EB=A6=BF=20=EC=A0=90?= =?UTF-8?q?=EA=B2=80=20=EA=B2=B0=EA=B3=BC=20=EB=B0=98=EC=98=81=20=E2=80=94?= =?UTF-8?q?=20Node=2024=C2=B7=EC=9D=B4=EB=AF=B8=EC=A7=80=20=EC=9C=84?= =?UTF-8?q?=EC=83=9D=C2=B7=EC=9A=B4=EC=98=81=20=EB=85=B8=EC=B6=9C=20?= =?UTF-8?q?=EC=B5=9C=EC=86=8C=ED=99=94?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 템플릿 점검에서 나온 항목을 한 번에 반영한다. 항목별 이유: - Node 20 → 24 LTS (Dockerfile·CI): Node 20 은 2026-04-30 에 지원이 끝나 보안 패치가 없다 - backend·frontend .dockerignore 추가: `COPY . .` 가 호스트 node_modules(Windows 바이너리)·dist· .env*(시크릿)를 이미지에 넣고 있었다 - 업로드 디렉터리 쓰기 검사(fail-fast): Linux 에서 Docker 가 root 소유로 만든 바인드 마운트에 비-root 앱이 쓰지 못해 첫 업로드에서야 SYS_001 로 터졌다. 기동 시 해결 명령을 안내한다 - DB 커넥션 풀 100 → 10 (DB_POOL_MAX): PostgreSQL 기본 max_connections(100)를 앱 하나가 다 잡았다 - Swagger 운영 기본 비활성 (SWAGGER_ENABLED): API 구조 전체가 공개 도메인에 노출됐다 - 헬스체크 운영 응답에서 오류 상세 제거: 드라이버 오류 문구에 내부 주소·DB 계정명이 담긴다. 원인은 error 로그로 남긴다 - nginx: location 의 add_header 때문에 정적 자원에서 보안 헤더가 빠지던 문제와, index.html 이 캐시돼 배포 직후 빈 화면이 날 수 있던 문제를 고친다 - vite allowedHosts: true 제거 (DEV_ALLOWED_HOSTS): DNS rebinding 보호가 꺼져 있었다 - 전역 설정을 configureApp() 으로 분리해 main.ts 와 e2e 가 공유: e2e 가 설정을 복사해 재현해 실제 설정과 어긋나도 통과할 수 있었다. PORT 도 빈 값을 방어하는 파서를 거친다 - 쓰이지 않던 WEBSOCKET_PORT 제거: 별도 포트는 같은 도메인 라우팅과 맞지 않는다 - 예제 useUser 가 메시지 대신 에러 코드를 보관하도록 수정, testing.md 표 깨짐 수정, settings.json 허용 목록에서 npm install 제거 (Windows lock 파일 규칙과 충돌) Co-Authored-By: Claude Opus 5.5 --- .claude/agents/release-ops.md | 3 + .claude/rules/checklist.md | 2 + .claude/rules/env-structure.md | 5 +- .claude/rules/response-format.md | 9 +- .claude/rules/security.md | 11 +++ .claude/rules/testing.md | 5 +- .claude/settings.json | 1 - .claude/skills/docker/SKILL.md | 3 + .claude/skills/nestjs/SKILL.md | 26 +++-- .claude/skills/vue3/SKILL.md | 10 +- .env.development.example | 19 +++- .env.production.example | 11 ++- .github/workflows/ci.yml | 6 +- README.md | 10 +- backend/.dockerignore | 25 +++++ backend/Dockerfile | 15 ++- backend/src/app.setup.spec.ts | 88 +++++++++++++++++ backend/src/app.setup.ts | 67 +++++++++++++ backend/src/main.ts | 98 ++++++------------- .../modules/health/health.controller.spec.ts | 37 ++++++- .../src/modules/health/health.controller.ts | 40 +++++++- .../src/modules/upload/upload.config.spec.ts | 40 +++++++- backend/src/modules/upload/upload.config.ts | 24 +++++ backend/src/modules/upload/upload.module.ts | 6 +- .../src/shared/config/database.config.spec.ts | 32 ++++++ backend/src/shared/config/database.config.ts | 26 +++-- .../src/shared/config/env.validation.spec.ts | 16 +++ backend/src/shared/config/env.validation.ts | 22 ++++- .../src/shared/config/swagger.config.spec.ts | 24 +++++ backend/src/shared/config/swagger.config.ts | 41 ++++++++ backend/src/shared/utils/env.ts | 8 ++ backend/test/app.e2e-spec.ts | 23 ++--- docker-compose.dev.yml | 1 - docker-compose.yml | 13 ++- frontend/.dockerignore | 25 +++++ frontend/Dockerfile | 7 +- frontend/nginx.conf | 33 +++++-- frontend/src/composables/useApi.ts | 14 +++ frontend/src/composables/useUser.spec.ts | 45 +++++++++ frontend/src/composables/useUser.ts | 16 ++- frontend/vite.config.ts | 17 +++- 41 files changed, 770 insertions(+), 154 deletions(-) create mode 100644 backend/.dockerignore create mode 100644 backend/src/app.setup.spec.ts create mode 100644 backend/src/app.setup.ts create mode 100644 backend/src/shared/config/database.config.spec.ts create mode 100644 backend/src/shared/config/swagger.config.spec.ts create mode 100644 backend/src/shared/config/swagger.config.ts create mode 100644 frontend/.dockerignore create mode 100644 frontend/src/composables/useUser.spec.ts diff --git a/.claude/agents/release-ops.md b/.claude/agents/release-ops.md index 39a754e..5a86608 100644 --- a/.claude/agents/release-ops.md +++ b/.claude/agents/release-ops.md @@ -35,6 +35,9 @@ tools: Read, Grep, Glob, Edit, Write, Bash, Skill API 를 별도 도메인으로 분리한 구성이라면 `BACKEND_API_URL`·`CORS_ORIGIN` 이 실제 도메인인지 확인한다 — `localhost`·`example.com` 이 남아 있으면 백엔드가 기동에 실패한다 ([[env-structure]]). - **프론트엔드**: 개발에서는 컨테이너로 띄우지 않는다(profile `frontend` 뒤에 있다). 운영만 nginx 정적 호스팅이다. +- **업로드 디렉터리 (Linux 운영)**: 앱은 uid 1000 으로 돈다. `data/uploads` 소유자가 root 면 백엔드가 기동에 실패한다 — + `sudo chown 1000:1000 data/uploads` (UPLOAD_DATA_DIR 을 바꿨다면 그 경로). +- **빌드 컨텍스트**: `backend/`·`frontend/` 의 `.dockerignore` 가 `node_modules`·`dist`·`.env*` 를 뺀다. 지우지 않는다 ([[security]]). ## 완료 기준 (실행하고 결과를 보고한다) diff --git a/.claude/rules/checklist.md b/.claude/rules/checklist.md index ebe8454..44bdab7 100644 --- a/.claude/rules/checklist.md +++ b/.claude/rules/checklist.md @@ -12,6 +12,8 @@ API 를 별도 도메인으로 분리할 때만 실제 도메인을 적는다 (`localhost`/`example.com` 이 남으면 기동 실패) - [ ] 운영 서버: NPM 과 공유하는 외부 네트워크 생성 `docker network create proxy` (없으면 compose 가 기동하지 않는다) → NPM 에 Proxy Host(`/` → frontend:8080) + Custom location(`/api` → backend:3000) 설정, **Cache Assets 끔** (README "운영 배포") +- [ ] 운영 서버(Linux): 업로드 디렉터리 소유자를 앱 사용자(uid 1000)로 — `mkdir -p data/uploads && sudo chown 1000:1000 data/uploads` + (Docker 가 root 소유로 만들면 백엔드가 **기동에 실패**하고 해결 명령을 로그로 알려준다) - [ ] `backend/.env.{env}.example` → `backend/.env.{env}` 복사 후 `JWT_SECRET` 등 고유 시크릿 작성 (compose `env_file` 로 로드 — 파일이 없으면 기동 실패) - [ ] `flutter/.env.example` → `flutter/.env` 복사 후 `API_URL` 확인 (Android 에뮬레이터: `10.0.2.2`) — **이 파일이 없으면 `flutter analyze` 가 asset 경고를 낸다** diff --git a/.claude/rules/env-structure.md b/.claude/rules/env-structure.md index 82ff059..df7de54 100644 --- a/.claude/rules/env-structure.md +++ b/.claude/rules/env-structure.md @@ -36,7 +36,8 @@ description: 환경변수 단일 진실 공급원(SSOT) 구조 — 루트 .env.{ - 모든 env 파일은 커밋 금지, `*.example` 만 커밋한다. (`.gitignore` 의 `!*.example` 재포함 규칙) - **설정이 잘못되면 서버가 뜨지 않아야 한다(fail-fast).** 조용히 기본값으로 굴러가다 운영에서 터지는 것이 더 위험하다. 검증은 `backend/src/shared/config/env.validation.ts` 가 담당하며 `ConfigModule.forRoot({ validate })` 에 연결되어 있다. - - 숫자 항목은 형식 검사 (모든 환경) + - 숫자 항목(`PORT`·`DB_PORT`·`DB_POOL_MAX`·`THROTTLE_*`)은 형식 검사 (모든 환경) + - 참/거짓 항목(`SWAGGER_ENABLED`)은 `true`/`false` 만 허용 (모든 환경) — 오타가 조용히 기본값으로 묻히지 않게 - `CORS_ORIGIN` 은 각 항목이 오리진 형식(`scheme://host[:port]`, 경로 없음)이어야 한다 (모든 환경) — 경로가 붙으면 브라우저 Origin 헤더와 절대 일치하지 않아 조용히 막힌다 - 운영 환경: `DB_HOST`/`DB_USER`/`DB_PASSWORD`/`DB_NAME` 필수 @@ -49,5 +50,5 @@ description: 환경변수 단일 진실 공급원(SSOT) 구조 — 루트 .env.{ - 문제는 하나씩이 아니라 **한 번에 모아서** 보여준다 (재기동 반복 방지) - 새 필수 설정을 추가하면 이 파일의 목록과 테스트도 함께 갱신한다 -> 루트 env의 대표 키: `PROJECT_NAME`, `APP_ENV`, `BUILD_MODE`, 각종 `*_PORT`, `BACKEND_API_URL`, `CORS_ORIGIN`, `DB_*`/`DB_DATA_DIR`, `REDIS_*`/`REDIS_DATA_DIR`, `THROTTLE_TTL_MS`/`THROTTLE_LIMIT`. 실제 목록은 `.env.development.example` 참조. +> 루트 env의 대표 키: `PROJECT_NAME`, `APP_ENV`, `BUILD_MODE`, 각종 `*_PORT`, `BACKEND_API_URL`, `CORS_ORIGIN`, `SWAGGER_ENABLED`, `DB_*`/`DB_DATA_DIR`/`DB_POOL_MAX`, `REDIS_*`/`REDIS_DATA_DIR`, `THROTTLE_TTL_MS`/`THROTTLE_LIMIT`, `DEV_ALLOWED_HOSTS`(호스트 vite 전용). 실제 목록은 `.env.development.example` 참조. > 실행/배포 명령은 [[docker]], 보안 규칙은 [[security]] 참조. diff --git a/.claude/rules/response-format.md b/.claude/rules/response-format.md index 9efd36d..737bd9b 100644 --- a/.claude/rules/response-format.md +++ b/.claude/rules/response-format.md @@ -43,14 +43,21 @@ exportCsv(@Res() res: Response) { /* ... */ } // 200 — 정상 { "status": "ok", "info": { "database": { "status": "up" } }, "error": {}, "details": { ... } } -// 503 — 실패 (원인이 보인다) +// 503 — 실패 (어느 구성요소가 죽었는지 보인다) { "status": "error", "info": {}, "error": { "database": { "status": "down", "message": "..." } }, ... } + +// 503 — 운영(NODE_ENV=production): 구성요소별 status 만 남기고 message 등 상세는 뺀다 +{ "status": "error", "info": {}, "error": { "database": { "status": "down" } }, "details": { "database": { "status": "down" } } } ``` 구현: `HealthController` 에 `@SkipTransform()` 을 붙이고, terminus 의 `ServiceUnavailableException` 은 컨트롤러에서 직접 잡아 503 + 원본 본문을 반환한다(전역 필터까지 가지 않게 한다). 같은 성격의 엔드포인트를 추가할 때 이 패턴을 재사용한다. +운영에서 상세를 빼는 이유: 같은 도메인 구성에서 `/api/health` 는 공개 주소로 열려 있고, +드라이버 오류 문구에는 내부 주소·DB 계정명이 담길 수 있다(`connect ECONNREFUSED 172.18.0.2:5432`). +원인은 응답 대신 **서버 로그(error)** 로 남긴다 ([[security]] — 응답에 내부 호스트명을 싣지 않는다). + ## 목록 응답 (페이지네이션) 목록 API 의 `data` 는 **항상 아래 구조**를 가진다. 배열을 그대로 반환하지 않는다. diff --git a/.claude/rules/security.md b/.claude/rules/security.md index 22ad3f7..fa5de20 100644 --- a/.claude/rules/security.md +++ b/.claude/rules/security.md @@ -8,6 +8,8 @@ - ✅ `DB_PASSWORD=change-me-in-local-env` - 시크릿이 한 번이라도 커밋되었다면 **값을 교체(rotate)** 한다. 커밋을 되돌리는 것만으로는 노출이 해소되지 않는다. - 로그·에러 응답에 시크릿을 남기지 않는다 ([[logging]]). +- **이미지에도 굽지 않는다.** `backend/`·`frontend/` 의 `.dockerignore` 가 `.env*` 를 빌드 컨텍스트에서 뺀다 — + 값은 실행 시 compose 의 `env_file`/`environment` 로만 들어간다. `.dockerignore` 를 지우거나 `.env*` 를 다시 넣지 않는다. ## 인증 · 토큰 @@ -21,6 +23,10 @@ - 입력값은 DTO(`class-validator`) 검증을 거친 뒤 서비스 계층에 전달한다. 전역 `ValidationPipe` 의 `whitelist`/`forbidNonWhitelisted` 를 끄지 않는다 - TypeORM ORM 쿼리 사용으로 SQL Injection 차단 (Raw 쿼리 시 파라미터 바인딩 필수) - 에러 응답에 스택·쿼리·내부 호스트명을 싣지 않는다 — 미정의 예외는 항상 `SYS_001` 로 수렴시킨다 ([[error-codes]]) + - 헬스체크(`/api/health`)도 운영에서는 구성요소별 status 만 내보낸다 — 드라이버 오류 문구에 내부 주소가 담긴다 ([[response-format]]) +- **Swagger 는 운영에서 기본으로 끈다** (`SWAGGER_ENABLED` 비움 = 운영에서만 off). API 구조 전체를 공개하기 때문이다. + 운영에서 켜야 하면 `SWAGGER_ENABLED=true` + NPM Access List 등으로 접근을 제한한다. + ### 파일 업로드 템플릿은 `modules/upload` 에 로컬 디스크 기준 골격을 제공한다. 새 업로드 엔드포인트는 이 패턴을 복제한다. @@ -69,6 +75,11 @@ - **보안 헤더는 CSP 까지** 설정한다 (`frontend/nginx.conf`). 외부 CDN·폰트·분석 스크립트를 추가하면 해당 도메인을 CSP 에 명시한다. `script-src` 에 `'unsafe-inline'`/`'unsafe-eval'` 을 넣으면 CSP 의 의미가 사라진다. API 는 같은 도메인의 `/api` 라 `connect-src 'self'` 로 충분하다. API 를 별도 도메인으로 분리하면 그 오리진을 추가해야 요청이 차단되지 않는다. + - ⚠️ nginx 는 location 에 `add_header` 가 하나라도 있으면 server 레벨의 보안 헤더를 **전부 상속하지 않는다.** + location 의 캐시 정책은 `add_header` 대신 `expires` 로 지정한다 (`frontend/nginx.conf` 주석 참조). +- **vite dev 서버의 `allowedHosts` 를 `true` 로 열지 않는다** — DNS rebinding 보호가 꺼져 악성 사이트가 + 개발자 브라우저를 거쳐 dev 서버(소스)와 `/api` 프록시(로컬 백엔드)에 닿을 수 있다. + 터널(ngrok 등)이 필요하면 루트 `DEV_ALLOWED_HOSTS` 에 그 도메인만 적는다. ## 의존성 diff --git a/.claude/rules/testing.md b/.claude/rules/testing.md index ee7d97f..247a0ed 100644 --- a/.claude/rules/testing.md +++ b/.claude/rules/testing.md @@ -22,7 +22,6 @@ description: 세 스택 공통 테스트 규칙 — 테스트 위치/네이밍, | 스택 | 러너 | 위치·네이밍 | 실행 | | --- | --- | --- | --- | | backend | Jest | 단위 `*.spec.ts` (소스 옆), e2e `test/*.e2e-spec.ts` | `npm run test`, `npm run test:e2e` | - | frontend | Vitest | `*.spec.ts` / `*.test.ts` (대상 옆 또는 `__tests__/`) | `npm run test:unit` | | flutter | flutter_test | `test/` 하위, `*_test.dart` | `flutter test` | @@ -51,8 +50,12 @@ describe('formatSomething', () => { | 에러 응답 포맷 | `backend/src/common/filters/http-exception.filter.spec.ts` | 코드/상태/traceId, **내부 정보 미노출**, 검증 상세 사유 미노출 | | 프론트 에러 사전 | `frontend/src/composables/useApi.spec.ts` | 코드 목록이 백엔드와 일치, 폴백 동작 | | 앱 에러 사전 | `flutter/test/error_lexicon_test.dart` | 코드 목록이 백엔드와 일치, 폴백 동작 | +| 전역 설정 | `backend/src/app.setup.spec.ts` | main.ts·e2e 가 공유하는 `configureApp()` 의 prefix·응답 래퍼·에러 필터·보안 헤더·CORS (DB 불필요) | | 응답 계약 (e2e) | `backend/test/app.e2e-spec.ts` | 실제 HTTP 로 래퍼·에러코드·traceId·페이지네이션·헬스체크 형식 검증 | +> **e2e 는 main.ts 와 같은 `configureApp()` 을 쓴다.** 테스트에서 전역 설정을 따로 흉내 내지 않는다 — +> 흉내 낸 설정은 실제와 어긋나도 테스트가 통과해 버린다. + > **e2e 는 DB 가 필요하다** (AppModule 이 TypeORM 을 초기화한다). > 로컬에서는 개발 스택을 띄운 뒤 컨테이너 안에서 실행하는 것이 가장 간단하다. > ```bash diff --git a/.claude/settings.json b/.claude/settings.json index 796a508..f20bcb1 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -10,7 +10,6 @@ "Bash(npm run sync:error-codes)", "Bash(npm run start:*)", "Bash(npm ci)", - "Bash(npm install)", "Bash(pnpm lint:*)", "Bash(pnpm build:*)", "Bash(flutter analyze:*)", diff --git a/.claude/skills/docker/SKILL.md b/.claude/skills/docker/SKILL.md index f8cbfc7..6a5edec 100644 --- a/.claude/skills/docker/SKILL.md +++ b/.claude/skills/docker/SKILL.md @@ -42,6 +42,9 @@ docker compose -f docker-compose.yml -f docker-compose.dev.yml --env-file .env.d > - location 은 `/api`(끝 슬래시 없음), Forward Hostname 에는 경로를 붙이지 않는다 — 경로가 그대로 넘어가야 백엔드 prefix 와 맞는다. > - `BACKEND_API_URL=/api`·`CORS_ORIGIN` 비움이 기본이다. API 를 별도 도메인으로 분리할 때만 실제 도메인을 적는다 — > 그때 `localhost` 나 예시 도메인(`example.com`)이 남아 있으면 백엔드가 기동에 실패한다 ([[env-structure]]). +> - **Linux 서버는 업로드 디렉터리 소유자를 먼저 맞춘다** — 앱은 uid 1000 으로 도는데 Docker 가 없는 디렉터리를 root 소유로 만든다. +> `mkdir -p data/uploads && sudo chown 1000:1000 data/uploads` (안 하면 백엔드가 기동에 실패하며 같은 명령을 안내한다) +> - Swagger(`/api-docs`)는 운영에서 기본으로 꺼진다 (`SWAGGER_ENABLED`). ```bash # 운영 환경 배포 diff --git a/.claude/skills/nestjs/SKILL.md b/.claude/skills/nestjs/SKILL.md index 499df70..b34d490 100644 --- a/.claude/skills/nestjs/SKILL.md +++ b/.claude/skills/nestjs/SKILL.md @@ -17,23 +17,25 @@ description: NestJS 백엔드(backend/) 개발 규칙 — 컨트롤러/서비스 | --- | --- | --- | | **에러 코드 레지스트리** | `src/common/errors/error-codes.ts` | 코드↔메시지↔HTTP 상태 **SSOT**. `npm run sync:error-codes` 로 클라이언트 사전 생성 | | **BusinessException** | `src/common/errors/business.exception.ts` | 에러 코드가 **생성자 필수 인자** — 코드 없는 실패를 만들 수 없다 | -| 표준 응답 인터셉터 | `src/common/interceptors/transform.interceptor.ts` | main.ts 전역 등록 — 컨트롤러는 raw 데이터만 반환. `@SkipTransform()` 으로 제외 | +| **전역 설정** | `src/app.setup.ts` 의 `configureApp()` | prefix·helmet·CORS·ValidationPipe·필터·인터셉터. **main.ts 와 e2e 가 같은 함수를 쓴다** — 전역 설정은 여기에만 추가한다 | +| 표준 응답 인터셉터 | `src/common/interceptors/transform.interceptor.ts` | `configureApp()` 에서 전역 등록 — 컨트롤러는 raw 데이터만 반환. `@SkipTransform()` 으로 제외 | | 전역 예외 필터 | `src/common/filters/http-exception.filter.ts` | 레지스트리 조회로 `{success:false,error:{code,message,traceId}}` 생성 ([[error-codes]]) | | 요청 추적 미들웨어 | `src/common/middleware/request-id.middleware.ts` | `x-request-id` 발급 → 로그·응답 `traceId` ([[logging]]) | | Swagger 래퍼 데코레이터 | `src/common/decorators/api-standard-response.decorator.ts` | `ApiStandardResponse` / `ApiErrorResponse` — 문서를 실응답과 일치시킨다 | | 페이지네이션 DTO | `src/common/dto/pagination.dto.ts` | 커서/오프셋 쿼리 + `PageInfoDto` + `toPaginatedResult()` | -| 전역 ValidationPipe | `main.ts` | `whitelist/forbidNonWhitelisted/transform` | -| Swagger | `main.ts` → `/api-docs` | 모든 엔드포인트 데코레이터 | -| 보안 미들웨어 | `main.ts` | helmet · CORS 화이트리스트(`shared/config/cors.config.ts` — 같은 도메인 구성이 기본이라 비어 있다. 다른 오리진만 `CORS_ORIGIN` 에 콤마로) | +| 전역 ValidationPipe | `app.setup.ts` | `whitelist/forbidNonWhitelisted/transform` | +| Swagger | `shared/config/swagger.config.ts` → `/api-docs` | 모든 엔드포인트 데코레이터. **운영에서는 기본 비활성** — `SWAGGER_ENABLED=true/false` 로 강제 | +| 보안 미들웨어 | `app.setup.ts` | helmet · CORS 화이트리스트(`shared/config/cors.config.ts` — 같은 도메인 구성이 기본이라 비어 있다. 다른 오리진만 `CORS_ORIGIN` 에 콤마로) | | Rate Limiting | `app.module.ts` 의 `ThrottlerGuard`(APP_GUARD) | 초과 시 429 → `REQ_001`. 루트 `.env` 의 `THROTTLE_*` 로 조정 | | 로깅 | `shared/logger/winston.config.ts` | `console.log` 대신 사용 ([[logging]]) | | env 검증 | `shared/config/env.validation.ts` | 잘못된 설정이면 **기동 실패**(fail-fast) ([[env-structure]]) | -| DB 설정 | `shared/config/database.config.ts` | 앱·CLI 공유 SSOT. `synchronize` 기본 off | +| DB 설정 | `shared/config/database.config.ts` | 앱·CLI 공유 SSOT. `synchronize` 기본 off. 풀 크기 `DB_POOL_MAX`(기본 10 — 인스턴스 수 × 풀 크기가 DB `max_connections` 를 넘지 않게) | | 마이그레이션 | `src/data-source.ts` + `src/migrations/` | `npm run migration:*` (아래 "DB 마이그레이션") | | Graceful shutdown | `main.ts` 의 `enableShutdownHooks()` + `shared/logger/shutdown.logger.ts` | SIGTERM 시 요청/커넥션 정리 후 종료 | +| 컨테이너 빌드 | `Dockerfile`(Node 24 LTS) + `.dockerignore` | 호스트 `node_modules`·`dist`·`.env*` 는 빌드 컨텍스트에서 빠진다 — 시크릿을 이미지에 굽지 않는다 | | 예제 모듈(참조용) | `modules/user`(DTO+Swagger+페이지네이션) | 새 모듈 패턴 참고. in-memory 데모 저장소 | -| 파일 업로드 | `modules/upload` | 로컬 디스크 저장 + 형식·크기 검증 + 안전한 파일명 생성 ([[security]]) | -| 헬스체크 | `modules/health` | `@SkipThrottle`+`@SkipTransform` — 기계가 읽는 엔드포인트 패턴 ([[response-format]]) | +| 파일 업로드 | `modules/upload` | 로컬 디스크 저장 + 형식·크기 검증 + 안전한 파일명 생성 ([[security]]). 저장 디렉터리에 쓸 수 없으면 **기동 실패** | +| 헬스체크 | `modules/health` | `@SkipThrottle`+`@SkipTransform` — 기계가 읽는 엔드포인트 패턴. 운영에서는 구성요소별 status 만 노출 ([[response-format]]) | | 순수 유틸 | `shared/utils/` | 순수 함수 분리 위치 | > **확장 시 따르는 규칙** (기능이 필요해지면 규칙대로 구현): @@ -42,6 +44,9 @@ description: NestJS 백엔드(backend/) 개발 규칙 — 컨트롤러/서비스 > `app.module.ts` 는 이미 `TypeOrmModule.forRootAsync` 로 연결되어 있다. > 스키마는 **마이그레이션으로 관리**하며 `synchronize` 는 기본 off 다 (아래 "DB 마이그레이션" 참조) > - **도메인 에러 코드**: `error-codes.ts` 의 `DOMAIN_ERROR_CODES` 에 등록 → `npm run sync:error-codes` +> - **WebSocket**: 별도 포트를 열지 않는다. 게이트웨이를 HTTP 서버에 붙이고 경로를 `/api` 아래에 둔다 +> (socket.io 면 `@WebSocketGateway({ path: '/api/socket.io' })`). 그래야 같은 도메인의 NPM location `/api` 를 그대로 탄다. +> NPM Proxy Host 의 **Websockets Support** 를 켜고, 개발용 vite 프록시(`/api`)에 `ws: true` 를 추가한다. > - `common/{guards,pipes}/` 는 해당 관심사 등장 시 생성 (아래 "모듈 구조"는 목표 구조) --- @@ -127,7 +132,8 @@ export class TransformInterceptor implements NestInterceptor { } ``` -- `main.ts`에서 전역 등록: `app.useGlobalInterceptors(new TransformInterceptor())` +- `app.setup.ts` 의 `configureApp()` 에서 전역 등록: `app.useGlobalInterceptors(new TransformInterceptor(app.get(Reflector)))` + — main.ts 와 e2e 가 이 함수를 공유한다. 전역 설정을 main.ts 에 직접 추가하지 말 것 (테스트가 실제 설정과 어긋난다) - 실패 응답(`success: false`)은 아래 Exception Filter가 생성한다. - 응답 포맷 SSOT는 [[response-format]] 참조. @@ -163,7 +169,7 @@ throw new BusinessException('USER_001', { ## Swagger 필수 적용 ```typescript -// main.ts +// shared/config/swagger.config.ts — main.ts 는 isSwaggerEnabled() 일 때만 setupSwagger(app) 를 호출한다 const config = new DocumentBuilder() .setTitle('API 문서') .setDescription('프로젝트 API 명세서') @@ -175,6 +181,8 @@ const document = SwaggerModule.createDocument(app, config); SwaggerModule.setup('api-docs', app, document); ``` +- 문서는 API 구조 전체를 공개하므로 **운영에서는 기본으로 꺼진다.** 필요하면 `SWAGGER_ENABLED=true` 로 켜고 + NPM Access List 등으로 접근을 제한한다 (`SWAGGER_ENABLED=false` 는 개발에서도 끈다). - 모든 Controller에 `@ApiTags()` 적용 - 모든 엔드포인트에 `@ApiOperation()` 작성 - **응답은 `@ApiResponse` 대신 래퍼 데코레이터를 쓴다** — 컨트롤러는 raw 를 반환하지만 실응답은 `{success,data}` 라 문서가 어긋난다. diff --git a/.claude/skills/vue3/SKILL.md b/.claude/skills/vue3/SKILL.md index b917fce..9cdaccc 100644 --- a/.claude/skills/vue3/SKILL.md +++ b/.claude/skills/vue3/SKILL.md @@ -29,6 +29,7 @@ description: Vue 3 프론트엔드(frontend/) 개발 규칙 — Composition API | env 타입 선언 | `frontend/env.d.ts` | `VITE_API_BASE_URL` | | dev API 프록시 | `vite.config.ts` 의 `server.proxy` | `/api` → 백엔드 (운영 NPM Custom location 과 같은 역할). 없으면 vite 가 SPA 폴백으로 **HTML 을 200 으로** 돌려줘 조용히 실패한다 | | dev 서버 포트 | `vite.config.ts` 의 `loadEnv` | 루트 `.env.{mode}` 의 `FRONTEND_PORT`/`BACKEND_PORT` 를 읽는다. `strictPort` 로 포트 충돌 시 fail-fast ([[env-structure]]) | +| dev 서버 허용 호스트 | `vite.config.ts` 의 `allowedHosts` | 기본은 localhost·IP 만 (DNS rebinding 보호). 터널은 루트 `DEV_ALLOWED_HOSTS` 에 콤마로 — `true` 로 열지 않는다 ([[security]]) | > **개발 서버는 호스트에서 띄운다** — `cd frontend && npm run dev` (→ `http://localhost:${FRONTEND_PORT}`). > 컨테이너 vite 는 바인드 마운트 때문에 첫 서빙에 수 분이 걸려 compose profile `frontend` 뒤로 숨겼다 ([[docker]]). @@ -153,18 +154,23 @@ try { // composables/useUser.ts — 도메인별 API Composable export function useUser() { const loading = ref(false) - const error = ref(null) + // 실패 시 **에러 코드만** 보관한다 — 화면은 code 로 분기하고, 알림 문구는 인터셉터가 이미 띄웠다 + const errorCode = ref(null) async function getUser(id: number) { loading.value = true + errorCode.value = null try { return await api.get(`/users/${id}`) + } catch (e) { + errorCode.value = isApiError(e) ? e.code : FALLBACK_ERROR_CODE // 메시지를 새로 만들지 않는다 + return null } finally { loading.value = false } } - return { loading, error, getUser } + return { loading, errorCode, getUser } } ``` diff --git a/.env.development.example b/.env.development.example index 61beede..4d5f93c 100644 --- a/.env.development.example +++ b/.env.development.example @@ -16,10 +16,18 @@ BACKEND_DIR=backend # ========================================== FRONTEND_PORT=5173 BACKEND_PORT=3000 -WEBSOCKET_PORT=3001 DB_PORT=5432 REDIS_PORT=6379 +# ========================================== +# vite dev 서버 접근 허용 호스트 (호스트에서 띄우는 프론트엔드 전용) +# +# 기본(비어 있음)은 localhost·IP 접근만 허용한다 — vite 의 DNS rebinding 보호가 켜진 상태다. +# ngrok 같은 터널로 외부에서 dev 서버를 열 때만 도메인을 콤마로 적는다. +# 점으로 시작하면 하위 도메인 전체를 허용한다. 예) DEV_ALLOWED_HOSTS=.ngrok-free.app +# ========================================== +DEV_ALLOWED_HOSTS= + # ========================================== # Database 설정 # ========================================== @@ -28,6 +36,8 @@ DB_USER=app_user DB_PASSWORD=change-me-in-local-env DB_NAME=project_db DB_DATA_DIR=./data/postgres +# 앱 인스턴스 하나의 커넥션 풀 크기 (PostgreSQL 기본 max_connections 100 을 넘지 않게 — 인스턴스 수 × 이 값 + 여유) +DB_POOL_MAX=10 # ========================================== # Redis 설정 @@ -49,6 +59,13 @@ REDIS_DATA_DIR=./data/redis BACKEND_API_URL=/api CORS_ORIGIN= +# ========================================== +# Swagger API 문서 (/api-docs) +# +# 비어 있으면 운영에서만 끈다 (개발에서는 켜진다). true/false 로 강제할 수 있다. +# ========================================== +SWAGGER_ENABLED= + # ========================================== # Rate Limiting (API 남용 방지) # 미설정 시 백엔드 기본값(60초 / 100회) 사용 diff --git a/.env.production.example b/.env.production.example index b55467e..029774a 100644 --- a/.env.production.example +++ b/.env.production.example @@ -18,7 +18,6 @@ BACKEND_DIR=backend # ========================================== FRONTEND_PORT=5173 BACKEND_PORT=3000 -WEBSOCKET_PORT=3001 DB_PORT=5432 REDIS_PORT=6379 @@ -30,6 +29,8 @@ DB_USER=app_user DB_PASSWORD=CHANGE-ME-BEFORE-DEPLOY DB_NAME=project_db DB_DATA_DIR=./data/postgres +# 앱 인스턴스 하나의 커넥션 풀 크기 (PostgreSQL 기본 max_connections 100 을 넘지 않게 — 인스턴스 수 × 이 값 + 여유) +DB_POOL_MAX=10 # ========================================== # Redis 설정 @@ -60,6 +61,14 @@ REDIS_DATA_DIR=./data/redis BACKEND_API_URL=/api CORS_ORIGIN= +# ========================================== +# Swagger API 문서 (/api-docs) +# +# 비어 있으면 운영에서는 꺼진다 — 문서가 API 구조 전체(경로·파라미터·스키마)를 공개하기 때문이다. +# 운영에서도 필요하면 true 로 켜고 NPM 의 Access List 등으로 접근을 제한한다. +# ========================================== +SWAGGER_ENABLED= + # ========================================== # Rate Limiting (API 남용 방지) # 미설정 시 백엔드 기본값(60초 / 100회) 사용 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bbd8045..a0a6937 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -43,7 +43,7 @@ jobs: - uses: actions/setup-node@v4 with: - node-version: '20' + node-version: '24' cache: npm cache-dependency-path: backend/package-lock.json @@ -84,7 +84,7 @@ jobs: - uses: actions/setup-node@v4 with: - node-version: '20' + node-version: '24' cache: npm cache-dependency-path: frontend/package-lock.json @@ -109,7 +109,7 @@ jobs: - uses: actions/setup-node@v4 with: - node-version: '20' + node-version: '24' cache: npm cache-dependency-path: backend/package-lock.json diff --git a/README.md b/README.md index 23ac72d..6dc60ec 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,8 @@ NestJS(백엔드) · Vue 3(웹) · Flutter(모바일)를 하나의 저장소에 ## 사전 요구사항 -- Docker / Docker Compose — backend·frontend·db·redis 구동 +- Docker / Docker Compose — backend·frontend·db·redis 구동 (컨테이너는 Node 24 LTS 이미지를 쓴다) +- Node.js 24 LTS 권장 (최소 22.12) — 호스트에서 띄우는 vite dev 서버와 lint·test 용 - Flutter SDK `^3.11` — 모바일 앱 실행용 (compose 대상 아님) ## 빠른 시작 (Docker) @@ -43,7 +44,7 @@ cd frontend && npm install && npm run dev - 웹: - API: — 브라우저가 쓰는 경로 (vite 프록시가 백엔드로 넘긴다, 운영과 같은 구조) · 백엔드 직접: -- Swagger 문서: +- Swagger 문서: — 운영에서는 기본으로 꺼진다 (`SWAGGER_ENABLED`) > **개발 환경에서 프론트엔드는 컨테이너로 뜨지 않습니다.** > vite 를 컨테이너에서 돌리면 소스가 Windows 바인드 마운트 너머에 있어 첫 서빙까지 수 분이 걸립니다. @@ -102,6 +103,10 @@ docker network connect proxy # NPM 이 아직 proxy ```bash cp .env.production.example .env.production # placeholder 교체 — BACKEND_API_URL=/api 는 그대로 둔다 cp backend/.env.production.example backend/.env.production + +# 업로드 디렉터리 소유자를 앱 사용자(node, uid 1000)로 — Docker 가 root 소유로 만들면 백엔드가 기동에 실패한다 +mkdir -p data/uploads && sudo chown 1000:1000 data/uploads + sudo docker compose --env-file .env.production up -d --build ``` @@ -122,6 +127,7 @@ sudo docker compose --env-file .env.production up -d --build > 프론트 정적 자원의 캐시 헤더는 frontend nginx 가 이미 붙입니다. > - location 은 `/api` (끝 슬래시 없음) — 접두어 매칭이라 Swagger(`/api-docs`)까지 백엔드로 갑니다. 개발의 vite 프록시와 같은 규칙입니다. +> (Swagger 는 운영에서 기본으로 꺼져 있습니다. 켜려면 `SWAGGER_ENABLED=true` + NPM Access List 로 접근을 제한하세요) > - Forward Hostname 에 경로를 붙이지 않습니다. 요청 경로가 그대로 넘어가야 백엔드의 `/api` prefix 와 맞습니다. > - **`/api` 로 시작하는 경로는 프론트 라우트로 쓰지 않습니다** (전부 백엔드로 갑니다). diff --git a/backend/.dockerignore b/backend/.dockerignore new file mode 100644 index 0000000..ed2dd4d --- /dev/null +++ b/backend/.dockerignore @@ -0,0 +1,25 @@ +# ========================================== +# 빌드 컨텍스트에서 제외할 파일 +# +# Dockerfile 의 `COPY . .` 가 아래 항목까지 이미지에 넣지 않도록 막는다. +# ========================================== + +# 의존성·빌드 산출물 — 컨테이너 안에서 npm ci·빌드를 다시 한다. +# 호스트(Windows) node_modules 가 섞이면 네이티브 바이너리가 리눅스용을 덮어써 컨테이너가 깨진다. +node_modules +dist +coverage + +# 시크릿 — 이미지에 굽지 않는다. 실행 시 compose 의 env_file/environment 로 주입된다. +.env +.env.* + +# 런타임 데이터·로그 +uploads +logs +*.log + +# 에디터·OS +.vscode +.idea +.DS_Store diff --git a/backend/Dockerfile b/backend/Dockerfile index 3773d5c..55af99f 100644 --- a/backend/Dockerfile +++ b/backend/Dockerfile @@ -1,8 +1,8 @@ -FROM node:20-alpine AS builder +FROM node:24-alpine AS builder WORKDIR /app -# 호스트의 npm 11 이 작성한 package-lock.json 형식과 호환되도록 npm 을 11 로 업그레이드 -# (전역 설치는 root 권한이 필요하므로 USER 전환 전에 수행) +# 호스트의 npm 11 이 작성한 package-lock.json 형식과 호환되도록 npm 을 11 로 고정 +# (베이스 이미지의 번들 npm 이 바뀌어도 lock 형식이 어긋나지 않게 한다. 전역 설치는 root 권한이 필요하므로 USER 전환 전에 수행) RUN npm install -g npm@11 # 개발 환경(docker-compose.dev.yml)은 이 스테이지를 그대로 구동하므로 비-root 로 전환한다. @@ -14,10 +14,11 @@ USER node COPY --chown=node:node package*.json ./ RUN npm ci +# 호스트의 node_modules·dist·.env 는 .dockerignore 로 제외된다 COPY --chown=node:node . . RUN npm run build -FROM node:20-alpine AS production +FROM node:24-alpine AS production WORKDIR /app ENV NODE_ENV=production @@ -31,9 +32,13 @@ RUN npm ci --omit=dev && npm cache clean --force COPY --from=builder /app/dist ./dist +# 업로드 디렉터리를 node 소유로 미리 만든다 — 볼륨 없이 띄우거나 named volume 을 붙여도 비-root 앱이 쓸 수 있다. +# 호스트 디렉터리를 바인드 마운트하면 호스트 쪽 소유권을 따른다 (README "운영 배포" 의 chown 참조) +RUN mkdir -p /app/uploads && chown node:node /app/uploads + EXPOSE 3000 # 비-root 실행 (보안 규칙) USER node -CMD ["node", "dist/main"] \ No newline at end of file +CMD ["node", "dist/main"] diff --git a/backend/src/app.setup.spec.ts b/backend/src/app.setup.spec.ts new file mode 100644 index 0000000..ecdb150 --- /dev/null +++ b/backend/src/app.setup.spec.ts @@ -0,0 +1,88 @@ +import { Controller, Get, INestApplication, Logger } from '@nestjs/common'; +import { Test } from '@nestjs/testing'; +import request from 'supertest'; +import type { Response } from 'supertest'; +import { App } from 'supertest/types'; + +import { configureApp } from '@/app.setup'; +import { BusinessException } from '@/common/errors/business.exception'; + +/** 전역 설정만 검증하기 위한 최소 컨트롤러 — DB 가 필요 없다 */ +@Controller('ping') +class PingController { + @Get() + ping(): { pong: boolean } { + return { pong: true }; + } + + @Get('missing') + missing(): never { + throw new BusinessException('RES_001'); + } +} + +/** supertest 의 body 는 any 이므로 계약 형태로 좁혀서 읽는다 */ +interface ContractBody { + success?: boolean; + data?: unknown; + error?: { code?: string }; +} + +const body = (res: Response): ContractBody => res.body as ContractBody; + +describe('configureApp (main.ts·e2e 공유 전역 설정)', () => { + let app: INestApplication; + + beforeAll(async () => { + // 의도된 실패 응답의 경고 로그가 테스트 출력을 오염시키지 않도록 억제 + jest.spyOn(Logger.prototype, 'warn').mockImplementation(() => undefined); + + const moduleRef = await Test.createTestingModule({ + controllers: [PingController], + }).compile(); + + app = moduleRef.createNestApplication(); + configureApp(app); + await app.init(); + }); + + afterAll(async () => { + await app.close(); + jest.restoreAllMocks(); + }); + + it('라우트는 /api 아래에 놓이고 성공 응답은 { success, data } 로 감싸진다', async () => { + const res = await request(app.getHttpServer()).get('/api/ping').expect(200); + + expect(body(res)).toEqual({ success: true, data: { pong: true } }); + }); + + it('prefix 밖의 루트(/)는 상태 확인 텍스트를 돌려준다 (docker healthcheck)', async () => { + const res = await request(app.getHttpServer()).get('/').expect(200); + + expect(res.text).toContain('정상 구동'); + }); + + it('실패는 전역 필터가 에러 코드 응답으로 바꾼다', async () => { + const res = await request(app.getHttpServer()) + .get('/api/ping/missing') + .expect(404); + + expect(body(res).success).toBe(false); + expect(body(res).error?.code).toBe('RES_001'); + }); + + it('보안 헤더(helmet)가 붙는다', async () => { + const res = await request(app.getHttpServer()).get('/api/ping'); + + expect(res.headers['x-content-type-options']).toBe('nosniff'); + }); + + it('화이트리스트 밖 오리진에는 CORS 헤더를 주지 않는다', async () => { + const res = await request(app.getHttpServer()) + .get('/api/ping') + .set('Origin', 'https://other.io'); + + expect(res.headers['access-control-allow-origin']).toBeUndefined(); + }); +}); diff --git a/backend/src/app.setup.ts b/backend/src/app.setup.ts new file mode 100644 index 0000000..073d4b8 --- /dev/null +++ b/backend/src/app.setup.ts @@ -0,0 +1,67 @@ +import { + INestApplication, + RequestMethod, + ValidationPipe, +} from '@nestjs/common'; +import { Reflector } from '@nestjs/core'; +import helmet from 'helmet'; +import type { + Express, + Request as ExpressRequest, + Response as ExpressResponse, +} from 'express'; + +import { HttpExceptionFilter } from '@/common/filters/http-exception.filter'; +import { TransformInterceptor } from '@/common/interceptors/transform.interceptor'; +import { buildCorsOptions } from '@/shared/config/cors.config'; + +/** 모든 라우트의 공통 prefix — Flutter·Web 의 baseURL, 리버스 프록시의 location /api 와 맞물려 있다 */ +export const GLOBAL_PREFIX = 'api'; + +/** + * 앱 전역 설정 — main.ts 와 e2e 테스트가 **같은 함수**를 쓴다. + * 테스트가 설정을 따로 흉내 내면 둘이 어긋나도 테스트는 통과해 버린다. + * 리스닝·Swagger·종료 훅처럼 실행 환경에만 필요한 것은 main.ts 에 둔다. + */ +export function configureApp(app: INestApplication): void { + // 리버스 프록시 뒤에서 실제 클라이언트 IP 를 식별한다 (rate limit 이 IP 기준이다). + // 운영은 Nginx Proxy Manager → backend 로 한 번 거친다 (Custom location 이 X-Forwarded-For 에 클라이언트 IP 를 싣는다). + const expressApp = app.getHttpAdapter().getInstance() as Express; + expressApp.set('trust proxy', 1); + + // 글로벌 prefix — 모든 라우트가 /api/* 로 정규화됨 (Flutter, Web 양쪽 baseURL과 일치) + // 리버스 프록시(운영 NPM · 개발 vite)는 /api 로 시작하는 요청을 경로 그대로 넘기므로 이 prefix 와 맞물려 있다. + app.setGlobalPrefix(GLOBAL_PREFIX, { + // 헬스체크 / 루트 상태 엔드포인트는 prefix 미적용 + exclude: [{ path: '/', method: RequestMethod.GET }], + }); + + // 기본 주소('/') 접속 시 상태 확인용 텍스트 응답 — docker healthcheck 가 사용한다 + expressApp.get('/', (_req: ExpressRequest, res: ExpressResponse) => { + res.send('Backend API Server is running 정상 구동 중입니다.'); + }); + + // 1. 보안 헤더 (Helmet) - XSS 방지 및 기본 웹 보안 + app.use(helmet()); + + // 2. CORS — 기본 구성은 프론트와 API 가 같은 도메인이라(브라우저는 /api 상대경로로 호출) 필요 없다. + // 다른 오리진에서 호출해야 할 때만 루트 .env 의 CORS_ORIGIN 에 콤마로 나열한다 (shared/config/cors.config.ts) + app.enableCors(buildCorsOptions()); + + // 3. Rate Limiting 은 AppModule 의 ThrottlerGuard(APP_GUARD)로 일원화되어 있다. + // 라우트 단위 제어(@Throttle / @SkipThrottle)가 가능하고, 한도 초과는 REQ_001(429)로 응답된다. + // (전역 예외 필터가 429 → REQ_001 로 매핑한다 — .claude/rules/error-codes.md) + + // 4. 전역 DTO 유효성 파이프 (강력한 검증 단계) + app.useGlobalPipes( + new ValidationPipe({ + whitelist: true, // DTO에 불필요한 값이 오면 삭제 + forbidNonWhitelisted: true, // DTO에 없는 필드가 주입되면 400 에러 발생 + transform: true, // 네트워크 데이터를 DTO나 기본 타입으로 자동 변환 + }), + ); + + // 5. 프론트엔드 연동을 위한 규격화된 에러 & 성공 페이로드 인터셉터 적용 + app.useGlobalFilters(new HttpExceptionFilter()); + app.useGlobalInterceptors(new TransformInterceptor(app.get(Reflector))); +} diff --git a/backend/src/main.ts b/backend/src/main.ts index a760292..18dfb7a 100644 --- a/backend/src/main.ts +++ b/backend/src/main.ts @@ -1,92 +1,52 @@ import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; -import { Logger, RequestMethod, ValidationPipe } from '@nestjs/common'; -import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; +import { Logger } from '@nestjs/common'; import { WinstonModule } from 'nest-winston'; -import helmet from 'helmet'; -import type { - Express, - Request as ExpressRequest, - Response as ExpressResponse, -} from 'express'; -import { Reflector } from '@nestjs/core'; - -import { HttpExceptionFilter } from '@/common/filters/http-exception.filter'; -import { TransformInterceptor } from '@/common/interceptors/transform.interceptor'; -import { buildCorsOptions } from '@/shared/config/cors.config'; +import { configureApp, GLOBAL_PREFIX } from '@/app.setup'; +import { + isSwaggerEnabled, + setupSwagger, + SWAGGER_PATH, +} from '@/shared/config/swagger.config'; import { winstonConfig } from '@/shared/logger/winston.config'; +import { parsePositiveInt } from '@/shared/utils/env'; + +/** 루트 .env 에 BACKEND_PORT 가 없을 때만 쓰는 기본 포트 */ +const DEFAULT_PORT = 3000; async function bootstrap() { const app = await NestFactory.create(AppModule, { logger: WinstonModule.createLogger(winstonConfig), }); - // 리버스 프록시 뒤에서 실제 클라이언트 IP 를 식별한다 (rate limit 이 IP 기준이다). - // 운영은 Nginx Proxy Manager → backend 로 한 번 거친다 (Custom location 이 X-Forwarded-For 에 클라이언트 IP 를 싣는다). - const expressApp = app.getHttpAdapter().getInstance() as Express; - expressApp.set('trust proxy', 1); + // 보안 헤더·CORS·prefix·검증 파이프·응답 래퍼 등 전역 설정 — e2e 테스트와 같은 함수를 쓴다 (app.setup.ts) + configureApp(app); - // 글로벌 prefix — 모든 라우트가 /api/* 로 정규화됨 (Flutter, Web 양쪽 baseURL과 일치) - // 리버스 프록시(운영 NPM · 개발 vite)는 /api 로 시작하는 요청을 경로 그대로 넘기므로 이 prefix 와 맞물려 있다. - app.setGlobalPrefix('api', { - // 헬스체크 / 루트 상태 엔드포인트는 prefix 미적용 - exclude: [{ path: '/', method: RequestMethod.GET }], - }); + // Swagger API 문서 — 운영에서는 기본으로 끈다 (shared/config/swagger.config.ts) + const swaggerEnabled = isSwaggerEnabled(); + if (swaggerEnabled) setupSwagger(app); - // 기본 주소('/') 접속 시 상태 확인용 텍스트 응답 추가 - expressApp.get('/', (_req: ExpressRequest, res: ExpressResponse) => { - res.send('Backend API Server is running 정상 구동 중입니다.'); - }); - - // 1. 보안 헤더 (Helmet) - XSS 방지 및 기본 웹 보안 - app.use(helmet()); - - // 2. CORS — 기본 구성은 프론트와 API 가 같은 도메인이라(브라우저는 /api 상대경로로 호출) 필요 없다. - // 다른 오리진에서 호출해야 할 때만 루트 .env 의 CORS_ORIGIN 에 콤마로 나열한다 (shared/config/cors.config.ts) - app.enableCors(buildCorsOptions()); - - // 3. Rate Limiting 은 AppModule 의 ThrottlerGuard(APP_GUARD)로 일원화되어 있다. - // 라우트 단위 제어(@Throttle / @SkipThrottle)가 가능하고, 한도 초과는 REQ_001(429)로 응답된다. - // (전역 예외 필터가 429 → REQ_001 로 매핑한다 — .claude/rules/error-codes.md) - - // 4. 전역 DTO 유효성 파이프 (강력한 검증 단계) - app.useGlobalPipes( - new ValidationPipe({ - whitelist: true, // DTO에 불필요한 값이 오면 삭제 - forbidNonWhitelisted: true, // DTO에 없는 필드가 주입되면 400 에러 발생 - transform: true, // 네트워크 데이터를 DTO나 기본 타입으로 자동 변환 - }), - ); - - // 5. 프론트엔드 연동을 위한 규격화된 에러 & 성공 페이로드 인터셉터 적용 - app.useGlobalFilters(new HttpExceptionFilter()); - app.useGlobalInterceptors(new TransformInterceptor(app.get(Reflector))); - - // 6. Swagger API 문서 설정 - const config = new DocumentBuilder() - .setTitle('Backend API Documentation') - .setDescription('The API documentation conforming to the global guidelines') - .setVersion('1.0') - .addBearerAuth() - .build(); - const document = SwaggerModule.createDocument(app, config); - SwaggerModule.setup('api-docs', app, document); - - // 7. Graceful shutdown — SIGTERM 수신 시 새 요청을 받지 않고 - // 처리 중인 요청을 마친 뒤 DB/Redis 커넥션을 정리하고 종료한다. - // (이 설정이 없으면 배포·재시작 때 처리 중이던 요청이 그대로 끊긴다) + // Graceful shutdown — SIGTERM 수신 시 새 요청을 받지 않고 + // 처리 중인 요청을 마친 뒤 DB/Redis 커넥션을 정리하고 종료한다. + // (이 설정이 없으면 배포·재시작 때 처리 중이던 요청이 그대로 끊긴다) app.enableShutdownHooks(); - // 종료 로그는 ShutdownLogger(OnApplicationShutdown)가 남긴다. + // 종료 로그는 ShutdownLogger(OnApplicationShutdown)가 남긴다. - const port = Number(process.env.PORT ?? 3000); + // compose 가 미정의 변수를 빈 문자열로 주입하므로 parsePositiveInt 로 방어한다 (Number('') 는 0 → 임의 포트) + const port = parsePositiveInt(process.env.PORT, DEFAULT_PORT); await app.listen(port, '0.0.0.0'); - Logger.log(`🚀 Backend running on http://localhost:${port}/api`, 'Bootstrap'); Logger.log( - `📘 Swagger docs at http://localhost:${port}/api-docs`, + `🚀 Backend running on http://localhost:${port}/${GLOBAL_PREFIX}`, 'Bootstrap', ); + if (swaggerEnabled) { + Logger.log( + `📘 Swagger docs at http://localhost:${port}/${SWAGGER_PATH}`, + 'Bootstrap', + ); + } } void bootstrap(); diff --git a/backend/src/modules/health/health.controller.spec.ts b/backend/src/modules/health/health.controller.spec.ts index 9cd9f36..59c4d20 100644 --- a/backend/src/modules/health/health.controller.spec.ts +++ b/backend/src/modules/health/health.controller.spec.ts @@ -1,4 +1,8 @@ -import { HttpStatus, ServiceUnavailableException } from '@nestjs/common'; +import { + HttpStatus, + Logger, + ServiceUnavailableException, +} from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { HealthCheckResult, @@ -29,6 +33,15 @@ describe('HealthController', () => { let check: jest.Mock; let res: { status: jest.Mock }; + beforeAll(() => { + // 의도된 실패의 error 로그가 테스트 출력을 오염시키지 않도록 억제 + jest.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined); + }); + + afterAll(() => { + jest.restoreAllMocks(); + }); + beforeEach(async () => { check = jest.fn(); res = { status: jest.fn() }; @@ -74,6 +87,28 @@ describe('HealthController', () => { expect(JSON.stringify(result)).toContain('database'); }); + it('운영에서는 구성요소별 status 만 노출한다 (오류 문구에 내부 주소·계정이 담길 수 있다)', async () => { + const originalEnv = process.env.NODE_ENV; + process.env.NODE_ENV = 'production'; + check.mockRejectedValue(new ServiceUnavailableException(downResult)); + + try { + const result = await controller.check(res as unknown as Response); + + expect(res.status).toHaveBeenCalledWith(HttpStatus.SERVICE_UNAVAILABLE); + // 어느 구성요소가 죽었는지는 그대로 보인다 + expect(result).toEqual({ + status: 'error', + info: {}, + error: { database: { status: 'down' } }, + details: { database: { status: 'down' } }, + }); + expect(JSON.stringify(result)).not.toContain('timeout'); + } finally { + process.env.NODE_ENV = originalEnv; + } + }); + it('terminus 예외가 아닌 오류는 전역 필터로 넘긴다', async () => { check.mockRejectedValue(new Error('예상치 못한 오류')); diff --git a/backend/src/modules/health/health.controller.ts b/backend/src/modules/health/health.controller.ts index 03c2e29..7c4b0f8 100644 --- a/backend/src/modules/health/health.controller.ts +++ b/backend/src/modules/health/health.controller.ts @@ -2,6 +2,7 @@ import { Controller, Get, HttpStatus, + Logger, Res, ServiceUnavailableException, } from '@nestjs/common'; @@ -11,17 +12,46 @@ import { HealthCheck, HealthCheckResult, HealthCheckService, + HealthIndicatorResult, TypeOrmHealthIndicator, } from '@nestjs/terminus'; import type { Response } from 'express'; import { SkipTransform } from '@/common/decorators/skip-transform.decorator'; +import { isProductionEnv } from '@/shared/utils/env'; // DB ping 타임아웃 — 기본값 1000ms 는 너무 짧다. // 커넥션 풀의 유휴 커넥션이 정리된 뒤(idleTimeoutMillis) 재연결하는 경우 1초를 넘겨 // 정상인 DB 를 down 으로 오판하고 헬스체크가 간헐적으로 실패한다. const DB_PING_TIMEOUT_MS = 5_000; +/** 구성요소별 결과에서 status 만 남긴다 */ +function keepStatusOnly( + section: Partial | undefined, +): HealthIndicatorResult { + return Object.fromEntries( + Object.entries(section ?? {}).flatMap(([key, value]) => + value ? [[key, { status: value.status }]] : [], + ), + ); +} + +/** + * 실패 결과에서 구성요소별 status 만 남기고 오류 문구(message 등)는 뺀다. + * 드라이버 오류 문구에는 내부 주소·DB 계정명이 담길 수 있다 ("connect ECONNREFUSED 172.18.0.2:5432"). + * 어느 구성요소가 죽었는지는 그대로 보이므로 모니터링에는 지장이 없다. 원인은 서버 로그에 남는다. + */ +export function hideFailureDetails( + result: HealthCheckResult, +): HealthCheckResult { + return { + status: result.status, + info: keepStatusOnly(result.info), + error: keepStatusOnly(result.error), + details: keepStatusOnly(result.details), + }; +} + /** * 헬스체크 엔드포인트 — Docker healthcheck, 모니터링 시스템이 읽는다. * @@ -30,6 +60,7 @@ const DB_PING_TIMEOUT_MS = 5_000; * * - 성공 200: `{ status: 'ok', info: { database: { status: 'up' } }, ... }` * - 실패 503: `{ status: 'error', error: { database: { status: 'down', message } }, ... }` + * (운영에서는 message 같은 상세를 빼고 구성요소별 status 만 노출한다 — 원인은 error 로그로 남긴다) * * 주기적으로 호출되므로 rate limit 대상에서도 제외한다 (한도를 소진시켜 실제 요청을 막으면 안 된다). */ @@ -38,6 +69,8 @@ const DB_PING_TIMEOUT_MS = 5_000; @ApiTags('Health') @Controller('health') export class HealthController { + private readonly logger = new Logger(HealthController.name); + constructor( private readonly health: HealthCheckService, private readonly db: TypeOrmHealthIndicator, @@ -64,8 +97,13 @@ export class HealthController { // terminus 는 실패 시 ServiceUnavailableException 을 던지며 본문에 상세 결과를 담는다. // 전역 필터가 SYS_001 로 덮어쓰지 않도록 여기서 직접 503 과 원본 본문을 반환한다. if (error instanceof ServiceUnavailableException) { + const result = error.getResponse() as HealthCheckResult; + + // 서버 책임 장애(DB 접속 실패 등)이므로 error 레벨 — 운영에서 응답에서 뺀 원인을 여기서 추적한다 + this.logger.error(`헬스체크 실패: ${JSON.stringify(result.error)}`); + res.status(HttpStatus.SERVICE_UNAVAILABLE); - return error.getResponse() as HealthCheckResult; + return isProductionEnv() ? hideFailureDetails(result) : result; } throw error; } diff --git a/backend/src/modules/upload/upload.config.spec.ts b/backend/src/modules/upload/upload.config.spec.ts index 768f47f..a2e11a1 100644 --- a/backend/src/modules/upload/upload.config.spec.ts +++ b/backend/src/modules/upload/upload.config.spec.ts @@ -1,4 +1,42 @@ -import { allowedExtensionList, isAllowedFile } from './upload.config'; +import fs, { existsSync, mkdtempSync, rmSync } from 'fs'; +import { tmpdir } from 'os'; +import { join } from 'path'; + +import { + allowedExtensionList, + ensureUploadDir, + isAllowedFile, +} from './upload.config'; + +describe('업로드 디렉터리 준비', () => { + let base: string; + + beforeEach(() => { + base = mkdtempSync(join(tmpdir(), 'upload-dir-')); + }); + + afterEach(() => { + jest.restoreAllMocks(); + rmSync(base, { recursive: true, force: true }); + }); + + it('없는 디렉터리는 하위 경로까지 만든다', () => { + const dir = join(base, 'nested', 'uploads'); + + ensureUploadDir(dir); + + expect(existsSync(dir)).toBe(true); + }); + + it('쓸 수 없으면 소유권을 맞추는 방법과 함께 기동을 멈춘다', () => { + // Linux 에서 root 소유로 만들어진 바인드 마운트를 흉내 낸다 (Windows 는 디렉터리 권한을 재현할 수 없다) + jest.spyOn(fs, 'accessSync').mockImplementation(() => { + throw new Error('EACCES: permission denied'); + }); + + expect(() => ensureUploadDir(base)).toThrow(/sudo chown -R 1000:1000/); + }); +}); describe('파일 업로드 검증', () => { it('확장자와 MIME 이 모두 맞으면 통과한다', () => { diff --git a/backend/src/modules/upload/upload.config.ts b/backend/src/modules/upload/upload.config.ts index 418461a..6f5aca2 100644 --- a/backend/src/modules/upload/upload.config.ts +++ b/backend/src/modules/upload/upload.config.ts @@ -1,3 +1,4 @@ +import { accessSync, constants, mkdirSync } from 'fs'; import { extname } from 'path'; import { parsePositiveInt } from '@/shared/utils/env'; @@ -12,6 +13,29 @@ import { parsePositiveInt } from '@/shared/utils/env'; /** 업로드 파일 저장 디렉터리 — 컨테이너에서는 compose 볼륨이 연결된다 */ export const UPLOAD_DIR = process.env.UPLOAD_DIR ?? './uploads'; +/** + * 업로드 디렉터리를 만들고 **쓰기 가능한지** 확인한다 — 안 되면 기동을 멈춘다 (fail-fast). + * + * 컨테이너의 앱은 비-root(node, uid 1000)로 실행된다. Linux 서버에서 compose 가 + * 없는 호스트 디렉터리를 바인드 마운트하면 root 소유로 만들어지므로, + * 그대로 두면 서버는 뜨지만 첫 업로드에서야 SYS_001 로 터진다. + */ +export function ensureUploadDir(dir: string): void { + try { + mkdirSync(dir, { recursive: true }); + accessSync(dir, constants.W_OK); + } catch (error) { + throw new Error( + [ + `업로드 디렉터리에 쓸 수 없어 서버를 시작할 수 없습니다: ${dir}`, + ` (${error instanceof Error ? error.message : String(error)})`, + '컨테이너의 앱은 node(uid 1000)로 실행됩니다. 호스트의 업로드 디렉터리 소유자를 맞춰 주세요:', + ' sudo chown -R 1000:1000 ./data/uploads # UPLOAD_DATA_DIR 을 바꿨다면 그 경로', + ].join('\n'), + ); + } +} + const MEGABYTE = 1024 * 1024; /** 파일 1개 최대 크기 (기본 5MB) */ diff --git a/backend/src/modules/upload/upload.module.ts b/backend/src/modules/upload/upload.module.ts index 137692b..614ddf3 100644 --- a/backend/src/modules/upload/upload.module.ts +++ b/backend/src/modules/upload/upload.module.ts @@ -2,20 +2,20 @@ import { Module } from '@nestjs/common'; import { MulterModule } from '@nestjs/platform-express'; import { randomUUID } from 'crypto'; import { diskStorage } from 'multer'; -import { mkdirSync } from 'fs'; import { extname } from 'path'; import { BusinessException } from '@/common/errors/business.exception'; import { MAX_FILE_SIZE_BYTES, UPLOAD_DIR, + ensureUploadDir, isAllowedFile, } from './upload.config'; import { UploadController } from './upload.controller'; import { UploadService } from './upload.service'; -// 저장 디렉터리는 기동 시 한 번 보장한다 (없으면 multer 가 매 요청 실패한다) -mkdirSync(UPLOAD_DIR, { recursive: true }); +// 저장 디렉터리는 기동 시 한 번 보장한다 (없거나 쓸 수 없으면 multer 가 매 요청 실패한다) +ensureUploadDir(UPLOAD_DIR); @Module({ imports: [ diff --git a/backend/src/shared/config/database.config.spec.ts b/backend/src/shared/config/database.config.spec.ts new file mode 100644 index 0000000..b215aef --- /dev/null +++ b/backend/src/shared/config/database.config.spec.ts @@ -0,0 +1,32 @@ +import { buildDatabaseOptions } from './database.config'; + +/** 풀 설정은 드라이버 옵션(extra)으로 넘어간다 */ +const poolMax = (): number => + (buildDatabaseOptions().extra as { max: number }).max; + +describe('buildDatabaseOptions — 커넥션 풀 크기', () => { + const original = process.env.DB_POOL_MAX; + + afterEach(() => { + if (original === undefined) { + delete process.env.DB_POOL_MAX; + } else { + process.env.DB_POOL_MAX = original; + } + }); + + it('기본값은 10 이다 (PostgreSQL 기본 max_connections 100 을 앱 하나가 다 잡지 않게)', () => { + delete process.env.DB_POOL_MAX; + expect(poolMax()).toBe(10); + }); + + it('DB_POOL_MAX 로 조정할 수 있다', () => { + process.env.DB_POOL_MAX = '25'; + expect(poolMax()).toBe(25); + }); + + it('빈 값이면 기본값을 쓴다 (compose 가 미정의 변수를 빈 문자열로 넘긴다)', () => { + process.env.DB_POOL_MAX = ''; + expect(poolMax()).toBe(10); + }); +}); diff --git a/backend/src/shared/config/database.config.ts b/backend/src/shared/config/database.config.ts index 85962e5..3178fdc 100644 --- a/backend/src/shared/config/database.config.ts +++ b/backend/src/shared/config/database.config.ts @@ -1,7 +1,7 @@ import { join } from 'path'; import { DataSourceOptions } from 'typeorm'; -import { parsePositiveInt } from '@/shared/utils/env'; +import { isProductionEnv, parsePositiveInt } from '@/shared/utils/env'; /** * DB 접속 설정 — 앱(TypeOrmModule)과 CLI(data-source.ts)가 **같은 설정을 공유**한다. @@ -19,17 +19,21 @@ const DEV_DB_DEFAULTS = { database: 'project_db', } as const; -/** 커넥션 풀 설정 */ -const POOL_OPTIONS = { - max: 100, +/** + * 커넥션 풀 크기 기본값 — node-postgres 의 기본값과 같다. + * + * PostgreSQL 의 기본 max_connections 는 100 이다. 풀을 100 으로 두면 앱 하나가 접속을 다 잡아 + * 마이그레이션 CLI·psql·두 번째 인스턴스가 "too many clients" 로 붙지 못한다. + * 인스턴스 수 × DB_POOL_MAX 에 여유분을 더한 값이 max_connections 를 넘지 않게 루트 .env 에서 조정한다. + */ +const DEFAULT_POOL_MAX = 10; + +/** 커넥션 풀 타임아웃 */ +const POOL_TIMEOUTS = { connectionTimeoutMillis: 5000, idleTimeoutMillis: 30000, } as const; -export function isProductionEnv(): boolean { - return process.env.NODE_ENV === 'production'; -} - /** * 스키마 자동 동기화 사용 여부. * @@ -72,7 +76,11 @@ export function buildDatabaseOptions(): DataSourceOptions { // 운영 배포 시 미적용 마이그레이션을 자동 실행한다 migrationsRun: isProduction, logging: !isProduction, - extra: { ...POOL_OPTIONS }, + extra: { + ...POOL_TIMEOUTS, + // compose 가 미정의 변수를 빈 문자열로 주입하므로 parsePositiveInt 로 방어한다 + max: parsePositiveInt(process.env.DB_POOL_MAX, DEFAULT_POOL_MAX), + }, entities: paths.entities, migrations: paths.migrations, }; diff --git a/backend/src/shared/config/env.validation.spec.ts b/backend/src/shared/config/env.validation.spec.ts index 8d3cba2..a27bec8 100644 --- a/backend/src/shared/config/env.validation.spec.ts +++ b/backend/src/shared/config/env.validation.spec.ts @@ -32,6 +32,22 @@ describe('validateEnv', () => { validateEnv({ NODE_ENV: 'development', THROTTLE_LIMIT: '' }), ).not.toThrow(); }); + + it('DB 커넥션 풀 크기도 양의 정수여야 한다', () => { + expect(() => + validateEnv({ NODE_ENV: 'development', DB_POOL_MAX: '0' }), + ).toThrow(/DB_POOL_MAX 는 양의 정수/); + }); + + it('SWAGGER_ENABLED 는 true/false 만 받는다 (오타가 기본값으로 묻히지 않게)', () => { + expect(() => + validateEnv({ NODE_ENV: 'development', SWAGGER_ENABLED: 'ture' }), + ).toThrow(/SWAGGER_ENABLED 는 true 또는 false/); + + expect(() => + validateEnv({ NODE_ENV: 'development', SWAGGER_ENABLED: '' }), + ).not.toThrow(); + }); }); describe('CORS_ORIGIN 형식 (모든 환경)', () => { diff --git a/backend/src/shared/config/env.validation.ts b/backend/src/shared/config/env.validation.ts index c804e58..a19030b 100644 --- a/backend/src/shared/config/env.validation.ts +++ b/backend/src/shared/config/env.validation.ts @@ -24,10 +24,14 @@ const REQUIRED_IN_PRODUCTION = [ const POSITIVE_INT_KEYS = [ 'PORT', 'DB_PORT', + 'DB_POOL_MAX', 'THROTTLE_TTL_MS', 'THROTTLE_LIMIT', ] as const; +/** 값이 있다면 true/false 여야 하는 키 — 오타(ture 등)가 조용히 기본값으로 처리되지 않게 한다 */ +const BOOLEAN_KEYS = ['SWAGGER_ENABLED'] as const; + /** 운영 환경에서 placeholder 로 남아 있으면 안 되는 키 */ const NO_PLACEHOLDER_IN_PRODUCTION = [ 'DB_PASSWORD', @@ -99,7 +103,17 @@ export function validateEnv( } } - // 2. CORS 오리진 형식 — 브라우저 Origin 헤더와 모양이 다르면 절대 일치하지 않아 **조용히** 막힌다 + // 2. 참/거짓 값 — 비어 있으면 코드의 기본 동작을 따른다 + for (const key of BOOLEAN_KEYS) { + const value = readString(config, key); + if (value !== undefined && value !== 'true' && value !== 'false') { + errors.push( + `${key} 는 true 또는 false 여야 합니다. (현재 값: "${value}")`, + ); + } + } + + // 3. CORS 오리진 형식 — 브라우저 Origin 헤더와 모양이 다르면 절대 일치하지 않아 **조용히** 막힌다 for (const origin of parseCorsOrigins(readString(config, 'CORS_ORIGIN'))) { if (!isValidOrigin(origin)) { errors.push( @@ -109,14 +123,14 @@ export function validateEnv( } if (isProduction) { - // 3. 운영 필수값 — 없으면 기동 실패 + // 4. 운영 필수값 — 없으면 기동 실패 for (const key of REQUIRED_IN_PRODUCTION) { if (readString(config, key) === undefined) { errors.push(`${key} 가 설정되지 않았습니다. (운영 환경 필수)`); } } - // 4. 예시 파일의 placeholder 가 그대로 배포되는 것을 막는다 + // 5. 예시 파일의 placeholder 가 그대로 배포되는 것을 막는다 for (const key of NO_PLACEHOLDER_IN_PRODUCTION) { const value = readString(config, key); if (value !== undefined && looksLikePlaceholder(value)) { @@ -126,7 +140,7 @@ export function validateEnv( } } - // 5. 공개 주소가 로컬 주소·예시 도메인으로 남은 채 배포되는 것을 막는다 + // 6. 공개 주소가 로컬 주소·예시 도메인으로 남은 채 배포되는 것을 막는다 const allowLocalhostUrl = readString(config, ALLOW_LOCALHOST_URL_KEY) === 'true'; diff --git a/backend/src/shared/config/swagger.config.spec.ts b/backend/src/shared/config/swagger.config.spec.ts new file mode 100644 index 0000000..d737c07 --- /dev/null +++ b/backend/src/shared/config/swagger.config.spec.ts @@ -0,0 +1,24 @@ +import { isSwaggerEnabled } from './swagger.config'; + +describe('isSwaggerEnabled', () => { + it('운영에서는 기본으로 끈다 (API 구조 전체가 공개되므로)', () => { + expect(isSwaggerEnabled({ NODE_ENV: 'production' })).toBe(false); + expect( + isSwaggerEnabled({ NODE_ENV: 'production', SWAGGER_ENABLED: '' }), + ).toBe(false); + }); + + it('운영이 아니면 기본으로 켠다', () => { + expect(isSwaggerEnabled({ NODE_ENV: 'development' })).toBe(true); + expect(isSwaggerEnabled({})).toBe(true); + }); + + it('SWAGGER_ENABLED 를 명시하면 환경과 무관하게 따른다', () => { + expect( + isSwaggerEnabled({ NODE_ENV: 'production', SWAGGER_ENABLED: 'true' }), + ).toBe(true); + expect( + isSwaggerEnabled({ NODE_ENV: 'development', SWAGGER_ENABLED: 'false' }), + ).toBe(false); + }); +}); diff --git a/backend/src/shared/config/swagger.config.ts b/backend/src/shared/config/swagger.config.ts new file mode 100644 index 0000000..14fd3ac --- /dev/null +++ b/backend/src/shared/config/swagger.config.ts @@ -0,0 +1,41 @@ +import { INestApplication } from '@nestjs/common'; +import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; + +import { isProductionEnv } from '@/shared/utils/env'; + +/** + * Swagger UI 경로. + * 같은 도메인 구성에서는 리버스 프록시의 location /api 접두어 매칭에 함께 걸려 백엔드로 간다. + */ +export const SWAGGER_PATH = 'api-docs'; + +/** + * Swagger 문서 노출 여부. + * 문서는 API 구조 전체(경로·파라미터·스키마)를 보여주므로 **운영에서는 기본으로 끈다.** + * + * - SWAGGER_ENABLED=true → 항상 켠다 (운영에서 켤 때는 NPM Access List 등으로 접근을 제한한다) + * - SWAGGER_ENABLED=false → 항상 끈다 + * - 비어 있음 → 운영이 아니면 켠다 + */ +export function isSwaggerEnabled( + env: NodeJS.ProcessEnv = process.env, +): boolean { + const flag = env.SWAGGER_ENABLED?.trim(); + if (flag === 'true') return true; + if (flag === 'false') return false; + + return !isProductionEnv(env); +} + +/** Swagger 문서를 SWAGGER_PATH 에 붙인다 */ +export function setupSwagger(app: INestApplication): void { + const config = new DocumentBuilder() + .setTitle('Backend API Documentation') + .setDescription('The API documentation conforming to the global guidelines') + .setVersion('1.0') + .addBearerAuth() + .build(); + + const document = SwaggerModule.createDocument(app, config); + SwaggerModule.setup(SWAGGER_PATH, app, document); +} diff --git a/backend/src/shared/utils/env.ts b/backend/src/shared/utils/env.ts index 366f163..509bce8 100644 --- a/backend/src/shared/utils/env.ts +++ b/backend/src/shared/utils/env.ts @@ -20,3 +20,11 @@ export function parsePositiveInt( return parsed; } + +/** + * 운영 환경인지 확인한다. + * NODE_ENV 는 compose 가 루트 APP_ENV 로 주입한다 (development | production). + */ +export function isProductionEnv(env: NodeJS.ProcessEnv = process.env): boolean { + return env.NODE_ENV === 'production'; +} diff --git a/backend/test/app.e2e-spec.ts b/backend/test/app.e2e-spec.ts index 7f6875a..9b69239 100644 --- a/backend/test/app.e2e-spec.ts +++ b/backend/test/app.e2e-spec.ts @@ -1,14 +1,11 @@ -import { INestApplication, ValidationPipe } from '@nestjs/common'; -import { Reflector } from '@nestjs/core'; +import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import request from 'supertest'; import type { Response } from 'supertest'; import { App } from 'supertest/types'; import { AppModule } from '@/app.module'; -import { HttpExceptionFilter } from '@/common/filters/http-exception.filter'; -import { TransformInterceptor } from '@/common/interceptors/transform.interceptor'; -import { RequestIdMiddleware } from '@/common/middleware/request-id.middleware'; +import { configureApp } from '@/app.setup'; /** * 세 플랫폼이 공유하는 응답 계약을 실제 HTTP 요청으로 검증한다. @@ -44,18 +41,10 @@ describe('응답 계약 (e2e)', () => { app = moduleFixture.createNestApplication(); - // main.ts 와 동일한 전역 설정을 적용해야 실제 응답과 같아진다 - app.setGlobalPrefix('api'); - app.use(new RequestIdMiddleware().use.bind(new RequestIdMiddleware())); - app.useGlobalPipes( - new ValidationPipe({ - whitelist: true, - forbidNonWhitelisted: true, - transform: true, - }), - ); - app.useGlobalFilters(new HttpExceptionFilter()); - app.useGlobalInterceptors(new TransformInterceptor(app.get(Reflector))); + // main.ts 와 같은 전역 설정 함수를 그대로 쓴다 (app.setup.ts). + // 여기서 설정을 따로 흉내 내면 둘이 어긋나도 테스트는 통과해 버린다. + // 추적 ID 는 AppModule 의 RequestIdMiddleware 가 붙인다 — 운영과 같은 경로다. + configureApp(app); await app.init(); }); diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml index 35bd0c5..0e9f434 100644 --- a/docker-compose.dev.yml +++ b/docker-compose.dev.yml @@ -48,7 +48,6 @@ services: command: npm run start:dev ports: - "${BACKEND_PORT}:${BACKEND_PORT}" - - "${WEBSOCKET_PORT}:${WEBSOCKET_PORT}" environment: - CHOKIDAR_USEPOLLING=true - WATCHPACK_POLLING=true diff --git a/docker-compose.yml b/docker-compose.yml index 5ad85ff..ebc185e 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -45,7 +45,10 @@ services: memory: 512m # ---------------------------------------- - # 2. Backend (HTTP API & WebSocket 통합) — NPM Custom location /api 의 대상 + # 2. Backend (HTTP API) — NPM Custom location /api 의 대상 + # + # WebSocket 을 도입할 때도 별도 포트를 열지 않는다. 게이트웨이를 HTTP 서버에 붙이고 + # 경로를 /api 아래에 두면 같은 도메인·같은 location 을 그대로 탄다 (.claude/skills/nestjs/SKILL.md) # ---------------------------------------- backend: container_name: ${PROJECT_NAME}-backend @@ -54,7 +57,6 @@ services: dockerfile: Dockerfile expose: - "${BACKEND_PORT}" - - "${WEBSOCKET_PORT}" # PID 1 을 tini 로 두어 SIGTERM 이 애플리케이션까지 확실히 전달되게 한다 (graceful shutdown) init: true # 처리 중인 요청을 마칠 시간 — 초과하면 SIGKILL (기본 10초) @@ -64,7 +66,8 @@ services: environment: - NODE_ENV=${APP_ENV} - PORT=${BACKEND_PORT} - - WEBSOCKET_PORT=${WEBSOCKET_PORT} + # 비어 있으면 운영에서만 Swagger(/api-docs)를 끈다 — true/false 로 강제할 수 있다 + - SWAGGER_ENABLED=${SWAGGER_ENABLED:-} # 같은 도메인 구성에서는 비어 있다 — 다른 오리진에서 호출할 때만 콤마로 나열 - CORS_ORIGIN=${CORS_ORIGIN:-} # 앱이 직접 쓰지는 않는다. API 를 별도 도메인으로 분리했을 때 로컬 주소가 남은 채 @@ -79,6 +82,7 @@ services: - DB_USER=${DB_USER} - DB_PASSWORD=${DB_PASSWORD} - DB_NAME=${DB_NAME} + - DB_POOL_MAX=${DB_POOL_MAX:-10} - DB_SYNCHRONIZE=${DB_SYNCHRONIZE:-false} - UPLOAD_DIR=/app/uploads - UPLOAD_MAX_SIZE_MB=${UPLOAD_MAX_SIZE_MB:-5} @@ -86,6 +90,9 @@ services: - REDIS_PORT=6379 - REDIS_PASSWORD=${REDIS_PASSWORD} # 업로드 파일은 컨테이너 재생성과 무관하게 보존되어야 한다 + # ⚠️ Linux 서버: 앱은 node(uid 1000)로 돈다. 호스트 디렉터리가 없으면 Docker 가 root 소유로 만들어 + # 기동이 실패하므로(업로드 디렉터리 쓰기 검사) 처음 한 번 소유자를 맞춘다: + # mkdir -p data/uploads && sudo chown 1000:1000 data/uploads volumes: - ${UPLOAD_DATA_DIR:-./data/uploads}:/app/uploads restart: unless-stopped diff --git a/frontend/.dockerignore b/frontend/.dockerignore new file mode 100644 index 0000000..6676cca --- /dev/null +++ b/frontend/.dockerignore @@ -0,0 +1,25 @@ +# ========================================== +# 빌드 컨텍스트에서 제외할 파일 +# +# Dockerfile 의 `COPY . .` 가 아래 항목까지 이미지에 넣지 않도록 막는다. +# ========================================== + +# 의존성·빌드 산출물 — 컨테이너 안에서 npm ci·빌드를 다시 한다. +# 호스트(Windows) node_modules 가 섞이면 네이티브 바이너리가 리눅스용을 덮어써 빌드가 깨진다. +node_modules +dist +coverage + +# 호스트 빌드용 env — 컨테이너 빌드의 값은 루트 .env 가 build arg 로만 넣는다 (SSOT: .claude/rules/env-structure.md) +# 여기서 막지 않으면 호스트에만 둔 로컬 설정이 운영 번들에 섞여 들어간다. +.env +.env.* + +# 로그 +logs +*.log + +# 에디터·OS (.vscode/extensions.json 은 빌드에 쓰이지 않는다) +.vscode +.idea +.DS_Store diff --git a/frontend/Dockerfile b/frontend/Dockerfile index ff92b33..294319c 100644 --- a/frontend/Dockerfile +++ b/frontend/Dockerfile @@ -1,8 +1,8 @@ -FROM node:20-alpine AS build-stage +FROM node:24-alpine AS build-stage WORKDIR /app -# 호스트의 npm 11 이 작성한 package-lock.json 형식과 호환되도록 npm 을 11 로 업그레이드 -# (전역 설치는 root 권한이 필요하므로 USER 전환 전에 수행) +# 호스트의 npm 11 이 작성한 package-lock.json 형식과 호환되도록 npm 을 11 로 고정 +# (베이스 이미지의 번들 npm 이 바뀌어도 lock 형식이 어긋나지 않게 한다. 전역 설치는 root 권한이 필요하므로 USER 전환 전에 수행) RUN npm install -g npm@11 # 개발 환경(docker-compose.dev.yml)은 이 스테이지에서 vite dev 서버를 구동하므로 비-root 로 전환한다. @@ -13,6 +13,7 @@ USER node COPY --chown=node:node package*.json ./ RUN npm ci +# 호스트의 node_modules·dist·.env 는 .dockerignore 로 제외된다 COPY --chown=node:node . . ARG BUILD_MODE=production diff --git a/frontend/nginx.conf b/frontend/nginx.conf index ab077c8..2f6bca4 100644 --- a/frontend/nginx.conf +++ b/frontend/nginx.conf @@ -3,8 +3,15 @@ server { listen 8080; server_name localhost; + # 빌드 산출물 위치 — 모든 location 이 공유한다 + root /usr/share/nginx/html; + # ---------------------------------------- # 보안 헤더 + # + # ⚠️ nginx 는 location 안에 add_header 가 하나라도 있으면 여기(server)의 add_header 를 + # **하나도 상속하지 않는다.** 그래서 아래 location 들은 캐시 정책을 add_header 대신 + # expires 로 지정한다 — location 에 add_header 를 넣으면 그 응답에서 보안 헤더가 전부 사라진다. # ---------------------------------------- add_header X-Frame-Options "SAMEORIGIN" always; add_header X-Content-Type-Options "nosniff" always; @@ -46,19 +53,31 @@ server { return 404; } + # ---------------------------------------- + # 캐시 정책 — add_header 대신 expires 를 쓴다 (위 보안 헤더 주의 참조) + # ---------------------------------------- + + # SPA 진입점 — 매번 재검증한다 (Cache-Control: no-cache). + # 배포 직후 옛 index.html 이 캐시에 남으면 이미 지워진 해시 파일을 요청해 빈 화면이 된다. + # (/ 접속과 SPA 폴백도 내부적으로 /index.html 로 넘어오므로 모두 여기에 걸린다) + location = /index.html { + expires -1; + } + + # 빌드 산출물(vite 의 assets 디렉터리) — 파일명에 내용 해시가 붙어 내용이 바뀌면 이름도 바뀌므로 오래 캐시해도 안전하다. + # 없는 파일은 index.html 로 폴백하지 않고 404 — HTML 을 JS 로 받아 생기는 MIME 오류를 막는다. + # (public/ 에서 복사되는 favicon 등은 해시가 없으므로 여기에 넣지 않는다) + location /assets/ { + expires 1y; + try_files $uri =404; + } + # ---------------------------------------- # SPA 라우팅 # ---------------------------------------- location / { - root /usr/share/nginx/html; index index.html index.htm; try_files $uri $uri/ /index.html; - - # 정적 자원 캐싱 (SPA 빌드 산출물은 해시 파일명이라 장기 캐싱 가능) - location ~* \.(?:js|css|woff2?|ttf|svg|png|jpg|jpeg|gif|ico)$ { - expires 30d; - add_header Cache-Control "public, immutable"; - } } error_page 500 502 503 504 /50x.html; diff --git a/frontend/src/composables/useApi.ts b/frontend/src/composables/useApi.ts index c95a444..aaaaa64 100644 --- a/frontend/src/composables/useApi.ts +++ b/frontend/src/composables/useApi.ts @@ -56,6 +56,20 @@ function isErrorCode(code: string): code is ErrorCode { return code in ERROR_CODE_MESSAGES } +/** + * 인터셉터가 정규화한 ApiError 인지 확인한다. + * 호출부의 catch 에서 code 로 분기하기 전에 쓴다 (API 가 아닌 오류도 catch 로 들어올 수 있다). + */ +export function isApiError(error: unknown): error is ApiError { + return ( + typeof error === 'object' && + error !== null && + 'code' in error && + typeof error.code === 'string' && + isErrorCode(error.code) + ) +} + /** 에러 코드 → 사용자 노출 문구. 사용자 문구는 이 사전에만 존재한다. */ export function getErrorMessage(code: string): string { return isErrorCode(code) diff --git a/frontend/src/composables/useUser.spec.ts b/frontend/src/composables/useUser.spec.ts new file mode 100644 index 0000000..9622bdf --- /dev/null +++ b/frontend/src/composables/useUser.spec.ts @@ -0,0 +1,45 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' + +import api, { type ApiError } from './useApi' +import { useUser } from './useUser' + +describe('useUser (도메인 composable 패턴)', () => { + afterEach(() => { + vi.restoreAllMocks() + }) + + it('성공하면 언래핑된 데이터를 돌려주고 에러 코드를 비운다', async () => { + const user = { id: 1, email: 'user@example.com', name: '홍길동' } + // 인터셉터가 { success, data } 를 벗긴 뒤의 값을 흉내 낸다 (axios 타입상 AxiosResponse 라 단언이 필요하다) + vi.spyOn(api, 'get').mockResolvedValue(user as never) + + const { getUser, errorCode, loading } = useUser() + + await expect(getUser(1)).resolves.toEqual(user) + expect(errorCode.value).toBeNull() + expect(loading.value).toBe(false) + }) + + it('실패하면 메시지가 아니라 에러 코드를 보관한다', async () => { + const error: ApiError = { + code: 'RES_001', + message: '요청하신 정보나 페이지를 찾을 수 없습니다.', + status: 404, + } + vi.spyOn(api, 'get').mockRejectedValue(error) + + const { getUser, errorCode } = useUser() + + await expect(getUser(999)).resolves.toBeNull() + expect(errorCode.value).toBe('RES_001') + }) + + it('API 가 아닌 오류는 폴백 코드(SYS_001)로 보관한다', async () => { + vi.spyOn(api, 'get').mockRejectedValue(new Error('예상치 못한 오류')) + + const { getUser, errorCode } = useUser() + + await expect(getUser(1)).resolves.toBeNull() + expect(errorCode.value).toBe('SYS_001') + }) +}) diff --git a/frontend/src/composables/useUser.ts b/frontend/src/composables/useUser.ts index 3588126..e0da312 100644 --- a/frontend/src/composables/useUser.ts +++ b/frontend/src/composables/useUser.ts @@ -1,5 +1,9 @@ import { ref } from 'vue' -import { useApi } from './useApi' +import { isApiError, useApi } from './useApi' +import { + FALLBACK_ERROR_CODE, + type ErrorCode, +} from '@/shared/constants/error-codes.generated' // 도메인별 API Composable 샘플 — 실제 도메인이 추가되면 이 패턴을 복제 export interface User { @@ -11,21 +15,23 @@ export interface User { export function useUser() { const api = useApi() const loading = ref(false) - const error = ref(null) + // 실패 시 에러 코드만 보관한다 — 화면은 code 로 분기하고, 알림 문구는 인터셉터가 사전에서 이미 띄웠다 + const errorCode = ref(null) async function getUser(id: number): Promise { loading.value = true - error.value = null + errorCode.value = null try { // 인터셉터에서 success/data 언래핑 후 데이터만 반환 return (await api.get(`/users/${id}`)) as unknown as User } catch (e) { - error.value = (e as Error)?.message ?? 'unknown error' + // 여기서 메시지를 새로 만들지 않는다 (.claude/rules/error-codes.md) + errorCode.value = isApiError(e) ? e.code : FALLBACK_ERROR_CODE return null } finally { loading.value = false } } - return { loading, error, getUser } + return { loading, errorCode, getUser } } diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts index 4a268a8..8731752 100644 --- a/frontend/vite.config.ts +++ b/frontend/vite.config.ts @@ -24,6 +24,16 @@ function parsePositiveInt(value: string | undefined, fallback: number): number { return parsed } +/** 콤마로 구분된 목록을 파싱한다 (공백·빈 항목 제거) */ +function parseList(value: string | undefined): string[] { + if (value === undefined) return [] + + return value + .split(',') + .map((entry) => entry.trim()) + .filter((entry) => entry !== '') +} + // https://vite.dev/config/ export default defineConfig(({ mode }) => { // 포트·주소의 SSOT 는 루트 `.env.{mode}` 다 (.claude/rules/env-structure.md). @@ -53,8 +63,11 @@ export default defineConfig(({ mode }) => { }, }, server: { - // ngrok 등 외부 도메인 접근 허용 (DNS Rebinding 보호 비활성화) - allowedHosts: true, + // dev 서버에 접근을 허용할 호스트. 기본(빈 목록)은 localhost·IP 접근만 허용한다. + // true 로 열면 vite 의 DNS rebinding 보호가 꺼져, 악성 사이트가 개발자의 브라우저를 거쳐 + // dev 서버(소스)와 /api 프록시(로컬 백엔드)에 닿을 수 있다. + // ngrok 같은 터널을 쓸 때만 루트 .env 의 DEV_ALLOWED_HOSTS 에 콤마로 적는다 (예: .ngrok-free.app) + allowedHosts: parseList(rootEnv.DEV_ALLOWED_HOSTS), // 루트 .env 의 FRONTEND_PORT 를 따른다. // 컨테이너로 띄울 때는 compose 의 `--port`(컨테이너 내부 고정 포트)가 이 값을 덮어쓴다. port: frontendPort,