Skip to content

[HOTFIX] secure, sameSite 값 환경변수 등록 #17

Merged
Takch02 merged 3 commits into
mainfrom
hotfix/secure_change
May 8, 2026
Merged

[HOTFIX] secure, sameSite 값 환경변수 등록 #17
Takch02 merged 3 commits into
mainfrom
hotfix/secure_change

Conversation

@Takch02

@Takch02 Takch02 commented May 8, 2026

Copy link
Copy Markdown
Contributor

Resolves #16

개요

개발 단계에서 지속적 로그인 풀리는 현상 발생

해결

  • Local 환경(HTTP) 에서 쿠키를 생성할 수 있도록 환경변수로 관리
  • NODE_ENV === production일 경우만 HTTPS 환경에서 쿠키를 줌.

Summary by CodeRabbit

릴리스 노트

  • 개선사항
    • 세션 쿠키 보안 설정을 실행 환경에 따라 자동으로 조정하도록 업데이트했습니다. 운영 환경에서는 강화된 보안 설정이 적용되고, 개발 환경에서는 개발 편의성을 위한 설정이 적용됩니다.

@coderabbitai

coderabbitai Bot commented May 8, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Rate limit exceeded

@Takch02 has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 48 minutes and 22 seconds before requesting another review.

You’ve run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 60da0d79-1077-40ce-9459-717cd1e9a955

📥 Commits

Reviewing files that changed from the base of the PR and between b6c974f and 5cb7d06.

📒 Files selected for processing (1)
  • src/main.ts
📝 Walkthrough

개요

Express 세션 쿠키의 보안 설정이 환경에 따라 동적으로 결정되도록 수정되었습니다. 프로덕션에서는 secure: truesameSite: "none"을 사용하고, 개발 환경에서는 secure: falsesameSite: "lax"를 적용합니다.

변경사항

세션 쿠키 보안 설정

Layer / File(s) Summary
환경 기반 쿠키 보안 설정
src/main.ts
세션 쿠키의 securesameSite 옵션이 NODE_ENV 환경변수를 기반으로 조건부 설정되어 프로덕션과 개발 환경의 보안 정책을 구분함.

보안 검토 포인트

  1. HTTPS 강제 여부: 프로덕션에서 secure: true로 설정하여 HTTPS 연결에서만 쿠키 전송을 보장합니다. ✅

  2. Cross-Site Request Forgery 방어:

    • 프로덕션에서 sameSite: "none"으로 설정 시, Secure 속성과 함께 명시적으로 크로스사이트 요청을 허용합니다.
    • 이는 의도적인 설정이라면 적절하나, XRPL 기반 국제 거래 플랫폼이므로 외부 도메인 통합이 필요한지 확인이 필요합니다.
  3. 개발 환경: 로컬 개발에서 HTTP 사용 시 secure: false로 설정하여 쿠키 전송이 가능하도록 합니다. ✅

가능 관련 이슈

코드 리뷰 난이도

🎯 1 (Trivial) | ⏱️ ~5 minutes

축하 시

🍪 쿠키도 환경을 생각한다네요
개발엔 편하게, 프로덕션은 철저하게
환경별 설정, 이제 더 똑똑해졌어요!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed 제목은 Pull Request의 주요 변경사항을 명확하게 반영하고 있습니다. 쿠키의 secure과 sameSite 값을 환경변수로 등록하는 것이 정확히 설명되어 있으며, [HOTFIX] 태그로 긴급 수정임을 나타냅니다.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch hotfix/secure_change

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/main.ts (2)

60-63: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

CORS origin: true + credentials: true 조합은 심각한 보안 취약점

origins"*"가 포함되면 origin: true가 설정되어 모든 출처에서의 인증 요청(세션 쿠키 포함)을 허용합니다. 이는 XRPL 결제가 포함된 B2B 플랫폼에서 CSRF 및 세션 탈취 위험을 크게 높입니다. credentials: true를 사용할 때는 허용 출처를 명시적인 도메인 목록으로만 제한해야 합니다.

🛡️ 허용 출처 명시적 제한 예시
   app.enableCors({
-    origin: origins.includes("*") ? true : origins,
+    origin: origins, // 와일드카드(*) 허용 금지; 환경변수에서 명시적 도메인만 설정
     credentials: true,
   });

환경변수(cors.origins)에 절대로 "*"가 포함되지 않도록 설정 유효성 검사를 추가하거나, 스타트업/도커 시작 시점에 경고를 출력하는 것을 권장합니다.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/main.ts` around lines 60 - 63, The CORS setup using app.enableCors with
origin: origins.includes("*") ? true : origins plus credentials: true permits
credentialed requests from any origin when cors.origins contains "*"; change
this by validating the origins array (the origins variable / cors.origins env)
at startup: if credentials is true (or credentials is always true in config)
reject or remove wildcard entries and require an explicit domain list, log a
clear error/warning and exit/startup-fail (or set credentials to false) so
app.enableCors is only called with an explicit origins array (not true) when
credentials are enabled; add a startup validation function to enforce
cors.origins does not include "*" and reference this check before calling
app.enableCors.

60-63: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

origin: true + credentials: true 조합 — XRPL 결제 플랫폼에서 심각한 보안 위험

origins 배열에 "*"가 포함될 경우 origin: true로 설정되어 모든 출처에서의 인증 요청(세션 쿠키 포함)이 허용됩니다. 해외 바이어와 국내 스타트업을 연결하는 B2B 플랫폼이며 XRPL 결제가 포함된 서비스에서 이 조합은 CSRF 및 세션 탈취 공격의 직접적인 경로가 됩니다. credentials: true 사용 시 허용 출처를 반드시 명시적인 도메인 목록으로만 제한해야 합니다.

🛡️ 와일드카드 출처 방어 예시
+  // credentials: true와 함께 wildcard origins는 허용 금지
+  if (origins.includes("*")) {
+    throw new Error("Wildcard CORS origin is not allowed when credentials are enabled");
+  }
+
   app.enableCors({
-    origin: origins.includes("*") ? true : origins,
+    origin: origins,
     credentials: true,
   });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/main.ts` around lines 60 - 63, The CORS config uses origin: true with
credentials: true when origins includes "*", which allows credentials for any
origin—change app.enableCors usage to restrict credentials to explicit
whitelisted domains: validate the origins array (variable origins) and if it
contains "*" do not set credentials: true (either set credentials: false or
reject wildcard); instead provide a whitelist-based origin handler (pass a
function that checks request origin against origins) so that app.enableCors({
origin, credentials }) only allows credentials for explicitly listed domains.
Ensure you update the code paths that reference app.enableCors, origins, origin,
and credentials to perform this whitelist check and fail-safe when wildcard is
present.
🧹 Nitpick comments (2)
src/main.ts (2)

49-50: 💤 Low value

process.env.NODE_ENVconfigService 대신 직접 사용

파일 내 다른 모든 설정값은 configService를 통해 읽지만, 변경된 두 줄만 process.env.NODE_ENV를 직접 참조하고 있습니다. NestJS의 ConfigModule을 통해 일관되게 관리하는 것을 권장합니다.

♻️ ConfigService를 통한 일관성 있는 접근
+  const isProduction = configService.get<string>("NODE_ENV") === "production";

   cookie: {
     httpOnly: true,
-    secure: process.env.NODE_ENV === "production",
-    sameSite: process.env.NODE_ENV === "production" ? "none" : "lax",
+    secure: isProduction,
+    sameSite: isProduction ? "none" : "lax",
     maxAge: sessionTtl * 1000,
   },
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/main.ts` around lines 49 - 50, The cookie options currently read
process.env.NODE_ENV directly for secure and sameSite; replace those direct env
accesses with the ConfigService so configuration is consistent—use the existing
configService (or the same ConfigService instance used elsewhere) to derive the
environment flag and compute secure and sameSite values for the cookie options
(the properties named secure and sameSite) instead of process.env.NODE_ENV.

49-50: ⚡ Quick win

express-session 1.19.0의 sameSite: 'auto'로 단순화 가능

express-session 1.19.0은 sameSite: 'auto' 옵션을 도입했으며, 이는 HTTPS 연결에서 자동으로 SameSite=None을, HTTP 연결에서 SameSite=Lax를 설정합니다. 현재 lines 49-50의 수동 조건 분기를 이 옵션으로 대체하면 코드가 단순해지고 trust proxy 설정과 연동되어 더 안정적으로 동작합니다.

♻️ `sameSite: 'auto'` 활용 예시
       cookie: {
         httpOnly: true,
-        secure: process.env.NODE_ENV === "production",
-        sameSite: process.env.NODE_ENV === "production" ? "none" : "lax",
+        secure: "auto",   // trust proxy 설정과 연동되어 자동으로 HTTPS 여부 판단
+        sameSite: "auto", // HTTPS → none, HTTP → lax 자동 처리
         maxAge: sessionTtl * 1000,
       },

secure: "auto" 역시 express-session 1.17.0+에서 지원되며, trust proxy 설정에 따라 자동으로 HTTPS/HTTP를 판단합니다.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/main.ts` around lines 49 - 50, Replace the manual environment checks for
cookie options with the built-in automatic mode: update the session options used
where you set secure and sameSite (the object passed to express-session in
main.ts) to use secure: "auto" and sameSite: "auto" instead of the ternary
branches, and ensure the Express app has trust proxy configured (app.set('trust
proxy', true)) so secure:auto and sameSite:auto can correctly detect HTTPS via
proxy.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/main.ts`:
- Around line 49-50: The session cookie options use secure/sameSite based on
NODE_ENV but the app never enables Express trust proxy, so behind a reverse
proxy req.secure will be false and secure cookies won't be sent; add a
conditional trust proxy setting (e.g., call app.set('trust proxy', 1) or
app.enable('trust proxy') when process.env.NODE_ENV === 'production') near the
Express app initialization so express-session and the secure/sameSite options
(the lines setting secure and sameSite) will honor X-Forwarded-Proto from
proxies.
- Around line 49-50: 프로덕션에서 secure 쿠키가 리버스 프록시(AWS ALB/nginx 등) 뒤에서도 정상 동작하도록
Express에 프록시를 신뢰하도록 설정해야 합니다; main.ts에서 app 변수(예: app = express())를 생성한 직후에
app.set('trust proxy', 1) 또는 적절한 값으로 프록시 신뢰를 설정하고 이 설정이 세션/쿠키 미들웨어를 등록하기 전에
적용되도록 하세요 — 현재 diff의 secure: process.env.NODE_ENV === "production" 및 sameSite
설정과 함께 사용되도록 위치를 조정하면 됩니다.

---

Outside diff comments:
In `@src/main.ts`:
- Around line 60-63: The CORS setup using app.enableCors with origin:
origins.includes("*") ? true : origins plus credentials: true permits
credentialed requests from any origin when cors.origins contains "*"; change
this by validating the origins array (the origins variable / cors.origins env)
at startup: if credentials is true (or credentials is always true in config)
reject or remove wildcard entries and require an explicit domain list, log a
clear error/warning and exit/startup-fail (or set credentials to false) so
app.enableCors is only called with an explicit origins array (not true) when
credentials are enabled; add a startup validation function to enforce
cors.origins does not include "*" and reference this check before calling
app.enableCors.
- Around line 60-63: The CORS config uses origin: true with credentials: true
when origins includes "*", which allows credentials for any origin—change
app.enableCors usage to restrict credentials to explicit whitelisted domains:
validate the origins array (variable origins) and if it contains "*" do not set
credentials: true (either set credentials: false or reject wildcard); instead
provide a whitelist-based origin handler (pass a function that checks request
origin against origins) so that app.enableCors({ origin, credentials }) only
allows credentials for explicitly listed domains. Ensure you update the code
paths that reference app.enableCors, origins, origin, and credentials to perform
this whitelist check and fail-safe when wildcard is present.

---

Nitpick comments:
In `@src/main.ts`:
- Around line 49-50: The cookie options currently read process.env.NODE_ENV
directly for secure and sameSite; replace those direct env accesses with the
ConfigService so configuration is consistent—use the existing configService (or
the same ConfigService instance used elsewhere) to derive the environment flag
and compute secure and sameSite values for the cookie options (the properties
named secure and sameSite) instead of process.env.NODE_ENV.
- Around line 49-50: Replace the manual environment checks for cookie options
with the built-in automatic mode: update the session options used where you set
secure and sameSite (the object passed to express-session in main.ts) to use
secure: "auto" and sameSite: "auto" instead of the ternary branches, and ensure
the Express app has trust proxy configured (app.set('trust proxy', true)) so
secure:auto and sameSite:auto can correctly detect HTTPS via proxy.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 6f48ce26-0c25-45c2-b722-5c147ff23771

📥 Commits

Reviewing files that changed from the base of the PR and between 6c746cf and b6c974f.

📒 Files selected for processing (1)
  • src/main.ts

Comment thread src/main.ts
@Takch02 Takch02 merged commit 62c9ef7 into main May 8, 2026
3 checks passed
@Takch02 Takch02 deleted the hotfix/secure_change branch May 8, 2026 12:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[HOTFIX] secure, sameSite 값 환경변수 등록

1 participant