Skip to content

correct origin cors middleware #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 15, 2025
Merged

correct origin cors middleware #2

merged 1 commit into from
Jun 15, 2025

Conversation

elhalj
Copy link
Owner

@elhalj elhalj commented Jun 15, 2025

correct cors middleware

Summary by Sourcery

Refine CORS middleware to dynamically validate request origins based on environment and a configurable allowlist

Bug Fixes:

  • Return a CORS error for unauthorized origins instead of always allowing a fixed origin

Enhancements:

  • Introduce an allowlist array for permitted frontend origins in production
  • Replace static origin string with a function that checks origins against the allowlist or localhost in development

Copy link

sourcery-ai bot commented Jun 15, 2025

Reviewer's Guide

This PR refactors the CORS middleware in server.js to replace a hard-coded origin with a dynamic origin function that validates incoming origins against an environment-aware allowlist (production) or a local development URL, and rejects unauthorized origins.

Sequence Diagram for CORS Origin Validation

sequenceDiagram
    actor Client
    participant ExpressApp
    participant CORS_Middleware
    participant OriginCallback

    Client->>ExpressApp: HTTP Request (Origin: example.com)
    ExpressApp->>CORS_Middleware: Process request
    CORS_Middleware->>OriginCallback: ValidateOrigin("example.com", cb)
    OriginCallback->>OriginCallback: Check origin against rules (NODE_ENV, allowlist)
    alt Origin Allowed
        OriginCallback-->>CORS_Middleware: cb(null, true)
        CORS_Middleware-->>ExpressApp: Proceed with request
        ExpressApp-->>Client: HTTP 200 OK / Response
    else Origin Denied
        OriginCallback-->>CORS_Middleware: cb(new Error("Not allowed by CORS"))
        CORS_Middleware-->>ExpressApp: Block request
        ExpressApp-->>Client: HTTP 403 Forbidden / CORS Error
    end
Loading

File-Level Changes

Change Details Files
Implement dynamic CORS origin validation using an environment-aware allowlist
  • Introduced an allowlist array containing production URLs and localhost
  • Replaced static origin string with a callback that allows: no origin (non-browser), allowlist entries in production, or localhost in development
  • Invoke callback with an error when the origin is not permitted
src/server.js

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@elhalj elhalj merged commit 83b68df into development Jun 15, 2025
1 check passed
Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @elhalj - I've reviewed your changes - here's some feedback:

  • The nested ternary in the if (!origin || process.env.NODE_ENV === "production" ? … : …) is hard to read and error‐prone—refactor into explicit if/else blocks or add parentheses to clarify which condition applies in production vs. development.
  • As written, a request without an Origin header will hit the allowlist check and be rejected; if you want to allow non-browser or same-origin calls, handle the !origin case separately before your production/dev logic.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- The nested ternary in the `if (!origin || process.env.NODE_ENV === "production" ? … : …)` is hard to read and error‐prone—refactor into explicit `if`/`else` blocks or add parentheses to clarify which condition applies in production vs. development.
- As written, a request without an `Origin` header will hit the allowlist check and be rejected; if you want to allow non-browser or same-origin calls, handle the `!origin` case separately before your production/dev logic.

## Individual Comments

### Comment 1
<location> `src/server.js:25` </location>
<code_context>
   cors({
-    origin: "http://localhost:5173", // Autoriser uniquement votre frontend
+    origin: (origin, callback) => {
+      if (
+        !origin || process.env.NODE_ENV === "production"
+          ? allowlist.includes(origin)
</code_context>

<issue_to_address>
Clarify ternary operator precedence

Consider adding parentheses around the production check or extracting the condition into a named variable to improve readability and prevent misinterpretation.
</issue_to_address>

### Comment 2
<location> `src/server.js:26` </location>
<code_context>
-    origin: "http://localhost:5173", // Autoriser uniquement votre frontend
+    origin: (origin, callback) => {
+      if (
+        !origin || process.env.NODE_ENV === "production"
+          ? allowlist.includes(origin)
+          : origin === "http://localhost:5173"
</code_context>

<issue_to_address>
Reconsider allowing requests with no Origin header

Requests without an Origin header are currently permitted, which could allow non-browser clients to bypass CORS. Confirm if this behavior is intended.
</issue_to_address>

### Comment 3
<location> `src/server.js:32` </location>
<code_context>
+      ) {
+        callback(null, true);
+      } else {
+        callback(new Error("Not allowed by CORS"));
+      }
+    },
</code_context>

<issue_to_address>
Use `callback(null, false)` instead of throwing an error

Calling the callback with an error causes a 500 response. Use `callback(null, false)` to reject the request without triggering an internal server error.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
      } else {
        callback(new Error("Not allowed by CORS"));
      }
=======
      } else {
        callback(null, false);
      }
>>>>>>> REPLACE

</suggested_fix>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

app.use(
cors({
origin: "http://localhost:5173", // Autoriser uniquement votre frontend
origin: (origin, callback) => {
if (
Copy link

Choose a reason for hiding this comment

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

suggestion: Clarify ternary operator precedence

Consider adding parentheses around the production check or extracting the condition into a named variable to improve readability and prevent misinterpretation.

origin: "http://localhost:5173", // Autoriser uniquement votre frontend
origin: (origin, callback) => {
if (
!origin || process.env.NODE_ENV === "production"
Copy link

Choose a reason for hiding this comment

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

🚨 question (security): Reconsider allowing requests with no Origin header

Requests without an Origin header are currently permitted, which could allow non-browser clients to bypass CORS. Confirm if this behavior is intended.

Comment on lines +31 to +33
} else {
callback(new Error("Not allowed by CORS"));
}
Copy link

Choose a reason for hiding this comment

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

suggestion (bug_risk): Use callback(null, false) instead of throwing an error

Calling the callback with an error causes a 500 response. Use callback(null, false) to reject the request without triggering an internal server error.

Suggested change
} else {
callback(new Error("Not allowed by CORS"));
}
} else {
callback(null, false);
}

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