Skip to content

refactor oauth providers - #590

Merged
Fermionic-Lyu merged 5 commits into
InsForge:lyu-transitionfrom
sunny775:refactor/oauth-providers
Nov 15, 2025
Merged

Fermionic-Lyu merged 5 commits into
InsForge:lyu-transitionfrom
sunny775:refactor/oauth-providers

Conversation

@sunny775

@sunny775 sunny775 commented Nov 15, 2025 •

Copy link
Copy Markdown
Contributor

Summary

Closes #551

Refactor OAuth providers into dedicated service files.

Completes the OAuth service refactoring by extracting each provider (GitHub, Discord, LinkedIn, Facebook, Microsoft) into dedicated service files, following the pattern established in the Google OAuth refactoring ( #550 )

What Changed

  • Created 5 new provider service files:
    • oauth.github.ts
    • oauth.discord.ts
    • oauth.linkedin.ts
    • oauth.facebook.ts
    • oauth.microsoft.ts
  • Refactored auth.ts to delegate to provider services (-601 lines)
  • Each provider now follows a consistent singleton pattern with:
    • generateOAuthUrl()
    • exchangeCodeToToken()
    • getUserInfo()/verifyToken()
    • handleCallback()

Files Changed

backend/src/core/auth/auth.ts 
backend/src/core/auth/oauth.discord.ts 
backend/src/core/auth/oauth.facebook.ts
backend/src/core/auth/oauth.github.ts
backend/src/core/auth/oauth.linkedin.ts 
backend/src/core/auth/oauth.microsoft.ts

Summary by CodeRabbit

  • Refactor
    • Moved provider-specific OAuth logic into dedicated services and centralized provider dispatching to simplify authentication flows.
  • New Features
    • Added a unified public OAuth routing API to generate provider URLs and handle provider callbacks, standardizing external sign-in behavior.
  • Improvements
    • Strengthened reliability and error handling across GitHub, Discord, LinkedIn, Facebook, and Microsoft sign-in flows.

@coderabbitai

coderabbitai Bot commented Nov 15, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Refactors backend OAuth by extracting provider-specific flows into singleton services for GitHub, Discord, LinkedIn, Facebook, and Microsoft. AuthService now exposes provider-agnostic generateOAuthUrl(provider, state?) and handleOAuthCallback(provider, payload) methods that delegate to those services; inline token/user-info logic and LinkedIn state tracking removed.

Changes

Cohort / File(s) Summary
AuthService refactor
backend/src/core/auth/auth.ts
Removed per-provider inline OAuth helpers and LinkedIn state tracking; added centralized generateOAuthUrl(provider, state?) and handleOAuthCallback(provider, payload) that dispatch to provider service singletons.
GitHub OAuth service
backend/src/core/auth/oauth.github.ts
Added GitHubOAuthService singleton: generate OAuth URL (shared or standard), exchange code→token, fetch user info (uses emails fallback), and handleCallback delegating to find-or-create user.
Discord OAuth service
backend/src/core/auth/oauth.discord.ts
Added DiscordOAuthService singleton: generate OAuth URL (shared or standard), exchange code→token, fetch Discord user info (id, username, email, avatar), and handleCallback delegating to find-or-create user.
LinkedIn OAuth service
backend/src/core/auth/oauth.linkedin.ts
Added LinkedInOAuthService singleton: generate OAuth URL (shared or standard), exchange code→tokens with in-memory deduplication and 60s token cache, verify id_token via JWKS/JOSE, and handleCallback.
Facebook OAuth service
backend/src/core/auth/oauth.facebook.ts
Added FacebookOAuthService singleton: generate OAuth URL (shared or standard), exchange code→token via Graph API, fetch user info (id, email, names, picture), and handleCallback.
Microsoft OAuth service
backend/src/core/auth/oauth.microsoft.ts
Added MicrosoftOAuthService singleton: generate OAuth URL, exchange code→token, fetch Microsoft Graph user info, and handleCallback.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

  • Areas needing extra attention:
    • Dispatch correctness in AuthService.generateOAuthUrl() and handleOAuthCallback() for all provider enum values.
    • LinkedIn deduplication (processedCodes) and tokenCache expiry/race conditions.
    • Shared-key vs standard flow branching and required state handling.
    • Provider-specific token exchange / user-info parsing and error paths (GitHub email fallback, Discord avatar/email mapping, Facebook Graph fields, Microsoft Graph mapping).
    • Config retrieval and failures from OAuthConfigService (missing client secrets, redirect URIs).

Possibly related PRs

Suggested reviewers

  • Fermionic-Lyu
  • tonychang04

Poem

🐇 I hopped through code, split one file in five,

Each provider found a burrow where tokens can thrive.
From GitHub to Microsoft, neat tunnels I made,
Callbacks tucked in, no inline mess to wade.
A carrot for reviewers — hop in, don’t be afraid!

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'refactor oauth providers' is concise and clearly summarizes the main change: extracting OAuth providers into dedicated service files following a consistent pattern.
Linked Issues check ✅ Passed The pull request fully implements the objective from issue #551 by creating separate service files for each OAuth provider (GitHub, Discord, LinkedIn, Facebook, Microsoft) and refactoring auth.ts to delegate to these services.
Out of Scope Changes check ✅ Passed All changes are directly scoped to the OAuth refactoring objective: five new provider service files added and auth.ts refactored to use them; no unrelated modifications present.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@sunny775

Copy link
Copy Markdown
Contributor Author

@Fermionic-Lyu kindly review

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4

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

86-93: Consider retry-friendly deduplication.

The current deduplication logic prevents concurrent processing, but if the first request fails after adding the code to processedCodes (line 103), concurrent requests will throw "currently being processed" even though they should be allowed to retry. While this is defensive, it may reject legitimate retry attempts during transient failures.

Consider using a Promise-based approach where concurrent requests await the same token exchange operation rather than rejecting them:

private pendingExchanges: Map<string, Promise<{ access_token: string; id_token: string }>>;

// In exchangeCodeToToken:
const pending = this.pendingExchanges.get(code);
if (pending) {
  return pending;
}

const exchangePromise = this._doExchange(code);
this.pendingExchanges.set(code, exchangePromise);

try {
  const result = await exchangePromise;
  return result;
} finally {
  this.pendingExchanges.delete(code);
}
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2f7e703 and b4e1c16.

📒 Files selected for processing (6)
  • backend/src/core/auth/auth.ts (10 hunks)
  • backend/src/core/auth/oauth.discord.ts (1 hunks)
  • backend/src/core/auth/oauth.facebook.ts (1 hunks)
  • backend/src/core/auth/oauth.github.ts (1 hunks)
  • backend/src/core/auth/oauth.linkedin.ts (1 hunks)
  • backend/src/core/auth/oauth.microsoft.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (6)
backend/src/core/auth/oauth.github.ts (5)
backend/src/app.config.ts (1)
  • config (30-54)
backend/src/utils/environment.ts (1)
  • getApiBaseUrl (39-41)
backend/src/utils/logger.ts (1)
  • logger (6-29)
backend/src/types/auth.ts (2)
  • GitHubUserInfo (77-83)
  • GitHubEmailInfo (85-90)
shared-schemas/src/auth-api.schema.ts (1)
  • CreateSessionResponse (324-324)
backend/src/core/auth/oauth.microsoft.ts (3)
backend/src/utils/environment.ts (1)
  • getApiBaseUrl (39-41)
backend/src/types/auth.ts (1)
  • MicrosoftUserInfo (92-97)
shared-schemas/src/auth-api.schema.ts (1)
  • CreateSessionResponse (324-324)
backend/src/core/auth/oauth.facebook.ts (5)
backend/src/app.config.ts (1)
  • config (30-54)
backend/src/utils/environment.ts (1)
  • getApiBaseUrl (39-41)
backend/src/utils/logger.ts (1)
  • logger (6-29)
backend/src/types/auth.ts (1)
  • FacebookUserInfo (116-127)
shared-schemas/src/auth-api.schema.ts (1)
  • CreateSessionResponse (324-324)
backend/src/core/auth/oauth.linkedin.ts (5)
backend/src/app.config.ts (1)
  • config (30-54)
backend/src/utils/environment.ts (1)
  • getApiBaseUrl (39-41)
backend/src/utils/logger.ts (1)
  • logger (6-29)
backend/src/types/auth.ts (1)
  • LinkedInUserInfo (105-114)
shared-schemas/src/auth-api.schema.ts (1)
  • CreateSessionResponse (324-324)
backend/src/core/auth/oauth.discord.ts (4)
backend/src/utils/environment.ts (1)
  • getApiBaseUrl (39-41)
backend/src/utils/logger.ts (1)
  • logger (6-29)
backend/src/types/auth.ts (1)
  • DiscordUserInfo (98-103)
shared-schemas/src/auth-api.schema.ts (1)
  • CreateSessionResponse (324-324)
backend/src/core/auth/auth.ts (5)
backend/src/core/auth/oauth.github.ts (1)
  • GitHubOAuthService (12-156)
backend/src/core/auth/oauth.discord.ts (1)
  • DiscordOAuthService (12-154)
backend/src/core/auth/oauth.microsoft.ts (1)
  • MicrosoftOAuthService (12-138)
backend/src/core/auth/oauth.linkedin.ts (1)
  • LinkedInOAuthService (12-215)
backend/src/core/auth/oauth.facebook.ts (1)
  • FacebookOAuthService (12-134)
🪛 GitHub Actions: Lint and Format Check
backend/src/core/auth/oauth.linkedin.ts

[error] 83-83: Prettier formatting error: Replace newline-separated 'code: string' property with a single line. (prettier/prettier)

🪛 GitHub Check: lint-and-format
backend/src/core/auth/oauth.microsoft.ts

[failure] 58-58:
Replace ⏎····code:·string⏎·· with code:·string


[failure] 2-2:
'logger' is defined but never used. Allowed unused vars must match /^_/u

backend/src/core/auth/oauth.linkedin.ts

[failure] 83-83:
Replace ⏎····code:·string⏎·· with code:·string

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

1-133: Facebook OAuth service integration looks solid

Config validation, shared-key handling, redirect URIs, and user info mapping all look consistent with the rest of the OAuth stack; no issues stand out.

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

1-155: GitHub OAuth service is consistent and correct

URL generation, token exchange, email resolution, and callback handling all look consistent with the other providers and with the GitHub types; no changes needed.

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

26-30: AuthService OAuth delegation pattern looks good

The new provider imports, per-provider generate*OAuthUrl wrappers, and the generic generateOAuthUrl / handleOAuthCallback switch-based routing cleanly delegate all provider-specific work into the respective OAuth services while reusing the existing findOrCreate*User helpers. With the Microsoft user shape aligned as noted in the Microsoft service comment, this centralization is coherent and maintainable.

Also applies to: 866-904, 947-975, 1011-1067, 1072-1132

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

1-154: Discord OAuth service implementation is consistent and well-structured

Shared-key handling, direct OAuth URL generation, token exchange, user info mapping, and callback wiring all align with the other providers and the DiscordUserInfo type; no issues found.

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

1-28: LGTM!

The singleton pattern is correctly implemented, and the use of processedCodes and tokenCache for deduplication is appropriate for preventing race conditions during OAuth flows.


198-214: LGTM!

The callback handler correctly supports both token and code flows, properly delegating to the appropriate verification methods.

Comment thread backend/src/core/auth/oauth.linkedin.ts Resolved
Comment thread backend/src/core/auth/oauth.linkedin.ts Resolved
Comment thread backend/src/core/auth/oauth.linkedin.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4

♻️ Duplicate comments (2)
backend/src/core/auth/oauth.linkedin.ts (2)

43-59: Handle missing auth_url more defensively.

If both response.data.auth_url and response.data.url are undefined, returning an empty string (line 58) could cause silent failures downstream. The past review comment on this issue has not been addressed.

Apply this diff:

      }
    );
-    return response.data.auth_url || response.data.url || '';
+    const authUrl = response.data.auth_url || response.data.url;
+    if (!authUrl) {
+      throw new Error('Shared LinkedIn OAuth API did not return a valid auth URL');
+    }
+    return authUrl;
  }

177-186: Validate required fields from token payload.

The email field is required in LinkedInUserInfo but falls back to an empty string if missing from the token payload (line 179). Downstream code expecting a valid email might fail silently. The past review comment on this issue has not been addressed.

Apply this diff:

+      const email = payload.email as string;
+      if (!email) {
+        throw new Error('LinkedIn token missing required email field');
+      }
+
      return {
        sub: String(payload.sub),
-        email: (payload.email as string) || '',
+        email,
        email_verified: Boolean(payload.email_verified),
        name: (payload.name as string) || '',
        picture: (payload.picture as string) || '',
        given_name: (payload.given_name as string) || '',
        family_name: (payload.family_name as string) || '',
        locale: (payload.locale as string) || '',
      };
🧹 Nitpick comments (2)
backend/src/core/auth/oauth.linkedin.ts (2)

169-169: Move jose import to file top for better performance.

Dynamic imports inside methods that may be called frequently can have performance overhead. Since jose is used exclusively in this method and is not a large bundle, consider importing it at the top of the file.

Apply this diff at the top of the file:

 import axios from 'axios';
+import { createRemoteJWKSet, jwtVerify } from 'jose';
 import logger from '@/utils/logger.js';

Then update the method:

    try {
-      const { createRemoteJWKSet, jwtVerify } = await import('jose');
      const JWKS = createRemoteJWKSet(new URL('https://www.linkedin.com/oauth/openid/jwks'));

137-140: Consider adding timer cleanup for test environments.

The setTimeout creates timers that won't be cleared if the service instance is destroyed or tests are torn down. This could lead to memory leaks in test suites.

Consider tracking timers and adding a cleanup method:

  private processedCodes: Set<string>;
  private tokenCache: Map<string, { access_token: string; id_token: string }>;
+  private cleanupTimers: Set<NodeJS.Timeout>;

  private constructor() {
    // Initialize OAuth helpers
    this.processedCodes = new Set();
    this.tokenCache = new Map();
+    this.cleanupTimers = new Set();
  }
  
+  // For testing/cleanup
+  public destroy(): void {
+    this.cleanupTimers.forEach(timer => clearTimeout(timer));
+    this.cleanupTimers.clear();
+    this.processedCodes.clear();
+    this.tokenCache.clear();
+  }

Then update the timer creation:

-      setTimeout(() => {
+      const timer = setTimeout(() => {
        this.processedCodes.delete(code);
        this.tokenCache.delete(code);
+        this.cleanupTimers.delete(timer);
      }, 60000);
+      this.cleanupTimers.add(timer);
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b4e1c16 and 02964c8.

📒 Files selected for processing (1)
  • backend/src/core/auth/oauth.linkedin.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
backend/src/core/auth/oauth.linkedin.ts (4)
backend/src/utils/environment.ts (1)
  • getApiBaseUrl (39-41)
backend/src/utils/logger.ts (1)
  • logger (6-29)
backend/src/types/auth.ts (1)
  • LinkedInUserInfo (105-114)
shared-schemas/src/auth-api.schema.ts (1)
  • CreateSessionResponse (324-324)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: E2E Tests
  • GitHub Check: CI Pre-merge Check

Comment thread backend/src/core/auth/oauth.linkedin.ts Resolved
Comment thread backend/src/core/auth/oauth.linkedin.ts Resolved
Comment on lines +84 to +91
if (this.processedCodes.has(code)) {
const cachedTokens = this.tokenCache.get(code);
if (cachedTokens) {
logger.debug('Returning cached tokens for already processed code.');
return cachedTokens;
}
throw new Error('Authorization code is currently being processed.');
}

@coderabbitai coderabbitai Bot Nov 15, 2025 •

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

Potential race condition in code deduplication.

Between checking has(code) (line 84) and adding it to the set (line 101), two concurrent requests with the same code could both pass the check. This could lead to duplicate token exchanges before either marks the code as processed.

Consider using a more atomic approach:

  async exchangeCodeToToken(code: string): Promise<{ access_token: string; id_token: string }> {
-    if (this.processedCodes.has(code)) {
-      const cachedTokens = this.tokenCache.get(code);
-      if (cachedTokens) {
-        logger.debug('Returning cached tokens for already processed code.');
-        return cachedTokens;
-      }
-      throw new Error('Authorization code is currently being processed.');
-    }
+    const cachedTokens = this.tokenCache.get(code);
+    if (cachedTokens) {
+      logger.debug('Returning cached tokens for already processed code.');
+      return cachedTokens;
+    }
+    
+    if (this.processedCodes.has(code)) {
+      throw new Error('Authorization code is currently being processed.');
+    }

    const oAuthConfigService = OAuthConfigService.getInstance();
    const config = await oAuthConfigService.getConfigByProvider('linkedin');

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

    try {
      this.processedCodes.add(code);

Note: This reduces but doesn't eliminate the race window. For production, consider using a distributed lock or database-level constraint if multiple instances run concurrently.

🤖 Prompt for AI Agents
In backend/src/core/auth/oauth.linkedin.ts around lines 84 to 101, there is a
race between checking processedCodes.has(code) and later adding the code which
can allow duplicate exchanges; fix by reserving the code atomically before
starting the async token exchange — e.g., insert a pending marker (or store the
promise) into tokenCache/processedCodes immediately when the first request
arrives, return/await that stored promise for concurrent requests, and ensure
you remove the reservation and store final tokens on success or clear it on
error so other attempts can retry; also add error handling to clean up the
reservation to avoid deadlocks.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Just as it is in old code. @Fermionic-Lyu I think we can create a separate issue to enhance this

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.

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

Comment thread backend/src/core/auth/oauth.linkedin.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

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

42-47: Consider extracting the default scope to avoid duplication.

The default scope string 'openid email profile offline_access User.Read' appears identically in both generateOAuthUrl (lines 44-46) and exchangeCodeToToken (lines 72-75). Extracting it to a class constant would improve maintainability.

Apply this diff:

 export class MicrosoftOAuthService {
   private static instance: MicrosoftOAuthService;
+  private static readonly DEFAULT_SCOPES = 'openid email profile offline_access User.Read';

   private constructor() {
     // Initialize OAuth helpers if needed
   }
...
     authUrl.searchParams.set(
       'scope',
       config.scopes && config.scopes.length > 0
         ? config.scopes.join(' ')
-        : 'openid email profile offline_access User.Read'
+        : MicrosoftOAuthService.DEFAULT_SCOPES
     );
...
       scope:
         config.scopes && config.scopes.length > 0
           ? config.scopes.join(' ')
-          : 'openid email profile offline_access User.Read',
+          : MicrosoftOAuthService.DEFAULT_SCOPES,

Also applies to: 72-76

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0c20dae and 8ada176.

📒 Files selected for processing (1)
  • backend/src/core/auth/oauth.microsoft.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
backend/src/core/auth/oauth.microsoft.ts (3)
backend/src/utils/environment.ts (1)
  • getApiBaseUrl (39-41)
backend/src/types/auth.ts (1)
  • MicrosoftUserInfo (92-97)
shared-schemas/src/auth-api.schema.ts (1)
  • CreateSessionResponse (324-324)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: E2E Tests
  • GitHub Check: CI Pre-merge Check
🔇 Additional comments (1)
backend/src/core/auth/oauth.microsoft.ts (1)

98-118: Previous issues resolved.

The type mismatch and unused import issues from the earlier review have been addressed. The getUserInfo method now correctly returns MicrosoftUserInfo with the name field (derived from displayName, userPrincipalName, or email as fallbacks), matching the interface definition in backend/src/types/auth.ts.

@Fermionic-Lyu
Fermionic-Lyu changed the base branch from main to lyu-transition November 15, 2025 19:09

@Fermionic-Lyu Fermionic-Lyu left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for your help! This helps code maintainence a lot.

@Fermionic-Lyu
Fermionic-Lyu merged commit 92c079e into InsForge:lyu-transition Nov 15, 2025
@sunny775

Copy link
Copy Markdown
Contributor Author

Thank you! Happy to help

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.

[Refactor]: More refactor on OAuth

2 participants