Skip to content

Feature/task 159 anh#160

Merged
2 commits merged intodevfrom
feature/task-159_anh
Aug 29, 2025
Merged

Feature/task 159 anh#160
2 commits merged intodevfrom
feature/task-159_anh

Conversation

@anhlnp
Copy link
Copy Markdown
Collaborator

@anhlnp anhlnp commented Aug 27, 2025

Summary by CodeRabbit

  • Bug Fixes

    • Improved authentication cookies for more reliable login/logout across environments with environment-aware security settings and consistent path.
  • Chores

    • Expanded CORS support: allow localhost in non-production and requests without an origin; added OPTIONS method and X-Requested-With header; exposed Set-Cookie header for clients.
    • Added runtime logging for blocked origins to aid debugging.

@vercel
Copy link
Copy Markdown

vercel bot commented Aug 27, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
neurolearn-backend Ready Ready Preview Comment Aug 27, 2025 6:46am

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Aug 27, 2025

Walkthrough

Updates CORS handling to allow no-origin and localhost in non-production, extend allowed methods/headers, and log blocked origins. Adjusts logout cookie flags to be environment-aware and removes explicit domain. Extends JWT token option interface with an optional domain and adds it to exported token option objects.

Changes

Cohort / File(s) Summary
CORS configuration
src/app.ts
Revises CORS origin logic (allow no-origin, allow localhost in non-prod, log blocked), adds OPTIONS to methods, adds X-Requested-With to allowed headers, and exposes Set-Cookie.
Auth cookie handling
src/controllers/user.controller.ts
Updates logout cookie settings: remove explicit domain, set secure and sameSite based on NODE_ENV, and add path '/'.
JWT token options
src/utils/jwt.ts
Adds domain?: string to ITokenOptions; includes domain field on accessTokenOptions and refreshTokenOptions; minor formatting updates.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Client
  participant Server as Express App
  participant CORS as CORS Middleware

  Client->>Server: HTTP Request
  Server->>CORS: Validate Origin
  alt No Origin
    CORS-->>Server: Allow (no-origin)
  else Origin in allowedOrigins
    CORS-->>Server: Allow (whitelist)
  else Non-production and origin includes "localhost"
    CORS-->>Server: Allow (dev localhost)
  else Disallowed
    CORS-->>Server: Block (error "Not allowed by CORS")
    Server-->>Server: Log blocked origin
  end
  Server-->>Client: Response
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • fix: auth #146 — Also modifies src/utils/jwt.ts token cookie options to make secure/sameSite environment-aware; closely related to the new domain field addition.

Poem

In fields of code I twitch my nose,
CORS now knows which way the wind blows.
Cookies hop with safer might,
SameSite shifts by day and night.
Tokens snug in burrows warm—
Domain optional, no alarm.
Hippity-hop, we ship the form! 🐇🍪

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/task-159_anh

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (6)
src/app.ts (4)

63-67: Broaden localhost dev allowance to include 127.0.0.1 and ::1.

Covers common local setups beyond “localhost”.

Apply:

-            if (process.env.NODE_ENV !== 'production' && origin.includes('localhost')) {
+            if (
+                process.env.NODE_ENV !== 'production' &&
+                /^(https?:\/\/)?(localhost|127\.0\.0\.1|\[::1\])(?::\d+)?$/i.test(origin)
+            ) {
                 return callback(null, true);
             }

69-71: Avoid noisy logs in production.

Gate the log behind non-prod or use a logger with levels.

-            console.log('Blocked origin:', origin);
+            if (process.env.NODE_ENV !== 'production') {
+                console.log('Blocked origin:', origin);
+            }

73-76: Remove forbidden/ineffective CORS headers.

  • Request header “Cookie” cannot be set by JS; removing it avoids confusion.
  • “Set-Cookie” cannot be exposed to JS; Access-Control-Expose-Headers won’t make it readable.
-        methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
-        allowedHeaders: ['Content-Type', 'Authorization', 'Cookie', 'X-Requested-With'],
-        exposedHeaders: ['Set-Cookie']
+        methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
+        allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With']

45-47: Trim/clean ORIGIN env list.

Prevents subtle mismatches due to whitespace or empty entries.

-const allowedOrigins = Array.from(
-    new Set([...(process.env.ORIGIN?.split(',') || []), 'http://localhost:3000', 'http://localhost:8000'])
-);
+const allowedOrigins = Array.from(
+    new Set([
+        ...((process.env.ORIGIN?.split(',').map((s) => s.trim()).filter(Boolean)) || []),
+        'http://localhost:3000',
+        'http://localhost:8000'
+    ])
+);
src/utils/jwt.ts (1)

27-27: Use the existing isProd constant for consistency.

Minor readability win; no behavior change.

-    sameSite: process.env.NODE_ENV === 'production' ? 'none' : 'lax',
+    sameSite: isProd ? 'none' : 'lax',

Also applies to: 37-37

src/controllers/user.controller.ts (1)

245-257: Use a definitive cookie clear (expires epoch + maxAge: 0).

maxAge: 1 can be flaky. Setting both ensures removal across browsers while keeping attributes aligned.

-    res.cookie('access_token', '', {
-        secure: process.env.NODE_ENV === 'production',
-        sameSite: process.env.NODE_ENV === 'production' ? 'none' : 'lax',
-        httpOnly: true,
-        maxAge: 1,
-        path: '/'
-    });
+    res.cookie('access_token', '', {
+        secure: process.env.NODE_ENV === 'production',
+        sameSite: process.env.NODE_ENV === 'production' ? 'none' : 'lax',
+        httpOnly: true,
+        expires: new Date(0),
+        maxAge: 0,
+        path: '/'
+    });
-    res.cookie('refresh_token', '', {
-        secure: process.env.NODE_ENV === 'production',
-        sameSite: process.env.NODE_ENV === 'production' ? 'none' : 'lax',
-        httpOnly: true,
-        maxAge: 1,
-        path: '/'
-    });
+    res.cookie('refresh_token', '', {
+        secure: process.env.NODE_ENV === 'production',
+        sameSite: process.env.NODE_ENV === 'production' ? 'none' : 'lax',
+        httpOnly: true,
+        expires: new Date(0),
+        maxAge: 0,
+        path: '/'
+    });
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 157a420 and 99d301b.

📒 Files selected for processing (3)
  • src/app.ts (1 hunks)
  • src/controllers/user.controller.ts (1 hunks)
  • src/utils/jwt.ts (3 hunks)
🔇 Additional comments (2)
src/app.ts (1)

53-56: Allowing no-origin requests is OK given mobile/curl use-cases.

With credentials enabled, this path is fine. No change requested.

src/utils/jwt.ts (1)

12-13: Interface extension looks good.

Optional domain support is reasonable for future subdomain needs.

Comment on lines +27 to 29
sameSite: process.env.NODE_ENV === 'production' ? 'none' : 'lax',
domain: process.env.NODE_ENV === 'production' ? undefined : undefined // Let browser set domain automatically
};
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove domain: undefined — possible TS type error under strict mode.

domain?: string cannot be explicitly assigned undefined. Omit the field when not used, or make it string | undefined. Recommend omission for clarity.

 export const accessTokenOptions: ITokenOptions = {
   ...
-    sameSite: process.env.NODE_ENV === 'production' ? 'none' : 'lax',
-    domain: process.env.NODE_ENV === 'production' ? undefined : undefined // Let browser set domain automatically
+    sameSite: process.env.NODE_ENV === 'production' ? 'none' : 'lax'
 };

 export const refreshTokenOptions: ITokenOptions = {
   ...
-    sameSite: process.env.NODE_ENV === 'production' ? 'none' : 'lax',
-    domain: process.env.NODE_ENV === 'production' ? undefined : undefined // Let browser set domain automatically
+    sameSite: process.env.NODE_ENV === 'production' ? 'none' : 'lax'
 };

Also applies to: 37-39

🤖 Prompt for AI Agents
In src/utils/jwt.ts around lines 27-29 and 37-39, the object literal sets
domain: undefined which can trigger a TypeScript strict-mode error because
domain?: string should be omitted rather than assigned undefined; remove the
domain: undefined entries and only include domain when you have a real string
(e.g., conditionally add domain: process.env.COOKIE_DOMAIN when NODE_ENV ===
'production'), or change the type to accept undefined if you intentionally need
the key — prefer omission for clarity.

@anhlnp anhlnp closed this pull request by merging all changes into dev in a21e5ae Aug 29, 2025
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.

1 participant