Skip to content

feat: refactor OAuth system for scalability and type safety - #484

Merged
tonychang04 merged 7 commits into
InsForge:oauth-refactorfrom
Laaaaksh:feat---oauth_code_refactor
Oct 22, 2025
Merged

tonychang04 merged 7 commits into
InsForge:oauth-refactorfrom
Laaaaksh:feat---oauth_code_refactor

Conversation

@Laaaaksh

@Laaaaksh Laaaaksh commented Oct 19, 2025 •

Copy link
Copy Markdown
Contributor

Summary

  • Replace hardcoded provider routes with unified wildcard endpoint
  • Implement generic OAuth methods using OAuthProvidersSchema
  • Add comprehensive error handling for unsupported providers
  • Remove repetitive code and improve maintainability
  • Fix route ordering to prevent wildcard route conflicts
  • Enhance type safety across frontend and backend
  • Add dynamic provider management in frontend
  • Remove noisy else statements for cleaner code"

Fixes - #464

How did you test this change?

🧪 Testing Status

✅ Verified (Code Implementation)

  • Unsupported Providers: 400 error handling implemented and verified
  • Error Messages: Clear validation messages with supported providers list
  • Type Safety: OAuthProvidersSchema validation working correctly
  • Code Quality: Linting passes (0 errors, 0 warnings)

⚠️ Pending (Live API Testing)

  • HTTP Responses: Requires running backend to test actual API responses
  • E2E OAuth Flow: Complete authentication flow testing
  • Frontend Integration: OAuth configuration UI testing

Summary by CodeRabbit

Release Notes

  • New Features

    • Unified OAuth initialization flow with provider validation
    • Origin-based validation for secure OAuth redirects
    • Cookie-based token propagation for improved security
    • Enhanced OAuth configuration endpoints with timestamps and resource IDs
  • Chores

    • Updated environment configuration to support OAuth allowed origins

@coderabbitai

coderabbitai Bot commented Oct 19, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Unified OAuth provider handling by introducing centralized routes with provider validation, origin-based redirect security, and secure cookie-based token propagation. Expanded backend and frontend code to generalize provider support (Google, GitHub, Discord, LinkedIn, Facebook, Microsoft, etc.) through typed schemas instead of string unions, added database metadata tracking (id, timestamps), and refactored seeding logic.

Changes

Cohort / File(s) Summary
OAuth Route Refactoring
backend/src/api/routes/auth.oauth.ts
Replaced provider-specific routes with unified GET /:provider flow; added provider and origin validation; implemented shared callback handler (/shared/callback/:state) and provider-specific callbacks; introduced cookie-based token propagation with helper functions (setAuthCookies, clearAuthCookies, validateRedirectOrigin); updated ListOAuthConfigsResponse structure to include id, timestamps.
Auth Service Abstraction
backend/src/core/auth/auth.ts
Added provider-agnostic entry points: generateAuthUrl() and handleOAuthCallback(); added provider-specific callback handlers (Google, GitHub, Discord, LinkedIn); changed return types for Google and LinkedIn URL generation from string | undefined to string; added OAuthProvidersSchema type import.
OAuth Configuration Layer
backend/src/core/auth/oauth.ts
Updated queries to include id and timestamps (createdAt, updatedAt); changed provider field type from string to OAuthProvidersSchema; expanded default scopes assignment with provider-specific switch logic; updated all CRUD operations to return new fields.
Database Seeding Generalization
backend/src/utils/seed.ts
Generalized provider seeding by replacing per-provider code with loops over provider arrays (defaultProviders and envMappings); added support for google, github, discord, linkedin via environment-based configuration.
Shared Schema Definitions
shared-schemas/src/auth.schema.ts
Added id (uuid), createdAt, updatedAt fields to oAuthConfigSchema; changed provider field type from z.string() to oAuthProvidersSchema; updated OAuthConfigSchema structure.
Request Schema Validation
shared-schemas/src/auth-api.schema.ts
Updated CreateOAuthConfigRequestSchema to omit id, createdAt, updatedAt; updated UpdateOAuthConfigRequestSchema to omit id, provider, createdAt, updatedAt and apply .partial() for optional fields.
Frontend OAuth Components
frontend/src/features/auth/components/AddOAuthDialog.tsx, AuthMethodTab.tsx, OAuthConfigDialog.tsx
Updated component prop/parameter types to use OAuthProvidersSchema instead of string unions; replaced hardcoded provider lists with dynamic provider schema usage; updated shared key provider checking to use array-based logic.
Frontend OAuth Hooks
frontend/src/features/auth/hooks/useOAuthConfig.ts
Updated selectedProvider state type from string | null to OAuthProvidersSchema | null; updated helper function signatures (isProviderConfigured, getProviderConfig) to accept OAuthProvidersSchema.
Environment Configuration
.env.example, docker-compose.yml
Added OAUTH_ALLOWED_ORIGINS and DEFAULT_FRONTEND_ORIGIN environment variables to support origin-based redirect validation.
Dependency Update
frontend/package.json
Updated devDependency @types/react from ^19.1.8 to ^19.2.2.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Route as OAuth Route
    participant Auth as AuthService
    participant DB as OAuthConfig DB
    participant Provider as OAuth Provider

    Client->>Route: GET /api/auth/oauth/:provider?redirectTo=...
    Route->>Route: Validate provider schema
    Route->>Route: Validate redirect origin
    Route->>Auth: generateAuthUrl(provider, state)
    Auth->>DB: Query provider config
    Auth->>Auth: Generate state JWT
    Auth->>Provider: Build auth URL
    Provider-->>Auth: Auth URL
    Auth-->>Route: Auth URL string
    Route-->>Client: Redirect to Provider

    Provider->>Client: User grants permission
    Client->>Route: GET /api/auth/oauth/:provider/callback?code=...
    Route->>Route: Extract code from query
    Route->>Auth: handleOAuthCallback(provider, {code})
    Auth->>Provider: Exchange code for token
    Provider-->>Auth: Access token + user info
    Auth->>DB: Find or create user
    DB-->>Auth: User
    Auth->>Auth: Create session
    Auth-->>Route: Session (CreateSessionResponse)
    Route->>Route: setAuthCookies(session)
    Route-->>Client: Redirect + Set-Cookie headers
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

The review demands careful attention across multiple interconnected layers: schema type changes affecting backend and frontend, security-critical logic (origin validation, cookie handling, JWT state management), provider-agnostic abstraction patterns applied consistently, and coordination between database migrations, service logic, and API contracts. While individual changes follow clear patterns, the breadth of files and density of coordinated logic across tiers elevates effort.

Possibly related PRs

  • PR feat: added facebook oauth provider #445: Related through modifications to OAuth flow routes and auth service to add/support Facebook provider across same code paths (auth.oauth.ts, auth.ts, oauth.ts).
  • PR Added linkedin oauth provider #421: Related through direct updates to OAuth route and auth service to handle LinkedIn provider, including URL generation, callback handling, and scopes configuration.
  • PR feat: add Discord OAuth2 integration #419: Related through concurrent modifications to OAuth flows for Discord support across routes (auth.oauth.ts), auth service (auth.ts/oauth.ts), seeding, schemas, and frontend components.

Suggested reviewers

  • Fermionic-Lyu
  • tonychang04

Poem

🐰 A unified hop through OAuth's domain,
No more per-provider refrain,
With cookies secure and origins tight,
The providers now dance in schema delight!
From Google to Discord, a generalized feat, ✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.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 "feat: refactor OAuth system for scalability and type safety" directly aligns with the primary changes in this changeset. The PR replaces hardcoded provider-specific routes with unified wildcard endpoints, implements generic OAuth methods using OAuthProvidersSchema, and removes repetitive code—all of which support both scalability and type safety improvements. The title is concise, uses the conventional "feat:" prefix, and clearly communicates the main objective without unnecessary noise or vague terms.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

@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: 10

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
backend/src/core/auth/oauth.ts (1)

221-229: Returned config is missing id/createdAt/updatedAt used by routes.

Routes access config.id/createdAt/updatedAt. These RETURNING clauses don’t include them, leading to undefined at runtime.

Please include these columns (and alias timestamps to camelCase) in INSERT/UPDATE RETURNING:

 RETURNING
-  provider,
-  client_id as "clientId",
-  redirect_uri as "redirectUri",
-  scopes,
-  use_shared_key as "useSharedKey"
+  id,
+  provider,
+  client_id as "clientId",
+  redirect_uri as "redirectUri",
+  scopes,
+  use_shared_key as "useSharedKey",
+  created_at as "createdAt",
+  updated_at as "updatedAt"

And in getAllConfigs/getConfigByProvider SELECTs for parity. Based on router usage.

Also applies to: 335-346

🧹 Nitpick comments (6)
backend/src/core/auth/oauth.ts (1)

180-216: Replace the switch with a constant map for default scopes.

The long switch is harder to maintain and easy to drift. A typed map keeps provider-to-scopes centralized and enforces exhaustiveness.

Apply this refactor:

-      if (!scopes) {
-        switch (input.provider) {
-          case 'google':
-            scopes = ['openid', 'email', 'profile'];
-            break;
-          case 'github':
-            scopes = ['user:email'];
-            break;
-          case 'discord':
-            scopes = ['identify', 'email'];
-            break;
-          case 'linkedin':
-            scopes = ['openid', 'profile', 'email'];
-            break;
-          case 'facebook':
-            scopes = ['email', 'public_profile'];
-            break;
-          case 'instagram':
-            scopes = ['user_profile', 'user_media'];
-            break;
-          case 'tiktok':
-            scopes = ['user.info.basic'];
-            break;
-          case 'apple':
-            scopes = ['name', 'email'];
-            break;
-          case 'x':
-            scopes = ['tweet.read', 'users.read'];
-            break;
-          case 'spotify':
-            scopes = ['user-read-email', 'user-read-private'];
-            break;
-          case 'microsoft':
-            scopes = ['openid', 'email', 'profile'];
-            break;
-          default:
-            scopes = ['email', 'profile'];
-        }
-      }
+      if (!scopes) {
+        const DEFAULT_SCOPES: Record<OAuthProvidersSchema, string[]> = {
+          google: ['openid', 'email', 'profile'],
+          github: ['user:email'],
+          discord: ['identify', 'email'],
+          linkedin: ['openid', 'profile', 'email'],
+          facebook: ['email', 'public_profile'],
+          instagram: ['user_profile', 'user_media'],
+          tiktok: ['user.info.basic'],
+          apple: ['name', 'email'],
+          x: ['tweet.read', 'users.read'],
+          spotify: ['user-read-email', 'user-read-private'],
+          microsoft: ['openid', 'email', 'profile'],
+        };
+        scopes = DEFAULT_SCOPES[input.provider] ?? ['email', 'profile'];
+      }
backend/src/core/auth/auth.ts (2)

901-946: Use getApiBaseUrl() consistently for LinkedIn.

Other providers call getApiBaseUrl(); LinkedIn hardcodes process.env/API default. Standardize to avoid env drift.

-    const selfBaseUrl = process.env.API_BASE_URL || 'http://localhost:7130';
+    const selfBaseUrl = getApiBaseUrl();

1091-1104: Clarify error for unimplemented providers.

Throwing generic Error makes route mapping inconsistent. Prefer a typed AppError (501) or narrow error message that routes can surface cleanly.

Option A: import AppError and throw with NOT_IMPLEMENTED; Option B: include “not implemented” in message and let router translate to 501.

Also applies to: 1109-1125

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

26-43: Use successResponse for consistency.

Other endpoints use successResponse; these two return res.json directly.

Wrap responses with successResponse to keep API shape consistent.

Also applies to: 67-76


392-403: Validate provider param on admin update/delete too.

You validate provider on public routes but not in admin update/delete. Enforce oAuthProvidersSchema here as well to avoid storing unsupported entries.

Use oAuthProvidersSchema.safeParse(req.params.provider) and 400 on failure.


249-303: Add basic rate limiting per guidelines.

OAuth init/callback endpoints are public and should be rate limited.

Add an Express rate-limit middleware (IP+provider key) to:

  • GET /:provider
  • GET /shared/callback/:state
  • GET /:provider/callback

Keep limits low (e.g., 10/min/IP) to reduce abuse. As per coding guidelines.

Also applies to: 306-367, 370-454

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9eb5ac6 and 5afe5c5.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (11)
  • backend/src/api/routes/auth.oauth.ts (5 hunks)
  • backend/src/core/auth/auth.ts (5 hunks)
  • backend/src/core/auth/oauth.ts (3 hunks)
  • backend/src/utils/seed.ts (4 hunks)
  • frontend/package.json (1 hunks)
  • frontend/src/components/OAuthTestPanel.tsx (1 hunks)
  • frontend/src/features/auth/components/AddOAuthDialog.tsx (3 hunks)
  • frontend/src/features/auth/components/AuthMethodTab.tsx (4 hunks)
  • frontend/src/features/auth/components/OAuthConfigDialog.tsx (2 hunks)
  • frontend/src/features/auth/hooks/useOAuthConfig.ts (2 hunks)
  • package.json (3 hunks)
🧰 Additional context used
📓 Path-based instructions (11)
**/*.{ts,tsx}

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

**/*.{ts,tsx}: Use TypeScript for all code files
Use ES modules (import/export syntax)
Prefer descriptive, unabbreviated variable and function names
Implement proper error handling with try-catch blocks and logging where appropriate
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 2-space indentation
Format code with the repository Prettier configuration
Variables, parameters, properties, and functions must use camelCase
Constants and enum members must use UPPER_CASE
Include JSDoc comments for complex functions

Files:

  • backend/src/core/auth/oauth.ts
  • frontend/src/features/auth/components/AuthMethodTab.tsx
  • frontend/src/features/auth/components/OAuthConfigDialog.tsx
  • frontend/src/components/OAuthTestPanel.tsx
  • frontend/src/features/auth/components/AddOAuthDialog.tsx
  • frontend/src/features/auth/hooks/useOAuthConfig.ts
  • backend/src/api/routes/auth.oauth.ts
  • backend/src/utils/seed.ts
  • backend/src/core/auth/auth.ts
backend/src/**/*.{ts,tsx}

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

backend/src/**/*.{ts,tsx}: Use async/await for asynchronous operations in the backend
Use Zod schemas for request/response validation
Return consistent API responses using utility functions
Validate all user inputs
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper caching strategies (server-side)

Files:

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

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

Implement proper database transaction handling

Files:

  • backend/src/core/auth/oauth.ts
  • backend/src/core/auth/auth.ts
**/*.{tsx,ts}

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

React components and TypeScript types/interfaces must use PascalCase

Files:

  • backend/src/core/auth/oauth.ts
  • frontend/src/features/auth/components/AuthMethodTab.tsx
  • frontend/src/features/auth/components/OAuthConfigDialog.tsx
  • frontend/src/components/OAuthTestPanel.tsx
  • frontend/src/features/auth/components/AddOAuthDialog.tsx
  • frontend/src/features/auth/hooks/useOAuthConfig.ts
  • backend/src/api/routes/auth.oauth.ts
  • backend/src/utils/seed.ts
  • backend/src/core/auth/auth.ts
**/[a-z][a-z0-9-]*.ts

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

Utility files should use kebab-case or camelCase (kebab-case validated here)

Files:

  • backend/src/core/auth/oauth.ts
  • frontend/src/features/auth/hooks/useOAuthConfig.ts
  • backend/src/api/routes/auth.oauth.ts
  • backend/src/utils/seed.ts
  • backend/src/core/auth/auth.ts
frontend/src/**/*.{tsx,ts}

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

frontend/src/**/*.{tsx,ts}: Use functional React components with hooks exclusively
Use Radix UI primitives for accessibility
Optimize React component re-renders

Files:

  • frontend/src/features/auth/components/AuthMethodTab.tsx
  • frontend/src/features/auth/components/OAuthConfigDialog.tsx
  • frontend/src/components/OAuthTestPanel.tsx
  • frontend/src/features/auth/components/AddOAuthDialog.tsx
  • frontend/src/features/auth/hooks/useOAuthConfig.ts
frontend/src/**/*.tsx

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

frontend/src/**/*.tsx: Implement TypeScript interfaces/types for all component props
Follow component composition patterns; keep components focused and single-purpose
Implement proper loading and error states in UI
Use a consistent icon set from lucide-react

Files:

  • frontend/src/features/auth/components/AuthMethodTab.tsx
  • frontend/src/features/auth/components/OAuthConfigDialog.tsx
  • frontend/src/components/OAuthTestPanel.tsx
  • frontend/src/features/auth/components/AddOAuthDialog.tsx
frontend/src/**/*.{ts,tsx}

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

frontend/src/**/*.{ts,tsx}: Use TanStack Query for server state management
Use React Hook Form for form handling with Zod validation
Optimize bundle size with proper imports

Files:

  • frontend/src/features/auth/components/AuthMethodTab.tsx
  • frontend/src/features/auth/components/OAuthConfigDialog.tsx
  • frontend/src/components/OAuthTestPanel.tsx
  • frontend/src/features/auth/components/AddOAuthDialog.tsx
  • frontend/src/features/auth/hooks/useOAuthConfig.ts
frontend/src/**/[A-Z]*.tsx

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

Component files must use PascalCase filenames (e.g., DataGrid.tsx)

Files:

  • frontend/src/features/auth/components/AuthMethodTab.tsx
  • frontend/src/features/auth/components/OAuthConfigDialog.tsx
  • frontend/src/components/OAuthTestPanel.tsx
  • frontend/src/features/auth/components/AddOAuthDialog.tsx
frontend/src/**/use[A-Z]*.ts

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

Hook files must be named usePascalCase.ts (e.g., useAuth.ts)

Files:

  • frontend/src/features/auth/hooks/useOAuthConfig.ts
backend/src/api/**/*.ts

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

backend/src/api/**/*.ts: Implement authentication and error-handling middleware
Follow RESTful conventions for API endpoints
Implement rate limiting for API endpoints

Files:

  • backend/src/api/routes/auth.oauth.ts
🧬 Code graph analysis (9)
backend/src/core/auth/oauth.ts (2)
shared-schemas/src/auth.schema.ts (1)
  • OAuthProvidersSchema (107-107)
backend/src/api/middleware/error.ts (1)
  • AppError (7-17)
frontend/src/features/auth/components/AuthMethodTab.tsx (1)
shared-schemas/src/auth.schema.ts (1)
  • OAuthProvidersSchema (107-107)
frontend/src/features/auth/components/OAuthConfigDialog.tsx (2)
shared-schemas/src/auth.schema.ts (1)
  • OAuthProvidersSchema (107-107)
frontend/src/lib/utils/utils.ts (1)
  • isInsForgeCloudProject (158-160)
frontend/src/components/OAuthTestPanel.tsx (4)
frontend/src/components/radix/Select.tsx (5)
  • Select (141-141)
  • SelectTrigger (144-144)
  • SelectValue (143-143)
  • SelectContent (145-145)
  • SelectItem (147-147)
frontend/src/components/radix/Input.tsx (1)
  • Input (22-22)
frontend/src/components/radix/Button.tsx (1)
  • Button (50-50)
frontend/src/components/radix/Badge.tsx (1)
  • Badge (33-33)
frontend/src/features/auth/components/AddOAuthDialog.tsx (2)
frontend/src/features/auth/components/AuthMethodTab.tsx (1)
  • OAuthProviderInfo (53-59)
shared-schemas/src/auth.schema.ts (1)
  • OAuthProvidersSchema (107-107)
frontend/src/features/auth/hooks/useOAuthConfig.ts (1)
shared-schemas/src/auth.schema.ts (2)
  • OAuthProvidersSchema (107-107)
  • OAuthConfigSchema (106-106)
backend/src/api/routes/auth.oauth.ts (4)
backend/src/api/middleware/auth.ts (2)
  • verifyAdmin (71-116)
  • AuthRequest (8-17)
shared-schemas/src/auth-api.schema.ts (1)
  • ListOAuthConfigsResponse (191-191)
shared-schemas/src/auth.schema.ts (1)
  • oAuthProvidersSchema (57-69)
backend/src/api/middleware/error.ts (1)
  • AppError (7-17)
backend/src/utils/seed.ts (1)
shared-schemas/src/auth.schema.ts (1)
  • OAuthProvidersSchema (107-107)
backend/src/core/auth/auth.ts (2)
shared-schemas/src/auth.schema.ts (1)
  • OAuthProvidersSchema (107-107)
shared-schemas/src/auth-api.schema.ts (1)
  • CreateSessionResponse (185-185)
🔇 Additional comments (14)
frontend/package.json (1)

53-53: LGTM!

The @types/react version bump is a standard dependency update with no functional impact.

backend/src/utils/seed.ts (2)

58-86: Excellent refactoring for scalability!

The loop-based approach eliminates code duplication and makes adding new providers trivial. Type safety with OAuthProvidersSchema ensures consistency across the codebase.


88-146: Well-structured environment-based seeding.

The envMappings array approach is clean and maintainable. The dynamic provider handling aligns well with the PR's scalability objectives.

frontend/src/features/auth/hooks/useOAuthConfig.ts (2)

8-16: Type safety enhancement approved.

The transition to OAuthProvidersSchema provides compile-time validation and aligns with the centralized schema approach.


85-98: Helper functions properly typed.

The parameter type updates ensure type-safe provider lookups throughout the application.

frontend/src/features/auth/components/OAuthConfigDialog.tsx (1)

71-79: Verify Facebook shared key support.

The sharedKeyProviders array includes facebook, but the backend seeding logic in backend/src/utils/seed.ts (lines 69, 100-125) only references google, github, discord, and linkedin.

Confirm whether Facebook shared keys are actually supported, or remove it from the array:

 const sharedKeyProviders: OAuthProvidersSchema[] = [
   'google',
   'github',
   'discord',
   'linkedin',
-  'facebook',
 ];

If Facebook is supported, ensure it's also added to the backend seeding configuration.

frontend/src/features/auth/components/AddOAuthDialog.tsx (2)

12-29: Clean type migration to OAuthProvidersSchema.

The interface updates properly enforce type safety for provider selection throughout the component.


43-51: Type-safe provider selection logic.

The schema-based typing prevents invalid provider IDs from being passed to the confirmation handler.

frontend/src/features/auth/components/AuthMethodTab.tsx (3)

20-59: Proper schema integration in provider definitions.

The type update to OAuthProviderInfo.id ensures compile-time validation against the centralized schema.


111-120: Dynamic provider enablement check is more maintainable.

The loop-based computation eliminates hardcoded provider checks and scales better as new providers are added.


80-96: Type-safe provider operations.

The parameter type updates ensure consistent, schema-validated provider handling in delete and selection operations.

Also applies to: 127-138

frontend/src/components/OAuthTestPanel.tsx (1)

19-31: Review comment is incorrect—all providers are schema-validated and supported.

The premise that providers beyond the four in seeding are "unsupported by the backend" is mistaken. The oAuthProvidersSchema in shared-schemas (lines 57-69) defines all 11 providers as valid, including facebook, instagram, tiktok, apple, x, spotify, and microsoft. The seeding logic in backend/src/utils/seed.ts only initializes four providers from environment variables (lines 99-126), but seeding incompleteness does not mean backend unsupport—the schema validates all 11.

The SUPPORTED_PROVIDERS array correctly mirrors the schema definition. No providers should be removed.

Likely an incorrect or invalid review comment.

backend/src/core/auth/oauth.ts (2)

7-11: Good move: provider now typed with the schema.

This tightens compile-time safety across the stack and prevents arbitrary provider values.


352-364: Secret-only update path is clearer now.

Ordering the “secret-only” path after main updates is fine and returns a fresh config. Ensure getConfigByProvider also selects id/createdAt/updatedAt to keep admin API responses consistent.

Comment thread backend/src/api/routes/auth.oauth.ts Outdated
Comment on lines 32 to 43
configs: configs.map((config) => ({
id: config.id,
provider: config.provider,
clientId: config.clientId,
scopes: config.scopes,
useSharedKey: config.useSharedKey,
createdAt: config.createdAt,
updatedAt: config.updatedAt,
})),
};
successResponse(res, response);
res.json(response);
} catch (error) {

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.

⚠️ Potential issue | 🟠 Major

Route expects id/createdAt/updatedAt not provided by service.

The mapper reads config.id/createdAt/updatedAt, but OAuthConfigService.getAllConfigs doesn’t SELECT them.

Either:

  • Update service SELECT to include id/created_at/updated_at (aliased), or
  • Adjust the response shape here to only return available fields.

Prefer updating service for consistency with GET-by-provider. Based on router usage.

🤖 Prompt for AI Agents
In backend/src/api/routes/auth.oauth.ts around lines 32 to 43, the mapper
references config.id, config.createdAt and config.updatedAt but
OAuthConfigService.getAllConfigs does not select those fields; update the
service method to include id, created_at and updated_at in its SELECT (aliasing
to id, createdAt, updatedAt to match the mapper), or alternatively change this
route to only return fields actually selected by the service — preferred fix is
to modify OAuthConfigService.getAllConfigs to SELECT id, created_at AS
createdAt, updated_at AS updatedAt so the response shape stays consistent with
GET-by-provider.

Comment on lines +67 to +76
res.json({
id: config.id,
provider: config.provider,
clientId: config.clientId,
clientSecret: clientSecret || undefined,
scopes: config.scopes,
useSharedKey: config.useSharedKey,
createdAt: config.createdAt,
updatedAt: config.updatedAt,
});

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.

⚠️ Potential issue | 🟠 Major

GET-by-provider uses fields the service doesn’t return.

config.id/createdAt/updatedAt will be undefined with current service SELECT.

Align service getConfigByProvider to include these columns (aliased), or adjust response to omit them. Prefer service change for parity with list.

🤖 Prompt for AI Agents
In backend/src/api/routes/auth.oauth.ts around lines 67 to 76: the response is
returning id, createdAt and updatedAt but the service getConfigByProvider
currently doesn't select those columns so they come back undefined; update the
service query (the getConfigByProvider implementation) to select id, created_at
and updated_at (alias them to id, createdAt, updatedAt or map them after
retrieval) so the route can return the same fields as the list endpoint, or
alternatively remove those fields from this response — preferred fix: extend the
service SELECT to include and alias the id/created_at/updated_at columns so
parity with list is preserved.

Comment thread backend/src/api/routes/auth.oauth.ts Resolved
Comment thread backend/src/api/routes/auth.oauth.ts Resolved
Comment thread backend/src/api/routes/auth.oauth.ts Resolved
Comment thread backend/src/api/routes/auth.oauth.ts Resolved
Comment thread backend/src/api/routes/auth.oauth.ts Resolved
Comment thread backend/src/core/auth/auth.ts Resolved
Comment thread package.json 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: 4

♻️ Duplicate comments (4)
backend/src/core/auth/oauth.ts (1)

57-66: SELECT parity achieved for id/createdAt/updatedAt.

The service now returns id/createdAt/updatedAt, aligning with route mappers. Good fix.

Also applies to: 86-95

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

26-37: Good: no default JWT secret; hard requirement enforced.

This addresses prior critical risk.


39-75: Good: redirect allowlist and origin-only state eliminate open redirect.

Validating origins and storing only origin in state fixes the earlier vulnerability.

Also applies to: 371-427

backend/src/core/auth/auth.ts (1)

55-61: Env loading no longer short-circuits init.

Removal of the early return resolves the initialization bug.

🧹 Nitpick comments (7)
frontend/src/components/OAuthTestPanel.tsx (2)

115-121: Harden clipboard copy with error handling.

Navigator clipboard can fail (permissions/HTTP). Show a toast on failure.

-  const copyToClipboard = (text: string) => {
-    navigator.clipboard.writeText(text);
-    toast({
-      title: 'Copied',
-      description: 'URL copied to clipboard',
-    });
-  };
+  const copyToClipboard = async (text: string) => {
+    try {
+      await navigator.clipboard.writeText(text);
+      toast({ title: 'Copied', description: 'URL copied to clipboard' });
+    } catch {
+      toast({ title: 'Copy failed', description: 'Press Ctrl/Cmd+C instead', variant: 'destructive' });
+    }
+  };

232-246: Icon-only buttons need accessible labels.

Add aria-labels for screen readers.

-                        <Button
+                        <Button
                           size="sm"
                           variant="outline"
-                          onClick={() => copyToClipboard(result.authUrl!)}
+                          aria-label="Copy OAuth URL"
+                          onClick={() => copyToClipboard(result.authUrl!)}
                         >
@@
-                        <Button
+                        <Button
                           size="sm"
                           variant="outline"
-                          onClick={() => openInNewTab(result.authUrl!)}
+                          aria-label="Open OAuth URL in new tab"
+                          onClick={() => openInNewTab(result.authUrl!)}
                         >
backend/src/core/auth/oauth.ts (2)

183-222: Default scopes switch looks sane; consider centralizing and typing.

Non-blocking: extract this provider→scopes map to a typed constant to reuse in seeds/docs and avoid drift.

// e.g., const DEFAULT_SCOPES: Record<OAuthProvidersSchema, string[]> = { ... }

226-246: DB constraint advice: enforce uniqueness at the database.

You check for existing provider before INSERT; add a UNIQUE index on LOWER(provider) to prevent races.

Example migration:

CREATE UNIQUE INDEX IF NOT EXISTS ux_oauth_configs_provider_ci
ON _oauth_configs ((LOWER(provider)));
backend/src/api/routes/auth.oauth.ts (1)

117-145: Dead code: sanitizeLogData is defined but never used.

Either remove it or apply it to logger calls that may receive sensitive data.

backend/src/core/auth/auth.ts (2)

900-946: Use getApiBaseUrl() for LinkedIn to match other providers.

Keep base URL resolution consistent across providers.

-    const selfBaseUrl = process.env.API_BASE_URL || 'http://localhost:7130';
+    const selfBaseUrl = getApiBaseUrl();
@@
-      const cloudBaseUrl = process.env.CLOUD_API_HOST || 'https://api.insforge.dev';
+      const cloudBaseUrl = process.env.CLOUD_API_HOST || 'https://api.insforge.dev';
       const redirectUri = `${selfBaseUrl}/api/auth/oauth/shared/callback/${state}`;

565-583: Avoid mixing fetch and axios in Node; pick one client.

Either import node-fetch types or switch to axios for consistency.

-      const authUrl = await fetch(
-        `${cloudBaseUrl}/auth/v1/shared/discord?redirect_uri=${encodeURIComponent(redirectUri)}`,
-        {
-          method: 'GET',
-          headers: {
-            'Content-Type': 'application/json',
-          },
-        }
-      );
-      if (!authUrl.ok) {
-        logger.error('Failed to fetch Discord auth URL:', {
-          status: authUrl.status,
-          statusText: authUrl.statusText,
-        });
-        throw new Error(`Failed to fetch Discord auth URL: ${authUrl.statusText}`);
-      }
-      const responseData = (await authUrl.json()) as { auth_url?: string; url?: string };
+      const resp = await axios.get(
+        `${cloudBaseUrl}/auth/v1/shared/discord`,
+        { params: { redirect_uri: redirectUri } }
+      );
+      const responseData = resp.data as { auth_url?: string; url?: string };
       return responseData.auth_url || responseData.url || '';
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5afe5c5 and 06f3c4a.

📒 Files selected for processing (4)
  • backend/src/api/routes/auth.oauth.ts (5 hunks)
  • backend/src/core/auth/auth.ts (5 hunks)
  • backend/src/core/auth/oauth.ts (6 hunks)
  • frontend/src/components/OAuthTestPanel.tsx (1 hunks)
🧰 Additional context used
📓 Path-based instructions (10)
**/*.{ts,tsx}

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

**/*.{ts,tsx}: Use TypeScript for all code files
Use ES modules (import/export syntax)
Prefer descriptive, unabbreviated variable and function names
Implement proper error handling with try-catch blocks and logging where appropriate
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 2-space indentation
Format code with the repository Prettier configuration
Variables, parameters, properties, and functions must use camelCase
Constants and enum members must use UPPER_CASE
Include JSDoc comments for complex functions

Files:

  • backend/src/api/routes/auth.oauth.ts
  • backend/src/core/auth/oauth.ts
  • frontend/src/components/OAuthTestPanel.tsx
  • backend/src/core/auth/auth.ts
backend/src/**/*.{ts,tsx}

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

backend/src/**/*.{ts,tsx}: Use async/await for asynchronous operations in the backend
Use Zod schemas for request/response validation
Return consistent API responses using utility functions
Validate all user inputs
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper caching strategies (server-side)

Files:

  • backend/src/api/routes/auth.oauth.ts
  • backend/src/core/auth/oauth.ts
  • backend/src/core/auth/auth.ts
backend/src/api/**/*.ts

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

backend/src/api/**/*.ts: Implement authentication and error-handling middleware
Follow RESTful conventions for API endpoints
Implement rate limiting for API endpoints

Files:

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

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

React components and TypeScript types/interfaces must use PascalCase

Files:

  • backend/src/api/routes/auth.oauth.ts
  • backend/src/core/auth/oauth.ts
  • frontend/src/components/OAuthTestPanel.tsx
  • backend/src/core/auth/auth.ts
**/[a-z][a-z0-9-]*.ts

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

Utility files should use kebab-case or camelCase (kebab-case validated here)

Files:

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

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

Implement proper database transaction handling

Files:

  • backend/src/core/auth/oauth.ts
  • backend/src/core/auth/auth.ts
frontend/src/**/*.{tsx,ts}

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

frontend/src/**/*.{tsx,ts}: Use functional React components with hooks exclusively
Use Radix UI primitives for accessibility
Optimize React component re-renders

Files:

  • frontend/src/components/OAuthTestPanel.tsx
frontend/src/**/*.tsx

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

frontend/src/**/*.tsx: Implement TypeScript interfaces/types for all component props
Follow component composition patterns; keep components focused and single-purpose
Implement proper loading and error states in UI
Use a consistent icon set from lucide-react

Files:

  • frontend/src/components/OAuthTestPanel.tsx
frontend/src/**/*.{ts,tsx}

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

frontend/src/**/*.{ts,tsx}: Use TanStack Query for server state management
Use React Hook Form for form handling with Zod validation
Optimize bundle size with proper imports

Files:

  • frontend/src/components/OAuthTestPanel.tsx
frontend/src/**/[A-Z]*.tsx

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

Component files must use PascalCase filenames (e.g., DataGrid.tsx)

Files:

  • frontend/src/components/OAuthTestPanel.tsx
🧬 Code graph analysis (4)
backend/src/api/routes/auth.oauth.ts (4)
backend/src/api/middleware/error.ts (1)
  • AppError (7-17)
backend/src/api/middleware/auth.ts (2)
  • verifyAdmin (71-116)
  • AuthRequest (8-17)
shared-schemas/src/auth-api.schema.ts (1)
  • ListOAuthConfigsResponse (191-191)
shared-schemas/src/auth.schema.ts (1)
  • oAuthProvidersSchema (57-69)
backend/src/core/auth/oauth.ts (2)
shared-schemas/src/auth.schema.ts (1)
  • OAuthProvidersSchema (107-107)
backend/src/api/middleware/error.ts (1)
  • AppError (7-17)
frontend/src/components/OAuthTestPanel.tsx (4)
frontend/src/components/radix/Select.tsx (5)
  • Select (141-141)
  • SelectTrigger (144-144)
  • SelectValue (143-143)
  • SelectContent (145-145)
  • SelectItem (147-147)
frontend/src/components/radix/Input.tsx (1)
  • Input (22-22)
frontend/src/components/radix/Button.tsx (1)
  • Button (50-50)
frontend/src/components/radix/Badge.tsx (1)
  • Badge (33-33)
backend/src/core/auth/auth.ts (2)
shared-schemas/src/auth.schema.ts (1)
  • OAuthProvidersSchema (107-107)
shared-schemas/src/auth-api.schema.ts (1)
  • CreateSessionResponse (185-185)
🔇 Additional comments (3)
backend/src/api/routes/auth.oauth.ts (1)

371-427: Unified OAuth flow: solid error handling and secure redirects.

Good structure, clear errors, and no token-in-URL. Nice work.

Also applies to: 429-498, 500-598

backend/src/core/auth/auth.ts (2)

1087-1124: New generic methods look good; unsupported providers throw clearly.

LGTM on generateAuthUrl/handleOAuthCallback structure.

Also applies to: 1108-1124


547-552: Review comment is incorrect.

The concern about missing DOM lib is based on a flawed assumption. The backend's TypeScript configuration is correct:

  • backend/tsconfig.json specifies "types": ["node"] which loads @types/node (version ^20.11.24)
  • @types/node 20.11.24 includes complete fetch API type definitions for Node.js 18+
  • DOM lib is a browser-only library and is not needed for Node.js backend fetch typing
  • The fetch call at line 565 in auth.ts is properly typed through @types/node without requiring DOM lib

No TypeScript type errors exist. The code is correctly configured.

Likely an incorrect or invalid review comment.

Comment thread backend/src/api/routes/auth.oauth.ts Resolved
@Fermionic-Lyu
Fermionic-Lyu self-requested a review October 20, 2025 03:02

@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.

Could you kindly address the eslint errors? And please try to only commit the issue relevant files, from the package.json file changes I see you are just changing the package orders.

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.

Hmmmm what is this component for?

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.

removed it was just for testing purpose.

@Fermionic-Lyu

Fermionic-Lyu commented Oct 22, 2025 •

Copy link
Copy Markdown
Member

Let me know if you are still working on this. We kinda need this issue solved asap to unblock more oauth provders.

@Laaaaksh

Copy link
Copy Markdown
Contributor Author

@Fermionic-Lyu Will do this today yes got occupied a bit!

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
backend/src/core/auth/auth.ts (1)

900-946: Inconsistent base URL source for LinkedIn; align with other providers.

Other providers use getApiBaseUrl(); LinkedIn uses process.env.API_BASE_URL with a different default, risking wrong callback URLs across environments.

-    const selfBaseUrl = process.env.API_BASE_URL || 'http://localhost:7130';
+    const selfBaseUrl = getApiBaseUrl();
@@
-      const selfBaseUrl = process.env.API_BASE_URL || 'http://localhost:7130';
+      const selfBaseUrl = getApiBaseUrl();
♻️ Duplicate comments (2)
frontend/src/components/OAuthTestPanel.tsx (1)

25-37: Derive providers and types from shared schema to prevent drift.

Import oAuthProvidersSchema and use its union for state and results; build SUPPORTED_PROVIDERS from schema.options. This keeps UI in lockstep with backend.

-import React, { useState } from 'react';
+import React, { useState } from 'react';
+import { oAuthProvidersSchema, type OAuthProvidersSchema } from '@insforge/shared-schemas';
@@
-interface OAuthTestResult {
-  provider: string;
+interface OAuthTestResult {
+  provider: OAuthProvidersSchema;
   success: boolean;
   authUrl?: string;
   error?: string;
   statusCode?: number;
 }
@@
-const SUPPORTED_PROVIDERS = [
-  'google', 'github', 'discord', 'linkedin', 'facebook', 'instagram',
-  'tiktok', 'apple', 'x', 'spotify', 'microsoft',
-];
+const SUPPORTED_PROVIDERS = oAuthProvidersSchema.options as readonly OAuthProvidersSchema[];
@@
-export const OAuthTestPanel: React.FC = () => {
-  const [selectedProvider, setSelectedProvider] = useState<string>('');
+export const OAuthTestPanel: React.FC = () => {
+  const [selectedProvider, setSelectedProvider] = useState<OAuthProvidersSchema | ''>('');
@@
-  const testSingleProvider = async (provider: string): Promise<OAuthTestResult> => {
+  const testSingleProvider = async (provider: OAuthProvidersSchema): Promise<OAuthTestResult> => {
@@
-            <Select value={selectedProvider} onValueChange={setSelectedProvider}>
+            <Select value={selectedProvider} onValueChange={setSelectedProvider as any}>

Also applies to: 39-45, 52-60, 140-151, 208-217

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

81-102: Avoid storing PII in cookies; set only the access token.

Storing user_id/email/name as HttpOnly cookies increases privacy/compliance risk and cookie surface. Keep cookies minimal; fetch user via /me using the token.

   if (result?.accessToken) {
     res.cookie('access_token', result.accessToken, cookieOptions);
   }
-  if (result?.user?.id) {
-    res.cookie('user_id', result.user.id, cookieOptions);
-  }
-  if (result?.user?.email) {
-    res.cookie('user_email', result.user.email, cookieOptions);
-  }
-  if (result?.user?.name) {
-    res.cookie('user_name', result.user.name, cookieOptions);
-  }

And in clearAuthCookies:

   res.cookie('access_token', '', cookieOptions);
-  res.cookie('user_id', '', cookieOptions);
-  res.cookie('user_email', '', cookieOptions);
-  res.cookie('user_name', '', cookieOptions);

Also applies to: 114-118

🧹 Nitpick comments (9)
shared-schemas/src/auth.schema.ts (1)

78-86: Tighten timestamp validation and optionality defaults in OAuth config.

  • Consider z.string().datetime() for createdAt/updatedAt to enforce ISO timestamps.
  • clientId/scopes/redirectUri are optional; if absent, downstream URL builders can break. Either make clientId required when useSharedKey is false, or encode that rule here with a refinement.

Apply:

 export const oAuthConfigSchema = z.object({
   id: z.string().uuid(),
   provider: oAuthProvidersSchema,
-  clientId: z.string().optional(),
-  scopes: z.array(z.string()).optional(),
-  redirectUri: z.string().optional(),
+  clientId: z.string().min(1).optional(),
+  scopes: z.array(z.string()).default([]),
+  redirectUri: z.string().url().optional(),
   useSharedKey: z.boolean(),
-  createdAt: z.string(), // PostgreSQL timestamp
-  updatedAt: z.string(), // PostgreSQL timestamp
+  createdAt: z.string().datetime(),
+  updatedAt: z.string().datetime(),
 }).superRefine((val, ctx) => {
   if (!val.useSharedKey && !val.clientId) {
     ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'clientId is required when useSharedKey is false', path: ['clientId'] });
   }
 });
frontend/src/components/OAuthTestPanel.tsx (2)

87-102: Prevent setState on unmounted component; support cancellation.

Wrap async tests with AbortController and a mounted flag; abort in cleanup to avoid leaks and flaky UI when navigating away.

+  const abortRef = React.useRef<AbortController | null>(null);
+  React.useEffect(() => () => { abortRef.current?.abort(); }, []);
@@
-  const testSelectedProvider = async () => {
+  const testSelectedProvider = async () => {
     if (!selectedProvider) {
       showToast('Please select a provider to test', 'error');
       return;
     }
     setIsLoading(true);
     try {
-      const result = await testSingleProvider(selectedProvider);
+      abortRef.current = new AbortController();
+      const result = await testSingleProvider(selectedProvider);
       setTestResults([result]);
     } catch (error) {
       console.error('Test failed:', error);
     } finally {
       setIsLoading(false);
     }
   };
@@
-  const testAllProviders = async () => {
+  const testAllProviders = async () => {
     setIsLoading(true);
     try {
-      const results = await Promise.all(
+      abortRef.current = new AbortController();
+      const results = await Promise.all(
         SUPPORTED_PROVIDERS.map((provider) => testSingleProvider(provider))
       );
       setTestResults(results);

Optionally pass signal: abortRef.current?.signal to fetch in testSingleProvider.

Also applies to: 104-116


52-60: Harden response parsing and surface provider-specific errors.

If neither authUrl nor url is present, return a structured error instead of success with undefined URL.

-      if (response.ok) {
-        return {
-          provider,
-          success: true,
-          authUrl: data.authUrl || data.url,
-          statusCode: response.status,
-        };
-      } else {
+      if (response.ok) {
+        const url = data.authUrl || data.url;
+        if (!url || typeof url !== 'string') {
+          return { provider, success: false, error: 'No auth URL returned', statusCode: response.status };
+        }
+        return { provider, success: true, authUrl: url, statusCode: response.status };
+      } else {

Also applies to: 62-69

backend/src/core/auth/auth.ts (4)

464-476: Don’t return empty strings for remote URL responses; throw instead.

Returning '' on missing auth_url/url yields confusing 200s with unusable URLs. Fail fast so callers can surface clear errors.

-      return response.data.auth_url || response.data.url || '';
+      const url = response.data.auth_url || response.data.url;
+      if (!url) throw new Error('No authorization URL returned from shared provider');
+      return url;

(Apply similarly in GitHub/Discord/LinkedIn shared-key branches.)

Also applies to: 520-527, 574-583, 924-926, 995-1002


1087-1103: Validate callback payloads with Zod before branching.

Define a small schema: either { token: string } or { code: string }. This reduces ad‑hoc checks and standardizes error messages.

+  private readonly callbackSchema = (() => {
+    const code = z.object({ code: z.string().min(1) });
+    const token = z.object({ token: z.string().min(1) });
+    return z.union([code, token]);
+  })();
@@
-    if (payload.token) {
+    const parsed = this.callbackSchema.safeParse(payload);
+    if (parsed.success && 'token' in parsed.data) {
       const googleUserInfo = await this.verifyGoogleToken(payload.token);
       return this.findOrCreateGoogleUser(googleUserInfo);
     }
@@
-    if (payload.code) {
+    if (parsed.success && 'code' in parsed.data) {
       const tokens = await this.exchangeCodeToTokenByGoogle(payload.code);

(Repeat for GitHub/Discord/LinkedIn handlers.)



Also applies to: 1108-1124, 1129-1145, 1150-1161, 1166-1177, 1182-1198

---

`742-766`: **Set explicit HTTP timeouts for token exchanges.**

Network hangs will exhaust worker threads. Add a reasonable timeout to axios calls.


```diff
-    const response = await axios.post('https://github.com/login/oauth/access_token', { ... }, { headers: { Accept: 'application/json' } });
+    const response = await axios.post('https://github.com/login/oauth/access_token', { ... }, { headers: { Accept: 'application/json' }, timeout: 10000 });

(Apply similar timeout to Google/Discord/LinkedIn token exchangers.)

Also applies to: 827-851


565-583: Prefer one HTTP client for consistency and proxy/timeout config.

This branch uses fetch while others use axios. Unify on axios (already imported) to share interceptors, timeouts, and error handling.

-      const authUrl = await fetch(`${cloudBaseUrl}/auth/v1/shared/discord?...`, { method: 'GET', headers: { 'Content-Type': 'application/json' } });
-      if (!authUrl.ok) { ... }
-      const responseData = (await authUrl.json()) as { auth_url?: string; url?: string };
-      return responseData.auth_url || responseData.url || '';
+      const resp = await axios.get(`${cloudBaseUrl}/auth/v1/shared/discord`, { params: { redirect_uri: redirectUri }, headers: { 'Content-Type': 'application/json' }, timeout: 10000 });
+      const url = resp.data.auth_url || resp.data.url;
+      if (!url) throw new Error('No authorization URL returned from shared provider');
+      return url;
backend/src/api/routes/auth.oauth.ts (2)

120-157: Use the sanitizer helper in logs and redact payloads.

You added _sanitizeLogData but current logs pass raw error objects. Wrap log metadata to avoid accidental token/PII leakage.

-    logger.error('Failed to get OAuth configs', { error });
+    logger.error('Failed to get OAuth configs', _sanitizeLogData({ error }));
@@
-    logger.error(`${req.params.provider} OAuth error`, { error });
+    logger.error(`${req.params.provider} OAuth error`, _sanitizeLogData({ error }));
@@
-    logger.error('Shared OAuth callback error', { error });
+    logger.error('Shared OAuth callback error', _sanitizeLogData({ error }));
@@
-    logger.error('OAuth callback error', {
+    logger.error('OAuth callback error', _sanitizeLogData({
       error: error instanceof Error ? error.message : 'Unknown error',
       provider: req.params.provider,
       hasCode: !!req.query.code,
       hasState: !!req.query.state,
       hasToken: !!req.query.token,
-    });
+    }));

Also applies to: 415-432, 500-504, 567-599


486-499: Validate base64 payload shape before processing.

Decode and Zod-validate payload to ensure only expected fields reach AuthService.

+    const payloadSchema = z.union([
+      z.object({ code: z.string().min(1) }),
+      z.object({ token: z.string().min(1) })
+    ]);
@@
-      const payloadData = JSON.parse(Buffer.from(payload as string, 'base64').toString('utf8'));
+      const decoded = JSON.parse(Buffer.from(payload as string, 'base64').toString('utf8'));
+      const parsed = payloadSchema.safeParse(decoded);
+      if (!parsed.success) {
+        throw new AppError('Invalid payload', 400, ERROR_CODES.INVALID_INPUT);
+      }
-      const result = await authService.handleOAuthCallback(validatedProvider, payloadData);
+      const result = await authService.handleOAuthCallback(validatedProvider, parsed.data);

Also applies to: 540-566

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 06f3c4a and a086f5c.

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

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

**/*.{ts,tsx}: Use TypeScript for all code files
Use ES modules (import/export syntax)
Prefer descriptive, unabbreviated variable and function names
Implement proper error handling with try-catch blocks and logging where appropriate
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 2-space indentation
Format code with the repository Prettier configuration
Variables, parameters, properties, and functions must use camelCase
Constants and enum members must use UPPER_CASE
Include JSDoc comments for complex functions

Files:

  • shared-schemas/src/auth.schema.ts
  • backend/src/core/auth/auth.ts
  • frontend/src/components/OAuthTestPanel.tsx
  • backend/src/api/routes/auth.oauth.ts
**/*.{tsx,ts}

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

React components and TypeScript types/interfaces must use PascalCase

Files:

  • shared-schemas/src/auth.schema.ts
  • backend/src/core/auth/auth.ts
  • frontend/src/components/OAuthTestPanel.tsx
  • backend/src/api/routes/auth.oauth.ts
**/[a-z][a-z0-9-]*.ts

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

Utility files should use kebab-case or camelCase (kebab-case validated here)

Files:

  • shared-schemas/src/auth.schema.ts
  • backend/src/core/auth/auth.ts
  • backend/src/api/routes/auth.oauth.ts
backend/src/**/*.{ts,tsx}

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

backend/src/**/*.{ts,tsx}: Use async/await for asynchronous operations in the backend
Use Zod schemas for request/response validation
Return consistent API responses using utility functions
Validate all user inputs
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper caching strategies (server-side)

Files:

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

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

Implement proper database transaction handling

Files:

  • backend/src/core/auth/auth.ts
frontend/src/**/*.{tsx,ts}

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

frontend/src/**/*.{tsx,ts}: Use functional React components with hooks exclusively
Use Radix UI primitives for accessibility
Optimize React component re-renders

Files:

  • frontend/src/components/OAuthTestPanel.tsx
frontend/src/**/*.tsx

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

frontend/src/**/*.tsx: Implement TypeScript interfaces/types for all component props
Follow component composition patterns; keep components focused and single-purpose
Implement proper loading and error states in UI
Use a consistent icon set from lucide-react

Files:

  • frontend/src/components/OAuthTestPanel.tsx
frontend/src/**/*.{ts,tsx}

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

frontend/src/**/*.{ts,tsx}: Use TanStack Query for server state management
Use React Hook Form for form handling with Zod validation
Optimize bundle size with proper imports

Files:

  • frontend/src/components/OAuthTestPanel.tsx
frontend/src/**/[A-Z]*.tsx

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

Component files must use PascalCase filenames (e.g., DataGrid.tsx)

Files:

  • frontend/src/components/OAuthTestPanel.tsx
backend/src/api/**/*.ts

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

backend/src/api/**/*.ts: Implement authentication and error-handling middleware
Follow RESTful conventions for API endpoints
Implement rate limiting for API endpoints

Files:

  • backend/src/api/routes/auth.oauth.ts
🧬 Code graph analysis (3)
backend/src/core/auth/auth.ts (2)
shared-schemas/src/auth.schema.ts (1)
  • OAuthProvidersSchema (110-110)
shared-schemas/src/auth-api.schema.ts (1)
  • CreateSessionResponse (185-185)
frontend/src/components/OAuthTestPanel.tsx (1)
frontend/src/lib/hooks/useToast.tsx (1)
  • useToast (223-229)
backend/src/api/routes/auth.oauth.ts (3)
backend/src/api/middleware/error.ts (1)
  • AppError (7-17)
backend/src/api/middleware/auth.ts (2)
  • verifyAdmin (71-116)
  • AuthRequest (8-17)
shared-schemas/src/auth.schema.ts (1)
  • oAuthProvidersSchema (57-69)
🔇 Additional comments (1)
backend/src/api/routes/auth.oauth.ts (1)

377-390: Code is already consistent across all routes.

Verification confirms all error messages already use oAuthProvidersSchema.options.join(', ') consistently across lines 386, 466, and 532. No changes needed.

Comment on lines +39 to +76
// Helper function to validate and normalize redirect origins
const validateRedirectOrigin = (redirectUri: string): string => {
let parsedUrl: URL;
try {
const { redirect_uri } = req.query;
if (!redirect_uri) {
throw new AppError('Redirect URI is required', 400, ERROR_CODES.INVALID_INPUT);
}

const jwtPayload = {
provider: 'github',
redirectUri: redirect_uri ? (redirect_uri as string) : undefined,
createdAt: Date.now(),
};
const state = jwt.sign(jwtPayload, process.env.JWT_SECRET || 'default_secret', {
algorithm: 'HS256',
expiresIn: '1h', // Set expiration time for the state token
});

const authUrl = await authService.generateGitHubAuthUrl(state);

res.json({ authUrl });
} catch (error) {
logger.error('GitHub OAuth error', { error });
next(
new AppError(
'GitHub OAuth is not properly configured. Please check your oauth configurations.',
500,
ERROR_CODES.AUTH_OAUTH_CONFIG_ERROR
)
);
parsedUrl = new URL(redirectUri);
} catch {
throw new AppError('Invalid redirect URI format', 400, ERROR_CODES.INVALID_INPUT);
}
});

// GET /api/auth/oauth/discord - Initialize Discord OAuth flow
router.get('/discord', async (req: Request, res: Response, next: NextFunction) => {
try {
const { redirect_uri } = req.query;
if (!redirect_uri) {
throw new AppError('Redirect URI is required', 400, ERROR_CODES.INVALID_INPUT);
}

const jwtPayload = {
provider: 'discord',
redirectUri: redirect_uri ? (redirect_uri as string) : undefined,
createdAt: Date.now(),
};
const state = jwt.sign(jwtPayload, process.env.JWT_SECRET || 'default_secret', {
algorithm: 'HS256',
expiresIn: '1h', // Set expiration time for the state token
});

const authUrl = await authService.generateDiscordAuthUrl(state);
// Get allowed origins from environment
const allowedOrigins =
process.env.OAUTH_ALLOWED_ORIGINS?.split(',').map((origin) => origin.trim()) || [];

res.json({ authUrl });
} catch (error) {
logger.error('Discord OAuth error', { error });
next(
new AppError(
'Discord OAuth is not properly configured. Please check your oauth configurations.',
500,
ERROR_CODES.AUTH_OAUTH_CONFIG_ERROR
)
if (allowedOrigins.length === 0) {
throw new AppError(
'OAuth redirect validation is not configured. OAUTH_ALLOWED_ORIGINS must be set.',
500,
ERROR_CODES.AUTH_OAUTH_CONFIG_ERROR
);
}
});

// GET /api/auth/oauth/linkedin - Initialize LinkedIn OAuth flow
router.get('/linkedin', async (req: Request, res: Response, next: NextFunction) => {
try {
const { redirect_uri } = req.query;
if (!redirect_uri) {
throw new AppError('Redirect URI is required', 400, ERROR_CODES.INVALID_INPUT);
}
const origin = `${parsedUrl.protocol}//${parsedUrl.host}`;

const jwtPayload = {
provider: 'linkedin',
redirectUri: redirect_uri ? (redirect_uri as string) : undefined,
createdAt: Date.now(),
};
const state = jwt.sign(jwtPayload, process.env.JWT_SECRET || 'default_secret', {
algorithm: 'HS256',
expiresIn: '1h',
if (!allowedOrigins.includes(origin)) {
logger.warn('OAuth redirect to disallowed origin blocked', {
origin,
allowedOrigins,
redirectUri,
});

const authUrl = await authService.generateLinkedInAuthUrl(state);

res.json({ authUrl });
} catch (error) {
logger.error('LinkedIn OAuth error', { error });
next(
new AppError(
'LinkedIn OAuth is not properly configured. Please check your oauth configurations.',
500,
ERROR_CODES.AUTH_OAUTH_CONFIG_ERROR
)
throw new AppError(
`Redirect origin not allowed. Allowed origins: ${allowedOrigins.join(', ')}`,
400,
ERROR_CODES.INVALID_INPUT
);
}
});

// GET /api/auth/oauth/shared/callback/:state - Shared callback for OAuth providers
router.get('/shared/callback/:state', async (req: Request, res: Response, next: NextFunction) => {
try {
const { state } = req.params;
const { success, error, payload } = req.query;

if (!state) {
logger.warn('Shared OAuth callback called without state parameter');
throw new AppError('State parameter is required', 400, ERROR_CODES.INVALID_INPUT);
}

let redirectUri: string;
let provider: string;
try {
const decodedState = jwt.verify(state, process.env.JWT_SECRET || 'default_secret') as {
provider: string;
redirectUri: string;
};
redirectUri = decodedState.redirectUri || '/';
provider = decodedState.provider || '';
} catch {
logger.warn('Invalid state parameter', { state });
throw new AppError('Invalid state parameter', 400, ERROR_CODES.INVALID_INPUT);
}

if (!['google', 'github', 'discord', 'linkedin'].includes(provider)) {
logger.warn('Invalid provider in state', { provider });
throw new AppError('Invalid provider in state', 400, ERROR_CODES.INVALID_INPUT);
}
if (!redirectUri) {
throw new AppError('Redirect URL is required', 400, ERROR_CODES.INVALID_INPUT);
}
return origin;
};

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.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

Confirm env docs and cross-site cookie strategy.

  • OAUTH_ALLOWED_ORIGINS and DEFAULT_FRONTEND_ORIGIN must be documented in .env.example/README.
  • If frontend and API are on different origins, SameSite='lax' will not include cookies on fetch; consider SameSite=None; Secure with CORS credentials.

Also applies to: 579-599


🏁 Script executed:

#!/bin/bash
# Check env templates and docs mention these vars
rg -n "OAUTH_ALLOWED_ORIGINS|DEFAULT_FRONTEND_ORIGIN" -g "*.{md,env,example}" -S || true

Length of output: 0



---

🏁 Script executed:

```shell
#!/bin/bash
# Find .env.example and similar environment template files
fd -type f -name ".env*" -o -name "*.example"

Length of output: 170


🏁 Script executed:

#!/bin/bash
# Search for OAUTH_ALLOWED_ORIGINS without case sensitivity and broader scope
rg -in "oauth_allowed_origins|default_frontend_origin" 

Length of output: 500


🏁 Script executed:

#!/bin/bash
# Find README and documentation files
fd -type f \( -name "README*" -o -name "*.md" \)

Length of output: 170


🏁 Script executed:

#!/bin/bash
# Search for SameSite, cookie configuration, and CORS in the backend
rg -n "SameSite|sameSite|setCookie|credentials" backend/src --type ts --type tsx -C2

Length of output: 27


🏁 Script executed:

#!/bin/bash
# Locate lines 579-599 in the auth.oauth.ts file to see the second concern
fd -type f -name "auth.oauth.ts" -path "*/backend/src/api/routes/*" -exec cat {} \; | sed -n '570,610p'

Length of output: 170


🏁 Script executed:

#!/bin/bash
# Check if DEFAULT_FRONTEND_ORIGIN is used anywhere in the codebase
rg -in "default_frontend_origin" --type ts --type tsx

Length of output: 27



---

🏁 Script executed:

```shell
#!/bin/bash
# Find .env example files with corrected syntax
fd -type f -name ".env*"

Length of output: 170


🏁 Script executed:

#!/bin/bash
# Find README and documentation files with corrected syntax
find . -type f \( -name "README*" -o -name "*.md" \) 2>/dev/null | head -20

Length of output: 658


🏁 Script executed:

#!/bin/bash
# Search for SameSite, setCookie, credentials with correct rg syntax
rg -n "SameSite|sameSite|setCookie|credentials" backend/src --type ts -C2

Length of output: 8680


🏁 Script executed:

#!/bin/bash
# Get the auth.oauth.ts file and show lines around 579-599
cat backend/src/api/routes/auth.oauth.ts | sed -n '570,610p'

Length of output: 954


🏁 Script executed:

#!/bin/bash
# Check if .env.example exists and show its content
if [ -f .env.example ]; then cat .env.example; else echo "No .env.example found"; fi

Length of output: 1871


🏁 Script executed:

#!/bin/bash
# Search for CORS and cookie configuration in the codebase
rg -n "cors|CORS" backend/src --type ts -C2

Length of output: 909


Document missing OAuth environment variables and fix cross-origin cookie strategy.

  1. Add OAUTH_ALLOWED_ORIGINS and DEFAULT_FRONTEND_ORIGIN to .env.example with descriptions (currently used at lines 50, 512, 580 but undocumented).

  2. Lines 85 and 109 use sameSite: 'lax', but CORS is configured with origin: true and credentials: true in backend/src/server.ts and backend/src/core/socket/socket.ts. This combination prevents cookies from being sent on cross-origin requests. Use sameSite: 'none' with secure: true for cross-origin OAuth flows, or document the single-origin assumption.

🤖 Prompt for AI Agents
In backend/src/api/routes/auth.oauth.ts around lines 39 to 76: the review points
out missing environment variable docs and a cross-origin cookie mismatch; add
OAUTH_ALLOWED_ORIGINS and DEFAULT_FRONTEND_ORIGIN to .env.example with clear
descriptions and example values (used at lines ~50, ~512, ~580) so deployers
know to configure allowed redirect origins and the default frontend origin, and
update the cookie strategy for cross-origin OAuth flows where CORS uses origin:
true and credentials: true — change cookies (where set at lines referenced in
the review: 85 and 109) to sameSite: 'none' and secure: true for cross-origin
compatibility, or alternatively document that the app only supports
single-origin flows and keep sameSite: 'lax' if you choose that constraint.

- Replace hardcoded provider routes with unified wildcard endpoint
- Implement generic OAuth methods using OAuthProvidersSchema
- Add comprehensive error handling for unsupported providers
- Remove repetitive code and improve maintainability
- Fix route ordering to prevent wildcard route conflicts
- Enhance type safety across frontend and backend
- Add dynamic provider management in frontend
- Remove noisy else statements for cleaner code"
@Laaaaksh
Laaaaksh force-pushed the feat---oauth_code_refactor branch from a086f5c to 7e75b81 Compare October 22, 2025 09:26

@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

♻️ Duplicate comments (6)
frontend/src/components/OAuthTestPanel.tsx (3)

52-52: Update function parameter type.

The testSingleProvider function parameter should use OAuthProvidersSchema instead of string.

Apply this diff:

-  const testSingleProvider = async (provider: string): Promise<OAuthTestResult> => {
+  const testSingleProvider = async (provider: OAuthProvidersSchema): Promise<OAuthTestResult> => {

39-45: Update state type to match schema.

The selectedProvider state should be typed as OAuthProvidersSchema | '' to align with the schema-driven approach.

Apply this diff:

 export const OAuthTestPanel: React.FC = () => {
-  const [selectedProvider, setSelectedProvider] = useState<string>('');
+  const [selectedProvider, setSelectedProvider] = useState<OAuthProvidersSchema | ''>('');

17-37: Derive providers from schema to prevent drift and enforce type safety.

The hardcoded SUPPORTED_PROVIDERS array and string type annotations contradict the PR's goal of centralized, type-safe provider management. This creates drift risk if providers are added/removed from OAuthProvidersSchema.

Apply this diff to use schema-derived types:

 import React, { useState } from 'react';
+import { oAuthProvidersSchema, type OAuthProvidersSchema } from '@insforge/shared-schemas';
 import { Button } from '@/components/radix/Button';
 // ... other imports

 interface OAuthTestResult {
-  provider: string;
+  provider: OAuthProvidersSchema;
   success: boolean;
   authUrl?: string;
   error?: string;
   statusCode?: number;
 }

-const SUPPORTED_PROVIDERS = [
-  'google',
-  'github',
-  'discord',
-  'linkedin',
-  'facebook',
-  'instagram',
-  'tiktok',
-  'apple',
-  'x',
-  'spotify',
-  'microsoft',
-];
+const SUPPORTED_PROVIDERS = oAuthProvidersSchema.options as readonly OAuthProvidersSchema[];
backend/src/api/routes/auth.oauth.ts (3)

78-102: Duplicate: Still storing PII in cookies.

Lines 93-101 set user_id, user_email, and user_name as HTTP-only cookies, which stores PII unnecessarily and increases privacy/compliance risk. This was flagged in a previous review (lines 78-102 in past comments).

Recommendation: Only store access_token in cookies. The frontend should fetch user details via a /me endpoint after authentication.

Apply this diff:

 const setAuthCookies = (res: Response, result: AuthResult) => {
   const cookieOptions = {
     httpOnly: true,
     secure: process.env.NODE_ENV === 'production',
     sameSite: 'lax' as const,
     maxAge: 24 * 60 * 60 * 1000, // 24 hours
     path: '/',
   };
 
   if (result?.accessToken) {
     res.cookie('access_token', result.accessToken, cookieOptions);
   }
-  if (result?.user?.id) {
-    res.cookie('user_id', result.user.id, cookieOptions);
-  }
-  if (result?.user?.email) {
-    res.cookie('user_email', result.user.email, cookieOptions);
-  }
-  if (result?.user?.name) {
-    res.cookie('user_name', result.user.name, cookieOptions);
-  }
 };

And update clearAuthCookies accordingly:

 const clearAuthCookies = (res: Response) => {
   const cookieOptions = {
     httpOnly: true,
     secure: process.env.NODE_ENV === 'production',
     sameSite: 'lax' as const,
     maxAge: 0,
     path: '/',
   };
 
   res.cookie('access_token', '', cookieOptions);
-  res.cookie('user_id', '', cookieOptions);
-  res.cookie('user_email', '', cookieOptions);
-  res.cookie('user_name', '', cookieOptions);
 };

40-76: Duplicate: Document missing OAuth environment variables.

OAUTH_ALLOWED_ORIGINS (lines 50, 393) and DEFAULT_FRONTEND_ORIGIN (lines 506, 574) are used throughout but not documented. This was flagged in a previous review (lines 39-76 in past comments).

Required: Add these variables to .env.example with descriptions and example values so deployers know to configure them.

Example .env.example entry:

# OAuth Configuration
# Comma-separated list of allowed redirect origins for OAuth flows
OAUTH_ALLOWED_ORIGINS=http://localhost:3000,https://app.example.com

# Default frontend origin for OAuth redirects when state is invalid
DEFAULT_FRONTEND_ORIGIN=http://localhost:3000

78-118: Duplicate: Fix sameSite for cross-origin or document single-origin constraint.

Lines 85 and 109 use sameSite: 'lax', but the codebase has CORS configured with origin: true and credentials: true. This combination prevents cookies from being sent on cross-origin requests. This was flagged in a previous review (lines 39-76 in past comments).

Options:

  1. Change to sameSite: 'none' with secure: true for cross-origin OAuth flows
  2. Document that the app only supports single-origin flows and keep sameSite: 'lax'

For cross-origin support:

 const cookieOptions = {
   httpOnly: true,
   secure: process.env.NODE_ENV === 'production',
-  sameSite: 'lax' as const,
+  sameSite: 'none' as const,
   maxAge: 24 * 60 * 60 * 1000,
   path: '/',
 };

Ensure secure: true is always used with sameSite: 'none':

 const cookieOptions = {
   httpOnly: true,
-  secure: process.env.NODE_ENV === 'production',
+  secure: true, // Required for sameSite: 'none'
   sameSite: 'none' as const,
   maxAge: 24 * 60 * 60 * 1000,
   path: '/',
 };
🧹 Nitpick comments (1)
frontend/src/components/OAuthTestPanel.tsx (1)

145-149: Consider extracting provider name formatting.

The inline capitalization logic (provider.charAt(0).toUpperCase() + provider.slice(1)) is repeated in the results section. Consider extracting to a helper function for consistency.

Example:

const formatProviderName = (provider: OAuthProvidersSchema): string => 
  provider.charAt(0).toUpperCase() + provider.slice(1);

Then use:

-  {provider.charAt(0).toUpperCase() + provider.slice(1)}
+  {formatProviderName(provider)}
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a086f5c and 7e75b81.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (12)
  • backend/src/api/routes/auth.oauth.ts (5 hunks)
  • backend/src/core/auth/auth.ts (4 hunks)
  • backend/src/core/auth/oauth.ts (6 hunks)
  • backend/src/utils/seed.ts (4 hunks)
  • frontend/package.json (1 hunks)
  • frontend/src/components/OAuthTestPanel.tsx (1 hunks)
  • frontend/src/features/auth/components/AddOAuthDialog.tsx (3 hunks)
  • frontend/src/features/auth/components/AuthMethodTab.tsx (4 hunks)
  • frontend/src/features/auth/components/OAuthConfigDialog.tsx (2 hunks)
  • frontend/src/features/auth/hooks/useOAuthConfig.ts (2 hunks)
  • package.json (2 hunks)
  • shared-schemas/src/auth.schema.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
  • frontend/src/features/auth/components/OAuthConfigDialog.tsx
  • frontend/src/features/auth/components/AuthMethodTab.tsx
  • shared-schemas/src/auth.schema.ts
  • frontend/src/features/auth/hooks/useOAuthConfig.ts
  • package.json
🧰 Additional context used
📓 Path-based instructions (10)
**/*.{ts,tsx}

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

**/*.{ts,tsx}: Use TypeScript for all code files
Use ES modules (import/export syntax)
Prefer descriptive, unabbreviated variable and function names
Implement proper error handling with try-catch blocks and logging where appropriate
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 2-space indentation
Format code with the repository Prettier configuration
Variables, parameters, properties, and functions must use camelCase
Constants and enum members must use UPPER_CASE
Include JSDoc comments for complex functions

Files:

  • backend/src/core/auth/oauth.ts
  • backend/src/core/auth/auth.ts
  • backend/src/api/routes/auth.oauth.ts
  • backend/src/utils/seed.ts
  • frontend/src/features/auth/components/AddOAuthDialog.tsx
  • frontend/src/components/OAuthTestPanel.tsx
backend/src/**/*.{ts,tsx}

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

backend/src/**/*.{ts,tsx}: Use async/await for asynchronous operations in the backend
Use Zod schemas for request/response validation
Return consistent API responses using utility functions
Validate all user inputs
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper caching strategies (server-side)

Files:

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

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

Implement proper database transaction handling

Files:

  • backend/src/core/auth/oauth.ts
  • backend/src/core/auth/auth.ts
**/*.{tsx,ts}

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

React components and TypeScript types/interfaces must use PascalCase

Files:

  • backend/src/core/auth/oauth.ts
  • backend/src/core/auth/auth.ts
  • backend/src/api/routes/auth.oauth.ts
  • backend/src/utils/seed.ts
  • frontend/src/features/auth/components/AddOAuthDialog.tsx
  • frontend/src/components/OAuthTestPanel.tsx
**/[a-z][a-z0-9-]*.ts

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

Utility files should use kebab-case or camelCase (kebab-case validated here)

Files:

  • backend/src/core/auth/oauth.ts
  • backend/src/core/auth/auth.ts
  • backend/src/api/routes/auth.oauth.ts
  • backend/src/utils/seed.ts
backend/src/api/**/*.ts

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

backend/src/api/**/*.ts: Implement authentication and error-handling middleware
Follow RESTful conventions for API endpoints
Implement rate limiting for API endpoints

Files:

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

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

frontend/src/**/*.{tsx,ts}: Use functional React components with hooks exclusively
Use Radix UI primitives for accessibility
Optimize React component re-renders

Files:

  • frontend/src/features/auth/components/AddOAuthDialog.tsx
  • frontend/src/components/OAuthTestPanel.tsx
frontend/src/**/*.tsx

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

frontend/src/**/*.tsx: Implement TypeScript interfaces/types for all component props
Follow component composition patterns; keep components focused and single-purpose
Implement proper loading and error states in UI
Use a consistent icon set from lucide-react

Files:

  • frontend/src/features/auth/components/AddOAuthDialog.tsx
  • frontend/src/components/OAuthTestPanel.tsx
frontend/src/**/*.{ts,tsx}

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

frontend/src/**/*.{ts,tsx}: Use TanStack Query for server state management
Use React Hook Form for form handling with Zod validation
Optimize bundle size with proper imports

Files:

  • frontend/src/features/auth/components/AddOAuthDialog.tsx
  • frontend/src/components/OAuthTestPanel.tsx
frontend/src/**/[A-Z]*.tsx

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

Component files must use PascalCase filenames (e.g., DataGrid.tsx)

Files:

  • frontend/src/features/auth/components/AddOAuthDialog.tsx
  • frontend/src/components/OAuthTestPanel.tsx
🧬 Code graph analysis (6)
backend/src/core/auth/oauth.ts (2)
shared-schemas/src/auth.schema.ts (1)
  • OAuthProvidersSchema (110-110)
backend/src/api/middleware/error.ts (1)
  • AppError (7-17)
backend/src/core/auth/auth.ts (2)
shared-schemas/src/auth.schema.ts (1)
  • OAuthProvidersSchema (110-110)
shared-schemas/src/auth-api.schema.ts (1)
  • CreateSessionResponse (185-185)
backend/src/api/routes/auth.oauth.ts (4)
backend/src/api/middleware/error.ts (1)
  • AppError (7-17)
backend/src/utils/logger.ts (1)
  • logger (6-29)
backend/src/api/middleware/auth.ts (2)
  • verifyAdmin (71-116)
  • AuthRequest (8-17)
shared-schemas/src/auth.schema.ts (1)
  • oAuthProvidersSchema (57-69)
backend/src/utils/seed.ts (1)
shared-schemas/src/auth.schema.ts (1)
  • OAuthProvidersSchema (110-110)
frontend/src/features/auth/components/AddOAuthDialog.tsx (2)
frontend/src/features/auth/components/AuthMethodTab.tsx (1)
  • OAuthProviderInfo (69-75)
shared-schemas/src/auth.schema.ts (1)
  • OAuthProvidersSchema (110-110)
frontend/src/components/OAuthTestPanel.tsx (1)
frontend/src/lib/hooks/useToast.tsx (1)
  • useToast (223-229)
🔇 Additional comments (17)
frontend/package.json (1)

53-53: LGTM! Types update aligns with React 19.

The @types/react version bump from ^19.1.8 to ^19.2.2 is appropriate for the React 19.1.1 runtime and supports the type safety improvements in this PR.

frontend/src/features/auth/components/AddOAuthDialog.tsx (1)

12-12: LGTM! Consistent migration to centralized schema type.

The component correctly adopts OAuthProvidersSchema for all provider-related types, enhancing type safety and alignment with the backend schema. The migration is complete and consistent throughout.

Also applies to: 18-19, 29-29, 43-43

frontend/src/components/OAuthTestPanel.tsx (4)

87-102: LGTM! Proper validation and error handling.

The function correctly validates provider selection, manages loading state, and handles errors appropriately.


104-116: LGTM! Efficient concurrent testing.

Using Promise.all to test all providers concurrently is an appropriate approach for batch testing.


118-125: LGTM! Secure and user-friendly utilities.

The clipboard copy and new tab functions are implemented correctly with proper security attributes (noopener,noreferrer) and user feedback.


202-282: LGTM! Comprehensive and user-friendly results display.

The results section effectively presents test outcomes with status badges, generated URLs, copy/open actions, error messages, and summary statistics. The nullish coalescing operators (lines 243, 250) provide proper safety.

backend/src/utils/seed.ts (2)

58-86: LGTM: Clean refactor with improved type safety.

The loop-based approach eliminates code duplication and leverages OAuthProvidersSchema for type safety. Dynamic logging per provider is a nice touch.


88-146: LGTM: Scalable generalization for environment-based OAuth config.

The envMappings array approach is much more maintainable than discrete if/else blocks. Adding new providers now requires only a new entry in the array.

backend/src/core/auth/oauth.ts (2)

7-7: LGTM: Type safety and field completeness improvements.

The stricter provider typing with OAuthProvidersSchema and the addition of id/createdAt/updatedAt fields address previous review feedback and align with the schema updates.

Also applies to: 10-10, 53-77, 82-112


344-375: LGTM: Consistent field extensions and clearer post-update handling.

The extended RETURNING clause aligns with the schema changes, and the dedicated post-update block for secret-only updates improves code clarity.

backend/src/core/auth/auth.ts (3)

454-454: LGTM: More accurate return type.

Changing from Promise<string | undefined> to Promise<string> correctly reflects that these methods always return a string or throw an error.

Also applies to: 506-506, 1023-1023


1326-1363: LGTM: Provider-agnostic OAuth entry points implemented.

The generateAuthUrl and handleOAuthCallback methods provide clean abstraction for unified OAuth handling. The limitation to 4 providers (google, github, discord, linkedin) aligns with the PR's incremental refactoring approach.

Note: Microsoft OAuth methods are defined in this file (lines 829-945) but not included in these routing switches, creating an inconsistency flagged in the oauth.ts review.


1365-1437: LGTM: Well-structured provider-specific callback handlers.

The private callback handlers follow a consistent pattern with appropriate token vs. code flow support for each provider. Error handling is clear and informative.

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

26-76: LGTM: Strong security validation for JWT secret and redirect origins.

The validateJwtSecret and validateRedirectOrigin helpers enforce critical security requirements and address previous review feedback about JWT secret fallbacks and open redirect vulnerabilities.


159-367: LGTM: OAuth config management routes well-implemented.

The admin-protected config management routes include proper validation, error handling, audit logging, and real-time updates via socket broadcasting. The response structure cleanly wraps the configs array.


369-498: LGTM: Unified OAuth flow with strong validation and security.

The provider-agnostic route with schema-based validation, redirect origin allowlisting, and secure cookie-based token propagation addresses previous security concerns. Error messages that list supported providers provide good developer experience.


500-594: LGTM: Provider callback route securely implemented.

The provider-specific callback route follows the same secure pattern as the shared callback, with proper validation, cookie-based token propagation, and comprehensive error handling.

Comment thread backend/src/api/routes/auth.oauth.ts Resolved
Comment on lines +186 to 222
switch (input.provider) {
case 'google':
scopes = ['openid', 'email', 'profile'];
break;
case 'github':
scopes = ['user:email'];
break;
case 'discord':
scopes = ['identify', 'email'];
break;
case 'linkedin':
scopes = ['openid', 'profile', 'email'];
break;
case 'facebook':
scopes = ['email', 'public_profile'];
break;
case 'instagram':
scopes = ['user_profile', 'user_media'];
break;
case 'tiktok':
scopes = ['user.info.basic'];
break;
case 'apple':
scopes = ['name', 'email'];
break;
case 'x':
scopes = ['tweet.read', 'users.read'];
break;
case 'spotify':
scopes = ['user-read-email', 'user-read-private'];
break;
case 'microsoft':
scopes = ['openid', 'email', 'profile'];
break;
default:
scopes = ['email', 'profile'];
}

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.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

Verify Microsoft OAuth implementation completeness.

The switch includes default scopes for Microsoft (lines 217-219), and backend/src/core/auth/auth.ts defines Microsoft-specific methods (generateMicrosoftAuthUrl, exchangeCodeToTokenByMicrosoft, getMicrosoftUserInfo, findOrCreateMicrosoftUser at lines 829-945), but Microsoft is not included in the generateAuthUrl or handleOAuthCallback routing switches (lines 1326-1342, 1344-1363). This means Microsoft OAuth will throw "not yet implemented" errors despite having supporting methods defined.

Verify whether Microsoft should be added to the routing switches:


🏁 Script executed:

#!/bin/bash
# Check if Microsoft OAuth is intended to be fully functional
rg -n "microsoft" backend/src/core/auth/auth.ts -C 3

Length of output: 2981



---

🏁 Script executed:

```shell
#!/bin/bash
# Check generateAuthUrl switch (around lines 1326-1342)
sed -n '1320,1350p' backend/src/core/auth/auth.ts

Length of output: 945


🏁 Script executed:

#!/bin/bash
# Check handleOAuthCallback switch (around lines 1344-1363)
sed -n '1340,1375p' backend/src/core/auth/auth.ts

Length of output: 1085


🏁 Script executed:

#!/bin/bash
# Search for all case statements mentioning providers in routing methods
rg -n "case\s+'(google|github|discord|linkedin|microsoft)" backend/src/core/auth/auth.ts

Length of output: 213


Add Microsoft OAuth routing to both switch statements in auth.ts.

The review comment correctly identifies an incomplete implementation. Microsoft OAuth methods are fully defined (generateMicrosoftAuthUrl, exchangeCodeToTokenByMicrosoft, getMicrosoftUserInfo, findOrCreateMicrosoftUser at lines 829-945), and scopes are configured in oauth.ts, but Microsoft is missing from the routing switches:

  • generateAuthUrl (lines 1331-1340) only routes google, github, discord, linkedin
  • handleOAuthCallback (lines 1352-1361) only routes google, github, discord, linkedin

Any Microsoft OAuth attempt will throw "not yet implemented" error. Add case 'microsoft' to both switches to route to the corresponding methods, matching the pattern used for other providers.

🤖 Prompt for AI Agents
In backend/src/core/auth/oauth.ts around lines 1331-1340 and 1352-1361, the
switch statements that route provider logic for generateAuthUrl and
handleOAuthCallback are missing a case for 'microsoft'; add a case 'microsoft'
in both switches that follows the existing pattern (i.e. route generateAuthUrl
to the generateMicrosoftAuthUrl helper and route handleOAuthCallback to the
Microsoft callback flow used for other providers —
exchangeCodeToTokenByMicrosoft, getMicrosoftUserInfo, findOrCreateMicrosoftUser)
so Microsoft OAuth requests are handled instead of throwing "not yet
implemented".

@Laaaaksh

Copy link
Copy Markdown
Contributor Author

@Fermionic-Lyu Please check!

@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 (2)
backend/src/api/routes/auth.oauth.ts (2)

110-122: Verify service returns id/createdAt/updatedAt fields.

Past reviews flagged that OAuthConfigService.getAllConfigs may not SELECT id, created_at, and updated_at columns, but the response mapper at lines 113-116 expects them via ListOAuthConfigsResponse.

#!/bin/bash
# Verify OAuthConfigService.getAllConfigs returns required fields
ast-grep --pattern 'getAllConfigs() {
  $$$
}'

125-154: Verify service returns id/createdAt/updatedAt for single config.

Similar to the list endpoint, OAuthConfigService.getConfigByProvider may not SELECT id, created_at, and updated_at, but the response at lines 142-145 spreads the config object which should include these fields per the schema.

#!/bin/bash
# Verify getConfigByProvider returns required fields including timestamps
ast-grep --pattern 'getConfigByProvider($PROVIDER) {
  $$$
}'
🧹 Nitpick comments (3)
backend/src/api/routes/auth.oauth.ts (2)

342-342: Storing only origin loses user's intended redirect path.

Line 342 stores only the validated origin (protocol + host) in the JWT, discarding any path from the original redirect_uri. This means redirects at lines 437 and 500 always go to ${origin}/?success=true, losing the user's intended path (e.g., /dashboard/settings).

If this is intentional for security (preventing path-based open redirects), consider documenting it. Otherwise, validate and preserve the full path.


455-455: Validate DEFAULT_FRONTEND_ORIGIN against allowlist.

DEFAULT_FRONTEND_ORIGIN is used as a fallback when state is missing or invalid, but it's not validated against OAUTH_ALLOWED_ORIGINS. If an admin misconfigures this variable to point to an untrusted origin, it could bypass the allowlist protection.

Consider adding startup validation that DEFAULT_FRONTEND_ORIGIN is in OAUTH_ALLOWED_ORIGINS, or at minimum document this requirement in .env.example.

Apply this diff to validate at startup:

+// Validate DEFAULT_FRONTEND_ORIGIN on module load
+(() => {
+  const defaultOrigin = process.env.DEFAULT_FRONTEND_ORIGIN;
+  if (defaultOrigin) {
+    const allowedOrigins = process.env.OAUTH_ALLOWED_ORIGINS?.split(',').map(o => o.trim()) || [];
+    if (allowedOrigins.length > 0 && !allowedOrigins.includes(defaultOrigin)) {
+      logger.warn('DEFAULT_FRONTEND_ORIGIN is not in OAUTH_ALLOWED_ORIGINS allowlist', {
+        defaultOrigin,
+        allowedOrigins
+      });
+    }
+  }
+})();
+
 const router = Router();

Also applies to: 523-523

.env.example (1)

72-89: Consider documenting DEFAULT_FRONTEND_ORIGIN allowlist requirement.

The documentation is comprehensive, but consider adding a note that DEFAULT_FRONTEND_ORIGIN should typically be included in OAUTH_ALLOWED_ORIGINS to ensure consistency and avoid configuration errors.

Example addition:

 # Default Frontend Origin (fallback redirect)
 # Used when OAuth state doesn't specify a redirect URI
+# Note: Should typically be included in OAUTH_ALLOWED_ORIGINS
 # Examples:
 #   Development: http://localhost:3000
 #   Production: https://yourdomain.com
 DEFAULT_FRONTEND_ORIGIN=http://localhost:3000
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7e75b81 and c7ef523.

📒 Files selected for processing (5)
  • .env.example (1 hunks)
  • backend/src/api/routes/auth.oauth.ts (5 hunks)
  • docker-compose.yml (1 hunks)
  • frontend/src/features/auth/components/OAuthConfigDialog.tsx (2 hunks)
  • shared-schemas/src/auth-api.schema.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (10)
**/.env.example

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

Document environment variables and configuration in .env.example

Files:

  • .env.example
**/*.{ts,tsx}

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

**/*.{ts,tsx}: Use TypeScript for all code files
Use ES modules (import/export syntax)
Prefer descriptive, unabbreviated variable and function names
Implement proper error handling with try-catch blocks and logging where appropriate
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 2-space indentation
Format code with the repository Prettier configuration
Variables, parameters, properties, and functions must use camelCase
Constants and enum members must use UPPER_CASE
Include JSDoc comments for complex functions

Files:

  • frontend/src/features/auth/components/OAuthConfigDialog.tsx
  • shared-schemas/src/auth-api.schema.ts
  • backend/src/api/routes/auth.oauth.ts
frontend/src/**/*.{tsx,ts}

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

frontend/src/**/*.{tsx,ts}: Use functional React components with hooks exclusively
Use Radix UI primitives for accessibility
Optimize React component re-renders

Files:

  • frontend/src/features/auth/components/OAuthConfigDialog.tsx
frontend/src/**/*.tsx

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

frontend/src/**/*.tsx: Implement TypeScript interfaces/types for all component props
Follow component composition patterns; keep components focused and single-purpose
Implement proper loading and error states in UI
Use a consistent icon set from lucide-react

Files:

  • frontend/src/features/auth/components/OAuthConfigDialog.tsx
frontend/src/**/*.{ts,tsx}

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

frontend/src/**/*.{ts,tsx}: Use TanStack Query for server state management
Use React Hook Form for form handling with Zod validation
Optimize bundle size with proper imports

Files:

  • frontend/src/features/auth/components/OAuthConfigDialog.tsx
**/*.{tsx,ts}

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

React components and TypeScript types/interfaces must use PascalCase

Files:

  • frontend/src/features/auth/components/OAuthConfigDialog.tsx
  • shared-schemas/src/auth-api.schema.ts
  • backend/src/api/routes/auth.oauth.ts
frontend/src/**/[A-Z]*.tsx

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

Component files must use PascalCase filenames (e.g., DataGrid.tsx)

Files:

  • frontend/src/features/auth/components/OAuthConfigDialog.tsx
**/[a-z][a-z0-9-]*.ts

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

Utility files should use kebab-case or camelCase (kebab-case validated here)

Files:

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

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

backend/src/**/*.{ts,tsx}: Use async/await for asynchronous operations in the backend
Use Zod schemas for request/response validation
Return consistent API responses using utility functions
Validate all user inputs
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper caching strategies (server-side)

Files:

  • backend/src/api/routes/auth.oauth.ts
backend/src/api/**/*.ts

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

backend/src/api/**/*.ts: Implement authentication and error-handling middleware
Follow RESTful conventions for API endpoints
Implement rate limiting for API endpoints

Files:

  • backend/src/api/routes/auth.oauth.ts
🧬 Code graph analysis (3)
frontend/src/features/auth/components/OAuthConfigDialog.tsx (2)
shared-schemas/src/auth.schema.ts (1)
  • OAuthProvidersSchema (110-110)
frontend/src/lib/utils/utils.ts (1)
  • isInsForgeCloudProject (158-160)
shared-schemas/src/auth-api.schema.ts (1)
shared-schemas/src/auth.schema.ts (1)
  • oAuthConfigSchema (77-86)
backend/src/api/routes/auth.oauth.ts (3)
backend/src/api/middleware/error.ts (1)
  • AppError (7-17)
backend/src/api/middleware/auth.ts (2)
  • verifyAdmin (71-116)
  • AuthRequest (8-17)
shared-schemas/src/auth.schema.ts (1)
  • oAuthProvidersSchema (57-69)
🔇 Additional comments (4)
backend/src/api/routes/auth.oauth.ts (1)

27-106: LGTM: Security helpers and cookie management are well-implemented.

The helper functions properly address previous security concerns:

  • validateJwtSecret enforces JWT_SECRET presence (no fallback)
  • validateRedirectOrigin validates against OAUTH_ALLOWED_ORIGINS allowlist
  • Cookie functions use sameSite: 'none' correctly for cross-origin OAuth flows with CORS credentials
  • PII removed from cookies (only access_token stored)
docker-compose.yml (1)

96-97: LGTM: OAuth environment variables properly configured.

The OAuth origin environment variables are correctly added with sensible defaults for local development (http://localhost:3000).

frontend/src/features/auth/components/OAuthConfigDialog.tsx (1)

18-22: LGTM: Type-safe provider handling with OAuthProvidersSchema.

The changes improve type safety by:

  • Importing and using OAuthProvidersSchema from shared schemas
  • Defining sharedKeyProviders with proper typing and satisfies assertion
  • Type-safe includes check at line 80

This aligns well with the PR's goal of enhancing type safety across the codebase.

Also applies to: 72-80

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

133-156: LGTM: Request schemas correctly omit managed fields.

The schema changes properly separate client-provided fields from server-managed ones:

  • Create request omits id, createdAt, updatedAt (server-managed)
  • Update request additionally omits provider (immutable identifier) and applies .partial() for optional updates
  • clientSecret appropriately optional in both (not needed for shared keys)

This follows best practices for API schema design.

@Fermionic-Lyu
Fermionic-Lyu changed the base branch from main to oauth-refactor October 22, 2025 18:51

@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.

Thanks for your PR! I'll approve to unblock first.

scopes = ['user-read-email', 'user-read-private'];
break;
case 'microsoft':
scopes = ['openid', 'email', 'profile'];

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.

I think it's ['User.Read'] for microsoft

@tonychang04 tonychang04 linked an issue Oct 22, 2025 that may be closed by this pull request
@tonychang04
tonychang04 merged commit a4fe151 into InsForge:oauth-refactor Oct 22, 2025
Fermionic-Lyu pushed a commit that referenced this pull request Oct 22, 2025
feat: refactor OAuth system for scalability and type safety
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.

[Feature]: Refactor OAuth providers

3 participants