Repository navigation
[Refactor] Simplify OAuth files - #594
Conversation
refactor oauth providers
WalkthroughReplaces per-provider OAuth handlers with provider-specific singleton services and a unified AuthService flow; adds Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes
Possibly related PRs
Suggested reviewers
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: CodeRabbit UI Review profile: CHILL Plan: Pro ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
⏰ 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)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 8
🧹 Nitpick comments (11)
backend/src/types/auth.ts (1)
129-142: Tightenprovidertyping for better safety and autocomplete
provideris currently a plainstring, even though all call sites use a small fixed set of values ('google' | 'github' | 'discord' | 'linkedin' | 'facebook' | 'microsoft'). Narrowing this to a string-literal union (or exportedOAuthProvidertype) would catch typos at compile time and improve editor support.You could do something like:
+export type OAuthProvider = + | 'google' + | 'github' + | 'discord' + | 'linkedin' + | 'facebook' + | 'microsoft'; + export interface OAuthUserData { - provider: string; + provider: OAuthProvider;backend/src/core/auth/oauth.github.ts (1)
61-69: Consider validating presence ofclientIdbefore building the auth URLIf
config.clientIdis missing, this still generates an auth URL with an emptyclient_id, which will just fail later at GitHub. A quick guard here would make misconfiguration easier to diagnose:if (!config.clientId) { throw new Error('GitHub OAuth clientId not configured'); }backend/src/core/auth/oauth.facebook.ts (1)
123-137: User info retrieval is straightforward but could normalize shape explicitlyReturning
response.datadirectly asFacebookUserInfois fine, and the requestedfieldsensure all properties used later (id,name,first_name,last_name,picture) are present when the API cooperates.If you ever see shape mismatches at runtime, you might want to map explicitly like in the GitHub/Discord services, but that’s optional for now.
backend/src/api/routes/auth.oauth.ts (1)
355-364: GitHub shared-callback mapping looks solid; only minor edge-case considerationsThe normalization here is consistent with the GitHub OAuth service and should behave well. The only edge case is if
payloadData.loginis unexpectedly missing whilepayloadData.emailis also absent, which would produce an[email protected]email; if that scenario is impossible by contract with the shared service, this is fine, otherwise consider a small fallback username/email.backend/src/core/auth/oauth.microsoft.ts (3)
61-104: Token exchange flow is sound; consider tightening error surfacing if neededThe code handles missing config, builds a correct form-encoded body, and logs structured details on failure. Returning both
access_tokenand optionalid_tokenkeeps the surface flexible for future use, even though the current flow only usesaccess_token.
119-143: User info retrieval is straightforward; be cautious about logging full error objectsThe Graph
/mecall and normalization (id, email with sensible fallback, name) are solid. The only concern islogger.error('Microsoft user info retrieval failed:', error);potentially serializing the full error object, which may include request headers (and thus bearer tokens) in some logger setups; consider logging a slimmer shape (message, status, response data) instead.
149-167: Callback handler is correct for code-based flows; token parameter in signature is unusedThe callback orchestration (require
code, exchange for tokens, fetch user info, map to OAuthUserData) is clean and aligns with the generic AuthService flow. Since thetokenfield inpayloadis currently unused for Microsoft, you might either support a token-based path (parallel to Google/LinkedIn) or drop it from the signature to avoid confusion.backend/src/core/auth/oauth.linkedin.ts (2)
82-154: Code exchange with caching is well-structured; behavior on concurrent reuse is deliberateThe processed-code set and token cache prevent duplicate exchanges while allowing a cached response for retries, and the 60s cleanup avoids unbounded growth. Throwing when a code is “currently being processed” is a reasonable safety choice; if that ever proves noisy in practice, you could switch to a simple queue or always rely on the cached result.
159-190: ID token verification via JWKS is robust; log content could be trimmedUsing LinkedIn’s JWKS, validating issuer and audience, and mapping claims into
LinkedInUserInfois the right approach. Similar to other providers, consider logging a reduced error shape instead of the full object inlogger.error('LinkedIn token verification failed:', error);to avoid leaking token or request details into logs.backend/src/core/auth/auth.ts (2)
98-104: Constructor initialization of OAuth services is straightforwardInitializing all OAuth service singletons during AuthService construction is simple and matches how other dependencies (DB, config) are set up. If construction ever becomes heavy, you could lazily initialize these, but it’s not necessary now.
920-952: Unified handleOAuthCallback flow looks good; consider trusting the enum provider over payload.providerDelegating to per-provider
handleCallbackmethods and then funneling everything throughfindOrCreateThirdPartyUseris exactly the right consolidation.One small robustness tweak: since
provideris already validated asOAuthProvidersSchema, you could pass it through instead ofuserData.providerwhen callingfindOrCreateThirdPartyUser, in case a buggy service ever returns a mismatched provider string:- return this.findOrCreateThirdPartyUser( - userData.provider, + return this.findOrCreateThirdPartyUser( + provider, userData.providerId, userData.email, userData.userName, userData.avatarUrl, userData.identityData );
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (9)
backend/src/api/routes/auth.oauth.ts(1 hunks)backend/src/core/auth/auth.ts(5 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.google.ts(2 hunks)backend/src/core/auth/oauth.linkedin.ts(1 hunks)backend/src/core/auth/oauth.microsoft.ts(1 hunks)backend/src/types/auth.ts(1 hunks)
🧰 Additional context used
🧬 Code graph analysis (7)
backend/src/core/auth/oauth.github.ts (3)
backend/src/utils/environment.ts (1)
getApiBaseUrl(39-41)backend/src/utils/logger.ts (1)
logger(6-29)backend/src/types/auth.ts (3)
GitHubUserInfo(77-83)GitHubEmailInfo(85-90)OAuthUserData(130-143)
backend/src/core/auth/oauth.discord.ts (4)
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)
DiscordUserInfo(98-103)OAuthUserData(130-143)
backend/src/core/auth/oauth.google.ts (1)
backend/src/types/auth.ts (2)
OAuthUserData(130-143)GoogleUserInfo(66-75)
backend/src/core/auth/oauth.microsoft.ts (3)
backend/src/utils/environment.ts (1)
getApiBaseUrl(39-41)backend/src/utils/logger.ts (1)
logger(6-29)backend/src/types/auth.ts (2)
MicrosoftUserInfo(92-97)OAuthUserData(130-143)
backend/src/core/auth/oauth.facebook.ts (4)
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)
FacebookUserInfo(116-127)OAuthUserData(130-143)
backend/src/core/auth/oauth.linkedin.ts (3)
backend/src/app.config.ts (1)
config(30-54)backend/src/utils/environment.ts (1)
getApiBaseUrl(39-41)backend/src/types/auth.ts (2)
LinkedInUserInfo(105-114)OAuthUserData(130-143)
backend/src/core/auth/auth.ts (7)
backend/src/core/auth/oauth.google.ts (1)
GoogleOAuthService(12-229)backend/src/core/auth/oauth.github.ts (1)
GitHubOAuthService(11-184)backend/src/core/auth/oauth.discord.ts (1)
DiscordOAuthService(11-173)backend/src/core/auth/oauth.linkedin.ts (1)
LinkedInOAuthService(11-218)backend/src/core/auth/oauth.facebook.ts (1)
FacebookOAuthService(11-166)backend/src/core/auth/oauth.microsoft.ts (1)
MicrosoftOAuthService(11-168)backend/src/types/auth.ts (1)
OAuthUserData(130-143)
🪛 Gitleaks (8.29.0)
backend/src/core/auth/oauth.linkedin.ts
[high] 196-196: Discovered a LinkedIn Client secret, potentially compromising LinkedIn application integrations and user data.
(linkedin-client-secret)
⏰ 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 (18)
backend/src/core/auth/oauth.github.ts (2)
75-121: Token exchange flow and logging look solidThe token exchange logic is straightforward, logs useful context (without leaking secrets), and handles Axios errors cleanly by logging status and response payload before throwing a descriptive error.
126-155: Robust handling of missing GitHub emailThe fallback to
/user/emailswhenuser.emailis missing, plus the final fallback to theusers.noreply.github.comaddress, is a pragmatic way to ensure an email value for downstream logic while still preferring real primary email when available.backend/src/core/auth/oauth.discord.ts (3)
61-71: Discord auth URL generation looks correct and consistentThe constructed authorization URL uses the expected endpoint, includes client_id, redirect_uri,
response_type=code, and joins scopes with spaces, which matches Discord’s expectations. Optional state handling is also wired correctly.
76-123: Token exchange flow is well-structuredUsing
application/x-www-form-urlencodedwithURLSearchParamsfor Discord’s token endpoint is appropriate. Logging and Axios error handling mirror the GitHub implementation and look good.
128-143: Good mapping of Discord user info, with sensible fallbacksMapping
global_name || usernameand deriving the avatar CDN URL is appropriate. Returning an empty string when no avatar is available is reasonable for downstream UI logic.backend/src/core/auth/oauth.google.ts (2)
6-6: Type imports align with the new unified OAuth modelImporting
GoogleUserInfoandOAuthUserDatahere keeps the Google service in sync with the shared OAuth typing introduced inauth.ts. No issues.
206-227: Unified Google callback flow looks correct and consistentThe updated
handleCallback:
- Supports both direct ID-token verification (
payload.token) and code → tokens → ID-token verification (payload.code).- Throws a clear error when neither is provided.
- Maps
GoogleUserInfointoOAuthUserDatawith stable fallbacks (nameor email local part foruserName, empty string for missing picture).This aligns well with the new provider-agnostic OAuth pipeline.
To be safe, please double-check that all call sites now expect a
Promise<OAuthUserData>(instead of the previous session-creation response) and that any front-end sendingtokenis indeed passing the Google ID token, not the access token. A quick repo-wide search forhandleCallback(onGoogleOAuthServiceand for the payload shape used in the OAuth callback route should confirm this.backend/src/core/auth/oauth.facebook.ts (2)
60-73: Facebook auth URL construction looks correctThe generated authorization URL uses the expected dialog endpoint, client_id, redirect_uri,
response_type=code, and scopes joined by commas, which matches typical Facebook OAuth expectations. Optional state handling is in place.
78-118: Token exchange logic is consistent with other providersUsing the Graph API
/oauth/access_tokenendpoint with query params, plus logging and structured Axios error handling, is clear and consistent with the GitHub/Discord flows.backend/src/api/routes/auth.oauth.ts (2)
382-391: Discord mapping is consistent with direct flow and looks goodUsername and email fallbacks here mirror the Discord OAuth service behavior (including the
noreply.discord.localpattern), so the shared callback path should behave consistently with direct Discord OAuth.
409-421: Facebook shared-callback normalization aligns with direct service behaviorThe username derivation and avatar extraction here match the Facebook OAuth service semantics and should work well for both complete and partial payloads; good job keeping this consistent across flows.
backend/src/core/auth/oauth.microsoft.ts (1)
28-56: Microsoft authorization URL generation is correct and matches the new unified patternThe URL construction (client_id, response_type=code, redirect_uri, scopes, optional state) looks correct and consistent with the other provider services. The explicit note that shared keys are not implemented for Microsoft is helpful and avoids accidental misuse of the shared-key flow.
backend/src/core/auth/oauth.linkedin.ts (2)
32-77: LinkedIn auth URL generation (local + shared-key) looks correctBoth branches are wired cleanly: shared-key mode delegates to the cloud endpoint with a signed state-bound redirect, and local mode builds a standard LinkedIn authorization URL with appropriate scopes and optional state. This fits well into the unified
/shared/callbackand per-provider callback flows.
195-217: LinkedIn callback handler correctly supports both token and code pathsHandling either an incoming ID token or an authorization code, then normalizing to OAuthUserData with a sane username fallback, matches the unified AuthService contract and should interoperate cleanly with
findOrCreateThirdPartyUser.backend/src/core/auth/auth.ts (4)
26-30: Importing provider-specific OAuth services is aligned with the new designPulling in the dedicated OAuth service classes keeps AuthService slimmer and makes the per-provider concerns explicit and testable in isolation.
41-42: Using OAuthUserData as the shared contract simplifies callback handlingImporting
OAuthUserDatahere and using it as the cross-provider payload type is a good abstraction that decouples provider details from the session-creation logic.
62-68: Cached OAuth service instances on AuthService are a good fitStoring the singleton instances on private fields avoids repeated lookups and makes it obvious which providers are supported in this class.
894-908: generateOAuthUrl delegations are clear and keep provider logic out of AuthServiceThe switch cleanly maps each provider enum value to the corresponding service method, and the default case sensibly rejects unsupported providers.
| if (config?.useSharedKey) { | ||
| if (!state) { | ||
| logger.warn('Shared Discord OAuth called without state parameter'); | ||
| throw new Error('State parameter is required for shared Discord OAuth'); | ||
| } | ||
| // Use shared keys if configured | ||
| const cloudBaseUrl = process.env.CLOUD_API_HOST || 'https://api.insforge.dev'; | ||
| const redirectUri = `${selfBaseUrl}/api/auth/oauth/shared/callback/${state}`; | ||
| 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 || ''; | ||
| } |
There was a problem hiding this comment.
Handle missing auth URL from shared Discord OAuth more explicitly
Like the GitHub service, this returns an empty string if the cloud shared-OAuth endpoint doesn’t return auth_url or url. That can cause confusing behavior upstream.
Consider throwing when no URL is present:
- return response.data.auth_url || response.data.url || '';
+ const url = response.data.auth_url || response.data.url;
+ if (!url) {
+ throw new Error('Shared Discord OAuth did not return an authorization URL');
+ }
+ return url;📝 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.
| if (config?.useSharedKey) { | |
| if (!state) { | |
| logger.warn('Shared Discord OAuth called without state parameter'); | |
| throw new Error('State parameter is required for shared Discord OAuth'); | |
| } | |
| // Use shared keys if configured | |
| const cloudBaseUrl = process.env.CLOUD_API_HOST || 'https://api.insforge.dev'; | |
| const redirectUri = `${selfBaseUrl}/api/auth/oauth/shared/callback/${state}`; | |
| 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 || ''; | |
| } | |
| if (config?.useSharedKey) { | |
| if (!state) { | |
| logger.warn('Shared Discord OAuth called without state parameter'); | |
| throw new Error('State parameter is required for shared Discord OAuth'); | |
| } | |
| // Use shared keys if configured | |
| const cloudBaseUrl = process.env.CLOUD_API_HOST || 'https://api.insforge.dev'; | |
| const redirectUri = `${selfBaseUrl}/api/auth/oauth/shared/callback/${state}`; | |
| const response = await axios.get( | |
| `${cloudBaseUrl}/auth/v1/shared/discord?redirect_uri=${encodeURIComponent(redirectUri)}`, | |
| { | |
| headers: { | |
| 'Content-Type': 'application/json', | |
| }, | |
| } | |
| ); | |
| const url = response.data.auth_url || response.data.url; | |
| if (!url) { | |
| throw new Error('Shared Discord OAuth did not return an authorization URL'); | |
| } | |
| return url; | |
| } |
🤖 Prompt for AI Agents
In backend/src/core/auth/oauth.discord.ts around lines 38 to 55, the current
branch returns an empty string when the cloud shared-OAuth endpoint does not
provide response.data.auth_url or response.data.url; change this to explicitly
detect a missing URL, log a clear warning/error, and throw an Error instead of
returning ''. After the axios call extract the URL (response.data.auth_url ||
response.data.url), if falsy call logger.error or logger.warn with context
(including cloudBaseUrl and state) and throw a descriptive Error like "Missing
auth URL from shared Discord OAuth response" so callers cannot proceed with an
empty redirect.
| async handleCallback(payload: { code?: string; token?: string }): Promise<OAuthUserData> { | ||
| if (!payload.code) { | ||
| throw new Error('No authorization code provided'); | ||
| } | ||
|
|
||
| const accessToken = await this.exchangeCodeToToken(payload.code); | ||
| const discordUserInfo = await this.getUserInfo(accessToken); | ||
|
|
||
| // Transform Discord user info to generic format | ||
| const userName = discordUserInfo.username; | ||
| const email = discordUserInfo.email || `${discordUserInfo.id}@users.noreply.discord.local`; | ||
| return { | ||
| provider: 'discord', | ||
| providerId: discordUserInfo.id, | ||
| email, | ||
| userName, | ||
| avatarUrl: discordUserInfo.avatar || '', | ||
| identityData: discordUserInfo, | ||
| }; |
There was a problem hiding this comment.
Align handleCallback payload type with actual behavior
As with GitHub, handleCallback only supports the authorization code path and ignores payload.token, but the payload type suggests both are valid. Either support token-based handling or narrow the type to require code to prevent incorrect usage.
🤖 Prompt for AI Agents
In backend/src/core/auth/oauth.discord.ts around lines 153 to 171, the
handleCallback signature declares payload as { code?: string; token?: string }
but the implementation only uses the authorization code flow; update the API to
require a code or implement token-based handling. Fix by changing the payload
type to { code: string } (and update the function signature) and add a runtime
check that throws a clear error if code is missing; also update all call sites
to pass a code (or, if you prefer to support token flow instead, implement logic
to accept payload.token by using it directly as the access token and skip
exchangeCodeToToken, and update types accordingly). Ensure TypeScript types and
all references are adjusted to match the chosen approach.
| if (config?.useSharedKey) { | ||
| if (!state) { | ||
| logger.warn('Shared Facebook OAuth called without state parameter'); | ||
| throw new Error('State parameter is required for shared Facebook OAuth'); | ||
| } | ||
| const cloudBaseUrl = process.env.CLOUD_API_HOST || 'https://api.insforge.dev'; | ||
| const redirectUri = `${selfBaseUrl}/api/auth/oauth/shared/callback/${state}`; | ||
| const response = await axios.get( | ||
| `${cloudBaseUrl}/auth/v1/shared/facebook?redirect_uri=${encodeURIComponent(redirectUri)}`, | ||
| { | ||
| headers: { | ||
| 'Content-Type': 'application/json', | ||
| }, | ||
| } | ||
| ); | ||
| return response.data.auth_url || response.data.url || ''; | ||
| } |
There was a problem hiding this comment.
Guard against missing auth URL from shared Facebook OAuth
Here too, the shared-key branch returns an empty string if the cloud endpoint doesn’t provide a URL. That can lead to confusing redirects.
Recommend failing fast:
- );
- return response.data.auth_url || response.data.url || '';
+ );
+ const url = response.data.auth_url || response.data.url;
+ if (!url) {
+ throw new Error('Shared Facebook OAuth did not return an authorization URL');
+ }
+ return url;📝 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.
| if (config?.useSharedKey) { | |
| if (!state) { | |
| logger.warn('Shared Facebook OAuth called without state parameter'); | |
| throw new Error('State parameter is required for shared Facebook OAuth'); | |
| } | |
| const cloudBaseUrl = process.env.CLOUD_API_HOST || 'https://api.insforge.dev'; | |
| const redirectUri = `${selfBaseUrl}/api/auth/oauth/shared/callback/${state}`; | |
| const response = await axios.get( | |
| `${cloudBaseUrl}/auth/v1/shared/facebook?redirect_uri=${encodeURIComponent(redirectUri)}`, | |
| { | |
| headers: { | |
| 'Content-Type': 'application/json', | |
| }, | |
| } | |
| ); | |
| return response.data.auth_url || response.data.url || ''; | |
| } | |
| if (config?.useSharedKey) { | |
| if (!state) { | |
| logger.warn('Shared Facebook OAuth called without state parameter'); | |
| throw new Error('State parameter is required for shared Facebook OAuth'); | |
| } | |
| const cloudBaseUrl = process.env.CLOUD_API_HOST || 'https://api.insforge.dev'; | |
| const redirectUri = `${selfBaseUrl}/api/auth/oauth/shared/callback/${state}`; | |
| const response = await axios.get( | |
| `${cloudBaseUrl}/auth/v1/shared/facebook?redirect_uri=${encodeURIComponent(redirectUri)}`, | |
| { | |
| headers: { | |
| 'Content-Type': 'application/json', | |
| }, | |
| } | |
| ); | |
| const url = response.data.auth_url || response.data.url; | |
| if (!url) { | |
| throw new Error('Shared Facebook OAuth did not return an authorization URL'); | |
| } | |
| return url; | |
| } |
🤖 Prompt for AI Agents
In backend/src/core/auth/oauth.facebook.ts around lines 38 to 54, the shared-key
branch currently returns an empty string when the cloud endpoint does not
provide an auth URL; change this to fail fast by validating the response and
throwing a descriptive error (and logging a warning/error) if neither
response.data.auth_url nor response.data.url is present or is empty, so callers
never receive an empty redirect URL; ensure the thrown error includes context
(cloudBaseUrl and redirectUri) for debugging.
| async handleCallback(payload: { code?: string; token?: string }): Promise<OAuthUserData> { | ||
| if (!payload.code) { | ||
| throw new Error('No authorization code provided'); | ||
| } | ||
|
|
||
| const accessToken = await this.exchangeCodeToToken(payload.code); | ||
| const facebookUserInfo = await this.getUserInfo(accessToken); | ||
|
|
||
| // Transform Facebook user info to generic format | ||
| const email = facebookUserInfo.email || ''; | ||
| const userName = | ||
| facebookUserInfo.name || | ||
| facebookUserInfo.first_name || | ||
| `User${facebookUserInfo.id.substring(0, 6)}`; | ||
| const avatarUrl = facebookUserInfo.picture?.data?.url || ''; | ||
| return { | ||
| provider: 'facebook', | ||
| providerId: facebookUserInfo.id, | ||
| email, | ||
| userName, | ||
| avatarUrl, | ||
| identityData: facebookUserInfo, | ||
| }; |
There was a problem hiding this comment.
Clarify token usage and email fallback behavior in Facebook callback
handleCallback currently:
- Requires
payload.codeand ignorespayload.token, despite the type allowing both. - Falls back to an empty string for missing email, even though
OAuthUserData.emailis required.
Consider:
- Either supporting a token-based path (if you expect one) or narrowing the payload type to
{ code: string }. - Optionally introducing a synthetic “noreply” email like the GitHub/Discord flows, so downstream logic never sees an empty email string.
| if (config?.useSharedKey) { | ||
| if (!state) { | ||
| logger.warn('Shared GitHub OAuth called without state parameter'); | ||
| throw new Error('State parameter is required for shared GitHub OAuth'); | ||
| } | ||
| // Use shared keys if configured | ||
| const cloudBaseUrl = process.env.CLOUD_API_HOST || 'https://api.insforge.dev'; | ||
| const redirectUri = `${selfBaseUrl}/api/auth/oauth/shared/callback/${state}`; | ||
| const response = await axios.get( | ||
| `${cloudBaseUrl}/auth/v1/shared/github?redirect_uri=${encodeURIComponent(redirectUri)}`, | ||
| { | ||
| headers: { | ||
| 'Content-Type': 'application/json', | ||
| }, | ||
| } | ||
| ); | ||
| return response.data.auth_url || response.data.url || ''; | ||
| } |
There was a problem hiding this comment.
Fail fast instead of returning an empty auth URL in shared-key flow
In the shared-key branch, if the cloud service response doesn’t contain auth_url or url, this method returns an empty string. That will likely lead to confusing behavior at the caller (e.g., redirecting to an empty URL) rather than a clear error.
Consider throwing an explicit error instead so misconfiguration or backend issues surface quickly:
- return response.data.auth_url || response.data.url || '';
+ const url = response.data.auth_url || response.data.url;
+ if (!url) {
+ throw new Error('Shared GitHub OAuth did not return an authorization URL');
+ }
+ return url;🤖 Prompt for AI Agents
In backend/src/core/auth/oauth.github.ts around lines 38 to 55, the shared-key
branch currently returns an empty string when the cloud response lacks auth_url
or url; change this to fail fast by throwing a descriptive Error (include
response status and any response body/message available) instead of returning
'', so callers get an explicit exception on misconfiguration or backend failure;
ensure the thrown error includes context like the cloudBaseUrl and the
missing-field condition for easier debugging.
| async handleCallback(payload: { code?: string; token?: string }): Promise<OAuthUserData> { | ||
| if (!payload.code) { | ||
| throw new Error('No authorization code provided'); | ||
| } | ||
|
|
||
| const accessToken = await this.exchangeCodeToToken(payload.code); | ||
| const githubUserInfo = await this.getUserInfo(accessToken); | ||
|
|
||
| // Transform GitHub user info to generic format | ||
| const userName = githubUserInfo.name || githubUserInfo.login; | ||
| const email = githubUserInfo.email || `${githubUserInfo.login}@users.noreply.github.com`; | ||
| return { | ||
| provider: 'github', | ||
| providerId: githubUserInfo.id.toString(), | ||
| email, | ||
| userName, | ||
| avatarUrl: githubUserInfo.avatar_url || '', | ||
| identityData: githubUserInfo, | ||
| }; |
There was a problem hiding this comment.
Clarify or support token usage in handleCallback
The signature accepts { code?: string; token?: string }, but the implementation only supports code and throws "No authorization code provided" even if token is present. That’s surprising to callers and inconsistent with the Google implementation, which supports both.
Either:
- Add token-based handling (e.g., when a pre-obtained access token is passed), or
- Narrow the payload type to
{ code: string }so the API contract matches the behavior.
🤖 Prompt for AI Agents
In backend/src/core/auth/oauth.github.ts around lines 164 to 182, the
handleCallback signature accepts a payload with optional code and token but
currently throws when code is missing and ignores token; update behavior so the
signature and implementation match: either change the payload type to require {
code: string } (and remove token from callers/types) or add token-based handling
by accepting payload.token as a pre-obtained access token (skip
exchangeCodeToToken when token present), use that token to call getUserInfo, and
preserve existing return shape; pick one approach and make corresponding type
and runtime changes so callers are consistent.
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (2)
backend/src/api/routes/auth.oauth.ts (2)
369-377: Critical: Unsafe email handling can crash Microsoft OAuth.
payloadData.email.split('@')[0]will throw a TypeError ifpayloadData.emailis undefined or null, breaking the authentication flow.Apply the defensive fix suggested in the previous review:
- const userName = payloadData.name || payloadData.email.split('@')[0] || 'user'; + const email = + payloadData.email || `${payloadData.providerId}@users.noreply.microsoft.com`; + const userName = payloadData.name || email.split('@')[0] || 'user'; result = await authService.findOrCreateThirdPartyUser( 'microsoft', payloadData.providerId, - payloadData.email, + email, userName, payloadData.avatar || '', payloadData );
396-404: Critical: Unsafe email handling can crash LinkedIn OAuth.Similar to Microsoft,
payloadData.email.split('@')[0]will throw if email is missing.Apply the defensive fix:
- const userName = payloadData.name || payloadData.email.split('@')[0]; + const email = payloadData.email || `${payloadData.providerId}@users.noreply.linkedin.com`; + const userName = payloadData.name || email.split('@')[0] || 'user'; result = await authService.findOrCreateThirdPartyUser( 'linkedin', payloadData.providerId, - payloadData.email, + email, userName, payloadData.avatar || '', payloadData );
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
frontend/src/assets/logos/x.svgis excluded by!**/*.svg
📒 Files selected for processing (8)
.env.example(1 hunks)backend/src/api/routes/auth.oauth.ts(2 hunks)backend/src/core/auth/auth.ts(7 hunks)backend/src/core/auth/oauth.x.ts(1 hunks)backend/src/types/auth.ts(1 hunks)frontend/src/features/auth/components/OAuthConfigDialog.tsx(2 hunks)frontend/src/features/auth/components/UsersDataGrid.tsx(1 hunks)frontend/src/features/auth/helpers.tsx(2 hunks)
🧰 Additional context used
🧬 Code graph analysis (3)
backend/src/core/auth/oauth.x.ts (4)
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)
XUserInfo(129-136)OAuthUserData(139-153)
frontend/src/features/auth/components/OAuthConfigDialog.tsx (1)
frontend/src/lib/utils/utils.ts (1)
getBackendUrl(162-165)
backend/src/core/auth/auth.ts (8)
backend/src/core/auth/oauth.google.ts (1)
GoogleOAuthService(12-229)backend/src/core/auth/oauth.github.ts (1)
GitHubOAuthService(11-184)backend/src/core/auth/oauth.discord.ts (1)
DiscordOAuthService(11-173)backend/src/core/auth/oauth.linkedin.ts (1)
LinkedInOAuthService(11-218)backend/src/core/auth/oauth.facebook.ts (1)
FacebookOAuthService(11-166)backend/src/core/auth/oauth.microsoft.ts (1)
MicrosoftOAuthService(11-168)backend/src/core/auth/oauth.x.ts (1)
XOAuthService(8-179)backend/src/types/auth.ts (2)
XUserInfo(129-136)OAuthUserData(139-153)
⏰ 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 (21)
.env.example (1)
70-73: LGTM! Consistent environment variable naming.The X OAuth credentials follow the same pattern as other OAuth providers in the file.
frontend/src/features/auth/components/UsersDataGrid.tsx (1)
66-71: LGTM! Provider badge styling is consistent.The X provider badge follows the same pattern as other providers and uses appropriate neutral styling.
frontend/src/features/auth/components/OAuthConfigDialog.tsx (2)
29-35: X-specific localhost callback URL rewriting looks correct.Twitter/X OAuth has specific callback URL requirements that reject
http://localhostbut accepthttp://www.localhost. This rewriting ensures local development works correctly.Consider adding a brief comment explaining why X requires this special handling:
let backendUrl = getBackendUrl(); - // Check if backend URL contains "localhost" and provider is "x" + // X OAuth requires www.localhost instead of bare localhost for callback URLs if (provider === 'x' && backendUrl.includes('localhost')) { backendUrl = backendUrl.replace('://localhost', '://www.localhost'); }
84-84: LGTM! X provider added to shared keys list.This aligns with the backend X OAuth service that supports shared-key flows.
backend/src/types/auth.ts (2)
129-136: Well-structured XUserInfo interface.The interface correctly represents Twitter API v2 user data with appropriate optional fields.
138-153: Excellent abstraction with OAuthUserData interface.This unified interface standardizes OAuth data across all providers, making the codebase more maintainable and enabling the consolidated
findOrCreateThirdPartyUserflow.backend/src/core/auth/oauth.x.ts (4)
27-79: PKCE implementation looks solid.The PKCE flow correctly generates challenge, stores verifier with state key, and cleans up after timeout. The 10-minute timeout is reasonable for OAuth flows.
39-45: Good security practice: mandatory state parameter.Requiring the state parameter prevents CSRF attacks and is essential for PKCE flows where the verifier must be associated with state.
166-168: Email pattern is consistent across OAuth providers. The verification confirms that X's synthetic email pattern (@users.noreply.x.local) aligns with Discord's pattern for non-email-providing providers, while GitHub and Microsoft use their respective real domains for fallback emails. The design is intentional and consistent.
47-60: Verify and align X provider endpoint pattern with other OAuth providers.The X/Twitter provider uses
/oauth/twitterendpoint while all other providers consistently use/auth/v1/shared/{provider}pattern (Google:/auth/v1/shared/google, Discord:/auth/v1/shared/discord, GitHub:/auth/v1/shared/github, Facebook:/auth/v1/shared/facebook, LinkedIn:/auth/v1/shared/linkedin). Confirm the cloud API supports the/oauth/twitterendpoint, or update to use the/auth/v1/shared/xpattern for consistency across all providers.backend/src/api/routes/auth.oauth.ts (5)
353-365: GitHub shared callback handles missing email safely.The fallback email uses
payloadData.loginwhich should always be present in the payload, avoiding potential crashes.
380-392: Discord shared callback handles missing email safely.The fallback email pattern prevents crashes and follows the established pattern for providers that don't guarantee email.
407-423: Facebook shared callback handles missing data safely.The userName derivation has multiple fallbacks, and empty string is acceptable for email when missing.
424-440: X shared callback implementation looks safe.The email derivation always produces a valid string using the username or name with a fallback, preventing crashes.
500-504: Good addition: state parameter passed to OAuth handler.This enables PKCE flows (like X OAuth) that require the state to retrieve the code verifier.
backend/src/core/auth/auth.ts (5)
64-71: Excellent refactoring: OAuth services properly encapsulated.Moving OAuth logic into dedicated singleton services improves maintainability and follows the single responsibility principle. The initialization in the constructor ensures services are ready when needed.
Also applies to: 101-108
713-713: Type unions properly extended for X provider.XUserInfo correctly added to the discriminated unions, maintaining type safety across the OAuth flow.
Also applies to: 819-819
900-919: Clean provider routing in generateOAuthUrl.The switch statement properly delegates to each provider service. All providers including the new X OAuth are covered.
924-964: Well-designed unified OAuth callback flow.The refactoring introduces a clean, consistent pattern:
- Each provider service returns standardized
OAuthUserData- Single
findOrCreateThirdPartyUsermethod handles all providers- Type safety maintained through discriminated unions
This significantly improves code maintainability.
926-926: State parameter addition enables PKCE flows.Adding optional
stateto the payload supports X OAuth's PKCE implementation while remaining backward compatible with providers that don't need it.frontend/src/features/auth/helpers.tsx (1)
8-8: LGTM! Import follows the established pattern.The X logo import is consistent with other OAuth provider imports in the file.
tonychang04
left a comment
There was a problem hiding this comment.
honestly looks fine to me. it's fine without code rabbit's suggestion
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (4)
backend/src/core/auth/oauth.facebook.ts (2)
38-54: Guard against missing auth URL from shared Facebook OAuthLine 53 returns an empty string when the cloud endpoint doesn't provide a URL, which can lead to confusing redirects.
Recommend:
- return response.data.auth_url || response.data.url || ''; + const url = response.data.auth_url || response.data.url; + if (!url) { + logger.error('Shared Facebook OAuth did not return an authorization URL', { + cloudBaseUrl, + redirectUri, + }); + throw new Error('Shared Facebook OAuth did not return an authorization URL'); + } + return url;
142-165: Payload type mismatch with implementationSimilar to Discord, the signature accepts
{ code?: string; token?: string }but only thecodepath is implemented (lines 143-145).Consider narrowing the type:
- async handleCallback(payload: { code?: string; token?: string }): Promise<OAuthUserData> { + async handleCallback(payload: { code: string }): Promise<OAuthUserData> {Note: The empty email handling (line 151) is correct. Based on learnings, Facebook's email field requires App Review approval and may be unavailable even in production.
backend/src/core/auth/oauth.discord.ts (2)
153-172: Align payload type with implementation or support token flowThe
handleCallbacksignature accepts{ code?: string; token?: string }but the implementation only uses thecodepath (lines 154-156). Thetokenfield is never used.Either:
- Narrow the type to require
code:- async handleCallback(payload: { code?: string; token?: string }): Promise<OAuthUserData> { + async handleCallback(payload: { code: string }): Promise<OAuthUserData> {
- Or implement token-based handling if needed for the Discord OAuth flow.
38-55: Fail fast when shared OAuth endpoint doesn't return a URLLine 54 returns an empty string when the cloud endpoint doesn't provide
auth_urlorurl. This can cause confusing behavior upstream where an empty redirect URL might be used.Consider failing explicitly:
- return response.data.auth_url || response.data.url || ''; + const url = response.data.auth_url || response.data.url; + if (!url) { + logger.error('Shared Discord OAuth did not return an authorization URL', { + cloudBaseUrl, + state, + }); + throw new Error('Shared Discord OAuth did not return an authorization URL'); + } + return url;
🧹 Nitpick comments (3)
backend/src/core/auth/oauth.google.ts (1)
230-247: Consistent userName fallback needed in shared callbackLine 243 has the same pattern as
handleCallback:name || email.split('@')[0]. IfuserName.For consistency with the direct callback flow and to ensure robustness, consider adding a final fallback:
- return { - provider: 'google', - providerId, - email, - userName: name || email.split('@')[0], - avatarUrl: avatar, - identityData: payloadData, - }; + const userName = name || (email ? email.split('@')[0] : '') || 'user'; + return { + provider: 'google', + providerId, + email, + userName, + avatarUrl: avatar, + identityData: payloadData, + };backend/src/core/auth/oauth.linkedin.ts (2)
195-217: Handle empty email in userName derivationLine 208 derives
userNameusinglinkedinUserInfo.name || linkedinUserInfo.email.split('@')[0]. SinceverifyTokenmay return an empty email (line 178), this could result in an emptyuserName.Consider adding a fallback:
- const userName = linkedinUserInfo.name || linkedinUserInfo.email.split('@')[0]; + const userName = linkedinUserInfo.name || (linkedinUserInfo.email ? linkedinUserInfo.email.split('@')[0] : '') || 'user';
222-238: Add fallback for empty userName in shared callbackLine 228 uses the same pattern that could produce an empty
userNameif bothnameandApply the same defensive approach:
- const userName = name || email.split('@')[0]; + const userName = name || (email ? email.split('@')[0] : '') || 'user';
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (9)
backend/src/api/routes/auth.oauth.ts(2 hunks)backend/src/core/auth/auth.ts(7 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.google.ts(2 hunks)backend/src/core/auth/oauth.linkedin.ts(1 hunks)backend/src/core/auth/oauth.x.ts(1 hunks)backend/src/types/auth.ts(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
- backend/src/core/auth/oauth.github.ts
- backend/src/types/auth.ts
- backend/src/core/auth/oauth.x.ts
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-10-19T20:34:22.374Z
Learnt from: HarshSharma0801
Repo: InsForge/InsForge PR: 445
File: backend/src/core/auth/oauth.ts:189-190
Timestamp: 2025-10-19T20:34:22.374Z
Learning: For Facebook OAuth integration, the 'email' scope requires Meta App Review approval and Business Verification for production use. Without Advanced access, email permission only works for app admins and testers. Default scopes should use only 'public_profile' to avoid App Review requirements, and the FacebookUserInfo.email field should be optional to match the actual API behavior.
Applied to files:
backend/src/core/auth/oauth.facebook.ts
🧬 Code graph analysis (5)
backend/src/core/auth/oauth.linkedin.ts (4)
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)
LinkedInUserInfo(105-114)OAuthUserData(139-154)
backend/src/core/auth/auth.ts (8)
backend/src/core/auth/oauth.google.ts (1)
GoogleOAuthService(12-248)backend/src/core/auth/oauth.github.ts (1)
GitHubOAuthService(11-207)backend/src/core/auth/oauth.discord.ts (1)
DiscordOAuthService(11-194)backend/src/core/auth/oauth.linkedin.ts (1)
LinkedInOAuthService(11-239)backend/src/core/auth/oauth.facebook.ts (1)
FacebookOAuthService(11-193)backend/src/core/auth/oauth.microsoft.ts (1)
MicrosoftOAuthService(11-168)backend/src/core/auth/oauth.x.ts (1)
XOAuthService(8-201)backend/src/types/auth.ts (2)
XUserInfo(129-136)OAuthUserData(139-154)
backend/src/core/auth/oauth.discord.ts (4)
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)
DiscordUserInfo(98-103)OAuthUserData(139-154)
backend/src/core/auth/oauth.google.ts (1)
backend/src/types/auth.ts (2)
OAuthUserData(139-154)GoogleUserInfo(66-75)
backend/src/core/auth/oauth.facebook.ts (3)
backend/src/utils/environment.ts (1)
getApiBaseUrl(39-41)backend/src/utils/logger.ts (1)
logger(6-29)backend/src/types/auth.ts (2)
FacebookUserInfo(116-127)OAuthUserData(139-154)
⏰ 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). (3)
- GitHub Check: build-and-push
- GitHub Check: CI Pre-merge Check
- GitHub Check: E2E Tests
🔇 Additional comments (6)
backend/src/api/routes/auth.oauth.ts (2)
337-342: LGTM! Clean unified callback handlingThe refactor to use a single
handleSharedCallbackpathway is much cleaner than the previous per-provider logic. This delegates payload transformation to provider-specific services, improving maintainability.
401-405: State parameter correctly threaded through OAuth callbackThe addition of
stateto thehandleOAuthCallbackpayload is necessary for providers like X that require state for PKCE verification. This maintains proper OAuth flow semantics.backend/src/core/auth/oauth.facebook.ts (1)
170-192: Well-structured shared callback with defensive handlingThe nested picture structure handling (lines 178-179) and multiple userName fallbacks (line 181) demonstrate good defensive programming. Empty email handling aligns with Facebook's optional email behavior.
backend/src/core/auth/auth.ts (3)
64-108: Clean OAuth service initialization with cached singletonsThe centralized initialization of all OAuth services (lines 101-108) through cached singletons provides a clean, maintainable architecture. This eliminates the need for ad-hoc service instantiation throughout the codebase.
924-964: Unified OAuth callback flow with X provider supportThe refactored
handleOAuthCallbackdemonstrates excellent consolidation:
- Unified
OAuthUserDatareturn type across all providers- State parameter support for PKCE-based flows (X OAuth)
- Single
findOrCreateThirdPartyUsercall eliminates duplicationThis is a significant maintainability improvement over the previous per-provider approach.
970-1008: New unified shared callback handlerThe new
handleSharedCallbackmethod provides a clean pathway for shared OAuth flows, delegating to provider-specific services. The explicit error for Microsoft (lines 995-997) clearly documents that shared keys are not implemented for that provider.
Summary
How did you test this change?
Tested on cloud with OAuth project
Summary by CodeRabbit
New Features
Refactor
Chores