Skip to content

Update CSRF Checks - #22

Merged
azeemstack merged 1 commit into
mainfrom
API-LogicBuilding
Apr 16, 2026
Merged

azeemstack merged 1 commit into
mainfrom
API-LogicBuilding

Conversation

@azeemstack

Copy link
Copy Markdown
Owner

No description provided.

Copilot AI review requested due to automatic review settings April 16, 2026 00:10
@coderabbitai

coderabbitai Bot commented Apr 16, 2026

Copy link
Copy Markdown

Warning

Rate limit exceeded

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

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 24 minutes and 46 seconds.

⌛ 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: 0b1b8123-7782-4f33-a4d0-8d1fe71c0ae5

📥 Commits

Reviewing files that changed from the base of the PR and between 7136ab3 and 86d1c21.

📒 Files selected for processing (3)
  • src/middleware/auth/requireAuth.ts
  • src/middleware/security/requireCsrf.ts
  • src/utils/tokens.ts
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch API-LogicBuilding

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.

@azeemstack
azeemstack merged commit 982f0cc into main Apr 16, 2026
4 checks passed

Copilot AI 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.

Pull request overview

Updates CSRF validation logic to strengthen request-origin checks and perform constant-time CSRF token comparisons.

Changes:

  • Enforce Origin/Referer presence and validate against ALLOWED_ORIGINS for unsafe HTTP methods.
  • Compare CSRF header token vs cookie using a timing-safe comparison helper.
  • Apply formatting/quoting consistency updates in token/auth utilities.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 5 comments.

File Description
src/utils/tokens.ts Adjusts token utility formatting and changes the constant-time compare helper used by CSRF validation.
src/middleware/security/requireCsrf.ts Tightens CSRF checks: method gating, origin validation, and timing-safe token comparison.
src/middleware/auth/requireAuth.ts Formatting/quoting consistency changes in auth middleware.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +11 to +15
const origin = req.headers.origin || req.headers.referer;

const origin = req.headers.origin as string | undefined;
if (!origin) {
throw new UnauthorizedError('Missing Origin or Referer header');
}

Copilot AI Apr 16, 2026

Copy link

Choose a reason for hiding this comment

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

This change rejects unsafe-method requests that omit both Origin and Referer headers. Since csrfMiddleware is applied to all private API routes (src/routes/api.ts:20), this can break non-browser clients (mobile apps, server-to-server, CLI) that rely on cookie auth but don't send these headers. If those clients are supported, consider allowing missing Origin/Referer for same-site requests, or gating this strictness behind an environment flag/documented contract.

Copilot uses AI. Check for mistakes.
Comment thread src/utils/tokens.ts
Comment on lines 36 to +43
export function compareHashTokens(hash1: string, hash2: string): boolean {
const hash1Buffer = Buffer.from(hash1, "hex");
const hash2Buffer = Buffer.from(hash2, "hex");
if (
hash1Buffer.length !== hash2Buffer.length ||
!crypto.timingSafeEqual(hash1Buffer, hash2Buffer)
) {
const hash1Buffer = Buffer.from(hash1, 'utf-8');
const hash2Buffer = Buffer.from(hash2, 'utf-8');
if (hash1Buffer.length !== hash2Buffer.length) {
return false;
}
return true;

return crypto.timingSafeEqual(hash1Buffer, hash2Buffer);

Copilot AI Apr 16, 2026

Copy link

Choose a reason for hiding this comment

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

compareHashTokens now compares UTF-8 bytes of the string values, but the function name and surrounding token utilities imply hex-encoded hashes (and verifyToken uses Buffer.from(..., 'hex')). This mismatch is easy to misuse later (e.g., passing a hex digest expecting byte-level compare). Consider either decoding as 'hex' here as well, or renaming the function to something like constantTimeEqual and documenting that it compares raw strings.

Copilot uses AI. Check for mistakes.
Comment thread src/utils/tokens.ts
sessionId: string,
reduceTime: boolean = false
) {
export function generateRefreshToken(userId: Types.ObjectId, sessionId: string, reduceTime: boolean = false) {

Copilot AI Apr 16, 2026

Copy link

Choose a reason for hiding this comment

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

reduceTime is declared but unused. If it's no longer needed, remove it to avoid confusion; if it is needed, wire it into the expiresIn selection (or add a comment explaining why it's intentionally unused).

Suggested change
export function generateRefreshToken(userId: Types.ObjectId, sessionId: string, reduceTime: boolean = false) {
export function generateRefreshToken(userId: Types.ObjectId, sessionId: string, reduceTime: boolean = false) {
// Intentionally kept for API compatibility with callers that may still pass this flag.
// Refresh tokens currently always use the configured default expiration window.
void reduceTime;

Copilot uses AI. Check for mistakes.
@@ -1,31 +1,37 @@
import crypto from 'crypto';

Copilot AI Apr 16, 2026

Copy link

Choose a reason for hiding this comment

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

Unused crypto import. This will be flagged by linters/formatters and adds noise; remove it (or use it directly instead of compareHashTokens).

Suggested change
import crypto from 'crypto';

Copilot uses AI. Check for mistakes.
}

if (origin && !ALLOWED_ORIGINS.includes(origin)) {
const originUrl = new URL(origin as string).origin;

Copilot AI Apr 16, 2026

Copy link

Choose a reason for hiding this comment

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

new URL(origin as string) will throw for non-absolute/invalid values (e.g., Origin: null, malformed Referer). That will turn a bad request into an unhandled exception/500 instead of a clean 401. Wrap URL parsing in a try/catch and convert failures into UnauthorizedError('Invalid origin') (or similar).

Suggested change
const originUrl = new URL(origin as string).origin;
let originUrl: string;
try {
originUrl = new URL(origin as string).origin;
} catch {
throw new UnauthorizedError('Invalid origin');
}

Copilot uses AI. Check for mistakes.
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.

2 participants