Skip to content

✨Introduced apis to refresh tokens - #622

Merged
Leo-rq-yu merged 25 commits into
mainfrom
feat/refresh-token
Dec 16, 2025
Merged

Leo-rq-yu merged 25 commits into
mainfrom
feat/refresh-token

Conversation

@Leo-rq-yu

@Leo-rq-yu Leo-rq-yu commented Dec 5, 2025 •

Copy link
Copy Markdown
Contributor

Summary

This PR introduces refresh token support for new version of Insforge SDK.
Added cookie-parser package to enable OSS backend to set cookies.
Introduced cookie.ts file to define refresh token's cookie option. Also to set and clear refresh token cookie.
Defined refresh token's payload in token manager. Also generation and verification of the cookies.
Then in the oauth routes /api/auth/oauth/:provider/callback and /api/auth/oauth/shared/callback/:state, set refresh token in cookie before return response.
In the auth routes /api/auth/email/verify, /api/auth/users, and /api/auth/sessions also make sure to set cookies before return a response.
Then introduce new endpoint /api/auth/refresh to handle refreshing access token.
Introduced csrf token based on tutorial: https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html

How did you test this change?

Create a new project in production server, and vibe code a project in local.
Then test the signup & signin procedures with the old version sdk and oss.
After this step, you can first upgrade sdk and auth component by installing @insforge/[email protected] & @insforge/[email protected]. Then test again the authentication flow, to see if everything works fine.
After that you can reset the project’s version to v1.2.11-refresh-token-v5 which then you are using both the new sdk and oss. You can test again the whole authentication flow.

Summary by CodeRabbit

  • New Features

    • Added token refresh endpoint for secure session renewal with automatic token rotation.
    • Added logout endpoint to clear active sessions.
    • Implemented CSRF token protection across authentication flows for enhanced security.
    • Enabled HttpOnly cookie-based session management for safer credential storage.
  • Chores

    • Updated shared schema version to support new authentication response formats.
    • Added dependencies for session and cookie management.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai

coderabbitai Bot commented Dec 5, 2025 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Review was skipped due to path filters

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json

CodeRabbit blocks several paths by default. You can override this behavior by explicitly including those paths in the path filters. For example, including **/dist/** will override the default block on the dist directory, by removing the pattern from both the lists.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

This PR implements cookie-based session management with CSRF protection. It adds HTTP-only refresh token cookies, CSRF token generation and verification, token rotation endpoints, updates OAuth and auth routes to set cookies and propagate CSRF tokens, introduces TokenManager extensions for refresh token handling, and creates cookie utility helpers.

Changes

Cohort / File(s) Summary
Dependencies & Package Management
backend/package.json, shared-schemas/package.json
Added cookie-parser runtime and @types/cookie-parser dev dependencies; bumped shared-schemas version from 1.1.30 to 1.1.34
Token & Cookie Infrastructure
backend/src/infra/security/token.manager.ts, backend/src/utils/cookies.ts
Extended TokenManager with refresh token generation/verification and CSRF token support; introduced new cookie utility module exporting REFRESH_TOKEN_COOKIE_NAME constant and setAuthCookie/clearAuthCookie functions
Server Configuration
backend/src/server.ts
Added cookie-parser middleware registration and removed inline comment from health handler
Authentication Routes
backend/src/api/routes/auth/index.routes.ts, backend/src/api/routes/auth/oauth.routes.ts
Added refresh and logout endpoints with token rotation and CSRF protection; integrated httpOnly refresh token cookies and CSRF token propagation across login, signup, verification flows, and OAuth callbacks
Shared Auth Schemas
shared-schemas/src/auth-api.schema.ts
Added optional csrfToken fields to createUserResponseSchema, createSessionResponseSchema, and verifyEmailResponseSchema; introduced new refreshSessionResponseSchema and RefreshSessionResponse type
Frontend Library
auth/src/lib/broadcastService.ts
Added TODO comment referencing future PKCE implementation

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • TokenManager CSRF verification logic — timing-safe comparison implementation and refresh token verification error handling require attention
  • Token rotation flow in POST /api/auth/refresh endpoint — verify correct token replacement, cookie setting, and error cases (user not found)
  • OAuth callback flows — ensure consistent cookie/CSRF propagation across shared/callback, provider callback, and handleOAuthCallback paths
  • Cookie security settings — validate httpOnly, secure, sameSite configurations across setAuthCookie/clearAuthCookie implementations

Possibly related PRs

Suggested reviewers

  • Fermionic-Lyu
  • tonychang04

Poem

🐰 Hopping through the auth-scape bright,
Cookies tucked in HTTP-only night,
CSRF tokens dance, refresh tokens spin,
Sessions secured, the tokens begin!
No more stolen, no cross-site sin! ✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly describes the main objective: introducing APIs to refresh tokens, which aligns with the core changes across multiple files adding refresh token support and new endpoints.

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

chatgpt-codex-connector[bot]

This comment was marked as resolved.

coderabbitai[bot]

This comment was marked as resolved.

coderabbitai[bot]

This comment was marked as outdated.

coderabbitai[bot]

This comment was marked as outdated.

coderabbitai[bot]

This comment was marked as outdated.

coderabbitai[bot]

This comment was marked as resolved.

coderabbitai[bot]

This comment was marked as outdated.

coderabbitai[bot]

This comment was marked as outdated.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
backend/src/api/routes/auth/index.routes.ts (1)

179-230: Add rate limiting and revisit CSRF/CORS posture for the /refresh endpoint.

The refresh handler correctly verifies the refresh token, rotates both access and refresh tokens, reloads the user, and clears the cookie if the user is missing or an error occurs. However:

  • There is still no rate limiting on /api/auth/refresh, so repeated requests can be used for brute-force or token-enumeration attempts. Prior review already called this out for this route.
  • With cookie-based refresh tokens and sameSite: 'none' in cloud plus permissive CORS (as previously noted in server config), arbitrary origins can potentially call /refresh with credentials: 'include' and read the JSON response, which may expose an access token if CORS is not locked down or CSRF protections are missing.

To harden this, at minimum add a limiter (reusing an existing one is fine), and ensure CORS/CSRF protections are aligned with the cookie-based refresh design. For example:

-// POST /api/auth/refresh - Refresh access token using httpOnly cookie
-router.post('/refresh', async (req: Request, res: Response, next: NextFunction) => {
+// POST /api/auth/refresh - Refresh access token using httpOnly cookie
+router.post('/refresh', verifyOTPLimiter, async (req: Request, res: Response, next: NextFunction) => {

And verify that the CORS configuration restricts origin to a trusted allowlist when credentials: true is used, or add CSRF protections if broader CORS is required.

🧹 Nitpick comments (4)
backend/src/api/routes/auth/oauth.routes.ts (1)

5-5: Reuse cookie helper to avoid duplicated refresh-token logic (role choice looks correct).

Both callback handlers inline the TokenManager.generateRefreshToken + setRefreshTokenCookie sequence with role: 'authenticated'. That role value is consistent with how non-admin user sessions are handled elsewhere, and the user object here does not carry a role, so keeping 'authenticated' is fine.

To reduce duplication and keep behavior centralized, consider delegating to issueRefreshTokenCookie(res, result.user) from @/utils/cookies.js, as is done in the email/password flows. That way, any future changes to refresh-token issuance (TTL, role defaults, etc.) only need to be made in one place.

Also applies to: 10-10, 346-355, 362-362, 421-430, 438-438

backend/src/utils/cookies.ts (1)

19-27: Cookie options and helpers look solid; clarify intended role for issued refresh tokens.

The cookie configuration is well thought out: httpOnly, environment-aware secure/sameSite, explicit /api/auth path, and matching options in clearRefreshTokenCookie align with least-privilege and reliable clearing.

issueRefreshTokenCookie correctly guards on user.id/user.email and centralizes refresh-token generation and cookie setting. Since it always embeds role: 'authenticated', it is effectively a helper for regular user sessions, not admin/project_admin flows.

To avoid accidental misuse later, consider tightening the JSDoc (e.g., “Issue refresh token for standard authenticated users (role: 'authenticated')”) or renaming the function to make that scope explicit.

Also applies to: 33-35, 41-48, 59-71

backend/src/api/routes/auth/index.routes.ts (2)

13-18: Auth flows: refresh-cookie issuance and sessionMode flag look consistent; ensure docs/types reflect it.

User registration, login, and email-verification now all:

  • Issue a refresh token in an httpOnly cookie via issueRefreshTokenCookie when an access token and user are present.
  • Add sessionMode: 'secure' to responses so clients know to keep access tokens in secure storage (e.g., memory).

This is consistent and keeps the refresh-token behavior centralized in cookies.ts. Just make sure the corresponding response schemas/OpenAPI definitions are updated so sessionMode is documented and typed for these endpoints.

Also applies to: 47-47, 120-150, 152-177, 495-538


232-245: Logout behavior is straightforward; consider whether clearing cookie on all refresh errors is desired.

/logout simply clears the refresh-token cookie and returns a success payload, which is appropriate for a stateless JWT setup and does not need authentication since it only affects the caller’s cookie.

In the /refresh handler, the catch block always calls clearRefreshTokenCookie(res) before delegating to the error middleware. This aggressively logs users out even for transient server errors (e.g., DB outages), not just for invalid/expired tokens. If you want a softer UX, you could restrict cookie clearing to authorization-related errors (e.g., AUTH_UNAUTHORIZED) and leave valid cookies intact on internal failures.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e4f6803 and c950414.

📒 Files selected for processing (3)
  • backend/src/api/routes/auth/index.routes.ts (5 hunks)
  • backend/src/api/routes/auth/oauth.routes.ts (3 hunks)
  • backend/src/utils/cookies.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (10)
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx,js,jsx}: Use TypeScript for all code files
Prefer descriptive, unabbreviated variable and function names
Follow consistent file naming: kebab-case for files, PascalCase for components
Use ES modules (import/export syntax)
Implement proper error handling with try-catch blocks
Add appropriate logging for debugging
Use camelCase for variables, parameters, properties, and functions
Use UPPER_CASE for constants and Enum members
Avoid snake_case except in SQL queries and external APIs
Use single quotes for strings
Include semicolons at the end of statements
Use arrow functions for callbacks and inline functions
Prefer const over let, avoid var
Use template literals for string interpolation
Maintain consistent indentation (2 spaces)
Format code with Prettier configuration
Include JSDoc comments for complex functions

Files:

  • backend/src/utils/cookies.ts
  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/api/routes/auth/oauth.routes.ts
backend/src/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

backend/src/**/*.{ts,js}: Use async/await for asynchronous operations in backend code
Implement proper database transaction handling
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper database indexing

Files:

  • backend/src/utils/cookies.ts
  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/api/routes/auth/oauth.routes.ts
{backend/src/**/*.{ts,js},shared-schemas/**/*.{ts,js}}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use Zod schemas for request/response validation in backend

Files:

  • backend/src/utils/cookies.ts
  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/api/routes/auth/oauth.routes.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use PascalCase for React components and TypeScript types/interfaces

Files:

  • backend/src/utils/cookies.ts
  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/api/routes/auth/oauth.routes.ts
{backend,frontend}/src/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use environment variables for configuration

Files:

  • backend/src/utils/cookies.ts
  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/api/routes/auth/oauth.routes.ts
{backend/src,frontend/src}/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

{backend/src,frontend/src}/**/*.{ts,tsx,js,jsx}: Implement proper caching strategies
Monitor and log performance metrics

Files:

  • backend/src/utils/cookies.ts
  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/api/routes/auth/oauth.routes.ts
backend/src/api/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

backend/src/api/**/*.{ts,js}: Implement proper middleware for authentication and error handling
Follow RESTful conventions for API endpoints
Implement rate limiting for API endpoints

Files:

  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/api/routes/auth/oauth.routes.ts
backend/src/{controllers,api}/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Return consistent API responses using utility functions

Files:

  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/api/routes/auth/oauth.routes.ts
backend/src/{api,core,controllers}/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Implement proper authentication and authorization

Files:

  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/api/routes/auth/oauth.routes.ts
{backend/src/api,openapi}/**/*.{ts,yaml,yml,json}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Document all API endpoints with clear descriptions

Files:

  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/api/routes/auth/oauth.routes.ts
🧠 Learnings (5)
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/{api,core,controllers}/**/*.{ts,js} : Implement proper authentication and authorization

Applied to files:

  • backend/src/utils/cookies.ts
  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/api/routes/auth/oauth.routes.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/api/**/*.{ts,js} : Implement proper middleware for authentication and error handling

Applied to files:

  • backend/src/utils/cookies.ts
  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/api/routes/auth/oauth.routes.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to {backend/src,frontend/src}/**/*.{ts,tsx,js,jsx} : Implement proper caching strategies

Applied to files:

  • backend/src/utils/cookies.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/api/**/*.{ts,js} : Implement rate limiting for API endpoints

Applied to files:

  • backend/src/api/routes/auth/index.routes.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to {backend/src/**/*.{ts,js},shared-schemas/**/*.{ts,js}} : Use Zod schemas for request/response validation in backend

Applied to files:

  • backend/src/api/routes/auth/index.routes.ts
🧬 Code graph analysis (1)
backend/src/utils/cookies.ts (2)
backend/src/utils/environment.ts (1)
  • isCloudEnvironment (9-11)
backend/src/infra/security/token.manager.ts (1)
  • TokenManager (36-180)

coderabbitai[bot]

This comment was marked as resolved.

coderabbitai[bot]

This comment was marked as outdated.

coderabbitai[bot]

This comment was marked as outdated.

coderabbitai[bot]

This comment was marked as outdated.

coderabbitai[bot]

This comment was marked as outdated.

coderabbitai[bot]

This comment was marked as outdated.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
backend/src/api/routes/auth/index.routes.ts (1)

180-182: Add rate limiting to the /refresh endpoint.

This endpoint lacks rate limiting, unlike other authentication endpoints that use sendEmailOTPLimiter or verifyOTPLimiter. Without rate limiting, this endpoint is vulnerable to abuse. As per coding guidelines, API endpoints should implement rate limiting.

 // POST /api/auth/refresh - Refresh access token using httpOnly cookie
 // Requires X-CSRF-Token header for CSRF protection
-router.post('/refresh', async (req: Request, res: Response, next: NextFunction) => {
+router.post('/refresh', verifyOTPLimiter, async (req: Request, res: Response, next: NextFunction) => {
🧹 Nitpick comments (4)
backend/src/api/routes/auth/index.routes.ts (2)

193-195: Use a more appropriate error code for CSRF failures.

Returning HTTP 403 with ERROR_CODES.AUTH_UNAUTHORIZED is inconsistent—403 typically indicates "Forbidden" (authorization failure), while AUTH_UNAUTHORIZED suggests authentication issues (401). Consider using a dedicated CSRF error code or AUTH_FORBIDDEN if available.

-      throw new AppError('Invalid CSRF token', 403, ERROR_CODES.AUTH_UNAUTHORIZED);
+      throw new AppError('Invalid CSRF token', 403, ERROR_CODES.AUTH_FORBIDDEN);

236-240: Consider selective cookie clearing to avoid unintended logouts.

Currently, the catch block clears the refresh token cookie on any error, including transient database or network failures. This could log users out unnecessarily during temporary infrastructure issues.

Consider clearing the cookie only for authentication-related errors (invalid/expired tokens, missing user):

   } catch (error) {
-    // Clear invalid cookie on error
-    clearRefreshTokenCookie(res);
+    // Only clear cookie for auth-related errors, not transient failures
+    if (error instanceof AppError && 
+        (error.code === ERROR_CODES.AUTH_UNAUTHORIZED || 
+         error.code === ERROR_CODES.AUTH_INVALID_CREDENTIALS)) {
+      clearRefreshTokenCookie(res);
+    }
     next(error);
   }
backend/src/utils/cookies.ts (2)

42-50: Consider reusing getRefreshTokenCookieOptions in clearRefreshTokenCookie.

The options are duplicated here. While this was intentionally done to ensure matching options, it introduces a maintenance burden if options change in the future.

 export function clearRefreshTokenCookie(res: Response): void {
-  const isCloud = isCloudEnvironment();
-  res.clearCookie(REFRESH_TOKEN_COOKIE_NAME, {
-    httpOnly: true,
-    secure: isCloud,
-    sameSite: isCloud ? ('none' as const) : ('lax' as const),
-    path: '/api/auth',
-  });
+  const { maxAge, ...clearOptions } = getRefreshTokenCookieOptions();
+  res.clearCookie(REFRESH_TOKEN_COOKIE_NAME, clearOptions);
 }

20-29: The cookie maxAge is already correctly aligned with the token expiration, but the implementation approach needs adjustment.

The cookie's maxAge (7 days in milliseconds) and REFRESH_TOKEN_EXPIRES_IN ('7d') are currently aligned. However, REFRESH_TOKEN_EXPIRES_IN is not exported from TokenManager and is a string format unsuitable for direct use. To avoid these values drifting in the future, consider extracting the expiration value to a shared constant or exporting it from TokenManager in milliseconds.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 91cec80 and 50faee5.

📒 Files selected for processing (4)
  • backend/src/api/routes/auth/index.routes.ts (5 hunks)
  • backend/src/api/routes/auth/oauth.routes.ts (3 hunks)
  • backend/src/infra/security/csrf.manager.ts (1 hunks)
  • backend/src/utils/cookies.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • backend/src/api/routes/auth/oauth.routes.ts
🧰 Additional context used
📓 Path-based instructions (10)
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx,js,jsx}: Use TypeScript for all code files
Prefer descriptive, unabbreviated variable and function names
Follow consistent file naming: kebab-case for files, PascalCase for components
Use ES modules (import/export syntax)
Implement proper error handling with try-catch blocks
Add appropriate logging for debugging
Use camelCase for variables, parameters, properties, and functions
Use UPPER_CASE for constants and Enum members
Avoid snake_case except in SQL queries and external APIs
Use single quotes for strings
Include semicolons at the end of statements
Use arrow functions for callbacks and inline functions
Prefer const over let, avoid var
Use template literals for string interpolation
Maintain consistent indentation (2 spaces)
Format code with Prettier configuration
Include JSDoc comments for complex functions

Files:

  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/infra/security/csrf.manager.ts
  • backend/src/utils/cookies.ts
backend/src/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

backend/src/**/*.{ts,js}: Use async/await for asynchronous operations in backend code
Implement proper database transaction handling
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper database indexing

Files:

  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/infra/security/csrf.manager.ts
  • backend/src/utils/cookies.ts
backend/src/api/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

backend/src/api/**/*.{ts,js}: Implement proper middleware for authentication and error handling
Follow RESTful conventions for API endpoints
Implement rate limiting for API endpoints

Files:

  • backend/src/api/routes/auth/index.routes.ts
{backend/src/**/*.{ts,js},shared-schemas/**/*.{ts,js}}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use Zod schemas for request/response validation in backend

Files:

  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/infra/security/csrf.manager.ts
  • backend/src/utils/cookies.ts
backend/src/{controllers,api}/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Return consistent API responses using utility functions

Files:

  • backend/src/api/routes/auth/index.routes.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use PascalCase for React components and TypeScript types/interfaces

Files:

  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/infra/security/csrf.manager.ts
  • backend/src/utils/cookies.ts
{backend,frontend}/src/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use environment variables for configuration

Files:

  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/infra/security/csrf.manager.ts
  • backend/src/utils/cookies.ts
backend/src/{api,core,controllers}/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Implement proper authentication and authorization

Files:

  • backend/src/api/routes/auth/index.routes.ts
{backend/src,frontend/src}/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

{backend/src,frontend/src}/**/*.{ts,tsx,js,jsx}: Implement proper caching strategies
Monitor and log performance metrics

Files:

  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/infra/security/csrf.manager.ts
  • backend/src/utils/cookies.ts
{backend/src/api,openapi}/**/*.{ts,yaml,yml,json}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Document all API endpoints with clear descriptions

Files:

  • backend/src/api/routes/auth/index.routes.ts
🧠 Learnings (6)
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/{api,core,controllers}/**/*.{ts,js} : Implement proper authentication and authorization

Applied to files:

  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/infra/security/csrf.manager.ts
  • backend/src/utils/cookies.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/api/**/*.{ts,js} : Implement proper middleware for authentication and error handling

Applied to files:

  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/utils/cookies.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/api/**/*.{ts,js} : Follow RESTful conventions for API endpoints

Applied to files:

  • backend/src/api/routes/auth/index.routes.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/api/**/*.{ts,js} : Implement rate limiting for API endpoints

Applied to files:

  • backend/src/api/routes/auth/index.routes.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to {backend/src/**/*.{ts,js},shared-schemas/**/*.{ts,js}} : Use Zod schemas for request/response validation in backend

Applied to files:

  • backend/src/api/routes/auth/index.routes.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to {backend/src,frontend/src}/**/*.{ts,tsx,js,jsx} : Implement proper caching strategies

Applied to files:

  • backend/src/utils/cookies.ts
🧬 Code graph analysis (2)
backend/src/api/routes/auth/index.routes.ts (6)
backend/src/utils/cookies.ts (4)
  • issueRefreshTokenCookie (60-78)
  • REFRESH_TOKEN_COOKIE_NAME (10-10)
  • setRefreshTokenCookie (34-36)
  • clearRefreshTokenCookie (42-50)
backend/src/utils/response.ts (1)
  • successResponse (22-24)
backend/src/api/middlewares/error.ts (1)
  • AppError (7-17)
backend/src/infra/security/csrf.manager.ts (1)
  • CsrfManager (12-62)
backend/src/utils/logger.ts (1)
  • logger (6-29)
backend/src/infra/security/token.manager.ts (1)
  • TokenManager (36-196)
backend/src/utils/cookies.ts (3)
backend/src/utils/environment.ts (1)
  • isCloudEnvironment (9-11)
backend/src/infra/security/token.manager.ts (1)
  • TokenManager (36-196)
backend/src/infra/security/csrf.manager.ts (1)
  • CsrfManager (12-62)
🔇 Additional comments (7)
backend/src/infra/security/csrf.manager.ts (1)

12-61: LGTM! Well-implemented CSRF protection using HMAC token derivation.

The implementation follows security best practices:

  • HMAC-SHA256 derivation prevents attackers from forging CSRF tokens without knowing the secret
  • Timing-safe comparison prevents timing attacks
  • Proper error handling for missing tokens and length mismatches

The 32-character truncation (128 bits of entropy) is sufficient for CSRF protection.

backend/src/api/routes/auth/index.routes.ts (5)

243-256: LGTM! Logout endpoint correctly clears the refresh token cookie.

The implementation appropriately allows unauthenticated logout calls, which is standard practice to ensure users can clear cookies even with invalid/expired tokens.


136-147: LGTM! Proper refresh token issuance after user registration.

The implementation correctly:

  • Checks for both accessToken and user before issuing cookies
  • Uses the centralized issueRefreshTokenCookie helper
  • Includes the CSRF token in the response for SDK consumption

168-178: LGTM! Consistent refresh token issuance for login flow.

Pattern matches the registration flow correctly.


542-549: LGTM! Email verification flow correctly issues refresh tokens.

Consistent with registration and login flows—CSRF token included in response.


202-220: LGTM! Proper token rotation implementation.

Token rotation (issuing a new refresh token on each use) is a security best practice that limits the window for token theft. The CSRF token is correctly regenerated from the new refresh token.

backend/src/utils/cookies.ts (1)

60-78: LGTM! Well-designed helper function for refresh token issuance.

The function:

  • Properly validates user input before token generation
  • Encapsulates the refresh token + CSRF token workflow
  • Returns null on invalid input rather than throwing, allowing callers to handle gracefully

The hardcoded role: 'authenticated' is correct per codebase conventions—admin roles are handled separately.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (3)
auth/src/pages/SignUpPage.tsx (1)

20-20: Security: Avoid passing CSRF tokens via URL parameters.

Passing the CSRF token as a URL query parameter exposes it to multiple security risks:

  • Browser history storage
  • Server access log exposure
  • Leakage via Referer headers to external sites
  • Potential exposure if the URL is bookmarked or shared

The OWASP CSRF Prevention Cheat Sheet recommends transmitting CSRF tokens via custom request headers or hidden form fields, not URL parameters. Since the backend already sets refresh tokens via httpOnly cookies, consider transmitting the CSRF token via a separate cookie (as done in the backend) instead of query parameters.

Also applies to: 30-32

auth/src/pages/SignInPage.tsx (1)

20-20: Security: Avoid passing CSRF tokens via URL parameters.

Passing the CSRF token as a URL query parameter exposes it to multiple security risks:

  • Browser history storage
  • Server access log exposure
  • Leakage via Referer headers to external sites
  • Potential exposure if the URL is bookmarked or shared

The OWASP CSRF Prevention Cheat Sheet recommends transmitting CSRF tokens via custom request headers or hidden form fields, not URL parameters. Since the backend already sets refresh tokens via httpOnly cookies, consider transmitting the CSRF token via a separate cookie (as done in the backend) instead of query parameters.

Also applies to: 30-32

backend/src/api/routes/auth/index.routes.ts (1)

186-251: Critical: Address CSRF and token exfiltration risk from permissive CORS with sameSite: 'none' cookies.

The /api/auth/refresh endpoint has CSRF protection (lines 196-202), which is good. However, a critical vulnerability remains: the combination of permissive CORS (origin: true, credentials: true in server.ts) and sameSite: 'none' cookies (in cloud environments) allows arbitrary origins to exfiltrate access tokens:

  1. Any origin can call /api/auth/refresh with fetch(..., { credentials: 'include' })
  2. The browser sends the httpOnly refresh cookie because sameSite: 'none' permits cross-site requests
  3. JavaScript on that origin can read the CSRF token from the non-httpOnly CSRF cookie
  4. The malicious origin includes X-CSRF-Token header, passes CSRF validation
  5. The origin receives the JSON response containing the new accessToken

Result: Logged-in users' access tokens are retrievable by arbitrary third-party origins.

To harden this:

  • Restrict CORS to an allowlist of trusted frontend origins instead of origin: true
  • Use sameSite: 'lax' for same-site refresh flows, or use secure redirect-based token delivery for cross-origin scenarios
  • Add origin validation in the refresh endpoint to ensure the request originates from a trusted domain
#!/bin/bash
# Verify CORS configuration and cookie sameSite settings
echo "=== CORS Configuration ==="
rg -n "cors.*origin.*true|credentials.*true" backend/src/server.ts -A 3 -B 3

echo -e "\n=== Cookie sameSite Configuration ==="
rg -n "sameSite.*none|sameSite.*'none'" backend/src/utils/cookies.ts -A 2 -B 2

echo -e "\n=== Refresh Token Cookie Options ==="
rg -n "getRefreshTokenCookieOptions|getCsrfTokenCookieOptions" backend/src/utils/cookies.ts -A 10
🧹 Nitpick comments (2)
backend/src/infra/security/token.manager.ts (1)

95-120: Enhance error handling with specific error codes.

The verifyRefreshToken method throws generic AppError with AUTH_UNAUTHORIZED for all failure cases. Consider using more specific error codes to help clients distinguish between token type mismatch, expiration, and invalid signature.

 verifyRefreshToken(token: string): RefreshTokenPayload {
   try {
     const decoded = jwt.verify(token, JWT_SECRET) as RefreshTokenPayload;

     // Ensure this is a refresh token, not an access token
     if (decoded.type !== 'refresh') {
-      throw new AppError('Invalid refresh token type', 401, ERROR_CODES.AUTH_UNAUTHORIZED);
+      throw new AppError('Invalid refresh token type', 401, ERROR_CODES.AUTH_INVALID_CREDENTIALS);
     }

     return {
       sub: decoded.sub,
       email: decoded.email,
       role: decoded.role,
       type: 'refresh',
     };
   } catch (error) {
     if (error instanceof AppError) {
       throw error;
     }
+    // Distinguish between expired and invalid tokens
+    if (error instanceof jwt.TokenExpiredError) {
+      throw new AppError('Refresh token expired', 401, ERROR_CODES.AUTH_UNAUTHORIZED);
+    }
-    throw new AppError('Invalid or expired refresh token', 401, ERROR_CODES.AUTH_UNAUTHORIZED);
+    throw new AppError('Invalid refresh token', 401, ERROR_CODES.AUTH_INVALID_CREDENTIALS);
   }
 }
backend/src/infra/security/csrf.manager.ts (1)

24-30: Consider independent CSRF tokens for better security separation.

Currently, the CSRF token is derived from the refresh token using HMAC. While this works, it creates a dependency between the two tokens. If the refresh token is compromised, the CSRF token can be recalculated.

For enhanced security isolation, consider generating independent random CSRF tokens stored server-side or in a separate cookie, decoupled from the refresh token lifecycle.

This is an optional improvement and doesn't affect the current security posture, as the HMAC derivation is cryptographically sound.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 75f62c5 and 416642a.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (11)
  • auth/package.json (1 hunks)
  • auth/src/lib/broadcastService.ts (1 hunks)
  • auth/src/pages/SignInPage.tsx (2 hunks)
  • auth/src/pages/SignUpPage.tsx (2 hunks)
  • backend/package.json (2 hunks)
  • backend/src/api/routes/auth/index.routes.ts (6 hunks)
  • backend/src/api/routes/auth/oauth.routes.ts (3 hunks)
  • backend/src/infra/security/csrf.manager.ts (1 hunks)
  • backend/src/infra/security/token.manager.ts (3 hunks)
  • backend/src/server.ts (2 hunks)
  • backend/src/utils/cookies.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (6)
  • backend/package.json
  • backend/src/api/routes/auth/oauth.routes.ts
  • auth/package.json
  • backend/src/server.ts
  • auth/src/lib/broadcastService.ts
  • backend/src/utils/cookies.ts
🧰 Additional context used
📓 Path-based instructions (10)
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx,js,jsx}: Use TypeScript for all code files
Prefer descriptive, unabbreviated variable and function names
Follow consistent file naming: kebab-case for files, PascalCase for components
Use ES modules (import/export syntax)
Implement proper error handling with try-catch blocks
Add appropriate logging for debugging
Use camelCase for variables, parameters, properties, and functions
Use UPPER_CASE for constants and Enum members
Avoid snake_case except in SQL queries and external APIs
Use single quotes for strings
Include semicolons at the end of statements
Use arrow functions for callbacks and inline functions
Prefer const over let, avoid var
Use template literals for string interpolation
Maintain consistent indentation (2 spaces)
Format code with Prettier configuration
Include JSDoc comments for complex functions

Files:

  • auth/src/pages/SignUpPage.tsx
  • auth/src/pages/SignInPage.tsx
  • backend/src/infra/security/token.manager.ts
  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/infra/security/csrf.manager.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use PascalCase for React components and TypeScript types/interfaces

Files:

  • auth/src/pages/SignUpPage.tsx
  • auth/src/pages/SignInPage.tsx
  • backend/src/infra/security/token.manager.ts
  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/infra/security/csrf.manager.ts
backend/src/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

backend/src/**/*.{ts,js}: Use async/await for asynchronous operations in backend code
Implement proper database transaction handling
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper database indexing

Files:

  • backend/src/infra/security/token.manager.ts
  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/infra/security/csrf.manager.ts
{backend/src/**/*.{ts,js},shared-schemas/**/*.{ts,js}}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use Zod schemas for request/response validation in backend

Files:

  • backend/src/infra/security/token.manager.ts
  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/infra/security/csrf.manager.ts
{backend,frontend}/src/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use environment variables for configuration

Files:

  • backend/src/infra/security/token.manager.ts
  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/infra/security/csrf.manager.ts
{backend/src,frontend/src}/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

{backend/src,frontend/src}/**/*.{ts,tsx,js,jsx}: Implement proper caching strategies
Monitor and log performance metrics

Files:

  • backend/src/infra/security/token.manager.ts
  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/infra/security/csrf.manager.ts
backend/src/api/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

backend/src/api/**/*.{ts,js}: Implement proper middleware for authentication and error handling
Follow RESTful conventions for API endpoints
Implement rate limiting for API endpoints

Files:

  • backend/src/api/routes/auth/index.routes.ts
backend/src/{controllers,api}/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Return consistent API responses using utility functions

Files:

  • backend/src/api/routes/auth/index.routes.ts
backend/src/{api,core,controllers}/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Implement proper authentication and authorization

Files:

  • backend/src/api/routes/auth/index.routes.ts
{backend/src/api,openapi}/**/*.{ts,yaml,yml,json}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Document all API endpoints with clear descriptions

Files:

  • backend/src/api/routes/auth/index.routes.ts
🧠 Learnings (8)
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to frontend/src/**/*.{tsx,jsx} : Implement proper form validation with inline errors in frontend

Applied to files:

  • auth/src/pages/SignUpPage.tsx
  • auth/src/pages/SignInPage.tsx
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Follow OWASP security best practices

Applied to files:

  • auth/src/pages/SignInPage.tsx
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to **/*.{ts,tsx,js,jsx} : Include JSDoc comments for complex functions

Applied to files:

  • backend/src/infra/security/token.manager.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/{api,core,controllers}/**/*.{ts,js} : Implement proper authentication and authorization

Applied to files:

  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/infra/security/csrf.manager.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/api/**/*.{ts,js} : Implement proper middleware for authentication and error handling

Applied to files:

  • backend/src/api/routes/auth/index.routes.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/api/**/*.{ts,js} : Follow RESTful conventions for API endpoints

Applied to files:

  • backend/src/api/routes/auth/index.routes.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/api/**/*.{ts,js} : Implement rate limiting for API endpoints

Applied to files:

  • backend/src/api/routes/auth/index.routes.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to {backend/src/**/*.{ts,js},shared-schemas/**/*.{ts,js}} : Use Zod schemas for request/response validation in backend

Applied to files:

  • backend/src/api/routes/auth/index.routes.ts
🧬 Code graph analysis (2)
backend/src/infra/security/token.manager.ts (2)
shared-schemas/src/auth.schema.ts (1)
  • TokenPayloadSchema (127-127)
backend/src/api/middlewares/error.ts (1)
  • AppError (7-17)
backend/src/api/routes/auth/index.routes.ts (6)
backend/src/utils/cookies.ts (7)
  • issueRefreshTokenCookie (100-121)
  • REFRESH_TOKEN_COOKIE_NAME (10-10)
  • CSRF_TOKEN_COOKIE_NAME (11-11)
  • setRefreshTokenCookie (35-37)
  • setCsrfTokenCookie (75-77)
  • clearRefreshTokenCookie (43-51)
  • clearCsrfTokenCookie (82-90)
backend/src/utils/response.ts (1)
  • successResponse (22-24)
backend/src/api/middlewares/error.ts (1)
  • AppError (7-17)
backend/src/infra/security/csrf.manager.ts (1)
  • CsrfManager (7-46)
backend/src/utils/logger.ts (1)
  • logger (6-29)
backend/src/infra/security/token.manager.ts (1)
  • TokenManager (36-196)
🪛 GitHub Actions: Lint and Format Check
backend/src/infra/security/token.manager.ts

[error] 86-86: TS2322: Type '"anon" | "authenticated" | "project_admin"' is not assignable to type '"authenticated" | "project_admin"'.

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: CI Pre-merge Check
  • GitHub Check: E2E Tests
🔇 Additional comments (6)
backend/src/api/routes/auth/index.routes.ts (5)

139-143: LGTM! Refresh token issuance properly integrated.

The registration and login flows correctly use issueRefreshTokenCookie to set both refresh and CSRF cookies, and include the CSRF token in the response for subsequent requests. The centralized helper ensures consistent cookie configuration.

Also applies to: 174-178


188-202: Good: CSRF protection properly implemented on /refresh endpoint.

The endpoint correctly validates CSRF tokens using double-submit cookie pattern, comparing the X-CSRF-Token header with the cookie value using timing-safe comparison. This prevents basic CSRF attacks.


216-228: Good: Token rotation implemented for enhanced security.

The refresh flow generates new refresh tokens on each request (token rotation), which limits the window of opportunity for token replay attacks. New CSRF tokens are also generated for the rotated refresh tokens.


253-267: Good: Logout properly clears security cookies.

The logout endpoint correctly clears both refresh token and CSRF token cookies, ensuring complete session termination.


553-560: Email verification correctly issues refresh tokens.

After successful email verification, the flow appropriately sets refresh and CSRF cookies and includes the CSRF token in the response, enabling authenticated sessions.

backend/src/infra/security/csrf.manager.ts (1)

1-46: LGTM! Solid CSRF protection implementation.

The CsrfManager correctly implements the Double Submit Cookie pattern with:

  • HMAC-SHA256 token derivation from refresh token
  • Timing-safe comparison to prevent timing attacks
  • Proper validation of both header and cookie presence
  • Graceful error handling in verify method

The implementation aligns with OWASP CSRF Prevention Cheat Sheet recommendations.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
backend/src/infra/security/token.manager.ts (1)

7-10: Refresh/access token expiry are identical; consider separate config for refresh TTL
Having JWT_EXPIRES_IN and REFRESH_TOKEN_EXPIRES_IN both set to '7d' removes the usual security/UX distinction between short-lived access tokens and longer-lived refresh tokens. Consider making REFRESH_TOKEN_EXPIRES_IN environment-configurable (and likely longer) to match the intended flow.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 416642a and 2bbc52c.

📒 Files selected for processing (1)
  • backend/src/infra/security/token.manager.ts (3 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx,js,jsx}: Use TypeScript for all code files
Prefer descriptive, unabbreviated variable and function names
Follow consistent file naming: kebab-case for files, PascalCase for components
Use ES modules (import/export syntax)
Implement proper error handling with try-catch blocks
Add appropriate logging for debugging
Use camelCase for variables, parameters, properties, and functions
Use UPPER_CASE for constants and Enum members
Avoid snake_case except in SQL queries and external APIs
Use single quotes for strings
Include semicolons at the end of statements
Use arrow functions for callbacks and inline functions
Prefer const over let, avoid var
Use template literals for string interpolation
Maintain consistent indentation (2 spaces)
Format code with Prettier configuration
Include JSDoc comments for complex functions

Files:

  • backend/src/infra/security/token.manager.ts
backend/src/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

backend/src/**/*.{ts,js}: Use async/await for asynchronous operations in backend code
Implement proper database transaction handling
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper database indexing

Files:

  • backend/src/infra/security/token.manager.ts
{backend/src/**/*.{ts,js},shared-schemas/**/*.{ts,js}}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use Zod schemas for request/response validation in backend

Files:

  • backend/src/infra/security/token.manager.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use PascalCase for React components and TypeScript types/interfaces

Files:

  • backend/src/infra/security/token.manager.ts
{backend,frontend}/src/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use environment variables for configuration

Files:

  • backend/src/infra/security/token.manager.ts
{backend/src,frontend/src}/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

{backend/src,frontend/src}/**/*.{ts,tsx,js,jsx}: Implement proper caching strategies
Monitor and log performance metrics

Files:

  • backend/src/infra/security/token.manager.ts
🧠 Learnings (3)
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to **/*.{ts,tsx,js,jsx} : Include JSDoc comments for complex functions

Applied to files:

  • backend/src/infra/security/token.manager.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/{api,core,controllers}/**/*.{ts,js} : Implement proper authentication and authorization

Applied to files:

  • backend/src/infra/security/token.manager.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/api/**/*.{ts,js} : Implement proper middleware for authentication and error handling

Applied to files:

  • backend/src/infra/security/token.manager.ts
🧬 Code graph analysis (1)
backend/src/infra/security/token.manager.ts (2)
shared-schemas/src/auth.schema.ts (1)
  • TokenPayloadSchema (127-127)
backend/src/api/middlewares/error.ts (1)
  • AppError (7-17)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: E2E Tests
🔇 Additional comments (1)
backend/src/infra/security/token.manager.ts (1)

11-19: RefreshTokenPayload shape looks good (explicit type: 'refresh')
The explicit discriminator makes it harder to confuse refresh vs access tokens.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 (1)
backend/src/infra/security/token.manager.ts (1)

155-166: Add explicit algorithm restriction to access token verification.

A previous review recommended applying the same algorithm restriction pattern to verifyToken() for consistency and security. While the defaults in jsonwebtoken v9+ are safe, explicit restriction is a security best practice.

Apply this diff:

   verifyToken(token: string): TokenPayloadSchema {
     try {
-      const decoded = jwt.verify(token, JWT_SECRET) as TokenPayloadSchema;
+      const decoded = jwt.verify(token, JWT_SECRET, {
+        algorithms: ['HS256'],
+      }) as TokenPayloadSchema;
       return {
         sub: decoded.sub,
         email: decoded.email,
         role: decoded.role || 'authenticated',
       };
     } catch {
       throw new AppError('Invalid token', 401, ERROR_CODES.AUTH_UNAUTHORIZED);
     }
   }
🧹 Nitpick comments (1)
backend/src/infra/security/token.manager.ts (1)

78-100: Prefer a dedicated signing secret for refresh tokens.

Both access and refresh tokens currently use JWT_SECRET. Using separate secrets reduces the blast radius if one key is compromised—a recommended security practice for token-based authentication that was noted in previous review rounds.

Define a new environment variable and constant:

const REFRESH_TOKEN_SECRET = process.env.REFRESH_TOKEN_SECRET ?? JWT_SECRET;

Then update the signing call:

   return jwt.sign(refreshPayload, JWT_SECRET, {
-    algorithm: 'HS256',
+  return jwt.sign(refreshPayload, REFRESH_TOKEN_SECRET, {
+    algorithm: 'HS256',
     expiresIn: REFRESH_TOKEN_EXPIRES_IN,
   });

And update the constructor validation and verifyRefreshToken accordingly to use REFRESH_TOKEN_SECRET.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2bbc52c and e6c2d55.

📒 Files selected for processing (1)
  • backend/src/infra/security/token.manager.ts (3 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx,js,jsx}: Use TypeScript for all code files
Prefer descriptive, unabbreviated variable and function names
Follow consistent file naming: kebab-case for files, PascalCase for components
Use ES modules (import/export syntax)
Implement proper error handling with try-catch blocks
Add appropriate logging for debugging
Use camelCase for variables, parameters, properties, and functions
Use UPPER_CASE for constants and Enum members
Avoid snake_case except in SQL queries and external APIs
Use single quotes for strings
Include semicolons at the end of statements
Use arrow functions for callbacks and inline functions
Prefer const over let, avoid var
Use template literals for string interpolation
Maintain consistent indentation (2 spaces)
Format code with Prettier configuration
Include JSDoc comments for complex functions

Files:

  • backend/src/infra/security/token.manager.ts
backend/src/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

backend/src/**/*.{ts,js}: Use async/await for asynchronous operations in backend code
Implement proper database transaction handling
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper database indexing

Files:

  • backend/src/infra/security/token.manager.ts
{backend/src/**/*.{ts,js},shared-schemas/**/*.{ts,js}}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use Zod schemas for request/response validation in backend

Files:

  • backend/src/infra/security/token.manager.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use PascalCase for React components and TypeScript types/interfaces

Files:

  • backend/src/infra/security/token.manager.ts
{backend,frontend}/src/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use environment variables for configuration

Files:

  • backend/src/infra/security/token.manager.ts
{backend/src,frontend/src}/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

{backend/src,frontend/src}/**/*.{ts,tsx,js,jsx}: Implement proper caching strategies
Monitor and log performance metrics

Files:

  • backend/src/infra/security/token.manager.ts
🧠 Learnings (3)
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to **/*.{ts,tsx,js,jsx} : Include JSDoc comments for complex functions

Applied to files:

  • backend/src/infra/security/token.manager.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/{api,core,controllers}/**/*.{ts,js} : Implement proper authentication and authorization

Applied to files:

  • backend/src/infra/security/token.manager.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/api/**/*.{ts,js} : Implement proper middleware for authentication and error handling

Applied to files:

  • backend/src/infra/security/token.manager.ts
🧬 Code graph analysis (1)
backend/src/infra/security/token.manager.ts (2)
shared-schemas/src/auth.schema.ts (1)
  • TokenPayloadSchema (127-127)
backend/src/api/middlewares/error.ts (1)
  • AppError (7-17)
🪛 GitHub Actions: Lint and Format Check
backend/src/infra/security/token.manager.ts

[error] 112-112: ESLint: prettier/prettier - Delete extra newline at line 112. Run 'eslint --fix' or 'prettier --write' to fix formatting.

🪛 GitHub Check: lint-and-format
backend/src/infra/security/token.manager.ts

[failure] 112-112:
Delete ⏎

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: CI Pre-merge Check
  • GitHub Check: E2E Tests
🔇 Additional comments (1)
backend/src/infra/security/token.manager.ts (1)

102-135: Well-implemented refresh token verification.

The method properly restricts algorithms, validates all required fields at runtime, and handles errors appropriately. The implementation addresses the security recommendations from previous review rounds.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 (3)
backend/src/infra/security/token.manager.ts (3)

11-19: RefreshTokenPayload shape looks good; consider including iat/jti for rotation/reuse detection.
If you’re rotating refresh tokens, a jti (and optionally a “family” id) makes server-side revocation/reuse detection much easier.


78-100: Refresh-token generation is correctly guarded for anon; consider separate signing secret/key.
The anon guard + typed payload is solid. For defense-in-depth, consider signing refresh tokens with a dedicated REFRESH_TOKEN_SECRET (separate from JWT_SECRET) to reduce blast radius of a key leak.


102-134: Refresh-token verification is nicely hardened; add explicit “decoded is object + string fields” checks.
jwt.verify can yield non-object payloads; today this still fails closed, but adding typeof decoded === 'object' && decoded !== null plus typeof decoded.sub/email === 'string' will avoid edge-case coercions and make the checks unambiguous.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e6c2d55 and e245cfb.

📒 Files selected for processing (1)
  • backend/src/infra/security/token.manager.ts (3 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx,js,jsx}: Use TypeScript for all code files
Prefer descriptive, unabbreviated variable and function names
Follow consistent file naming: kebab-case for files, PascalCase for components
Use ES modules (import/export syntax)
Implement proper error handling with try-catch blocks
Add appropriate logging for debugging
Use camelCase for variables, parameters, properties, and functions
Use UPPER_CASE for constants and Enum members
Avoid snake_case except in SQL queries and external APIs
Use single quotes for strings
Include semicolons at the end of statements
Use arrow functions for callbacks and inline functions
Prefer const over let, avoid var
Use template literals for string interpolation
Maintain consistent indentation (2 spaces)
Format code with Prettier configuration
Include JSDoc comments for complex functions

Files:

  • backend/src/infra/security/token.manager.ts
backend/src/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

backend/src/**/*.{ts,js}: Use async/await for asynchronous operations in backend code
Implement proper database transaction handling
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper database indexing

Files:

  • backend/src/infra/security/token.manager.ts
{backend/src/**/*.{ts,js},shared-schemas/**/*.{ts,js}}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use Zod schemas for request/response validation in backend

Files:

  • backend/src/infra/security/token.manager.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use PascalCase for React components and TypeScript types/interfaces

Files:

  • backend/src/infra/security/token.manager.ts
{backend,frontend}/src/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use environment variables for configuration

Files:

  • backend/src/infra/security/token.manager.ts
{backend/src,frontend/src}/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

{backend/src,frontend/src}/**/*.{ts,tsx,js,jsx}: Implement proper caching strategies
Monitor and log performance metrics

Files:

  • backend/src/infra/security/token.manager.ts
🧠 Learnings (3)
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to **/*.{ts,tsx,js,jsx} : Include JSDoc comments for complex functions

Applied to files:

  • backend/src/infra/security/token.manager.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/{api,core,controllers}/**/*.{ts,js} : Implement proper authentication and authorization

Applied to files:

  • backend/src/infra/security/token.manager.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/api/**/*.{ts,js} : Implement proper middleware for authentication and error handling

Applied to files:

  • backend/src/infra/security/token.manager.ts
🧬 Code graph analysis (1)
backend/src/infra/security/token.manager.ts (2)
shared-schemas/src/auth.schema.ts (1)
  • TokenPayloadSchema (127-127)
backend/src/api/middlewares/error.ts (1)
  • AppError (7-17)
🔇 Additional comments (1)
backend/src/infra/security/token.manager.ts (1)

52-60: Access-token generation change is fine.
JSDoc update is clear and matches the surrounding style.

@Fermionic-Lyu Fermionic-Lyu left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fix the AI spaghetti code plz

Comment thread auth/package.json Resolved
Comment thread backend/src/utils/cookies.ts Resolved
httpOnly: true,
secure: isCloud,
sameSite: isCloud ? ('none' as const) : ('lax' as const),
path: '/api/auth',

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Why not just strictly '/api/auth/refresh'?

@Leo-rq-yu Leo-rq-yu Dec 16, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The logout api also needs to access this cookie to clean it.

Comment thread backend/src/utils/cookies.ts Resolved
Comment thread backend/src/utils/cookies.ts Resolved
Comment thread backend/src/utils/cookies.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
backend/src/api/routes/auth/index.routes.ts (1)

187-243: Add rate limiting to prevent brute-force attacks on the refresh endpoint.

The /refresh endpoint lacks rate limiting, making it vulnerable to token enumeration and brute-force attacks. Other authentication endpoints in this file use rate limiters (e.g., sendEmailOTPLimiter, verifyOTPLimiter).

Apply this diff to add rate limiting:

 // POST /api/auth/refresh - Refresh access token using httpOnly cookie
 // Requires X-CSRF-Token header for CSRF protection
-router.post('/refresh', async (req: Request, res: Response, next: NextFunction) => {
+router.post('/refresh', verifyOTPLimiter, async (req: Request, res: Response, next: NextFunction) => {

The rest of the implementation is solid:

  • CSRF validation prevents cross-site token theft
  • User existence check prevents deleted users from maintaining sessions
  • Token rotation (new refresh + access tokens) follows security best practices
  • Error handling correctly clears cookies on failure

Based on coding guidelines, API endpoints should implement rate limiting.

🧹 Nitpick comments (1)
backend/src/utils/cookies.ts (1)

9-9: Import isProduction instead of duplicating the logic.

The isProduction() function already exists in backend/src/utils/environment.ts. Duplicating this logic creates a maintenance burden and violates DRY.

Apply this diff to use the existing utility:

 import { Response } from 'express';
+import { isProduction } from './environment.js';

 /**
  * Cookie names
  */
 export const REFRESH_TOKEN_COOKIE_NAME = 'insforge_refresh_token';
 export const CSRF_TOKEN_COOKIE_NAME = 'insforge_csrf_token';

-const isProduction = process.env.NODE_ENV === 'production';
-

Then update the function calls to use isProduction() instead of isProduction:

 export function setAuthCookie(res: Response, name: string, value: string): void {
   res.cookie(name, value, {
     httpOnly: true,
-    secure: isProduction,
+    secure: isProduction(),
     sameSite: 'none',
     path: '/api/auth',
     maxAge: 7 * 24 * 60 * 60 * 1000, // 7 days
   });
 }
 export function clearAuthCookie(res: Response, name: string): void {
   res.clearCookie(name, {
     httpOnly: true,
-    secure: isProduction,
+    secure: isProduction(),
     sameSite: 'none',
     path: '/api/auth',
   });
 }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e245cfb and 099d706.

📒 Files selected for processing (4)
  • backend/src/api/routes/auth/index.routes.ts (6 hunks)
  • backend/src/api/routes/auth/oauth.routes.ts (3 hunks)
  • backend/src/infra/security/token.manager.ts (4 hunks)
  • backend/src/utils/cookies.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (10)
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx,js,jsx}: Use TypeScript for all code files
Prefer descriptive, unabbreviated variable and function names
Follow consistent file naming: kebab-case for files, PascalCase for components
Use ES modules (import/export syntax)
Implement proper error handling with try-catch blocks
Add appropriate logging for debugging
Use camelCase for variables, parameters, properties, and functions
Use UPPER_CASE for constants and Enum members
Avoid snake_case except in SQL queries and external APIs
Use single quotes for strings
Include semicolons at the end of statements
Use arrow functions for callbacks and inline functions
Prefer const over let, avoid var
Use template literals for string interpolation
Maintain consistent indentation (2 spaces)
Format code with Prettier configuration
Include JSDoc comments for complex functions

Files:

  • backend/src/utils/cookies.ts
  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/infra/security/token.manager.ts
  • backend/src/api/routes/auth/oauth.routes.ts
backend/src/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

backend/src/**/*.{ts,js}: Use async/await for asynchronous operations in backend code
Implement proper database transaction handling
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper database indexing

Files:

  • backend/src/utils/cookies.ts
  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/infra/security/token.manager.ts
  • backend/src/api/routes/auth/oauth.routes.ts
{backend/src/**/*.{ts,js},shared-schemas/**/*.{ts,js}}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use Zod schemas for request/response validation in backend

Files:

  • backend/src/utils/cookies.ts
  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/infra/security/token.manager.ts
  • backend/src/api/routes/auth/oauth.routes.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use PascalCase for React components and TypeScript types/interfaces

Files:

  • backend/src/utils/cookies.ts
  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/infra/security/token.manager.ts
  • backend/src/api/routes/auth/oauth.routes.ts
{backend,frontend}/src/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use environment variables for configuration

Files:

  • backend/src/utils/cookies.ts
  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/infra/security/token.manager.ts
  • backend/src/api/routes/auth/oauth.routes.ts
{backend/src,frontend/src}/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

{backend/src,frontend/src}/**/*.{ts,tsx,js,jsx}: Implement proper caching strategies
Monitor and log performance metrics

Files:

  • backend/src/utils/cookies.ts
  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/infra/security/token.manager.ts
  • backend/src/api/routes/auth/oauth.routes.ts
backend/src/api/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

backend/src/api/**/*.{ts,js}: Implement proper middleware for authentication and error handling
Follow RESTful conventions for API endpoints
Implement rate limiting for API endpoints

Files:

  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/api/routes/auth/oauth.routes.ts
backend/src/{controllers,api}/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Return consistent API responses using utility functions

Files:

  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/api/routes/auth/oauth.routes.ts
backend/src/{api,core,controllers}/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Implement proper authentication and authorization

Files:

  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/api/routes/auth/oauth.routes.ts
{backend/src/api,openapi}/**/*.{ts,yaml,yml,json}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Document all API endpoints with clear descriptions

Files:

  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/api/routes/auth/oauth.routes.ts
🧠 Learnings (6)
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/{api,core,controllers}/**/*.{ts,js} : Implement proper authentication and authorization

Applied to files:

  • backend/src/utils/cookies.ts
  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/infra/security/token.manager.ts
  • backend/src/api/routes/auth/oauth.routes.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/api/**/*.{ts,js} : Implement proper middleware for authentication and error handling

Applied to files:

  • backend/src/utils/cookies.ts
  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/infra/security/token.manager.ts
  • backend/src/api/routes/auth/oauth.routes.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/api/**/*.{ts,js} : Follow RESTful conventions for API endpoints

Applied to files:

  • backend/src/api/routes/auth/index.routes.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/api/**/*.{ts,js} : Implement rate limiting for API endpoints

Applied to files:

  • backend/src/api/routes/auth/index.routes.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to {backend/src/**/*.{ts,js},shared-schemas/**/*.{ts,js}} : Use Zod schemas for request/response validation in backend

Applied to files:

  • backend/src/api/routes/auth/index.routes.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to **/*.{ts,tsx,js,jsx} : Include JSDoc comments for complex functions

Applied to files:

  • backend/src/infra/security/token.manager.ts
🧬 Code graph analysis (3)
backend/src/utils/cookies.ts (1)
backend/src/utils/environment.ts (1)
  • isProduction (31-33)
backend/src/infra/security/token.manager.ts (1)
backend/src/api/middlewares/error.ts (1)
  • AppError (7-17)
backend/src/api/routes/auth/oauth.routes.ts (2)
backend/src/infra/security/token.manager.ts (1)
  • TokenManager (36-217)
backend/src/utils/cookies.ts (3)
  • setAuthCookie (16-24)
  • REFRESH_TOKEN_COOKIE_NAME (6-6)
  • CSRF_TOKEN_COOKIE_NAME (7-7)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: E2E Tests
  • GitHub Check: CI Pre-merge Check
🔇 Additional comments (16)
backend/src/utils/cookies.ts (2)

1-8: LGTM!

The imports and cookie name constants are well-defined and follow naming conventions.


16-36: Cookie helpers are reasonable given multiple call sites.

Past review feedback suggested inlining these helpers to reduce indirection. However, given that setAuthCookie and clearAuthCookie are called from multiple endpoints across the authentication routes (login, registration, refresh, verification, OAuth callbacks), keeping them as reusable utilities is justified and improves maintainability.

The implementation correctly uses matching options for both setting and clearing cookies, which is essential for reliable cookie removal.

backend/src/api/routes/auth/oauth.routes.ts (3)

5-5: LGTM!

The new imports for token management and cookie utilities are properly structured and necessary for the refresh token implementation.

Also applies to: 10-14


350-362: Token management implementation looks solid.

The refresh token and CSRF token flow is correctly implemented:

  • Refresh token is generated with just the user ID (no hardcoded role, addressing past feedback)
  • CSRF token is derived from the refresh token using HMAC
  • Both tokens are set in httpOnly cookies before the redirect
  • CSRF token is included in the redirect URL for client-side access

This follows security best practices for cookie-based authentication.


429-442: LGTM!

The provider callback implements the same secure token management pattern as the shared callback, ensuring consistency across OAuth flows.

backend/src/api/routes/auth/index.routes.ts (5)

13-18: LGTM!

The new imports for cookie management and logging are properly organized and necessary for the refresh token implementation.

Also applies to: 47-47


135-153: LGTM!

Registration correctly sets refresh token and CSRF token in httpOnly cookies when a user is created, and includes the CSRF token in the response for client-side use.


174-185: LGTM!

Login correctly implements the token management pattern, setting refresh and CSRF tokens in httpOnly cookies and including the CSRF token in the response.


245-259: LGTM!

The logout endpoint correctly clears both the refresh token and CSRF token cookies, following the expected logout flow.


545-551: LGTM!

Email verification correctly sets refresh and CSRF tokens after successful verification, establishing a persistent session for the newly verified user.

backend/src/infra/security/token.manager.ts (6)

2-2: LGTM!

The crypto import and refresh token expiration constant are properly defined. (Note: Past feedback about different token lifetimes was acknowledged and deferred by the maintainer.)

Also applies to: 10-10


12-19: LGTM!

The RefreshTokenPayload interface is well-designed:

  • Contains only essential fields (sub, type, iss)
  • Removed email and role (reducing token size and attack surface)
  • Includes iss (issuer) to prevent token confusion attacks
  • exp is automatically added by jwt.sign, so it's not needed in the interface

This addresses past feedback effectively.


53-53: LGTM!

The generateRefreshToken method has been simplified and improved:

  • Takes only userId (cleaner signature)
  • Generates minimal payload with just essential fields
  • Properly sets type: 'refresh' and iss: 'insforge' for token type validation and issuer verification
  • JSDoc is clear and accurate

This is a significant improvement over passing the full payload.

Also applies to: 78-91


93-116: Refresh token verification is properly hardened.

The implementation correctly:

  • Restricts algorithms to ['HS256'] (prevents algorithm confusion attacks)
  • Validates issuer is 'insforge' (prevents token substitution)
  • Checks token type is 'refresh' (prevents access tokens from being used as refresh tokens)
  • Validates sub field exists
  • Returns the decoded payload directly (clean implementation)
  • Properly handles errors with appropriate error codes

This addresses all past security feedback.


193-202: LGTM!

The CSRF token generation uses HMAC-SHA256 to cryptographically derive the CSRF token from the refresh token, creating a secure binding between them. The 32-character hex output provides adequate entropy (128 bits) for CSRF protection.

This follows OWASP CSRF prevention best practices.


204-216: LGTM!

The CSRF token verification correctly implements the double-submit cookie pattern:

  • Validates both header and cookie are present
  • Uses crypto.timingSafeEqual to prevent timing attacks
  • Gracefully handles comparison errors (e.g., length mismatch)
  • Returns false for any validation failure (fail-safe)

This is a secure implementation of CSRF protection.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (3)
backend/src/infra/security/token.manager.ts (1)

94-117: Solid refresh token verification with proper security controls.

The implementation correctly restricts algorithms to ['HS256'] and validates the issuer claim, which prevents algorithm confusion attacks. The type check ensures access tokens cannot be used as refresh tokens.

Consider applying the same algorithms: ['HS256'] restriction to verifyToken() (line 139) for consistency. Currently it uses the default algorithm detection:

  verifyToken(token: string): TokenPayloadSchema {
    try {
-     const decoded = jwt.verify(token, JWT_SECRET) as TokenPayloadSchema;
+     const decoded = jwt.verify(token, JWT_SECRET, {
+       algorithms: ['HS256'],
+     }) as TokenPayloadSchema;
      return {
        sub: decoded.sub,
        email: decoded.email,
        role: decoded.role || 'authenticated',
      };
    } catch {
      throw new AppError('Invalid token', 401, ERROR_CODES.AUTH_UNAUTHORIZED);
    }
  }
backend/src/api/routes/auth/index.routes.ts (2)

184-236: Well-implemented refresh endpoint with CSRF protection and token rotation.

The implementation correctly:

  • Validates the CSRF token before processing (lines 196-201)
  • Checks user existence and clears cookies if not found (lines 207-211)
  • Implements token rotation for enhanced security (lines 220-224)
  • Returns fresh CSRF token with the rotated refresh token

Consider adding rate limiting to prevent brute-force attempts, as mentioned in past reviews. The verifyOTPLimiter or a dedicated limiter could be appropriate:

 // POST /api/auth/refresh - Refresh access token using httpOnly cookie
 // Requires X-CSRF-Token header for CSRF protection
-router.post('/refresh', async (req: Request, res: Response, next: NextFunction) => {
+router.post('/refresh', verifyOTPLimiter, async (req: Request, res: Response, next: NextFunction) => {

As per coding guidelines, API endpoints should implement rate limiting.


231-235: Consider selective cookie clearing on error.

Currently, any error clears the refresh token cookie, including transient issues. While this is a secure-by-default approach, it may force unnecessary re-authentication for non-security-related errors.

Consider only clearing the cookie for authentication-related errors:

   } catch (error) {
-    // Clear invalid cookie on error
-    clearAuthCookie(res, REFRESH_TOKEN_COOKIE_NAME);
+    // Only clear cookie for auth-related errors
+    if (error instanceof AppError && error.code === ERROR_CODES.AUTH_UNAUTHORIZED) {
+      clearAuthCookie(res, REFRESH_TOKEN_COOKIE_NAME);
+    }
     next(error);
   }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c1d7497 and 2d7625d.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (10)
  • auth/package.json (1 hunks)
  • auth/src/lib/broadcastService.ts (2 hunks)
  • auth/src/pages/SignInPage.tsx (2 hunks)
  • auth/src/pages/SignUpPage.tsx (2 hunks)
  • backend/package.json (2 hunks)
  • backend/src/api/routes/auth/index.routes.ts (6 hunks)
  • backend/src/api/routes/auth/oauth.routes.ts (3 hunks)
  • backend/src/infra/security/token.manager.ts (4 hunks)
  • backend/src/server.ts (2 hunks)
  • backend/src/utils/cookies.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (6)
  • auth/src/pages/SignUpPage.tsx
  • backend/src/utils/cookies.ts
  • backend/package.json
  • auth/src/pages/SignInPage.tsx
  • backend/src/server.ts
  • auth/package.json
🧰 Additional context used
📓 Path-based instructions (10)
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx,js,jsx}: Use TypeScript for all code files
Prefer descriptive, unabbreviated variable and function names
Follow consistent file naming: kebab-case for files, PascalCase for components
Use ES modules (import/export syntax)
Implement proper error handling with try-catch blocks
Add appropriate logging for debugging
Use camelCase for variables, parameters, properties, and functions
Use UPPER_CASE for constants and Enum members
Avoid snake_case except in SQL queries and external APIs
Use single quotes for strings
Include semicolons at the end of statements
Use arrow functions for callbacks and inline functions
Prefer const over let, avoid var
Use template literals for string interpolation
Maintain consistent indentation (2 spaces)
Format code with Prettier configuration
Include JSDoc comments for complex functions

Files:

  • backend/src/api/routes/auth/oauth.routes.ts
  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/infra/security/token.manager.ts
  • auth/src/lib/broadcastService.ts
backend/src/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

backend/src/**/*.{ts,js}: Use async/await for asynchronous operations in backend code
Implement proper database transaction handling
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper database indexing

Files:

  • backend/src/api/routes/auth/oauth.routes.ts
  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/infra/security/token.manager.ts
backend/src/api/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

backend/src/api/**/*.{ts,js}: Implement proper middleware for authentication and error handling
Follow RESTful conventions for API endpoints
Implement rate limiting for API endpoints

Files:

  • backend/src/api/routes/auth/oauth.routes.ts
  • backend/src/api/routes/auth/index.routes.ts
{backend/src/**/*.{ts,js},shared-schemas/**/*.{ts,js}}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use Zod schemas for request/response validation in backend

Files:

  • backend/src/api/routes/auth/oauth.routes.ts
  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/infra/security/token.manager.ts
backend/src/{controllers,api}/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Return consistent API responses using utility functions

Files:

  • backend/src/api/routes/auth/oauth.routes.ts
  • backend/src/api/routes/auth/index.routes.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use PascalCase for React components and TypeScript types/interfaces

Files:

  • backend/src/api/routes/auth/oauth.routes.ts
  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/infra/security/token.manager.ts
  • auth/src/lib/broadcastService.ts
{backend,frontend}/src/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use environment variables for configuration

Files:

  • backend/src/api/routes/auth/oauth.routes.ts
  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/infra/security/token.manager.ts
backend/src/{api,core,controllers}/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Implement proper authentication and authorization

Files:

  • backend/src/api/routes/auth/oauth.routes.ts
  • backend/src/api/routes/auth/index.routes.ts
{backend/src,frontend/src}/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

{backend/src,frontend/src}/**/*.{ts,tsx,js,jsx}: Implement proper caching strategies
Monitor and log performance metrics

Files:

  • backend/src/api/routes/auth/oauth.routes.ts
  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/infra/security/token.manager.ts
{backend/src/api,openapi}/**/*.{ts,yaml,yml,json}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Document all API endpoints with clear descriptions

Files:

  • backend/src/api/routes/auth/oauth.routes.ts
  • backend/src/api/routes/auth/index.routes.ts
🧠 Learnings (6)
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/{api,core,controllers}/**/*.{ts,js} : Implement proper authentication and authorization

Applied to files:

  • backend/src/api/routes/auth/oauth.routes.ts
  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/infra/security/token.manager.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/api/**/*.{ts,js} : Implement proper middleware for authentication and error handling

Applied to files:

  • backend/src/api/routes/auth/oauth.routes.ts
  • backend/src/api/routes/auth/index.routes.ts
  • backend/src/infra/security/token.manager.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/api/**/*.{ts,js} : Follow RESTful conventions for API endpoints

Applied to files:

  • backend/src/api/routes/auth/index.routes.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/api/**/*.{ts,js} : Implement rate limiting for API endpoints

Applied to files:

  • backend/src/api/routes/auth/index.routes.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to {backend/src/**/*.{ts,js},shared-schemas/**/*.{ts,js}} : Use Zod schemas for request/response validation in backend

Applied to files:

  • backend/src/api/routes/auth/index.routes.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to **/*.{ts,tsx,js,jsx} : Include JSDoc comments for complex functions

Applied to files:

  • backend/src/infra/security/token.manager.ts
🧬 Code graph analysis (3)
backend/src/api/routes/auth/oauth.routes.ts (2)
backend/src/infra/security/token.manager.ts (1)
  • TokenManager (37-219)
backend/src/utils/cookies.ts (2)
  • setAuthCookie (14-22)
  • REFRESH_TOKEN_COOKIE_NAME (7-7)
backend/src/api/routes/auth/index.routes.ts (5)
backend/src/infra/security/token.manager.ts (1)
  • TokenManager (37-219)
backend/src/utils/cookies.ts (3)
  • setAuthCookie (14-22)
  • REFRESH_TOKEN_COOKIE_NAME (7-7)
  • clearAuthCookie (28-35)
backend/src/utils/response.ts (1)
  • successResponse (22-24)
backend/src/api/middlewares/error.ts (1)
  • AppError (7-17)
backend/src/utils/logger.ts (1)
  • logger (6-29)
backend/src/infra/security/token.manager.ts (1)
backend/src/api/middlewares/error.ts (1)
  • AppError (7-17)
🔇 Additional comments (11)
backend/src/api/routes/auth/oauth.routes.ts (2)

5-10: Imports look correct for the new refresh token functionality.

The TokenManager and cookie utilities (setAuthCookie, REFRESH_TOKEN_COOKIE_NAME) are correctly imported to support the new cookie-based refresh token flow.


425-438: Consistent implementation with shared callback flow.

The provider callback correctly mirrors the shared callback pattern: setting the httpOnly refresh token cookie and generating the CSRF token. The same TODO note applies for the future PKCE migration.

backend/src/infra/security/token.manager.ts (4)

9-11: Token expiration TODO acknowledged.

The TODO at line 9 correctly notes the plan to reduce access token lifetime to 15 minutes. This was discussed in past reviews and deferred to maintain backward compatibility with older SDK versions. The current 7d/7d configuration is acceptable as an interim solution.


13-20: Clean, minimal refresh token payload design.

The RefreshTokenPayload correctly includes only essential claims (sub, type, iss). Removing email and role from the refresh token (as suggested in past reviews) reduces data exposure and ensures user attributes are fetched fresh from the database during token refresh.


79-92: Clean refresh token generation implementation.

The method correctly generates a minimal refresh token with the essential claims. Using iss: 'insforge' enables proper issuer validation during verification.


193-218: Robust CSRF token implementation following OWASP guidelines.

The HMAC-SHA256 derivation from the refresh token is a secure double-submit pattern variant. The timingSafeEqual comparison correctly prevents timing attacks, and the try-catch handles buffer length mismatches gracefully.

backend/src/api/routes/auth/index.routes.ts (5)

13-17: Cookie and logger imports correctly added.

The imports for REFRESH_TOKEN_COOKIE_NAME, setAuthCookie, clearAuthCookie, and logger are properly added to support the new refresh token functionality.


134-151: Registration correctly conditionally sets refresh token.

The conditional check (result.accessToken && result.user) properly handles registration flows that may require email verification before issuing tokens. The CSRF token is correctly included in the response.


172-182: Login correctly sets refresh token and CSRF token.

The implementation correctly sets the refresh token cookie and returns the CSRF token after successful authentication. The unconditional token generation is appropriate since login always returns user data on success.


238-250: Simple and correct logout implementation.

The logout endpoint correctly clears the refresh token cookie. The unauthenticated design is appropriate since clients can always clear their own cookies, and the operation is idempotent with no harmful side effects.


536-541: Email verification correctly issues refresh token.

The implementation consistently follows the same pattern as login and registration, appropriately granting an authenticated session with refresh token after successful email verification.

Comment thread auth/src/lib/broadcastService.ts Resolved
Comment thread auth/src/lib/broadcastService.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
backend/src/api/routes/auth/index.routes.ts (1)

179-181: Add rate limiting to the /refresh endpoint.

The /refresh endpoint lacks rate limiting, unlike other authentication endpoints that use verifyOTPLimiter. Without rate limiting, this endpoint is vulnerable to brute-force attempts to find valid refresh tokens. Per coding guidelines, API endpoints should implement rate limiting.

 // POST /api/auth/refresh - Refresh access token using httpOnly cookie
 // Requires X-CSRF-Token header for CSRF protection
-router.post('/refresh', async (req: Request, res: Response, next: NextFunction) => {
+router.post('/refresh', verifyOTPLimiter, async (req: Request, res: Response, next: NextFunction) => {
🧹 Nitpick comments (2)
backend/src/infra/security/token.manager.ts (1)

137-148: Consider adding explicit algorithm restriction for consistency.

verifyRefreshToken and verifyCloudToken both specify allowed algorithms, but verifyToken does not. While jsonwebtoken v9 defaults are safe, explicit restriction adds defense-in-depth and maintains consistency.

   verifyToken(token: string): TokenPayloadSchema {
     try {
-      const decoded = jwt.verify(token, JWT_SECRET) as TokenPayloadSchema;
+      const decoded = jwt.verify(token, JWT_SECRET, {
+        algorithms: ['HS256'],
+      }) as TokenPayloadSchema;
       return {
         sub: decoded.sub,
         email: decoded.email,
         role: decoded.role || 'authenticated',
       };
     } catch {
       throw new AppError('Invalid token', 401, ERROR_CODES.AUTH_UNAUTHORIZED);
     }
   }
backend/src/api/routes/auth/index.routes.ts (1)

226-230: Cookie clearing in error handler may be overly aggressive.

The catch block clears the refresh token cookie on any error, including potential transient failures (e.g., database connectivity issues). This could unexpectedly log out users during temporary outages. Consider clearing only for authentication-specific errors.

   } catch (error) {
-    // Clear invalid cookie on error
-    clearAuthCookie(res, REFRESH_TOKEN_COOKIE_NAME);
+    // Clear cookie only for auth-related errors, not transient failures
+    if (error instanceof AppError && error.code === ERROR_CODES.AUTH_UNAUTHORIZED) {
+      clearAuthCookie(res, REFRESH_TOKEN_COOKIE_NAME);
+    }
     next(error);
   }
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2d7625d and b8b160d.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (5)
  • auth/src/lib/broadcastService.ts (1 hunks)
  • backend/src/api/routes/auth/index.routes.ts (5 hunks)
  • backend/src/infra/security/token.manager.ts (4 hunks)
  • shared-schemas/package.json (1 hunks)
  • shared-schemas/src/auth-api.schema.ts (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • auth/src/lib/broadcastService.ts
🧰 Additional context used
📓 Path-based instructions (10)
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx,js,jsx}: Use TypeScript for all code files
Prefer descriptive, unabbreviated variable and function names
Follow consistent file naming: kebab-case for files, PascalCase for components
Use ES modules (import/export syntax)
Implement proper error handling with try-catch blocks
Add appropriate logging for debugging
Use camelCase for variables, parameters, properties, and functions
Use UPPER_CASE for constants and Enum members
Avoid snake_case except in SQL queries and external APIs
Use single quotes for strings
Include semicolons at the end of statements
Use arrow functions for callbacks and inline functions
Prefer const over let, avoid var
Use template literals for string interpolation
Maintain consistent indentation (2 spaces)
Format code with Prettier configuration
Include JSDoc comments for complex functions

Files:

  • shared-schemas/src/auth-api.schema.ts
  • backend/src/infra/security/token.manager.ts
  • backend/src/api/routes/auth/index.routes.ts
{backend/src/**/*.{ts,js},shared-schemas/**/*.{ts,js}}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use Zod schemas for request/response validation in backend

Files:

  • shared-schemas/src/auth-api.schema.ts
  • backend/src/infra/security/token.manager.ts
  • backend/src/api/routes/auth/index.routes.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use PascalCase for React components and TypeScript types/interfaces

Files:

  • shared-schemas/src/auth-api.schema.ts
  • backend/src/infra/security/token.manager.ts
  • backend/src/api/routes/auth/index.routes.ts
backend/src/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

backend/src/**/*.{ts,js}: Use async/await for asynchronous operations in backend code
Implement proper database transaction handling
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper database indexing

Files:

  • backend/src/infra/security/token.manager.ts
  • backend/src/api/routes/auth/index.routes.ts
{backend,frontend}/src/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use environment variables for configuration

Files:

  • backend/src/infra/security/token.manager.ts
  • backend/src/api/routes/auth/index.routes.ts
{backend/src,frontend/src}/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

{backend/src,frontend/src}/**/*.{ts,tsx,js,jsx}: Implement proper caching strategies
Monitor and log performance metrics

Files:

  • backend/src/infra/security/token.manager.ts
  • backend/src/api/routes/auth/index.routes.ts
backend/src/api/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

backend/src/api/**/*.{ts,js}: Implement proper middleware for authentication and error handling
Follow RESTful conventions for API endpoints
Implement rate limiting for API endpoints

Files:

  • backend/src/api/routes/auth/index.routes.ts
backend/src/{controllers,api}/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Return consistent API responses using utility functions

Files:

  • backend/src/api/routes/auth/index.routes.ts
backend/src/{api,core,controllers}/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Implement proper authentication and authorization

Files:

  • backend/src/api/routes/auth/index.routes.ts
{backend/src/api,openapi}/**/*.{ts,yaml,yml,json}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Document all API endpoints with clear descriptions

Files:

  • backend/src/api/routes/auth/index.routes.ts
🧠 Learnings (6)
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to {backend/src/**/*.{ts,js},shared-schemas/**/*.{ts,js}} : Use Zod schemas for request/response validation in backend

Applied to files:

  • shared-schemas/src/auth-api.schema.ts
  • backend/src/api/routes/auth/index.routes.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/{api,core,controllers}/**/*.{ts,js} : Implement proper authentication and authorization

Applied to files:

  • shared-schemas/src/auth-api.schema.ts
  • backend/src/infra/security/token.manager.ts
  • backend/src/api/routes/auth/index.routes.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to **/*.{ts,tsx,js,jsx} : Include JSDoc comments for complex functions

Applied to files:

  • backend/src/infra/security/token.manager.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/api/**/*.{ts,js} : Implement proper middleware for authentication and error handling

Applied to files:

  • backend/src/infra/security/token.manager.ts
  • backend/src/api/routes/auth/index.routes.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/api/**/*.{ts,js} : Follow RESTful conventions for API endpoints

Applied to files:

  • backend/src/api/routes/auth/index.routes.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/api/**/*.{ts,js} : Implement rate limiting for API endpoints

Applied to files:

  • backend/src/api/routes/auth/index.routes.ts
🧬 Code graph analysis (2)
shared-schemas/src/auth-api.schema.ts (1)
shared-schemas/src/auth.schema.ts (1)
  • userSchema (35-50)
backend/src/infra/security/token.manager.ts (1)
backend/src/api/middlewares/error.ts (1)
  • AppError (7-17)
🔇 Additional comments (12)
shared-schemas/package.json (1)

3-3: LGTM!

Version bump aligns with the schema additions for CSRF token support and the new RefreshSessionResponse type.

backend/src/infra/security/token.manager.ts (4)

16-20: Good simplification of refresh token payload.

The minimal payload (sub, type, iss) follows best practices for refresh tokens - they should contain only what's needed for token rotation. Email and role are correctly fetched from the database during refresh.


79-92: LGTM!

Clean implementation that generates minimal refresh tokens with just the user ID and token type. This addresses the previous type error with anon roles and follows the pattern suggested in prior reviews.


98-117: LGTM!

Refresh token verification is properly hardened with explicit algorithm restriction, issuer validation, and payload field checks as requested in prior reviews.


193-215: LGTM!

CSRF implementation follows OWASP recommendations: HMAC derivation from the refresh token for stateless verification, timing-safe comparison to prevent timing attacks, and proper null/undefined handling.

backend/src/api/routes/auth/index.routes.ts (4)

130-136: LGTM!

Correctly gates refresh token cookie setting on having both an access token and user, handling the email verification required flow where tokens aren't issued immediately.


167-172: LGTM!

Login flow correctly sets the refresh token cookie and generates CSRF token for the response.


233-245: LGTM!

Logout endpoint correctly clears the refresh token cookie. Allowing unauthenticated calls is appropriate as it enables clearing stale cookies.


531-536: LGTM!

Email verification flow correctly issues refresh token and CSRF token after successful verification.

shared-schemas/src/auth-api.schema.ts (3)

131-131: LGTM!

Adding csrfToken as nullable and optional maintains backward compatibility with existing SDK versions that don't expect this field.


156-164: LGTM!

The refreshSessionResponseSchema correctly requires csrfToken since this is a new endpoint where the contract can be enforced from the start. The required field ensures clients properly handle CSRF tokens in the refresh flow.


342-342: LGTM!

Type export is properly placed with other response types.

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.

3 participants