Repository navigation
refactor oauth providers - #590
Conversation
WalkthroughRefactors 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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes
Possibly related PRs
Suggested reviewers
Poem
Pre-merge checks and finishing touches✅ Passed checks (5 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
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. Comment |
|
@Fermionic-Lyu kindly review |
There was a problem hiding this comment.
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
📒 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 solidConfig 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 correctURL 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 goodThe new provider imports, per-provider
generate*OAuthUrlwrappers, and the genericgenerateOAuthUrl/handleOAuthCallbackswitch-based routing cleanly delegate all provider-specific work into the respective OAuth services while reusing the existingfindOrCreate*Userhelpers. 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-structuredShared-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
processedCodesandtokenCachefor 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.
There was a problem hiding this comment.
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_urlandresponse.data.urlare 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
LinkedInUserInfobut 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
joseis 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
setTimeoutcreates 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
📒 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
| 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.'); | ||
| } |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Just as it is in old code. @Fermionic-Lyu I think we can create a separate issue to enhance this
There was a problem hiding this comment.
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!
There was a problem hiding this comment.
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 bothgenerateOAuthUrl(lines 44-46) andexchangeCodeToToken(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
📒 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
getUserInfomethod now correctly returnsMicrosoftUserInfowith thenamefield (derived fromdisplayName,userPrincipalName, orbackend/src/types/auth.ts.
Fermionic-Lyu
left a comment
There was a problem hiding this comment.
Thanks for your help! This helps code maintainence a lot.
|
Thank you! Happy to help |
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
oauth.github.tsoauth.discord.tsoauth.linkedin.tsoauth.facebook.tsoauth.microsoft.tsauth.tsto delegate to provider services (-601 lines)generateOAuthUrl()exchangeCodeToToken()getUserInfo()/verifyToken()handleCallback()Files Changed
Summary by CodeRabbit