Skip to content

[Refactor] Simplify OAuth files - #594

Merged
Fermionic-Lyu merged 20 commits into
mainfrom
lyu-transition
Nov 17, 2025
Merged

Fermionic-Lyu merged 20 commits into
mainfrom
lyu-transition

Conversation

@Fermionic-Lyu

@Fermionic-Lyu Fermionic-Lyu commented Nov 16, 2025 •

Copy link
Copy Markdown
Member

Summary

  1. Refactor all oauth files into separate files for better maintainability.
  2. Added X Oauth (no shared keys support yet)

How did you test this change?

Tested on cloud with OAuth project

Summary by CodeRabbit

  • New Features

    • Added X (Twitter) as an OAuth provider across authentication flows and UI (login option, provider badge, and provider list).
  • Refactor

    • Consolidated third‑party OAuth into a unified, service‑based shared flow that standardizes callback handling and returned user data.
  • Chores

    • Added environment variables for configuring X OAuth.

@coderabbitai

coderabbitai Bot commented Nov 16, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Replaces per-provider OAuth handlers with provider-specific singleton services and a unified AuthService flow; adds OAuthUserData and XUserInfo types, new provider services (GitHub, Discord, LinkedIn, Facebook, Microsoft, X), updates routes to pass state and use shared callbacks, and surfaces X support in frontend and env example.

Changes

Cohort / File(s) Summary
Auth core refactor
backend/src/core/auth/auth.ts
AuthService now initializes cached singleton OAuth services, exposes unified generateOAuthUrl(provider, state?) and handleOAuthCallback(provider, payload) (state passed through), and removes many per-provider public methods in favor of service delegation.
API routes (shared & provider callbacks)
backend/src/api/routes/auth.oauth.ts
Shared OAuth callback now decodes payload uniformly into a generic map and delegates to authService.handleSharedCallback(validatedProvider, payloadData); provider callback forwards state into authService.handleOAuthCallback. Provider-specific parsing removed.
New provider service modules
backend/src/core/auth/oauth.github.ts, backend/src/core/auth/oauth.discord.ts, backend/src/core/auth/oauth.linkedin.ts, backend/src/core/auth/oauth.facebook.ts, backend/src/core/auth/oauth.microsoft.ts, backend/src/core/auth/oauth.x.ts, backend/src/core/auth/oauth.google.ts
Added singleton OAuth service classes implementing generateOAuthUrl, token exchange, user-info fetch, handleCallback, and handleSharedCallback, returning normalized OAuthUserData. Google adapted to the new return shape; X implements PKCE and per-state verifier lifecycle; LinkedIn adds token caching/processed-code guards.
Types
backend/src/types/auth.ts
Added OAuthUserData and XUserInfo, and extended identityData union to include XUserInfo.
Frontend: provider metadata & UI
frontend/src/features/auth/helpers.tsx, frontend/src/features/auth/components/OAuthConfigDialog.tsx, frontend/src/features/auth/components/UsersDataGrid.tsx
Added provider 'x' to oauthProviders and UI; special-case callback host remap for 'x' in callback URL builder; render X badge/icon in users grid.
Env example
.env.example
Added X_CLIENT_ID and X_CLIENT_SECRET entries.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

  • Files/areas needing extra attention:
    • Consistency of OAuthUserData shape across all provider services.
    • LinkedIn token caching, processed-code concurrency guards, and timed cleanup.
    • X PKCE verifier storage, retrieval, expiry and state threading.
    • Shared callback parsing/UTF-8 decoding and mapping to provider-specific handleSharedCallback.
    • Ensure no remaining references to removed per-provider findOrCreate* methods.

Possibly related PRs

Suggested reviewers

  • tonychang04

Poem

🐰 I hopped through keys and tokens bright,

stitched provider paths into one light,
a verifier tucked, a shared key found,
providers hum in a single round —
carrots for code and a joyful byte 🥕

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title '[Refactor] Simplify OAuth files' accurately reflects the main objective of the changeset—consolidating and simplifying OAuth implementation through refactoring.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch lyu-transition

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8ab10bf and 662a500.

⛔ Files ignored due to path filters (1)
  • frontend/src/assets/logos/x.svg is excluded by !**/*.svg
📒 Files selected for processing (2)
  • frontend/src/features/auth/components/OAuthConfigDialog.tsx (1 hunks)
  • frontend/src/features/auth/helpers.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • frontend/src/features/auth/helpers.tsx
  • frontend/src/features/auth/components/OAuthConfigDialog.tsx
⏰ 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

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: 8

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

129-142: Tighten provider typing for better safety and autocomplete

provider is currently a plain string, 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 exported OAuthProvider type) 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 of clientId before building the auth URL

If config.clientId is missing, this still generates an auth URL with an empty client_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 explicitly

Returning response.data directly as FacebookUserInfo is fine, and the requested fields ensure all properties used later (id, email, 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 considerations

The normalization here is consistent with the GitHub OAuth service and should behave well. The only edge case is if payloadData.login is unexpectedly missing while payloadData.email is 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 needed

The code handles missing config, builds a correct form-encoded body, and logs structured details on failure. Returning both access_token and optional id_token keeps the surface flexible for future use, even though the current flow only uses access_token.


119-143: User info retrieval is straightforward; be cautious about logging full error objects

The Graph /me call and normalization (id, email with sensible fallback, name) are solid. The only concern is logger.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 unused

The callback orchestration (require code, exchange for tokens, fetch user info, map to OAuthUserData) is clean and aligns with the generic AuthService flow. Since the token field in payload is 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 deliberate

The 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 trimmed

Using LinkedIn’s JWKS, validating issuer and audience, and mapping claims into LinkedInUserInfo is the right approach. Similar to other providers, consider logging a reduced error shape instead of the full object in logger.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 straightforward

Initializing 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.provider

Delegating to per-provider handleCallback methods and then funneling everything through findOrCreateThirdPartyUser is exactly the right consolidation.

One small robustness tweak: since provider is already validated as OAuthProvidersSchema, you could pass it through instead of userData.provider when calling findOrCreateThirdPartyUser, 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

📥 Commits

Reviewing files that changed from the base of the PR and between 0df9c46 and c24f0d4.

📒 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 solid

The 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 email

The fallback to /user/emails when user.email is missing, plus the final fallback to the users.noreply.github.com address, 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 consistent

The 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-structured

Using application/x-www-form-urlencoded with URLSearchParams for 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 fallbacks

Mapping global_name || username and 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 model

Importing GoogleUserInfo and OAuthUserData here keeps the Google service in sync with the shared OAuth typing introduced in auth.ts. No issues.


206-227: Unified Google callback flow looks correct and consistent

The 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 GoogleUserInfo into OAuthUserData with stable fallbacks (name or email local part for userName, 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 sending token is indeed passing the Google ID token, not the access token. A quick repo-wide search for handleCallback( on GoogleOAuthService and 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 correct

The 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 providers

Using the Graph API /oauth/access_token endpoint 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 good

Username and email fallbacks here mirror the Discord OAuth service behavior (including the noreply.discord.local pattern), so the shared callback path should behave consistently with direct Discord OAuth.


409-421: Facebook shared-callback normalization aligns with direct service behavior

The 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 pattern

The 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 correct

Both 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/callback and per-provider callback flows.


195-217: LinkedIn callback handler correctly supports both token and code paths

Handling 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 design

Pulling 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 handling

Importing OAuthUserData here 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 fit

Storing 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 AuthService

The switch cleanly maps each provider enum value to the corresponding service method, and the default case sensibly rejects unsupported providers.

Comment thread backend/src/api/routes/auth.oauth.ts Resolved
Comment thread backend/src/api/routes/auth.oauth.ts Resolved
Comment on lines +38 to +55
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 || '';
}

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 | 🟡 Minor

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.

Suggested change
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.

Comment on lines +153 to +171
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,
};

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 | 🟡 Minor

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.

Comment on lines +38 to +54
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 || '';
}

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 | 🟡 Minor

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.

Suggested change
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.

Comment on lines +142 to +164
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,
};

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 | 🟡 Minor

Clarify token usage and email fallback behavior in Facebook callback

handleCallback currently:

  • Requires payload.code and ignores payload.token, despite the type allowing both.
  • Falls back to an empty string for missing email, even though OAuthUserData.email is 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.

Comment on lines +38 to +55
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 || '';
}

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 | 🟡 Minor

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.

Comment on lines +164 to +182
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,
};

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 | 🟡 Minor

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.

@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 (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 if payloadData.email is 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

📥 Commits

Reviewing files that changed from the base of the PR and between c24f0d4 and 7959b68.

⛔ Files ignored due to path filters (1)
  • frontend/src/assets/logos/x.svg is 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://localhost but accept http://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 findOrCreateThirdPartyUser flow.

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/twitter endpoint 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/twitter endpoint, or update to use the /auth/v1/shared/x pattern 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.login which 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:

  1. Each provider service returns standardized OAuthUserData
  2. Single findOrCreateThirdPartyUser method handles all providers
  3. Type safety maintained through discriminated unions

This significantly improves code maintainability.


926-926: State parameter addition enables PKCE flows.

Adding optional state to 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.

Comment thread frontend/src/features/auth/helpers.tsx Resolved

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

honestly looks fine to me. it's fine without code rabbit's suggestion

@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 (4)
backend/src/core/auth/oauth.facebook.ts (2)

38-54: Guard against missing auth URL from shared Facebook OAuth

Line 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 implementation

Similar to Discord, the signature accepts { code?: string; token?: string } but only the code path 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 flow

The handleCallback signature accepts { code?: string; token?: string } but the implementation only uses the code path (lines 154-156). The token field is never used.

Either:

  1. Narrow the type to require code:
-  async handleCallback(payload: { code?: string; token?: string }): Promise<OAuthUserData> {
+  async handleCallback(payload: { code: string }): Promise<OAuthUserData> {
  1. Or implement token-based handling if needed for the Discord OAuth flow.

38-55: Fail fast when shared OAuth endpoint doesn't return a URL

Line 54 returns an empty string when the cloud endpoint doesn't provide auth_url or url. 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 callback

Line 243 has the same pattern as handleCallback: name || email.split('@')[0]. If email is an empty string (from line 235), this produces an empty userName.

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 derivation

Line 208 derives userName using linkedinUserInfo.name || linkedinUserInfo.email.split('@')[0]. Since verifyToken may return an empty email (line 178), this could result in an empty userName.

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 callback

Line 228 uses the same pattern that could produce an empty userName if both name and email are empty.

Apply 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

📥 Commits

Reviewing files that changed from the base of the PR and between 7959b68 and 8ab10bf.

📒 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 handling

The refactor to use a single handleSharedCallback pathway 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 callback

The addition of state to the handleOAuthCallback payload 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 handling

The 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 singletons

The 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 support

The refactored handleOAuthCallback demonstrates excellent consolidation:

  • Unified OAuthUserData return type across all providers
  • State parameter support for PKCE-based flows (X OAuth)
  • Single findOrCreateThirdPartyUser call eliminates duplication

This is a significant maintainability improvement over the previous per-provider approach.


970-1008: New unified shared callback handler

The new handleSharedCallback method 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.

Comment thread backend/src/core/auth/oauth.google.ts Resolved
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.

4 participants