Skip to content

feat: add Discord OAuth2 integration - #419

Merged
tonychang04 merged 1 commit into
InsForge:mainfrom
Silversoul-07:feat/discord-oauth-integration
Oct 18, 2025
Merged

tonychang04 merged 1 commit into
InsForge:mainfrom
Silversoul-07:feat/discord-oauth-integration

Conversation

@Silversoul-07

@Silversoul-07 Silversoul-07 commented Oct 14, 2025 •

Copy link
Copy Markdown
Contributor

Summary

This PR introduces Discord OAuth2 login integration across the backend and frontend, allowing users to authenticate using their Discord account. This closes issue #386

Key changes:

  • Backend

    • Added new route: /api/auth/oauth/discord
    • Implemented Discord OAuth2 flow in auth.oauth.ts and auth.ts
    • Updated types in auth.ts and seeding logic for OAuth users
    • Extended OpenAPI documentation (openapi/auth.yaml)
  • Frontend

    • Added Discord as an authentication provider in AuthMethodTab.tsx
  • Infrastructure

    • Updated docker-compose.yml and docker-compose.prod.yml for environment variable support
    • Added setup guide: DISCORD_OAUTH_SETUP.md

How did you test this change?

  1. Local testing

    • Created a Discord Developer application following the new DISCORD_OAUTH_SETUP.md instructions
    • Configured .env with DISCORD_CLIENT_ID, DISCORD_CLIENT_SECRET.
    • Started backend and frontend (docker compose up -d).
    • Use curl to get Callback url (curl -X GET "http://localhost:7130/api/auth/oauth/discord?redirect_uri=http://localhost:7131/dashboard")
    • Verified login via Discord redirects correctly and returns valid user tokens
  2. Functional tests

    • Tested successful login, logout, and token exchange
    • Verified user creation and linking for first-time Discord logins
    • Ensured existing login flows (e.g., GitHub OAuth) remain unaffected
  3. *Test

    npm test:e2e

    ✅ All tests passed

Summary by CodeRabbit

  • New Features

    • Discord OAuth support for sign-up, login, account linking, and admin setup; appears as a selectable provider in dialogs and user identity views (icon/label included).
  • Documentation

    • API docs updated with Discord OAuth initiation endpoint and callback support.
  • Chores

    • Added DISCORD_CLIENT_ID and DISCORD_CLIENT_SECRET to environment examples and compose files.

@Fermionic-Lyu
Fermionic-Lyu self-requested a review October 15, 2025 20:28
@Fermionic-Lyu

Copy link
Copy Markdown
Member

@Silversoul-07 Thanks for your PR! Do yo mind share some demo videos or pictures for your testing?

@Silversoul-07

Silversoul-07 commented Oct 16, 2025 •

Copy link
Copy Markdown
Contributor Author

@Fermionic-Lyu I apologise for the delay caused, I had bit trouble setting up screen recording on wayland.

Here what i tested and working:

  1. Add Ouath2 client and secret frontend loads them automatically. you can also manually ouath2 details at frontend which also works fine.
  2. Correct discord auth page and successful redirect to localhost (whatever redirect url)
  3. successful user creation using discord user name and email.
  4. Additionally when i used github to signin the badges where both github and discord but first username

here is demo:

2025-10-16.18-55-38.mp4
image

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

LGTM at first glance. Kindly resolve the conflict and fix the eslint errors, so we can build your PR into a new image to test internally.

Also try to change 'discord' to 'Discord' in user identities column for consistency. Thanks!

Comment thread DISCORD_OAUTH_SETUP.md Outdated

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.

Let's not add this md file for now

Comment thread backend/src/utils/seed.ts Outdated
}

// Seed Discord OAuth config if not exists
if (!existingProviders.includes('discord')) {

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.

This part is for InsForge cloud. Let's not add a default Discord OAuth for our cloud users.

@coderabbitai

coderabbitai Bot commented Oct 17, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds Discord as an OAuth provider: new env vars and Docker entries; backend route and AuthService methods for Discord OAuth; default Discord scopes in OAuth config; new DiscordUserInfo type; OpenAPI update; and frontend UI/types updated to surface Discord alongside existing providers.

Changes

Cohort / File(s) Summary
Configuration & Deployment
\.env.example, docker-compose.yml, docker-compose.prod.yml
Added DISCORD_CLIENT_ID and DISCORD_CLIENT_SECRET environment variables to env example and the insforge Docker service.
Backend Routes
backend/src/api/routes/auth.oauth.ts
Added GET /api/auth/oauth/discord; extended shared and provider-specific callback handlers to accept discord, validate state, exchange code, fetch Discord user info, and invoke user creation/find logic.
Backend Auth Service
backend/src/core/auth/auth.ts
Added Discord flows: generateDiscordAuthUrl, exchangeDiscordCodeForToken, getDiscordUserInfo, findOrCreateDiscordUser; expanded third-party user type unions to include DiscordUserInfo.
Backend OAuth Config
backend/src/core/auth/oauth.ts
Default scopes branch added for provider discord when no scopes provided: ['identify','email'].
Types
backend/src/types/auth.ts
Added exported DiscordUserInfo interface: { id: string; username: string; email?: string; avatar?: string }.
Frontend Auth UI
frontend/src/features/auth/components/*
frontend/src/features/auth/components/AuthMethodTab.tsx, AddOAuthDialog.tsx, UsersDataGrid.tsx
Added Discord provider entry and logo; extended provider id unions, props, and state to include discord; updated provider label/icon and provider enable/delete wiring.
API Spec
openapi/auth.yaml
Added GET /api/auth/oauth/discord and included discord in provider enum for callback paths.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Frontend
    participant Backend
    participant Discord as Discord OAuth

    User->>Frontend: Click "Connect Discord"
    Frontend->>Backend: GET /api/auth/oauth/discord?redirect_uri=...
    Backend->>Backend: validate redirect_uri & create state JWT (provider=discord)
    Backend-->>Frontend: 200 { authUrl }
    Frontend->>Discord: Redirect user to authUrl
    Discord->>User: Login & consent
    Discord-->>Frontend: Redirect to callback with code & state
    Frontend->>Backend: GET /api/auth/oauth/discord/callback?code=...&state=...
    Backend->>Backend: Verify state JWT
    Backend->>Discord: Exchange code for access_token
    Discord-->>Backend: Return access_token
    Backend->>Discord: Request user info (identify,email)
    Discord-->>Backend: Return user info
    Backend->>Backend: findOrCreateDiscordUser -> lookup/create local user, create session/token
    Backend-->>Frontend: Return session/token or redirect
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • Added linkedin oauth provider #421 — Adds another OAuth provider with parallel changes to auth routes, AuthService, types, OAuth config, and frontend provider UI (strongly related).

Suggested reviewers

  • Fermionic-Lyu
  • tonychang04

Poem

🐇 I hopped to add a Discord door,
Keys tucked safe in env once more,
State sealed, codes exchanged with cheer,
New users hop the session here,
Nose twitch — another friend is near.

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 PR title "feat: add Discord OAuth2 integration" accurately summarizes the primary objective of the changeset. The title is specific and clearly references Discord OAuth2 integration, which is the core focus across both backend and frontend modifications. The changes span environment configuration, backend OAuth routes and logic, type definitions, API documentation, and frontend UI components—all unified around enabling Discord as an OAuth provider. The title uses appropriate conventional commit formatting and is concise enough for easy scanning in commit history.
✨ 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: 5

Caution

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

⚠️ Outside diff range comments (1)
frontend/src/features/auth/components/AuthMethodTab.tsx (1)

118-129: Bug: selection handler excludes 'discord'; prevents configuring Discord.

Update the type to accept all provider ids and everything will compile/work.

Apply this diff:

-  const handleConfirmSelected = (selectedId: 'google' | 'github') => {
+  const handleConfirmSelected = (selectedId: OAuthProviderInfo['id']) => {
     // Find the selected provider
     const selectedProvider = providers.find((p) => p.id === selectedId);
     if (!selectedProvider) {
       return;
     }
♻️ Duplicate comments (1)
backend/src/utils/seed.ts (1)

85-92: Address previous review feedback: Discord seeding for cloud users.

A previous review comment from Fermionic-Lyu on line 86 stated: "This part is for InsForge cloud. Let's not add a default Discord OAuth for our cloud users." This Discord OAuth config is being seeded in seedDefaultOAuthConfigs, which only runs in cloud environments (line 184-185).

Consider one of these options:

  1. Remove this Discord seeding block from seedDefaultOAuthConfigs entirely
  2. Move it to seedLocalOAuthConfigs instead (lines 104-147) if Discord should only be available for self-hosted instances

Based on learnings (past review comment from maintainer).

🧹 Nitpick comments (6)
frontend/src/features/auth/components/UsersDataGrid.tsx (1)

36-41: Minor formatting: trailing space on line 40.

The Discord provider case is correctly implemented and follows the established pattern. However, there's a trailing space at the end of line 40 after the color string.

Apply this diff to remove the trailing space:

       case 'discord':
         return {
           label: 'Discord',
           color:
-            'bg-gray-100 text-gray-700 dark:bg-neutral-800 dark:text-zinc-300 dark:border-gray-500' ,
+            'bg-gray-100 text-gray-700 dark:bg-neutral-800 dark:text-zinc-300 dark:border-gray-500',
         };
backend/src/core/documentation/openapi.ts (1)

343-374: Docs added for Discord OAuth look good; consider documenting state query param as optional.

Parity with service methods that accept state helps clients implement CSRF protection consistently across providers. Suggest adding state?: string to the query schema.

Apply this diff within this block:

       request: {
         query: z
           .object({
-            redirect_uri: z.string().optional().describe('URL to redirect after OAuth completion'),
+            redirect_uri: z.string().optional().describe('URL to redirect after OAuth completion'),
+            state: z.string().optional().describe('Opaque value to maintain state and prevent CSRF'),
           })
           .openapi('OAuthRequest'),
       },
frontend/src/features/auth/components/AuthMethodTab.tsx (1)

105-111: Memo may be stale; recompute when configs change.

enabledProviders depends on config state but only lists isProviderConfigured in deps. Add configs or compute inline.

Apply this diff:

-  const enabledProviders = useMemo(() => {
+  const enabledProviders = useMemo(() => {
     return {
       google: isProviderConfigured('google'),
       github: isProviderConfigured('github'),
       discord: isProviderConfigured('discord'),
     };
-  }, [isProviderConfigured]);
+  }, [isProviderConfigured, configs]);
backend/src/core/documentation/agent.ts (1)

660-667: Quick reference still lists only Google/GitHub; include Discord.

Align the quickref with the new provider.

Apply this diff:

           authenticationSteps: [
@@
-            '5. OAuth login available via Google and GitHub providers',
+            '5. OAuth login available via Google, GitHub and Discord providers',
backend/src/core/auth/auth.ts (1)

610-680: Optional: add one-time code processing guard to GitHub/Discord like Google.

Prevents double-submission/race on code exchange. Extract guard into a helper used by all providers.

I can draft a small helper (e.g., withCodeProcessingGuard(code, fn)) and apply it to GitHub/Discord flows for parity. Based on learnings.

Also applies to: 748-778, 833-865

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

90-121: Consider extracting common OAuth initialization logic.

The Discord OAuth initialization endpoint follows the exact same pattern as Google (lines 26-55) and GitHub (lines 58-88). All three endpoints share nearly identical logic: validate redirect_uri, create JWT state payload, generate provider-specific auth URL, and handle errors uniformly.

Consider refactoring to a parameterized handler to reduce duplication:

// Helper function to handle OAuth initialization
async function initializeOAuthFlow(
  provider: 'google' | 'github' | 'discord',
  redirectUri: string,
  generateAuthUrl: (state: string) => Promise<string>
): Promise<string> {
  const jwtPayload = {
    provider,
    redirectUri,
    createdAt: Date.now(),
  };
  const state = jwt.sign(jwtPayload, process.env.JWT_SECRET || 'default_secret', {
    algorithm: 'HS256',
    expiresIn: '1h',
  });
  return await generateAuthUrl(state);
}

// Then each endpoint becomes:
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 authUrl = await initializeOAuthFlow(
      'discord',
      redirect_uri as string,
      (state) => authService.generateDiscordAuthUrl(state)
    );
    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
      )
    );
  }
});
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 703e085 and e2c98a3.

📒 Files selected for processing (14)
  • .env.example (1 hunks)
  • backend/logs/insforge.logs.jsonl (1 hunks)
  • backend/src/api/routes/auth.oauth.ts (5 hunks)
  • backend/src/core/auth/auth.ts (3 hunks)
  • backend/src/core/auth/oauth.ts (1 hunks)
  • backend/src/core/documentation/agent.ts (1 hunks)
  • backend/src/core/documentation/openapi.ts (2 hunks)
  • backend/src/types/auth.ts (1 hunks)
  • backend/src/utils/seed.ts (2 hunks)
  • docker-compose.prod.yml (1 hunks)
  • docker-compose.yml (1 hunks)
  • frontend/src/features/auth/components/AuthMethodTab.tsx (4 hunks)
  • frontend/src/features/auth/components/UsersDataGrid.tsx (1 hunks)
  • openapi/auth.yaml (1 hunks)
🧰 Additional context used
📓 Path-based instructions (12)
**/*.{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/types/auth.ts
  • backend/src/core/auth/oauth.ts
  • backend/src/core/documentation/agent.ts
  • backend/src/core/documentation/openapi.ts
  • frontend/src/features/auth/components/AuthMethodTab.tsx
  • backend/src/utils/seed.ts
  • backend/src/core/auth/auth.ts
  • frontend/src/features/auth/components/UsersDataGrid.tsx
  • 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/types/auth.ts
  • backend/src/core/auth/oauth.ts
  • backend/src/core/documentation/agent.ts
  • backend/src/core/documentation/openapi.ts
  • backend/src/utils/seed.ts
  • backend/src/core/auth/auth.ts
  • 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/types/auth.ts
  • backend/src/core/auth/oauth.ts
  • backend/src/core/documentation/agent.ts
  • backend/src/core/documentation/openapi.ts
  • frontend/src/features/auth/components/AuthMethodTab.tsx
  • backend/src/utils/seed.ts
  • backend/src/core/auth/auth.ts
  • frontend/src/features/auth/components/UsersDataGrid.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:

  • backend/src/types/auth.ts
  • backend/src/core/auth/oauth.ts
  • backend/src/core/documentation/agent.ts
  • backend/src/core/documentation/openapi.ts
  • backend/src/utils/seed.ts
  • backend/src/core/auth/auth.ts
  • backend/src/api/routes/auth.oauth.ts
**/.env.example

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

Document environment variables and configuration in .env.example

Files:

  • .env.example
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/documentation/agent.ts
  • backend/src/core/documentation/openapi.ts
  • backend/src/core/auth/auth.ts
openapi/**/*.{yml,yaml,json}

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

Document all API endpoints with clear OpenAPI documentation

Files:

  • openapi/auth.yaml
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/UsersDataGrid.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/AuthMethodTab.tsx
  • frontend/src/features/auth/components/UsersDataGrid.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/UsersDataGrid.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/AuthMethodTab.tsx
  • frontend/src/features/auth/components/UsersDataGrid.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
🧠 Learnings (1)
📚 Learning: 2025-10-15T18:18:47.505Z
Learnt from: CR
PR: InsForge/InsForge#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.505Z
Learning: Applies to frontend/src/**/*.tsx : Use a consistent icon set from lucide-react

Applied to files:

  • frontend/src/features/auth/components/AuthMethodTab.tsx
🧬 Code graph analysis (2)
backend/src/core/auth/auth.ts (3)
backend/src/core/auth/oauth.ts (1)
  • OAuthConfigService (26-400)
backend/src/types/auth.ts (1)
  • DiscordUserInfo (92-97)
shared-schemas/src/auth-api.schema.ts (1)
  • CreateSessionResponse (185-185)
backend/src/api/routes/auth.oauth.ts (1)
backend/src/api/middleware/error.ts (1)
  • AppError (7-17)
🔇 Additional comments (15)
.env.example (1)

55-57: LGTM! Discord OAuth environment variables properly documented.

The Discord OAuth configuration follows the established pattern for Google and GitHub OAuth, with appropriate documentation and links to the developer portal.

docker-compose.yml (1)

100-101: LGTM! Discord environment variables properly configured.

The Discord OAuth environment variables are correctly added to the development Docker Compose configuration, following the established pattern for Google and GitHub OAuth.

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

185-186: LGTM! Discord default scopes are appropriate.

The default scopes ['identify', 'email'] are correct for Discord OAuth. The identify scope provides basic user information, and email provides the email address, which are the minimal required scopes for authentication.

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

92-97: LGTM! DiscordUserInfo interface correctly defined.

The interface properly represents Discord OAuth user data with appropriate field types. The optional email and avatar fields correctly handle cases where users haven't verified their email or set a custom avatar.

docker-compose.prod.yml (1)

97-98: LGTM! Production Discord OAuth configuration aligned.

The Discord OAuth environment variables are correctly added to the production Docker Compose configuration, mirroring the development setup.

openapi/auth.yaml (1)

422-438: LGTM! Discord OAuth endpoint properly documented.

The Discord OAuth endpoint specification follows the established pattern for Google and GitHub OAuth endpoints, with consistent parameters, responses, and tags. The OpenAPI documentation is complete and accurate.

backend/src/core/documentation/openapi.ts (1)

386-386: Provider enum updated to include 'discord' — LGTM.

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

6-6: Discord logo import — LGTM.


35-41: Discord provider card — LGTM.


45-45: Type union extended with 'discord' — LGTM.

backend/src/core/documentation/agent.ts (1)

249-275: Discord OAuth doc entry — LGTM.

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

148-151: LGTM! Provider validation correctly updated.

The addition of 'discord' to the allowed providers list is correct and maintains consistency with the new Discord OAuth flow.


187-195: LGTM! Discord payload handling implemented correctly.

The Discord OAuth payload handling follows the same pattern as Google and GitHub, with appropriate field mappings (providerId → id, username, email, avatar) for Discord's user data structure.


233-235: LGTM! Provider validation correctly updated.

Correctly adds Discord to the allowed providers list in the provider-specific callback handler, maintaining consistency with the shared callback validation.


265-272: LGTM! Discord OAuth callback flow implemented correctly.

The Discord OAuth callback handling follows the standard OAuth2 authorization code flow and mirrors the GitHub implementation:

  1. Validates authorization code presence
  2. Exchanges code for access token
  3. Retrieves user information
  4. Creates or links the user account

The implementation is consistent with existing patterns and properly integrates into the callback handler.

Comment thread backend/logs/insforge.logs.jsonl Outdated
Comment on lines +1 to +35
{"id":"1760679676409-0.5129073168679235","timestamp":"2025-10-17T05:41:16.404Z","message":"AuthService initialized","level":"info","metadata":{}}
{"id":"1760679676567-0.7831507109012312","timestamp":"2025-10-17T05:41:16.566Z","message":"OAuthService initialized","level":"info","metadata":{}}
{"id":"1760679676567-0.8804450828275245","timestamp":"2025-10-17T05:41:16.567Z","message":"AuditService initialized","level":"info","metadata":{}}
{"id":"1760679677254-0.33671802243676807","timestamp":"2025-10-17T05:41:17.253Z","message":"Using log provider: File-based (no AWS credentials required)","level":"info","metadata":{}}
{"id":"1760679677257-0.8638529081123547","timestamp":"2025-10-17T05:41:17.256Z","message":"File-based analytics initialized at: /app/backend/insforge-logs","level":"info","metadata":{}}
{"id":"1760679677292-0.3038744660382384","timestamp":"2025-10-17T05:41:17.291Z","message":"\n🚀 Insforge Backend Starting...","level":"info","metadata":{}}
{"id":"1760679677293-0.6488743084249315","timestamp":"2025-10-17T05:41:17.293Z","message":"✅ Admin configured: [email protected]","level":"info","metadata":{}}
{"id":"1760679677359-0.019469610963994688","timestamp":"2025-10-17T05:41:17.358Z","message":"Secret retrieved by key","level":"info","metadata":{"key":"API_KEY"}}
{"id":"1760679677361-0.9135926119164446","timestamp":"2025-10-17T05:41:17.361Z","message":"✅ API key exists in database","level":"info","metadata":{}}
{"id":"1760679677373-0.3769574824746007","timestamp":"2025-10-17T05:41:17.372Z","message":"✅ Database connected to PostgreSQL","level":"info","metadata":{"host":"postgres","port":"5432","database":"insforge"}}
{"id":"1760679677374-0.3870425123969805","timestamp":"2025-10-17T05:41:17.373Z","message":"✅ Found 1 user tables","level":"info","metadata":{}}
{"id":"1760679677389-0.30655185037052135","timestamp":"2025-10-17T05:41:17.389Z","message":"Secret retrieved by key","level":"info","metadata":{"key":"INSFORGE_INTERNAL_URL"}}
{"id":"1760679677391-0.9344396304084086","timestamp":"2025-10-17T05:41:17.390Z","message":"API key generated: ik_your-api-key-here-32-chars-minimum","level":"info","metadata":{}}
{"id":"1760679677392-0.16235238721671807","timestamp":"2025-10-17T05:41:17.391Z","message":"Setup complete:\n - Save this API key for your apps!\n - Dashboard: http://localhost:7131\n - API: http://localhost:7130/api\n ","level":"info","metadata":{}}
{"id":"1760679677405-0.9255247313264019","timestamp":"2025-10-17T05:41:17.404Z","message":"Socket.IO server initialized","level":"info","metadata":{}}
{"id":"1760679677406-0.4250607088624221","timestamp":"2025-10-17T05:41:17.406Z","message":"Backend API service listening on port 7130","level":"info","metadata":{}}
{"id":"1760679681206-0.585296998691214","timestamp":"2025-10-17T05:41:21.206Z","message":"Socket client connected","level":"info","metadata":{"socketId":"MjeH0141OeFo5GcEAAAB","userId":"00000000-0000-0000-0000-000000000001","role":"project_admin","restoredSubscriptions":0}}
{"id":"1760680681860-0.4883844275036524","timestamp":"2025-10-17T05:58:01.860Z","message":"Shutting down gracefully...","level":"info","metadata":{}}
{"id":"1760680682471-0.5420558107841886","timestamp":"2025-10-17T05:58:02.470Z","message":"AuthService initialized","level":"info","metadata":{}}
{"id":"1760680682511-0.9020840978286504","timestamp":"2025-10-17T05:58:02.511Z","message":"OAuthService initialized","level":"info","metadata":{}}
{"id":"1760680682511-0.7884339867089933","timestamp":"2025-10-17T05:58:02.511Z","message":"AuditService initialized","level":"info","metadata":{}}
{"id":"1760680682617-0.45207862393601483","timestamp":"2025-10-17T05:58:02.617Z","message":"Using log provider: File-based (no AWS credentials required)","level":"info","metadata":{}}
{"id":"1760680682618-0.1573183025102336","timestamp":"2025-10-17T05:58:02.618Z","message":"File-based analytics initialized at: /app/backend/insforge-logs","level":"info","metadata":{}}
{"id":"1760680682621-0.31382620878077083","timestamp":"2025-10-17T05:58:02.621Z","message":"\n🚀 Insforge Backend Starting...","level":"info","metadata":{}}
{"id":"1760680682622-0.3756955974918348","timestamp":"2025-10-17T05:58:02.621Z","message":"✅ Admin configured: [email protected]","level":"info","metadata":{}}
{"id":"1760680682635-0.6893499493641642","timestamp":"2025-10-17T05:58:02.634Z","message":"Secret retrieved by key","level":"info","metadata":{"key":"API_KEY"}}
{"id":"1760680682635-0.33451766053292586","timestamp":"2025-10-17T05:58:02.635Z","message":"✅ API key exists in database","level":"info","metadata":{}}
{"id":"1760680682637-0.3465342211671578","timestamp":"2025-10-17T05:58:02.637Z","message":"✅ Database connected to PostgreSQL","level":"info","metadata":{"host":"postgres","port":"5432","database":"insforge"}}
{"id":"1760680682637-0.48930435643625025","timestamp":"2025-10-17T05:58:02.637Z","message":"✅ Found 1 user tables","level":"info","metadata":{}}
{"id":"1760680682642-0.3908969470735142","timestamp":"2025-10-17T05:58:02.642Z","message":"Secret retrieved by key","level":"info","metadata":{"key":"INSFORGE_INTERNAL_URL"}}
{"id":"1760680682642-0.7551866583548543","timestamp":"2025-10-17T05:58:02.642Z","message":"API key generated: ik_your-api-key-here-32-chars-minimum","level":"info","metadata":{}}
{"id":"1760680682642-0.9603727239165565","timestamp":"2025-10-17T05:58:02.642Z","message":"Setup complete:\n - Save this API key for your apps!\n - Dashboard: http://localhost:7131\n - API: http://localhost:7130/api\n ","level":"info","metadata":{}}
{"id":"1760680682644-0.38660268040515966","timestamp":"2025-10-17T05:58:02.644Z","message":"Socket.IO server initialized","level":"info","metadata":{}}
{"id":"1760680682644-0.987171223193537","timestamp":"2025-10-17T05:58:02.644Z","message":"Backend API service listening on port 7130","level":"info","metadata":{}}
{"id":"1760680683798-0.01222057521141795","timestamp":"2025-10-17T05:58:03.798Z","message":"Socket client connected","level":"info","metadata":{"socketId":"cudVTeedlHzJtoz-AAAB","userId":"00000000-0000-0000-0000-000000000001","role":"project_admin","restoredSubscriptions":0}}

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

Remove committed logs; redact secrets and PII in logging.

This JSONL includes an API key and user/role/socket IDs. Committing logs is a security/compliance risk and can leak secrets.

  • Delete this file from the repo and add an ignore rule (e.g., backend/logs/**, *.jsonl).
  • Ensure logger redacts secrets (API keys, tokens, emails). Mask values at source.
  • Rotate any keys that may have been exposed.

Run to find other committed logs and “API key” leaks:


🏁 Script executed:

#!/bin/bash
fd -HI --full-path '(logs|log|\.jsonl|\.log)$'
rg -nI -C2 -e 'API key generated|Bearer\s+[A-Za-z0-9\-\._]+' -S

Length of output: 8576



---

🏁 Script executed:

```shell
#!/bin/bash
# Check if .gitignore exists and what it says about logs
if [ -f .gitignore ]; then
  echo "=== .gitignore content (full) ==="
  cat .gitignore
  echo ""
  echo "=== Grep for log-related rules ==="
  grep -n -i -E '(log|\.jsonl|\.log)' .gitignore || echo "No log-related rules found"
else
  echo ".gitignore not found"
fi

# Check git status to see if logs file is tracked
echo ""
echo "=== Git tracking status of backend/logs/ ==="
git ls-files --others backend/logs/ 2>/dev/null || git ls-files backend/logs/ 2>/dev/null || echo "Git status check skipped"

Length of output: 91


Remove committed logs and establish gitignore rules; redact secrets in logging.

The file backend/logs/insforge.logs.jsonl contains an API key (ik_your-api-key-here-32-chars-minimum), user IDs, socket IDs, roles, and email addresses. Committing logs is a security and compliance risk that exposes PII and credentials.

Additionally, no .gitignore file exists in the repository, so there are no protections preventing future log file commits.

Action required:

  • Remove backend/logs/ from git history: git rm --cached backend/logs/ and commit
  • Create or update .gitignore with entries for logs: backend/logs/, *.jsonl, *.log
  • Update the logger to redact or omit API keys, user IDs, and socket IDs at the source before logging
  • Rotate the exposed API key if it was ever used in production
🤖 Prompt for AI Agents
In backend/logs/insforge.logs.jsonl around lines 1–35 the repository contains
committed logs with sensitive data (API key, user/socket IDs, emails); remove
the logs from version control and stop future commits by running git rm --cached
backend/logs/ and committing the removal, then add entries to .gitignore for
backend/logs/, *.jsonl, and *.log; update the logging pipeline at source to
redact/omit API keys, user IDs, and socket IDs (replace or filter those fields
before writing logs) and ensure any logger configuration writes sanitized output
only; finally rotate the exposed API key if it was ever used in any environment.

Comment thread backend/src/core/auth/auth.ts Resolved
Comment thread backend/src/core/auth/auth.ts Resolved
Comment thread backend/src/core/auth/auth.ts Resolved
Comment on lines +71 to +74
const deleteOAuthConfig = async (
providerId: 'google' | 'github' | 'discord',
providerName: string
) => {

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

Await deletion to catch errors; current try/catch won’t catch rejected promise.

deleteConfig is likely async. Without await, errors bypass the catch.

Apply this diff:

-  const deleteOAuthConfig = async (
+  const deleteOAuthConfig = async (
     providerId: 'google' | 'github' | 'discord',
     providerName: string
   ) => {
@@
-    if (shouldDelete) {
-      try {
-        deleteConfig(providerId);
-      } catch (error) {
+    if (shouldDelete) {
+      try {
+        await deleteConfig(providerId);
+      } catch (error) {
         console.error(`Failed to delete ${providerId} OAuth:`, error);
       }
     }
   };

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In frontend/src/features/auth/components/AuthMethodTab.tsx around lines 71 to
74, the call to deleteConfig is not awaited so any rejection escapes the
surrounding try/catch; update the try block to await the deleteConfig(...)
invocation (e.g., await deleteConfig(providerId, providerName)) so thrown errors
are caught, and keep any subsequent error handling or state updates after the
awaited call.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (5)
backend/logs/insforge.logs.jsonl (1)

1-71: This file must be removed from version control (critical security/compliance issue).

This concern has already been flagged in a previous review. The log file exposes:

  • API key (lines 13, 31, 49, 67) - even placeholder keys reveal credential patterns
  • User IDs, socket IDs, and roles (lines 17, 35, 53, 71)
  • Admin email addresses (lines 7, 25, 43, 61)
  • Database connection details (lines 10, 28, 46, 64)

Required actions remain unchanged:

  1. Remove from git: git rm --cached backend/logs/insforge.logs.jsonl
  2. Add to .gitignore: backend/logs/, *.jsonl, *.log
  3. Update logger to redact API keys, user IDs, socket IDs, and emails at source
  4. Rotate the exposed API key if used in any environment

Based on learnings from previous review.

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

71-90: Await deleteConfig to catch errors properly.

Line 85 calls deleteConfig without awaiting it, so any rejected promise will escape the try/catch block and potentially cause unhandled promise rejections.

Apply this diff:

     if (shouldDelete) {
       try {
-        deleteConfig(providerId);
+        await deleteConfig(providerId);
       } catch (error) {
         console.error(`Failed to delete ${providerId} OAuth:`, error);
       }
     }
backend/src/core/auth/auth.ts (3)

550-605: Use getApiBaseUrl() for consistency with Google/GitHub OAuth.

Line 561 uses a hardcoded fallback (process.env.API_BASE_URL || 'http://localhost:7130'), while Google (line 444) and GitHub (line 505) use getApiBaseUrl(). This inconsistency can break Discord OAuth redirects in different environments.

Apply this diff:

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

830-864: Use getApiBaseUrl() to ensure redirect_uri consistency.

Line 842 uses a hardcoded fallback that must exactly match the URL used in generateDiscordAuthUrl. Using getApiBaseUrl() ensures consistency and prevents OAuth failures due to redirect_uri mismatch.

Apply this diff:

     const clientSecret = await oauthConfigService.getClientSecretByProvider('discord');
-    const selfBaseUrl = process.env.API_BASE_URL || 'http://localhost:7130';
+    const selfBaseUrl = getApiBaseUrl();
     const response = await axios.post(

886-901: Provide a safe email fallback to prevent constraint violations.

Line 891 sets email to an empty string when Discord doesn't provide one. This can violate database constraints and break downstream flows. GitHub OAuth (line 818) uses a deterministic fallback pattern that should be replicated here.

Apply this diff:

   async findOrCreateDiscordUser(discordUserInfo: DiscordUserInfo): Promise<CreateSessionResponse> {
     const userName = discordUserInfo.username;
-    const email = discordUserInfo.email || '';
+    const email = 
+      discordUserInfo.email || 
+      `${discordUserInfo.id}@users.noreply.discord.local`;
 
     return this.findOrCreateThirdPartyUser(
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e2c98a3 and 1b378f7.

📒 Files selected for processing (13)
  • .env.example (1 hunks)
  • backend/logs/insforge.logs.jsonl (1 hunks)
  • backend/src/api/routes/auth.oauth.ts (5 hunks)
  • backend/src/core/auth/auth.ts (3 hunks)
  • backend/src/core/auth/oauth.ts (1 hunks)
  • backend/src/core/documentation/agent.ts (1 hunks)
  • backend/src/core/documentation/openapi.ts (2 hunks)
  • backend/src/types/auth.ts (1 hunks)
  • docker-compose.prod.yml (1 hunks)
  • docker-compose.yml (1 hunks)
  • frontend/src/features/auth/components/AuthMethodTab.tsx (4 hunks)
  • frontend/src/features/auth/components/UsersDataGrid.tsx (1 hunks)
  • openapi/auth.yaml (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
  • docker-compose.prod.yml
  • .env.example
  • backend/src/types/auth.ts
  • backend/src/core/auth/oauth.ts
  • frontend/src/features/auth/components/UsersDataGrid.tsx
🧰 Additional context used
📓 Path-based instructions (11)
openapi/**/*.{yml,yaml,json}

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

Document all API endpoints with clear OpenAPI documentation

Files:

  • openapi/auth.yaml
**/*.{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/documentation/openapi.ts
  • backend/src/core/auth/auth.ts
  • backend/src/api/routes/auth.oauth.ts
  • frontend/src/features/auth/components/AuthMethodTab.tsx
  • backend/src/core/documentation/agent.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/documentation/openapi.ts
  • backend/src/core/auth/auth.ts
  • backend/src/api/routes/auth.oauth.ts
  • backend/src/core/documentation/agent.ts
backend/src/{controllers,core}/**/*.ts

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

Implement proper database transaction handling

Files:

  • backend/src/core/documentation/openapi.ts
  • backend/src/core/auth/auth.ts
  • backend/src/core/documentation/agent.ts
**/*.{tsx,ts}

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

React components and TypeScript types/interfaces must use PascalCase

Files:

  • backend/src/core/documentation/openapi.ts
  • backend/src/core/auth/auth.ts
  • backend/src/api/routes/auth.oauth.ts
  • frontend/src/features/auth/components/AuthMethodTab.tsx
  • backend/src/core/documentation/agent.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/documentation/openapi.ts
  • backend/src/core/auth/auth.ts
  • backend/src/api/routes/auth.oauth.ts
  • backend/src/core/documentation/agent.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/AuthMethodTab.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/AuthMethodTab.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/**/[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
🧠 Learnings (1)
📚 Learning: 2025-10-15T18:18:47.505Z
Learnt from: CR
PR: InsForge/InsForge#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.505Z
Learning: Applies to frontend/src/**/*.tsx : Use a consistent icon set from lucide-react

Applied to files:

  • frontend/src/features/auth/components/AuthMethodTab.tsx
🧬 Code graph analysis (2)
backend/src/core/auth/auth.ts (3)
backend/src/core/auth/oauth.ts (1)
  • OAuthConfigService (26-400)
backend/src/types/auth.ts (1)
  • DiscordUserInfo (92-97)
shared-schemas/src/auth-api.schema.ts (1)
  • CreateSessionResponse (185-185)
backend/src/api/routes/auth.oauth.ts (1)
backend/src/api/middleware/error.ts (1)
  • AppError (7-17)
🔇 Additional comments (15)
docker-compose.yml (1)

100-101: LGTM!

The Discord OAuth environment variables follow the same pattern as Google and GitHub OAuth configuration. The empty defaults are appropriate for optional OAuth providers.

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

22-28: LGTM!

The import of DiscordUserInfo is necessary for the new Discord OAuth functionality and follows the existing pattern for other OAuth provider types.


866-884: LGTM!

The Discord user info retrieval correctly handles the Discord API response and constructs avatar URLs when available.

backend/src/core/documentation/openapi.ts (2)

343-374: LGTM!

The Discord OAuth endpoint documentation is complete and follows the same structure as the Google and GitHub endpoints.


386-386: LGTM!

The provider enum correctly includes 'discord' alongside 'google' and 'github' for the OAuth callback parameter validation.

openapi/auth.yaml (1)

422-438: LGTM!

The Discord OAuth endpoint specification is consistent with the existing Google and GitHub OAuth endpoints, with appropriate parameters and response codes.

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

6-6: LGTM!

The Discord logo import follows the existing pattern for Google and GitHub logos.

Based on learnings


35-41: LGTM!

The Discord provider configuration is complete with appropriate icon, name, description, and setup URL.


44-50: LGTM!

The OAuthProviderInfo interface correctly extends the id union type to include 'discord'.


105-111: LGTM!

The enabledProviders object correctly includes Discord in the provider status tracking.

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

90-121: LGTM!

The Discord OAuth initialization endpoint correctly mirrors the Google and GitHub patterns, including JWT state generation, error handling, and redirect URI validation.


148-151: LGTM!

The provider validation correctly includes 'discord' in the allowed providers list for the shared OAuth callback.


187-196: LGTM!

The Discord handling in the shared OAuth callback correctly constructs Discord user info from the payload and calls the appropriate service method.


233-235: LGTM!

The provider validation correctly includes 'discord' in the allowed providers list for the provider-specific OAuth callback.


265-273: LGTM!

The Discord OAuth callback handling correctly exchanges the authorization code for an access token, retrieves user info, and creates or links the user account, following the same pattern as GitHub.

Comment thread backend/src/core/documentation/agent.ts Outdated
Comment on lines +249 to +274
discordOAuth: {
method: 'GET',
path: '/api/auth/oauth/discord',
request: {
requiresAuth: false,
queryParams: {
redirect_uri: 'string (optional) - URL to redirect after OAuth completion',
},
},
response: {
success: {
status: 200,
body: {
authUrl: 'string - Discord OAuth authorization URL',
},
},
error: {
status: '500',
body: '{error: string, message: string, statusCode: number}',
},
},
example: {
request: 'GET /api/auth/oauth/discord?redirect_uri=http://localhost:3000/dashboard',
response: '{authUrl: "https://discord.com/api/oauth2/authorize?..."}',
},
},

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

Move discordOAuth inside the authenticationApi object.

Lines 249-274 define discordOAuth at the root level of the document object, but it should be nested inside authenticationApi like googleOAuth (lines 194-219) and githubOAuth (lines 221-246). This placement error will confuse AI agents and break the documentation structure.

Apply this diff to move it inside authenticationApi:

           response: '{authUrl: "https://github.com/login/oauth/authorize?..."}',
         },
       },
+
+      discordOAuth: {
+        method: 'GET',
+        path: '/api/auth/oauth/discord',
+        request: {
+          requiresAuth: false,
+          queryParams: {
+            redirect_uri: 'string (optional) - URL to redirect after OAuth completion',
+          },
+        },
+        response: {
+          success: {
+            status: 200,
+            body: {
+              authUrl: 'string - Discord OAuth authorization URL',
+            },
+          },
+          error: {
+            status: '500',
+            body: '{error: string, message: string, statusCode: number}',
+          },
+        },
+        example: {
+          request: 'GET /api/auth/oauth/discord?redirect_uri=http://localhost:3000/dashboard',
+          response: '{authUrl: "https://discord.com/api/oauth2/authorize?..."}',
+        },
+      },
     },
 
-    discordOAuth: {
-      method: 'GET',
-      path: '/api/auth/oauth/discord',
-      request: {
-        requiresAuth: false,
-        queryParams: {
-          redirect_uri: 'string (optional) - URL to redirect after OAuth completion',
-        },
-      },
-      response: {
-        success: {
-          status: 200,
-          body: {
-            authUrl: 'string - Discord OAuth authorization URL',
-          },
-        },
-        error: {
-          status: '500',
-          body: '{error: string, message: string, statusCode: number}',
-        },
-      },
-      example: {
-        request: 'GET /api/auth/oauth/discord?redirect_uri=http://localhost:3000/dashboard',
-        response: '{authUrl: "https://discord.com/api/oauth2/authorize?..."}',
-      },
-    },
-
     // Universal patterns for all tables
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
discordOAuth: {
method: 'GET',
path: '/api/auth/oauth/discord',
request: {
requiresAuth: false,
queryParams: {
redirect_uri: 'string (optional) - URL to redirect after OAuth completion',
},
},
response: {
success: {
status: 200,
body: {
authUrl: 'string - Discord OAuth authorization URL',
},
},
error: {
status: '500',
body: '{error: string, message: string, statusCode: number}',
},
},
example: {
request: 'GET /api/auth/oauth/discord?redirect_uri=http://localhost:3000/dashboard',
response: '{authUrl: "https://discord.com/api/oauth2/authorize?..."}',
},
},
// Universal patterns for all tables
🤖 Prompt for AI Agents
backend/src/core/documentation/agent.ts around lines 249 to 274: The
discordOAuth entry is currently defined at the root of the document object but
must be nested inside the authenticationApi object alongside googleOAuth and
githubOAuth; move the entire discordOAuth block into the authenticationApi
object (ensure commas and surrounding object structure remain valid) so that
discordOAuth becomes a sibling of googleOAuth and githubOAuth and remove the
misplaced root-level definition.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

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

359-366: Consider adding DiscordUserInfo to the type signature for consistency.

The createThirdPartyUser method's identityData parameter doesn't explicitly include DiscordUserInfo in its type union, while findOrCreateThirdPartyUser (line 285) does. Although DiscordUserInfo will match Record<string, unknown> at runtime, explicitly including it improves type safety and maintains consistency with the pattern.

Apply this diff to improve type safety:

   private async createThirdPartyUser(
     provider: string,
     userName: string,
     email: string,
     providerId: string,
-    identityData: GoogleUserInfo | GitHubUserInfo | Record<string, unknown>,
+    identityData: GoogleUserInfo | GitHubUserInfo | DiscordUserInfo | Record<string, unknown>,
     avatarUrl: string
   ): Promise<CreateSessionResponse> {
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1b378f7 and 3736150.

📒 Files selected for processing (10)
  • .env.example (1 hunks)
  • backend/src/api/routes/auth.oauth.ts (5 hunks)
  • backend/src/core/auth/auth.ts (4 hunks)
  • backend/src/core/auth/oauth.ts (1 hunks)
  • backend/src/types/auth.ts (1 hunks)
  • docker-compose.prod.yml (1 hunks)
  • docker-compose.yml (1 hunks)
  • frontend/src/features/auth/components/AuthMethodTab.tsx (4 hunks)
  • frontend/src/features/auth/components/UsersDataGrid.tsx (1 hunks)
  • openapi/auth.yaml (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (6)
  • frontend/src/features/auth/components/UsersDataGrid.tsx
  • frontend/src/features/auth/components/AuthMethodTab.tsx
  • backend/src/core/auth/oauth.ts
  • docker-compose.prod.yml
  • backend/src/api/routes/auth.oauth.ts
  • .env.example
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{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/types/auth.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/types/auth.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/types/auth.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/types/auth.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/auth.ts
openapi/**/*.{yml,yaml,json}

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

Document all API endpoints with clear OpenAPI documentation

Files:

  • openapi/auth.yaml
🧬 Code graph analysis (1)
backend/src/core/auth/auth.ts (3)
backend/src/types/auth.ts (3)
  • GoogleUserInfo (66-75)
  • GitHubUserInfo (77-83)
  • DiscordUserInfo (92-97)
backend/src/core/auth/oauth.ts (1)
  • OAuthConfigService (26-400)
backend/src/utils/environment.ts (1)
  • getApiBaseUrl (41-43)
🔇 Additional comments (7)
docker-compose.yml (1)

100-101: LGTM! Consistent with existing OAuth pattern.

The Discord environment variables follow the same pattern as Google and GitHub OAuth configuration, with appropriate empty defaults.

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

92-97: LGTM! Well-structured interface consistent with other OAuth providers.

The DiscordUserInfo interface properly mirrors the pattern of GoogleUserInfo and GitHubUserInfo, with appropriate optional fields for email and avatar since Discord may not always provide these even with the email scope requested.

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

22-28: LGTM! Import additions are correct.

The DiscordUserInfo type is properly imported alongside other OAuth provider types.


550-605: LGTM! Discord auth URL generation follows the established pattern.

The implementation correctly:

  • Uses getApiBaseUrl() for consistent base URL handling (addresses past review feedback)
  • Supports both shared-key and custom client flows
  • Uses Discord's proper OAuth2 authorization endpoint
  • Applies appropriate default scopes ('identify email')
  • Handles state parameter for CSRF protection

830-864: LGTM! Token exchange implementation is correct.

The Discord token exchange properly:

  • Uses getApiBaseUrl() to ensure redirect_uri matches the auth URL (addresses past review feedback)
  • Sends the correct Content-Type: application/x-www-form-urlencoded header required by Discord
  • Uses URLSearchParams for proper form encoding
  • Validates the access token is present before returning

866-884: LGTM! User info retrieval is well-implemented.

The method correctly fetches Discord user data and constructs the avatar URL using Discord's CDN pattern when an avatar is present.


886-901: LGTM! User creation handles missing email safely.

The implementation properly provides a fallback email pattern (${discordUserInfo.id}@users.noreply.discord.local) when Discord doesn't return an email, addressing the critical issue from past review feedback. This matches the pattern used for GitHub and prevents database constraint violations.

Comment thread openapi/auth.yaml Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (5)
backend/src/api/routes/auth.oauth.ts (2)

90-121: Consider refactoring OAuth initiation routes to eliminate duplication.

The Discord, Google, and GitHub initiation routes (lines 26-55, 58-88, 90-121) share identical logic with only the provider name and auth service method differing. This violates the DRY principle and increases maintenance burden.

Consider extracting a shared handler:

const createOAuthInitiationHandler = (
  provider: 'google' | 'github' | 'discord',
  generateAuthUrl: (state: string) => Promise<string>
) => {
  return 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,
        redirectUri: redirect_uri as string,
        createdAt: Date.now(),
      };
      const state = jwt.sign(jwtPayload, process.env.JWT_SECRET || 'default_secret', {
        algorithm: 'HS256',
        expiresIn: '1h',
      });

      const authUrl = await generateAuthUrl(state);
      res.json({ authUrl });
    } catch (error) {
      logger.error(`${provider} OAuth error`, { error });
      next(
        new AppError(
          `${provider} OAuth is not properly configured. Please check your oauth configurations.`,
          500,
          ERROR_CODES.AUTH_OAUTH_CONFIG_ERROR
        )
      );
    }
  };
};

// Usage:
router.get('/google', createOAuthInitiationHandler('google', (state) => authService.generateGoogleAuthUrl(state)));
router.get('/github', createOAuthInitiationHandler('github', (state) => authService.generateGitHubAuthUrl(state)));
router.get('/discord', createOAuthInitiationHandler('discord', (state) => authService.generateDiscordAuthUrl(state)));

148-148: Consider centralizing the OAuth provider allowlist.

The provider allowlist ['google', 'github', 'discord'] appears in multiple locations (lines 148 and 233). Centralizing this would improve maintainability when adding new providers.

Define at the top of the file:

const SUPPORTED_OAUTH_PROVIDERS = ['google', 'github', 'discord'] as const;
type SupportedOAuthProvider = typeof SUPPORTED_OAUTH_PROVIDERS[number];

// Usage:
if (!SUPPORTED_OAUTH_PROVIDERS.includes(provider)) {
  // ...
}
backend/src/core/auth/auth.ts (3)

550-605: Discord auth URL generation follows established pattern, but consider reducing duplication.

The generateDiscordAuthUrl method correctly implements the OAuth flow. However, it duplicates significant logic from generateGoogleAuthUrl and generateGitHubAuthUrl (lines 436-492, 497-548).

Consider extracting a generic OAuth URL generator:

private async generateOAuthUrl(
  provider: 'google' | 'github' | 'discord',
  authEndpoint: string,
  defaultScopes: string,
  state?: string
): Promise<string> {
  const oauthConfigService = OAuthConfigService.getInstance();
  const config = await oauthConfigService.getConfigByProvider(provider);

  if (!config) {
    throw new Error(`${provider} OAuth not configured`);
  }

  const selfBaseUrl = getApiBaseUrl();

  if (config?.useSharedKey) {
    if (!state) {
      logger.warn(`Shared ${provider} OAuth called without state parameter`);
      throw new Error(`State parameter is required for shared ${provider} OAuth`);
    }
    const cloudBaseUrl = process.env.CLOUD_API_HOST || 'https://api.insforge.dev';
    const redirectUri = `${selfBaseUrl}/api/auth/oauth/shared/callback/${state}`;
    const authUrl = await fetch(
      `${cloudBaseUrl}/auth/v1/shared/${provider}?redirect_uri=${encodeURIComponent(redirectUri)}`,
      {
        method: 'GET',
        headers: { 'Content-Type': 'application/json' },
      }
    );
    if (!authUrl.ok) {
      throw new Error(`Failed to fetch ${provider} auth URL: ${authUrl.statusText}`);
    }
    const responseData = await authUrl.json() as { auth_url?: string; url?: string };
    return responseData.auth_url || responseData.url || '';
  }

  const authUrl = new URL(authEndpoint);
  authUrl.searchParams.set('client_id', config.clientId ?? '');
  authUrl.searchParams.set('redirect_uri', `${selfBaseUrl}/api/auth/oauth/${provider}/callback`);
  authUrl.searchParams.set('scope', config.scopes ? config.scopes.join(' ') : defaultScopes);
  if (state) authUrl.searchParams.set('state', state);
  
  // Provider-specific parameters
  if (provider === 'google') {
    authUrl.searchParams.set('response_type', 'code');
    authUrl.searchParams.set('access_type', 'offline');
  } else if (provider === 'discord') {
    authUrl.searchParams.set('response_type', 'code');
  }

  return authUrl.toString();
}

830-864: Add error logging for Discord token exchange failures.

While the Discord token exchange implementation is correct, it lacks the detailed error logging present in exchangeCodeToTokenByGoogle (lines 671-678). This makes debugging OAuth failures more difficult.

Add error handling similar to Google's implementation:

   async exchangeDiscordCodeForToken(code: string): Promise<string> {
     const oauthConfigService = OAuthConfigService.getInstance();
     const config = await oauthConfigService.getConfigByProvider('discord');

     if (!config) {
       throw new Error('Discord OAuth not configured');
     }

     const clientSecret = await oauthConfigService.getClientSecretByProvider('discord');
     const selfBaseUrl = getApiBaseUrl();
-    const response = await axios.post(
-      'https://discord.com/api/oauth2/token',
-      new URLSearchParams({
-        client_id: config.clientId ?? '',
-        client_secret: clientSecret ?? '',
-        code,
-        redirect_uri: `${selfBaseUrl}/api/auth/oauth/discord/callback`,
-        grant_type: 'authorization_code',
-      }).toString(),
-      {
-        headers: {
-          'Content-Type': 'application/x-www-form-urlencoded',
-        },
-      }
-    );
+    try {
+      const response = await axios.post(
+        'https://discord.com/api/oauth2/token',
+        new URLSearchParams({
+          client_id: config.clientId ?? '',
+          client_secret: clientSecret ?? '',
+          code,
+          redirect_uri: `${selfBaseUrl}/api/auth/oauth/discord/callback`,
+          grant_type: 'authorization_code',
+        }).toString(),
+        {
+          headers: {
+            'Content-Type': 'application/x-www-form-urlencoded',
+          },
+        }
+      );

-    if (!response.data.access_token) {
-      throw new Error('Failed to get access token from Discord');
-    }
+      if (!response.data.access_token) {
+        throw new Error('Failed to get access token from Discord');
+      }

-    return response.data.access_token;
+      return response.data.access_token;
+    } catch (error) {
+      if (axios.isAxiosError(error) && error.response) {
+        logger.error('Discord token exchange failed', {
+          status: error.response.status,
+          error: error.response.data,
+        });
+        throw new Error(`Discord OAuth error: ${JSON.stringify(error.response.data)}`);
+      }
+      throw error;
+    }
   }

866-884: Add error handling for Discord API failures.

The getDiscordUserInfo method lacks error handling for API failures, unlike getGitHubUserInfo which handles email fetching errors gracefully (lines 783-811).

Add try-catch for better error messaging:

   async getDiscordUserInfo(accessToken: string) {
-    const response = await axios.get('https://discord.com/api/users/@me', {
-      headers: {
-        Authorization: `Bearer ${accessToken}`,
-      },
-    });
+    try {
+      const response = await axios.get('https://discord.com/api/users/@me', {
+        headers: {
+          Authorization: `Bearer ${accessToken}`,
+        },
+      });

-    return {
-      id: response.data.id,
-      username: response.data.username,
-      email: response.data.email,
-      avatar: response.data.avatar
-        ? `https://cdn.discordapp.com/avatars/${response.data.id}/${response.data.avatar}.png`
-        : '',
-    };
+      return {
+        id: response.data.id,
+        username: response.data.username,
+        email: response.data.email,
+        avatar: response.data.avatar
+          ? `https://cdn.discordapp.com/avatars/${response.data.id}/${response.data.avatar}.png`
+          : '',
+      };
+    } catch (error) {
+      if (axios.isAxiosError(error)) {
+        logger.error('Failed to fetch Discord user info', {
+          status: error.response?.status,
+          error: error.response?.data,
+        });
+        throw new Error(`Failed to fetch Discord user info: ${error.message}`);
+      }
+      throw error;
+    }
   }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between be15a57 and 3a946c8.

📒 Files selected for processing (10)
  • .env.example (1 hunks)
  • backend/src/api/routes/auth.oauth.ts (5 hunks)
  • backend/src/core/auth/auth.ts (4 hunks)
  • backend/src/core/auth/oauth.ts (1 hunks)
  • backend/src/types/auth.ts (1 hunks)
  • docker-compose.prod.yml (1 hunks)
  • docker-compose.yml (1 hunks)
  • frontend/src/features/auth/components/AuthMethodTab.tsx (4 hunks)
  • frontend/src/features/auth/components/UsersDataGrid.tsx (1 hunks)
  • openapi/auth.yaml (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
  • docker-compose.prod.yml
  • .env.example
  • frontend/src/features/auth/components/UsersDataGrid.tsx
  • frontend/src/features/auth/components/AuthMethodTab.tsx
  • backend/src/core/auth/oauth.ts
🧰 Additional context used
📓 Path-based instructions (7)
**/*.{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/types/auth.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/api/routes/auth.oauth.ts
  • backend/src/types/auth.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/types/auth.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/api/routes/auth.oauth.ts
  • backend/src/types/auth.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/auth.ts
openapi/**/*.{yml,yaml,json}

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

Document all API endpoints with clear OpenAPI documentation

Files:

  • openapi/auth.yaml
🧬 Code graph analysis (2)
backend/src/api/routes/auth.oauth.ts (1)
backend/src/api/middleware/error.ts (1)
  • AppError (7-17)
backend/src/core/auth/auth.ts (2)
backend/src/types/auth.ts (3)
  • GoogleUserInfo (66-75)
  • GitHubUserInfo (77-83)
  • DiscordUserInfo (92-97)
backend/src/utils/environment.ts (1)
  • getApiBaseUrl (41-43)
🔇 Additional comments (9)
docker-compose.yml (1)

100-101: LGTM! Environment variables follow established pattern.

The Discord OAuth environment variables are correctly configured with the same optional syntax as the existing Google and GitHub providers.

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

92-97: LGTM! Interface matches Discord API structure.

The DiscordUserInfo interface correctly models Discord's user data with appropriate optional fields for email and avatar.

openapi/auth.yaml (2)

422-439: LGTM! Discord OAuth endpoint documentation is consistent.

The Discord OAuth initiation endpoint follows the established pattern for Google and GitHub, with proper parameter definitions and response codes.


483-483: LGTM! Provider enum includes all supported providers.

The provider enum correctly includes discord alongside google and github.

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

187-195: LGTM! Discord payload handling is consistent.

The Discord user payload processing follows the established pattern for Google and GitHub providers.


265-272: LGTM! Discord callback handling mirrors GitHub pattern.

The Discord provider callback correctly exchanges the authorization code for a token, retrieves user information, and creates/links the user account.

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

22-28: LGTM! Import includes Discord type.

The DiscordUserInfo type is correctly imported alongside other OAuth provider types.


285-285: LGTM! Type signature correctly includes DiscordUserInfo.

The identityData parameter now properly accepts Discord user information alongside existing provider types.


889-901: LGTM! Discord user creation with proper email fallback.

The findOrCreateDiscordUser method correctly implements the email fallback pattern using @users.noreply.discord.local, addressing the previous review concern.

@Silversoul-07

Copy link
Copy Markdown
Contributor Author
image

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
frontend/src/features/auth/components/AuthMethodTab.tsx (1)

71-89: Await deletion to catch errors; current try/catch won't catch rejected promise.

deleteConfig is likely async. Without await, errors bypass the catch block at line 86.

Apply this diff:

   const deleteOAuthConfig = async (
-    providerId: 'google' | 'github' | 'discord',
+    providerId: 'google' | 'github' | 'discord',
     providerName: string
   ) => {
     const shouldDelete = await confirm({
       title: `Delete ${providerName} OAuth`,
       description: `Are you sure you want to delete the ${providerName} configuration? This action cannot be undone.`,
       confirmText: 'Delete',
       cancelText: 'Cancel',
       destructive: true,
     });
 
     if (shouldDelete) {
       try {
-        deleteConfig(providerId);
+        await deleteConfig(providerId);
       } catch (error) {
         console.error(`Failed to delete ${providerId} OAuth:`, error);
       }
     }
   };
🧹 Nitpick comments (4)
backend/src/api/routes/auth.oauth.ts (2)

90-121: LGTM! Discord OAuth initialization follows the established pattern.

The Discord route correctly validates redirect_uri, creates a JWT state token, and generates the auth URL via authService.generateDiscordAuthUrl. Error handling is consistent with Google and GitHub routes.

Consider consolidating the three nearly-identical OAuth initialization routes (Google, GitHub, Discord) into a single parameterized handler to reduce duplication:

// Example refactor to reduce duplication
const createOAuthInitHandler = (provider: 'google' | 'github' | 'discord') => {
  return 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,
        redirectUri: redirect_uri as string,
        createdAt: Date.now(),
      };
      const state = jwt.sign(jwtPayload, process.env.JWT_SECRET || 'default_secret', {
        algorithm: 'HS256',
        expiresIn: '1h',
      });

      const authUrl = await authService[`generate${provider.charAt(0).toUpperCase() + provider.slice(1)}AuthUrl`](state);
      res.json({ authUrl });
    } catch (error) {
      logger.error(`${provider} OAuth error`, { error });
      next(
        new AppError(
          `${provider} OAuth is not properly configured. Please check your oauth configurations.`,
          500,
          ERROR_CODES.AUTH_OAUTH_CONFIG_ERROR
        )
      );
    }
  };
};

router.get('/google', createOAuthInitHandler('google'));
router.get('/github', createOAuthInitHandler('github'));
router.get('/discord', createOAuthInitHandler('discord'));

187-196: LGTM! Discord payload handling is consistent.

The Discord user info mapping correctly extracts providerId, username, email, and avatar from the payload and calls findOrCreateDiscordUser.

The shared callback's if-else chain for provider handling could be refactored into a provider-to-handler map to improve maintainability:

// Example refactor
const providerHandlers = {
  google: async (payloadData: any) => {
    const googleUserInfo = {
      sub: payloadData.providerId,
      email: payloadData.email,
      name: payloadData.name || '',
      userName: payloadData.userName || '',
      picture: payloadData.avatar || '',
    };
    return authService.findOrCreateGoogleUser(googleUserInfo);
  },
  github: async (payloadData: any) => {
    const githubUserInfo = {
      id: payloadData.providerId,
      login: payloadData.login || '',
      email: payloadData.email,
      name: payloadData.name || '',
      avatar_url: payloadData.avatar || '',
    };
    return authService.findOrCreateGitHubUser(githubUserInfo);
  },
  discord: async (payloadData: any) => {
    const discordUserInfo = {
      id: payloadData.providerId,
      username: payloadData.username || '',
      email: payloadData.email,
      avatar: payloadData.avatar || '',
    };
    return authService.findOrCreateDiscordUser(discordUserInfo);
  },
};

// Then use: result = await providerHandlers[provider](payloadData);
backend/src/core/auth/auth.ts (2)

550-605: LGTM! Discord auth URL generation is consistent with other providers.

The implementation correctly uses getApiBaseUrl() (line 561), handles shared keys (lines 563-589), and builds the Discord authorization URL with appropriate scopes (line 599). The structure matches Google and GitHub flows.

The three generateXAuthUrl methods (Google, GitHub, Discord) share substantial logic. Consider extracting a common helper to reduce duplication:

// Example helper
private async generateOAuthUrl(
  provider: 'google' | 'github' | 'discord',
  state: string | undefined,
  config: {
    authEndpoint: string;
    defaultScopes: string;
    responseType?: string;
    additionalParams?: Record<string, string>;
  }
) {
  const oauthConfigService = OAuthConfigService.getInstance();
  const providerConfig = await oauthConfigService.getConfigByProvider(provider);
  
  if (!providerConfig) {
    throw new Error(`${provider} OAuth not configured`);
  }

  const selfBaseUrl = getApiBaseUrl();

  if (providerConfig.useSharedKey) {
    // Shared key logic...
  }

  const authUrl = new URL(config.authEndpoint);
  authUrl.searchParams.set('client_id', providerConfig.clientId ?? '');
  authUrl.searchParams.set('redirect_uri', `${selfBaseUrl}/api/auth/oauth/${provider}/callback`);
  // ... common parameter building
  
  return authUrl.toString();
}

550-901: Consider consolidating OAuth provider implementations.

The Discord, Google, and GitHub OAuth flows share substantial structural similarity. Each provider has four nearly-identical methods:

  • generate{Provider}AuthUrl
  • exchange{Provider}CodeForToken
  • get{Provider}UserInfo
  • findOrCreate{Provider}User

While the current implementation is correct, the duplication increases maintenance burden.

Consider introducing a provider configuration pattern:

// Define provider-specific config
interface OAuthProviderConfig {
  name: string;
  authEndpoint: string;
  tokenEndpoint: string;
  userInfoEndpoint: string;
  defaultScopes: string;
  tokenResponseType: 'json' | 'urlencoded';
  userInfoMapper: (data: any) => { id: string; username: string; email: string; avatar: string };
}

// Then implement generic methods that use the config
private async exchangeCodeForToken(provider: string, code: string, config: OAuthProviderConfig): Promise<string> {
  // Generic implementation using config
}

This would reduce the ~500 lines of OAuth code to a more maintainable structure while preserving the provider-specific logic where needed.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3a946c8 and e78524d.

📒 Files selected for processing (11)
  • .env.example (1 hunks)
  • backend/src/api/routes/auth.oauth.ts (5 hunks)
  • backend/src/core/auth/auth.ts (5 hunks)
  • backend/src/core/auth/oauth.ts (1 hunks)
  • backend/src/types/auth.ts (1 hunks)
  • docker-compose.prod.yml (1 hunks)
  • docker-compose.yml (1 hunks)
  • frontend/src/features/auth/components/AddOAuthDialog.tsx (3 hunks)
  • frontend/src/features/auth/components/AuthMethodTab.tsx (5 hunks)
  • frontend/src/features/auth/components/UsersDataGrid.tsx (1 hunks)
  • openapi/auth.yaml (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (6)
  • frontend/src/features/auth/components/UsersDataGrid.tsx
  • docker-compose.prod.yml
  • docker-compose.yml
  • backend/src/core/auth/oauth.ts
  • backend/src/types/auth.ts
  • openapi/auth.yaml
🧰 Additional context used
📓 Path-based instructions (11)
**/.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/AddOAuthDialog.tsx
  • backend/src/api/routes/auth.oauth.ts
  • frontend/src/features/auth/components/AuthMethodTab.tsx
  • 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/AddOAuthDialog.tsx
  • frontend/src/features/auth/components/AuthMethodTab.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/features/auth/components/AuthMethodTab.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/features/auth/components/AuthMethodTab.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/AddOAuthDialog.tsx
  • backend/src/api/routes/auth.oauth.ts
  • frontend/src/features/auth/components/AuthMethodTab.tsx
  • backend/src/core/auth/auth.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/AddOAuthDialog.tsx
  • frontend/src/features/auth/components/AuthMethodTab.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/api/routes/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
**/[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/auth.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
🧠 Learnings (1)
📚 Learning: 2025-10-15T18:18:47.505Z
Learnt from: CR
PR: InsForge/InsForge#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.505Z
Learning: Applies to frontend/src/**/*.tsx : Use a consistent icon set from lucide-react

Applied to files:

  • frontend/src/features/auth/components/AuthMethodTab.tsx
🧬 Code graph analysis (2)
backend/src/api/routes/auth.oauth.ts (1)
backend/src/api/middleware/error.ts (1)
  • AppError (7-17)
backend/src/core/auth/auth.ts (3)
backend/src/types/auth.ts (1)
  • DiscordUserInfo (92-97)
backend/src/core/auth/oauth.ts (1)
  • OAuthConfigService (26-400)
backend/src/utils/environment.ts (1)
  • getApiBaseUrl (41-43)
🔇 Additional comments (8)
.env.example (1)

55-57: Environment variables properly documented and consistent.

The Discord OAuth configuration follows the established pattern for OAuth providers (Google, GitHub) with clear naming (PROVIDER_CLIENT_ID, PROVIDER_CLIENT_SECRET), helpful documentation linking to the Discord Developer portal, and logical placement within the OAuth section.

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

35-41: LGTM! Discord provider integrated consistently.

The Discord provider follows the same structure as Google and GitHub, with appropriate icon, description, and setup URL.


105-116: LGTM! Type extensions are consistent.

The enabledProviders and allProvidersEnabled logic correctly includes Discord alongside Google and GitHub.

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

17-18: LGTM! Type extensions are consistent.

All Discord type additions follow the established pattern for Google and GitHub. The prop types, state, and handler function correctly include 'discord' in the union types.

Also applies to: 28-28, 42-42

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

265-273: LGTM! Discord OAuth callback implementation is correct.

The Discord callback properly validates the authorization code, exchanges it for an access token, fetches user info, and creates or finds the user. The flow matches the GitHub implementation pattern.

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

830-864: LGTM! Discord token exchange is implemented correctly.

The method uses getApiBaseUrl() for consistency (line 842), properly constructs the form-encoded request (lines 843-851), and handles the access token response (lines 859-863). The implementation follows the Discord OAuth2 specification.


869-884: LGTM! Discord user info retrieval is correct.

The method fetches user data from Discord's API (line 870) and properly constructs the avatar URL when available (lines 880-882). The fallback to empty string for missing avatars is appropriate.


889-901: LGTM! Email fallback prevents empty email issues.

Line 891 correctly provides a deterministic, non-empty fallback email (${discordUserInfo.id}@users.noreply.discord.local) when Discord doesn't return an email, preventing database constraint violations. This matches the pattern used for GitHub users.

@Silversoul-07

Silversoul-07 commented Oct 17, 2025 •

Copy link
Copy Markdown
Contributor Author

@Fermionic-Lyu I have resolved all review comments (expects 1 which I think is out of scope of this pr). Also Fixed the label inconsistency issue and linting error. Can you review the code and merge it. Thanks

I also apologise for so many commit amends. I wanted to keep commit history clean (rebased to latest commit 7h ago). I think contributing.md doesn't mention all the tests I have to check it which caused conflict with GitHub actions which was only resolved after running GitHub actions locally.

@Fermionic-Lyu

Fermionic-Lyu commented Oct 17, 2025 •

Copy link
Copy Markdown
Member

@Fermionic-Lyu I have resolved all review comments (expects 1 which I think is out of scope of this pr). Also Fixed the label inconsistency issue and linting error. Can you review the code and merge it. Thanks

I also apologise for so many commit amends. I wanted to keep commit history clean (rebased to latest commit 7h ago). I think contributing.md doesn't mention all the tests I have to check it which caused conflict with GitHub actions which was only resolved after running GitHub actions locally.

@Silversoul-07 No worries! I have built your PR into a new image and tested internally. It works well!

Since we have many OAuth PRs getting queued at the moment, merging causes conflicts. Can you kindly resolve them? Also another quick comment here: I think for Discord OAuth, they have both username and global_name. I am not 100% sure what's their reason behind this, but according to their doc, global_name is the display name. So I think global_name matches our name field more (a name that user can change freely & show public). It can be undefined though, so use fallback to username if global_name is not set.

@Silversoul-07

Silversoul-07 commented Oct 17, 2025 •

Copy link
Copy Markdown
Contributor Author

Thanks for the review. I've added global_name and fallback to username and also resolved all git conflicts. Let me know if i have to do anything.

image

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
frontend/src/features/auth/components/AuthMethodTab.tsx (1)

92-93: Missing await on deleteConfig still unresolved.

As flagged in a previous review, deleteConfig(providerId) is not awaited, so any rejection will escape the try/catch block.

Apply this diff:

     if (shouldDelete) {
       try {
-        deleteConfig(providerId);
+        await deleteConfig(providerId);
       } catch (error) {
🧹 Nitpick comments (1)
backend/src/core/auth/auth.ts (1)

564-581: Consider using axios for consistency with other OAuth flows.

Discord's shared-key flow uses fetch (lines 564–581), while Google (lines 465–473) and GitHub (lines 517–525) use axios.get. Unifying on a single HTTP client reduces cognitive load and ensures consistent error handling.

Apply this diff to align with Google/GitHub:

-      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 };
-      return responseData.auth_url || responseData.url || '';
+      const response = await axios.get(
+        `${cloudBaseUrl}/auth/v1/shared/discord?redirect_uri=${encodeURIComponent(redirectUri)}`,
+        {
+          headers: {
+            'Content-Type': 'application/json',
+          },
+        }
+      );
+      return response.data.auth_url || response.data.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 e78524d and 88e5bb0.

📒 Files selected for processing (11)
  • .env.example (1 hunks)
  • backend/src/api/routes/auth.oauth.ts (5 hunks)
  • backend/src/core/auth/auth.ts (5 hunks)
  • backend/src/core/auth/oauth.ts (1 hunks)
  • backend/src/types/auth.ts (1 hunks)
  • docker-compose.prod.yml (1 hunks)
  • docker-compose.yml (1 hunks)
  • frontend/src/features/auth/components/AddOAuthDialog.tsx (3 hunks)
  • frontend/src/features/auth/components/AuthMethodTab.tsx (6 hunks)
  • frontend/src/features/auth/components/UsersDataGrid.tsx (1 hunks)
  • openapi/auth.yaml (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (7)
  • backend/src/core/auth/oauth.ts
  • .env.example
  • openapi/auth.yaml
  • frontend/src/features/auth/components/AddOAuthDialog.tsx
  • frontend/src/features/auth/components/UsersDataGrid.tsx
  • backend/src/types/auth.ts
  • docker-compose.yml
🧰 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:

  • frontend/src/features/auth/components/AuthMethodTab.tsx
  • backend/src/core/auth/auth.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/AuthMethodTab.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/AuthMethodTab.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
**/*.{tsx,ts}

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

React components and TypeScript types/interfaces must use PascalCase

Files:

  • frontend/src/features/auth/components/AuthMethodTab.tsx
  • backend/src/core/auth/auth.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/AuthMethodTab.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/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
**/[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/auth.ts
  • 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
🧠 Learnings (1)
📚 Learning: 2025-10-15T18:18:47.505Z
Learnt from: CR
PR: InsForge/InsForge#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.505Z
Learning: Applies to frontend/src/**/*.tsx : Use a consistent icon set from lucide-react

Applied to files:

  • frontend/src/features/auth/components/AuthMethodTab.tsx
🧬 Code graph analysis (2)
backend/src/core/auth/auth.ts (3)
backend/src/types/auth.ts (1)
  • DiscordUserInfo (92-97)
backend/src/core/auth/oauth.ts (1)
  • OAuthConfigService (26-402)
backend/src/utils/environment.ts (1)
  • getApiBaseUrl (41-43)
backend/src/api/routes/auth.oauth.ts (1)
backend/src/api/middleware/error.ts (1)
  • AppError (7-17)
🔇 Additional comments (11)
docker-compose.prod.yml (1)

97-98: LGTM! Discord OAuth environment variables added consistently.

The Discord OAuth credentials follow the same pattern as Google and GitHub, using empty-string defaults with the :- fallback operator.

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

6-6: LGTM! Discord provider integrated consistently.

The Discord logo import, provider entry with metadata, and type union extension all follow the established pattern for Google, GitHub, and LinkedIn.

Also applies to: 36-42, 53-53


80-80: Discord wiring complete and consistent.

The deleteOAuthConfig, enabledProviders, and handleConfirmSelected updates correctly extend the Discord provider throughout the component's logic.

Also applies to: 117-117, 127-127

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

27-27: LGTM! DiscordUserInfo integrated into OAuth types.

The DiscordUserInfo import and union type extensions in findOrCreateThirdPartyUser and createThirdPartyUser align with the existing pattern for Google, GitHub, and LinkedIn.

Also applies to: 286-291, 370-375


543-598: Discord auth URL generation looks good; previous base URL issue resolved.

The method correctly uses getApiBaseUrl() (line 554) and follows the established OAuth flow pattern. Previous concerns about hardcoded base URLs have been addressed.


823-857: Discord token exchange correct; previous base URL issue resolved.

The method correctly uses getApiBaseUrl() (line 835) to construct redirect_uri, ensuring consistency with the authorization URL. Previous concerns have been addressed.


859-877: Discord user info retrieval looks good; global_name preference is correct.

Line 871 correctly prefers global_name over username (as suggested by the maintainer), and the avatar URL construction handles the optional avatar field appropriately.


879-894: Discord user creation correct; previous email fallback issue resolved.

Line 884 now provides a safe, non-empty email fallback (${discordUserInfo.id}@users.noreply.discord.local) when Discord does not return an email, addressing the previous critical issue.

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

90-121: LGTM! Discord OAuth initialization route matches established pattern.

The new /discord route follows the same structure as Google, GitHub, and LinkedIn: validates redirect_uri, builds a JWT state token, generates the auth URL, and handles errors consistently.


181-181: Discord integrated into shared callback correctly.

The provider allowlist now includes 'discord' (line 181), and the Discord payload handling (lines 220–228) extracts user info and calls findOrCreateDiscordUser, mirroring the existing Google/GitHub flows.

Also applies to: 220-228


275-275: Discord provider callback follows existing OAuth pattern.

The provider allowlist includes 'discord' (line 275), and the Discord case (lines 307–314) exchanges the code for a token, retrieves user info, and creates/finds the user—consistent with GitHub's flow.

Also applies to: 307-314

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

This PR lgtm!

@tonychang04 tonychang04 linked an issue Oct 18, 2025 that may be closed by this pull request
@tonychang04

Copy link
Copy Markdown
Member

can you helo resolve the conflict @Silversoul-07 should be a small one, thanks!

@Silversoul-07

Copy link
Copy Markdown
Contributor Author

@tonychang04 Ive resolved conflict. can you check and merge. Thanks

@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

Caution

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

⚠️ Outside diff range comments (3)
backend/src/api/routes/auth.oauth.ts (3)

25-41: Validate redirect_uri against an allowlist to prevent open redirects and token leakage.

redirect_uri is accepted from the client and later used for redirects; without origin validation this is an open redirect vector. Add an allowlist (e.g., API base URL and known front-end origin) and reject others.

Apply a scoped fix:

+import { getApiBaseUrl } from '@/utils/environment.js';
+
+function assertAllowedRedirect(redirectUriRaw: unknown) {
+  if (typeof redirectUriRaw !== 'string') {
+    throw new AppError('Redirect URI is required', 400, ERROR_CODES.INVALID_INPUT);
+  }
+  let target: URL;
+  try {
+    target = new URL(redirectUriRaw);
+  } catch {
+    throw new AppError('Invalid redirect URI', 400, ERROR_CODES.INVALID_INPUT);
+  }
+  const allowedOrigins = [
+    getApiBaseUrl(),
+    process.env.VITE_API_BASE_URL,
+    process.env.API_BASE_URL,
+  ]
+    .filter(Boolean)
+    .map((u) => new URL(u as string).origin);
+  if (!allowedOrigins.includes(target.origin)) {
+    throw new AppError('Redirect origin not allowed', 400, ERROR_CODES.INVALID_INPUT);
+  }
+  return target.toString();
+}
@@
-    const { redirect_uri } = req.query;
-    if (!redirect_uri) {
-      throw new AppError('Redirect URI is required', 400, ERROR_CODES.INVALID_INPUT);
-    }
+    const redirect_uri = assertAllowedRedirect(req.query.redirect_uri);
@@
-    const { redirect_uri } = req.query;
-    if (!redirect_uri) {
-      throw new AppError('Redirect URI is required', 400, ERROR_CODES.INVALID_INPUT);
-    }
+    const redirect_uri = assertAllowedRedirect(req.query.redirect_uri);
@@
-    const { redirect_uri } = req.query;
-    if (!redirect_uri) {
-      throw new AppError('Redirect URI is required', 400, ERROR_CODES.INVALID_INPUT);
-    }
+    const redirect_uri = assertAllowedRedirect(req.query.redirect_uri);
@@
-    const { redirect_uri } = req.query;
-    if (!redirect_uri) {
-      throw new AppError('Redirect URI is required', 400, ERROR_CODES.INVALID_INPUT);
-    }
+    const redirect_uri = assertAllowedRedirect(req.query.redirect_uri);

Also applies to: 57-74, 90-107, 123-140


38-41: Do not fall back to 'default_secret' for JWT state; require JWT_SECRET.

Using a known default makes state forgeable if env is misconfigured.

Apply this change:

-    const state = jwt.sign(jwtPayload, process.env.JWT_SECRET || 'default_secret', {
+    if (!process.env.JWT_SECRET) {
+      throw new AppError('JWT secret not configured', 500, ERROR_CODES.AUTH_OAUTH_CONFIG_ERROR);
+    }
+    const state = jwt.sign(jwtPayload, process.env.JWT_SECRET, {
       algorithm: 'HS256',
       expiresIn: '1h',
     });

And for verification:

-      const decodedState = jwt.verify(state, process.env.JWT_SECRET || 'default_secret') as {
+      if (!process.env.JWT_SECRET) {
+        throw new AppError('JWT secret not configured', 500, ERROR_CODES.AUTH_OAUTH_CONFIG_ERROR);
+      }
+      const decodedState = jwt.verify(state, process.env.JWT_SECRET) as {

Also applies to: 70-73, 103-106, 136-139, 170-179


335-350: Avoid placing access_token in query params; prefer fragment or secure cookie.

Tokens in query leak via logs, referrers, and browser history.

Consider:

  • Use URL fragment: redirect to ${redirectUri}#access_token=...&user_id=...
  • Or set an HttpOnly, Secure, SameSite cookie and redirect without token in URL.
    If keeping query for now, add a follow-up to immediately strip it via history.replaceState on the client.

Also applies to: 360-379

♻️ Duplicate comments (1)
frontend/src/features/auth/components/AuthMethodTab.tsx (1)

79-82: Await deletion to catch errors; current try/catch won’t catch rejected promise.

Same concern was flagged earlier; please await.

Apply:

-  const deleteOAuthConfig = async (
+  const deleteOAuthConfig = async (
     providerId: 'google' | 'github' | 'linkedin' | 'discord',
     providerName: string
   ) => {
@@
-    if (shouldDelete) {
-      try {
-        deleteConfig(providerId);
-      } catch (error) {
+    if (shouldDelete) {
+      try {
+        await deleteConfig(providerId);
+      } catch (error) {
         console.error(`Failed to delete ${providerId} OAuth:`, error);
       }
     }
   };
🧹 Nitpick comments (6)
.env.example (1)

55-58: Document required Discord redirect URI and scopes near the new vars.

Helps reduce setup errors.

Apply this doc tweak:

 # Discord OAuth - Get credentials from https://discord.com/developers/applications
 DISCORD_CLIENT_ID=
 DISCORD_CLIENT_SECRET=
+#
+# Required redirect URI (add in Discord app settings):
+#   ${API_BASE_URL}/api/auth/oauth/discord/callback
+# Default scopes used if none provided: identify, email
backend/src/api/routes/auth.oauth.ts (1)

360-371: Inconsistent state decoding on error path.

Success path decodes JWT; error path assumes base64 JSON. Unify to verify JWT everywhere.

Apply this tweak:

-    const redirectUri = state
-      ? (() => {
-          try {
-            const stateData = JSON.parse(Buffer.from(state as string, 'base64').toString());
-            return stateData.redirectUri || '/';
-          } catch {
-            return '/';
-          }
-        })()
-      : '/';
+    const redirectUri = (() => {
+      try {
+        if (!state || !process.env.JWT_SECRET) return '/';
+        const decoded = jwt.verify(state as string, process.env.JWT_SECRET) as { redirectUri?: string };
+        return decoded.redirectUri || '/';
+      } catch {
+        return '/';
+      }
+    })();
frontend/src/features/auth/components/AuthMethodTab.tsx (1)

52-58: Deduplicate provider ID unions via a shared type.

Reduces maintenance risk as providers evolve.

Minimal change:

 export interface OAuthProviderInfo {
-  id: 'google' | 'github' | 'discord' | 'linkedin';
+  id: OAuthProviderId;
   name: string;
   icon: ReactElement;
   description: string;
   setupUrl: string;
 }
+
+export type OAuthProviderId = 'google' | 'github' | 'discord' | 'linkedin';

Then update references in this file and in AddOAuthDialog to use OAuthProviderId.

Also applies to: 79-82, 127-138

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

17-19: Props/state extended for Discord: OK. Consider reusing a shared OAuthProviderId type.

Keeps unions consistent with AuthMethodTab.

If you export OAuthProviderId from AuthMethodTab:

-import { OAuthProviderInfo } from './AuthMethodTab';
+import { OAuthProviderInfo, OAuthProviderId } from './AuthMethodTab';
@@
-  onConfirm: (selectedId: 'google' | 'github' | 'discord' | 'linkedin') => void;
-  enabledProviders: Record<'google' | 'github' | 'discord' | 'linkedin', boolean>;
+  onConfirm: (selectedId: OAuthProviderId) => void;
+  enabledProviders: Record<OAuthProviderId, boolean>;
@@
-  const [selectedId, setSelectedId] = useState<'google' | 'github' | 'discord' | 'linkedin' | null>(
+  const [selectedId, setSelectedId] = useState<OAuthProviderId | null>(
@@
-  const selectProvider = (id: 'google' | 'github' | 'discord' | 'linkedin') => {
+  const selectProvider = (id: OAuthProviderId) => {

Also applies to: 28-30, 44-46

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

543-598: Discord auth URL: solid. Minor consistency nit.

You used fetch here while axios is used elsewhere; consider standardizing on one client.


907-916: Unify base URL resolution for LinkedIn with getApiBaseUrl().

Avoids environment drift with other providers.

Apply:

-    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();

Also applies to: 977-986

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a2abbe1 and 677caf9.

📒 Files selected for processing (11)
  • .env.example (1 hunks)
  • backend/src/api/routes/auth.oauth.ts (5 hunks)
  • backend/src/core/auth/auth.ts (5 hunks)
  • backend/src/core/auth/oauth.ts (1 hunks)
  • backend/src/types/auth.ts (1 hunks)
  • docker-compose.prod.yml (1 hunks)
  • docker-compose.yml (1 hunks)
  • frontend/src/features/auth/components/AddOAuthDialog.tsx (3 hunks)
  • frontend/src/features/auth/components/AuthMethodTab.tsx (6 hunks)
  • frontend/src/features/auth/components/UsersDataGrid.tsx (1 hunks)
  • openapi/auth.yaml (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • backend/src/core/auth/oauth.ts
  • backend/src/types/auth.ts
  • openapi/auth.yaml
  • docker-compose.yml
🧰 Additional context used
📓 Path-based instructions (11)
**/.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:

  • backend/src/api/routes/auth.oauth.ts
  • frontend/src/features/auth/components/AuthMethodTab.tsx
  • backend/src/core/auth/auth.ts
  • frontend/src/features/auth/components/UsersDataGrid.tsx
  • frontend/src/features/auth/components/AddOAuthDialog.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/api/routes/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
  • frontend/src/features/auth/components/AuthMethodTab.tsx
  • backend/src/core/auth/auth.ts
  • frontend/src/features/auth/components/UsersDataGrid.tsx
  • frontend/src/features/auth/components/AddOAuthDialog.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/api/routes/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/features/auth/components/AuthMethodTab.tsx
  • frontend/src/features/auth/components/UsersDataGrid.tsx
  • frontend/src/features/auth/components/AddOAuthDialog.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/AuthMethodTab.tsx
  • frontend/src/features/auth/components/UsersDataGrid.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/UsersDataGrid.tsx
  • frontend/src/features/auth/components/AddOAuthDialog.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/AuthMethodTab.tsx
  • frontend/src/features/auth/components/UsersDataGrid.tsx
  • frontend/src/features/auth/components/AddOAuthDialog.tsx
backend/src/{controllers,core}/**/*.ts

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

Implement proper database transaction handling

Files:

  • backend/src/core/auth/auth.ts
🧠 Learnings (1)
📚 Learning: 2025-10-15T18:18:47.505Z
Learnt from: CR
PR: InsForge/InsForge#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.505Z
Learning: Applies to frontend/src/**/*.tsx : Use a consistent icon set from lucide-react

Applied to files:

  • frontend/src/features/auth/components/AuthMethodTab.tsx
🧬 Code graph analysis (2)
backend/src/api/routes/auth.oauth.ts (1)
backend/src/api/middleware/error.ts (1)
  • AppError (7-17)
backend/src/core/auth/auth.ts (4)
backend/src/types/auth.ts (1)
  • DiscordUserInfo (92-97)
backend/src/core/auth/oauth.ts (1)
  • OAuthConfigService (26-402)
backend/src/utils/environment.ts (1)
  • getApiBaseUrl (41-43)
shared-schemas/src/auth-api.schema.ts (1)
  • CreateSessionResponse (185-185)
🔇 Additional comments (5)
frontend/src/features/auth/components/UsersDataGrid.tsx (1)

36-41: Discord provider mapping looks good.

Label and styling are consistent with existing providers.

docker-compose.prod.yml (1)

97-98: LGTM: Discord secrets wired into the service env.

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

36-42: Discord provider entry: OK.

Consistent with the others.

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

823-858: Discord token exchange flow: solid.

Redirect URI uses getApiBaseUrl(), matching auth URL.


879-894: Good: deterministic noreply email fallback for Discord.

Prevents empty-email user creation.

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]: Support Discord Oauth

3 participants