Skip to content

fix: align cors headers with production contract#994

Open
saurabhhhcodes wants to merge 2 commits into
Muneerali199:mainfrom
saurabhhhcodes:security/shared-header-config-877
Open

fix: align cors headers with production contract#994
saurabhhhcodes wants to merge 2 commits into
Muneerali199:mainfrom
saurabhhhcodes:security/shared-header-config-877

Conversation

@saurabhhhcodes

@saurabhhhcodes saurabhhhcodes commented Jun 12, 2026

Copy link
Copy Markdown
Contributor

Summary\n- align CORS and security header values with the production contract\n- keep both TS and MJS helpers in sync\n\n## Validation\n- reviewed the header config diff\n- no unrelated app changes

Summary by CodeRabbit

Release Notes

  • New Features

    • Added support for PDF files as static assets.
  • Security

    • Improved centralized security header and CORS configuration for enhanced protection.

@netlify

netlify Bot commented Jun 12, 2026

Copy link
Copy Markdown

👷 Deploy request for docmagic-muneer pending review.

Visit the deploys page to approve it

Name Link
🔨 Latest commit 0444602

@netlify

netlify Bot commented Jun 12, 2026

Copy link
Copy Markdown

👷 Deploy request for docmagic1 pending review.

Visit the deploys page to approve it

Name Link
🔨 Latest commit 0444602

@vercel

vercel Bot commented Jun 12, 2026

Copy link
Copy Markdown
Contributor

@saurabhhhcodes is attempting to deploy a commit to the muneerali199's projects Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitai Bot commented Jun 12, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

This PR centralizes security and CORS header handling by extracting shared definitions and utilities into dedicated modules, then refactoring middleware and Next.js config to consume these shared helpers instead of maintaining duplicate local header logic.

Changes

Security headers centralization

Layer / File(s) Summary
Shared security headers module (TypeScript)
lib/security-headers.ts
Defines constants for browser security headers (X-Frame-Options, X-XSS-Protection, etc.), CORS base headers, and a precomputed Next.js-compatible array combining security headers with CSP. Exports getAllowedOrigins() to parse comma-separated allowed origins with a localhost default, buildCorsHeaders(origin) to conditionally generate CORS response headers only when origin is in the allowlist (or list contains *), and applySecurityHeaders(headers) to mutate a mutable header object.
Shared security headers module (CommonJS)
lib/security-headers.mjs
Mirrors the TypeScript module for Node.js/CommonJS environments, exporting the same security header constants and utility functions to support non-ESM runtime contexts.
Middleware imports and rate-limit refactor
middleware.ts (imports, rate-limiter internals)
Updates imports to use shared CSP and security header utilities. Refactors the rate-limiter (checkRL) with explicit early-return object literals for initialization and limit-check paths while preserving per-IP counter/reset semantics and returned metadata fields; updates rlKey formatting while keeping endpoint category mapping (AUTH, GENERATE, API).
Middleware API routes with CORS and rate limiting
middleware.ts (/api/* branch)
Applies CORS headers via buildCorsHeaders based on origin allowlist. Injects rate-limit response headers (Retry-After, X-RateLimit-*) when request exceeds per-IP quota. Conditionally marks responses with X-Deployment-Error.
Middleware page load security headers and CSP
middleware.ts (page-load branch)
Applies shared security headers via applySecurityHeaders to non-asset page loads. Sets CSP using nonce-based buildCspWithNonce with x-nonce header for non-file routes, or default CSP_HEADER for assets. Conditionally marks responses with X-Deployment-Error.
Middleware config matcher
middleware.ts (config export)
Exported route matcher remains stable, excluding Next.js internals (_next/*), image optimization, favicon, and public assets from middleware processing.
Next.js config security headers and PDF assets
next.config.js (headers and Webpack)
Centralizes header definitions by importing NEXT_SECURITY_HEADERS and returning them from async headers(). Adds Webpack rule to serve .pdf files as bundled assets under static/files/[name][ext]. Updates image remote patterns and config formatting.
Next.js config PWA runtime caching
next.config.js (PWA config)
Updates service worker runtime caching rules for static resources, Google Fonts, Google static hosts, API routes, and catch-all routes. Preserves cache names and strategies (CacheFirst for static/fonts, NetworkFirst for APIs/dynamic) while adjusting handler option formatting.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • Muneerali199/Draftdeckai#918: Both PRs introduce and wire the same shared lib/security-headers utilities into middleware.ts and next.config.js, directly replacing local inline CORS/security header logic.
  • Muneerali199/Draftdeckai#781: Both PRs modify the CSP flow by using the shared lib/csp.ts nonce builder (buildCspWithNonce) and propagating the x-nonce header in middleware.ts.
  • Muneerali199/Draftdeckai#782: Both PRs refactor how Content-Security-Policy is sourced and applied—this PR routes CSP through shared security-header helpers, while the related PR makes CSP_HEADER a single-source constant.

Poem

🐰 Headers once scattered, now unite,
A single source of security light,
CORS and CSP in harmony blend,
Centralized config—a developer's friend!
No more duplication, just shared clarity,
Middleware and config rejoice in rarity!

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description provides a summary and validation details, but is missing several required template sections (issue number, type of change checkboxes, detailed testing information, and checklist items). Add the missing required sections: specify the issue number in 'Fixes #', select the appropriate type of change, provide detailed testing methodology and results, and complete the pre-merge checklist items.
Docstring Coverage ⚠️ Warning Docstring coverage is 58.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: aligning CORS headers with production contract, which matches the core objective of the pull request.
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.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
⚔️ Resolve merge conflicts
  • Resolve merge conflict in branch security/shared-header-config-877

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint install failed due to a network error.


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: 1

🧹 Nitpick comments (1)
middleware.ts (1)

6-11: ⚡ Quick win

DEPLOYMENT_ERROR_PATTERNS is defined but never used.

The constant is declared with regex patterns for deployment error detection, but isDeploymentError() only checks HTTP status codes. Either remove this dead code or integrate the patterns into the detection logic if body/header matching was intended.

🤖 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 `@middleware.ts` around lines 6 - 11, DEPLOYMENT_ERROR_PATTERNS is declared but
unused; either delete the constant or integrate it into isDeploymentError():
update isDeploymentError() to not only check numeric status codes but also
accept a response text/headers string (or response object) and test it against
each regex in DEPLOYMENT_ERROR_PATTERNS (e.g., loop patterns and return true on
a match), or if body/header matching is not needed, remove
DEPLOYMENT_ERROR_PATTERNS entirely to eliminate dead code; refer to the symbols
DEPLOYMENT_ERROR_PATTERNS and isDeploymentError() when making the change.
🤖 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 `@middleware.ts`:
- Around line 158-161: The deployment-error detection in middleware.ts is
ineffective because isDeploymentError(r) is called with r from
NextResponse.next(), which is a pass-through with status 200; remove or disable
the isDeploymentError checks and related calls (the blocks that call
isDeploymentError(r), logError(pathname, ...), and
r.headers.set("X-Deployment-Error", "true")) from the middleware and instead
implement the detection in code that has access to real server responses—for
example inside your API route handlers, React error boundaries, or an
observability layer where you can call isDeploymentError(response) against the
actual Response object and then call logError and set any headers on that real
response.

---

Nitpick comments:
In `@middleware.ts`:
- Around line 6-11: DEPLOYMENT_ERROR_PATTERNS is declared but unused; either
delete the constant or integrate it into isDeploymentError(): update
isDeploymentError() to not only check numeric status codes but also accept a
response text/headers string (or response object) and test it against each regex
in DEPLOYMENT_ERROR_PATTERNS (e.g., loop patterns and return true on a match),
or if body/header matching is not needed, remove DEPLOYMENT_ERROR_PATTERNS
entirely to eliminate dead code; refer to the symbols DEPLOYMENT_ERROR_PATTERNS
and isDeploymentError() when making the change.
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: 9dc57003-47a3-4a4b-8d4f-04e620774661

📥 Commits

Reviewing files that changed from the base of the PR and between ff793ac and 0444602.

📒 Files selected for processing (4)
  • lib/security-headers.mjs
  • lib/security-headers.ts
  • middleware.ts
  • next.config.js

Comment thread middleware.ts
Comment on lines 158 to 161
if (isDeploymentError(r)) {
logError(pathname, 'Deployment error detected', r.status, Date.now());
r.headers.set('X-Deployment-Error', 'true');
logError(pathname, "Deployment error detected", r.status, Date.now());
r.headers.set("X-Deployment-Error", "true");
}

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 | 🟠 Major | ⚡ Quick win

isDeploymentError(r) cannot detect errors in middleware at both middleware.ts lines 158-161 and 185-188.

Both locations call isDeploymentError(r) where r is the result of NextResponse.next(). This creates a pass-through response object, not the actual server response—middleware executes before the request reaches the server. The status is always 200, so these checks are dead code.

To detect deployment errors, move this logic to API route handlers, error boundaries, or an observability layer with access to actual responses.

🤖 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 `@middleware.ts` around lines 158 - 161, The deployment-error detection in
middleware.ts is ineffective because isDeploymentError(r) is called with r from
NextResponse.next(), which is a pass-through with status 200; remove or disable
the isDeploymentError checks and related calls (the blocks that call
isDeploymentError(r), logError(pathname, ...), and
r.headers.set("X-Deployment-Error", "true")) from the middleware and instead
implement the detection in code that has access to real server responses—for
example inside your API route handlers, React error boundaries, or an
observability layer where you can call isDeploymentError(response) against the
actual Response object and then call logError and set any headers on that real
response.

@Muneerali199 Muneerali199 added type:bug PR type: bug level:intermediate GSSoC difficulty: intermediate gssoc:approved Required GSSoC approval label mentor:muneerali199 Reviewed by mentor muneerali199 labels Jun 13, 2026
@Muneerali199

Copy link
Copy Markdown
Owner

@SaurabhhCodes please rebase on latest main to resolve conflicts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gssoc:approved Required GSSoC approval label level:intermediate GSSoC difficulty: intermediate mentor:muneerali199 Reviewed by mentor muneerali199 type:bug PR type: bug

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants