Repository navigation
feat: support X/twitter OAuth - #578
Conversation
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. Please check the settings in the CodeRabbit UI or the You can disable this status message by setting the WalkthroughAdds X (Twitter) OAuth support: new env keys, a backend XOAuthService with PKCE, token exchange, userinfo and find-or-create session flow, wiring into auth routes/core, a new XUserInfo type, and frontend UI/provider list updates. Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes
Possibly related PRs
Suggested reviewers
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 5
📜 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 (7)
.env.example(1 hunks)backend/src/api/routes/auth.oauth.ts(2 hunks)backend/src/core/auth/auth.ts(10 hunks)backend/src/types/auth.ts(1 hunks)frontend/src/features/auth/components/OAuthConfigDialog.tsx(1 hunks)frontend/src/features/auth/components/UsersDataGrid.tsx(1 hunks)frontend/src/features/auth/helpers.tsx(2 hunks)
🧰 Additional context used
📓 Path-based instructions (11)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
**/*.{ts,tsx}: Use TypeScript for all code files
Use ES modules (import/export syntax)
Prefer descriptive, unabbreviated variable and function names
Implement proper error handling with try-catch blocks and logging where appropriate
Use single quotes for strings
Include semicolons at the end of statements
Use arrow functions for callbacks and inline functions
Prefer const over let; avoid var
Use template literals for string interpolation
Maintain 2-space indentation
Format code with the repository Prettier configuration
Variables, parameters, properties, and functions must use camelCase
Constants and enum members must use UPPER_CASE
Include JSDoc comments for complex functions
Files:
backend/src/types/auth.tsfrontend/src/features/auth/components/UsersDataGrid.tsxfrontend/src/features/auth/helpers.tsxbackend/src/api/routes/auth.oauth.tsfrontend/src/features/auth/components/OAuthConfigDialog.tsxbackend/src/core/auth/auth.ts
backend/src/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
backend/src/**/*.{ts,tsx}: Use async/await for asynchronous operations in the backend
Use Zod schemas for request/response validation
Return consistent API responses using utility functions
Validate all user inputs
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper caching strategies (server-side)
Files:
backend/src/types/auth.tsbackend/src/api/routes/auth.oauth.tsbackend/src/core/auth/auth.ts
**/*.{tsx,ts}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
React components and TypeScript types/interfaces must use PascalCase
Files:
backend/src/types/auth.tsfrontend/src/features/auth/components/UsersDataGrid.tsxfrontend/src/features/auth/helpers.tsxbackend/src/api/routes/auth.oauth.tsfrontend/src/features/auth/components/OAuthConfigDialog.tsxbackend/src/core/auth/auth.ts
**/[a-z][a-z0-9-]*.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Utility files should use kebab-case or camelCase (kebab-case validated here)
Files:
backend/src/types/auth.tsbackend/src/api/routes/auth.oauth.tsbackend/src/core/auth/auth.ts
frontend/src/**/*.{tsx,ts}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
frontend/src/**/*.{tsx,ts}: Use functional React components with hooks exclusively
Use Radix UI primitives for accessibility
Optimize React component re-renders
Files:
frontend/src/features/auth/components/UsersDataGrid.tsxfrontend/src/features/auth/helpers.tsxfrontend/src/features/auth/components/OAuthConfigDialog.tsx
frontend/src/**/*.tsx
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
frontend/src/**/*.tsx: Implement TypeScript interfaces/types for all component props
Follow component composition patterns; keep components focused and single-purpose
Implement proper loading and error states in UI
Use a consistent icon set from lucide-react
Files:
frontend/src/features/auth/components/UsersDataGrid.tsxfrontend/src/features/auth/helpers.tsxfrontend/src/features/auth/components/OAuthConfigDialog.tsx
frontend/src/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
frontend/src/**/*.{ts,tsx}: Use TanStack Query for server state management
Use React Hook Form for form handling with Zod validation
Optimize bundle size with proper imports
Files:
frontend/src/features/auth/components/UsersDataGrid.tsxfrontend/src/features/auth/helpers.tsxfrontend/src/features/auth/components/OAuthConfigDialog.tsx
frontend/src/**/[A-Z]*.tsx
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Component files must use PascalCase filenames (e.g., DataGrid.tsx)
Files:
frontend/src/features/auth/components/UsersDataGrid.tsxfrontend/src/features/auth/components/OAuthConfigDialog.tsx
**/.env.example
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Document environment variables and configuration in .env.example
Files:
.env.example
backend/src/api/**/*.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
backend/src/api/**/*.ts: Implement authentication and error-handling middleware
Follow RESTful conventions for API endpoints
Implement rate limiting for API endpoints
Files:
backend/src/api/routes/auth.oauth.ts
backend/src/{controllers,core}/**/*.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Implement proper database transaction handling
Files:
backend/src/core/auth/auth.ts
🧠 Learnings (2)
📚 Learning: 2025-10-15T18:18:47.519Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.519Z
Learning: Applies to frontend/src/**/*.tsx : Use a consistent icon set from lucide-react
Applied to files:
frontend/src/features/auth/components/UsersDataGrid.tsx
📚 Learning: 2025-10-15T18:18:47.519Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.519Z
Learning: Applies to **/.env.example : Document environment variables and configuration in .env.example
Applied to files:
.env.example
🧬 Code graph analysis (1)
backend/src/core/auth/auth.ts (4)
backend/src/types/auth.ts (1)
XUserInfo(129-136)backend/src/core/auth/oauth.config.ts (1)
OAuthConfigService(26-441)backend/src/app.config.ts (1)
config(30-54)backend/src/utils/environment.ts (1)
getApiBaseUrl(39-41)
🔇 Additional comments (14)
.env.example (1)
70-73: LGTM! Consistent with existing OAuth provider patterns.The X OAuth environment variables follow the same naming convention and structure as other OAuth providers in the file.
frontend/src/features/auth/components/UsersDataGrid.tsx (1)
66-71: LGTM! Provider icon follows existing patterns.The X provider case is correctly implemented and follows the same structure as other OAuth providers.
frontend/src/features/auth/components/OAuthConfigDialog.tsx (1)
78-78: LGTM! Enables shared key support for X provider.The addition of 'x' to the sharedKeyProviders array correctly enables shared OAuth key functionality for X in cloud deployments.
backend/src/types/auth.ts (1)
129-136: LGTM! Interface structure aligns with Twitter API v2.The XUserInfo interface correctly defines the structure for X (Twitter) user data with appropriate field types and optionality.
frontend/src/features/auth/helpers.tsx (2)
8-8: LGTM! Icon import follows existing pattern.
67-73: LGTM! Provider configuration is complete and consistent.The X OAuth provider entry includes all required fields and follows the same structure as other OAuth providers.
backend/src/api/routes/auth.oauth.ts (1)
501-501: LGTM! State parameter required for PKCE flow.The addition of state to the handleOAuthCallback payload is necessary to support PKCE verification for X OAuth.
backend/src/core/auth/auth.ts (7)
38-38: LGTM! XUserInfo import added.
61-62: LGTM! PKCE verifier storage initialized.The verifierCodes Map is appropriately initialized for storing PKCE verifiers with state-based cleanup.
Also applies to: 96-97
739-739: LGTM! XUserInfo added to identity data unions.The type unions correctly include XUserInfo for the X OAuth flow.
Also applies to: 826-826
1676-1698: LGTM! User info retrieval correctly uses Twitter API v2.The getXUserInfo method properly fetches user data from Twitter API v2 with appropriate fields.
1744-1745: LGTM! X provider added to generateOAuthUrl switch.
1756-1756: LGTM! State parameter added for PKCE support.The payload type correctly includes the optional state parameter needed for PKCE flows.
1783-1784: LGTM! X provider added to handleOAuthCallback switch.
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (4)
backend/src/core/auth/auth.ts (4)
1547-1610: Fix redundant checks and endpoint inconsistency.Multiple issues in this method:
Redundant state check (lines 1570-1574): State is already validated at lines 1562-1564, making the check inside the
useSharedKeyblock redundant.Shared key endpoint inconsistency (line 1580): Uses
/oauth/twitterinstead of the/auth/v1/shared/xpattern used by other providers (e.g., GitHub uses/auth/v1/shared/githubat line 900, LinkedIn uses/auth/v1/shared/linkedinat line 1270).State set twice (lines 1602 and 1606-1608): The state parameter is set at line 1602, then set again conditionally at lines 1606-1608, which is redundant.
Apply this diff to fix all three issues:
this.verifierCodes.set(state, verifier); setTimeout(() => { this.verifierCodes.delete(state); }, 600000); if (config?.useSharedKey) { - if (!state) { - logger.warn('Shared X OAuth called without state parameter'); - throw new Error('State parameter is required for shared X OAuth'); - } - // Use shared keys if configured const cloudBasedUrl = process.env.CLOUD_API_HOST || 'https://api.insforge.dev'; const redirectUri = `${selfBaseUrl}/api/auth/oauth/shared/callback/${state}`; const response = await axios.get( - `${cloudBasedUrl}/oauth/twitter?redirect_uri=${encodeURIComponent(redirectUri)}`, + `${cloudBasedUrl}/auth/v1/shared/x?redirect_uri=${encodeURIComponent(redirectUri)}`, { headers: { 'Content-Type': 'application/json', }, } ); return response.data.auth_url || response.data.url || ''; } logger.debug('X OAuth Config (fresh from DB):', { clientId: config.clientId ? 'SET' : 'NOT SET', }); const authUrl = new URL('https://twitter.com/i/oauth2/authorize'); authUrl.searchParams.set('response_type', 'code'); authUrl.searchParams.set('client_id', config.clientId ?? ''); authUrl.searchParams.set('redirect_uri', `${selfBaseUrl}/api/auth/oauth/x/callback`); authUrl.searchParams.set( 'scope', config.scopes ? config.scopes.join(' ') : 'tweet.read users.read' ); authUrl.searchParams.set('state', state ?? ''); authUrl.searchParams.set('code_challenge', challenge); authUrl.searchParams.set('code_challenge_method', 'S256'); - if (state) { - authUrl.searchParams.set('state', state); - } return authUrl.toString();
1612-1656: Fix incorrect error message.Line 1652 has a copy-paste error: the error message says "Failed to get access token from GitHub" but should reference "X".
Apply this diff:
if (!response.data.access_token) { - throw new Error('Failed to get access token from GitHub'); + throw new Error('Failed to get access token from X'); }
1682-1697: Fix incorrect comment and handle missing username.Two issues:
- Line 1683: Comment incorrectly says "Find or create LinkedIn user" instead of "X user".
- Line 1686: The code assumes
usernameornameexists, but both are optional in XUserInfo (username) or could be empty (name). If both are undefined/empty, this will create an email like[email protected].Apply this diff:
/** - * Find or create LinkedIn user + * Find or create X user */ async findOrCreateXUser(xUserInfo: XUserInfo): Promise<CreateSessionResponse> { - const userName = xUserInfo.username || xUserInfo.name; + const userName = xUserInfo.username || xUserInfo.name || `user_${xUserInfo.id.substring(0, 8)}`; const email = `${userName}@users.noreply.x.local`;
1857-1872: Fix incorrect comment.Line 1858 has a copy-paste error: the comment says "Handle GitHub OAuth callback" instead of "Handle X OAuth callback".
Apply this diff:
/** - * Handle GitHub OAuth callback + * Handle X OAuth callback */ private async handleXCallback(payload: {
🧹 Nitpick comments (1)
backend/src/core/auth/auth.ts (1)
61-62: Inconsistent capitalization in comment.Use "OAuth" instead of "Oauth" for consistency with line 58 and standard OAuth terminology.
Apply this diff:
- // Oauth helper for X(Twitter) + // OAuth helper for X(Twitter) private verifierCodes: Map<string, string>;
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
backend/src/api/routes/auth.oauth.ts(2 hunks)backend/src/core/auth/auth.ts(10 hunks)frontend/src/features/auth/helpers.tsx(2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- backend/src/api/routes/auth.oauth.ts
🧰 Additional context used
📓 Path-based instructions (8)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
**/*.{ts,tsx}: Use TypeScript for all code files
Use ES modules (import/export syntax)
Prefer descriptive, unabbreviated variable and function names
Implement proper error handling with try-catch blocks and logging where appropriate
Use single quotes for strings
Include semicolons at the end of statements
Use arrow functions for callbacks and inline functions
Prefer const over let; avoid var
Use template literals for string interpolation
Maintain 2-space indentation
Format code with the repository Prettier configuration
Variables, parameters, properties, and functions must use camelCase
Constants and enum members must use UPPER_CASE
Include JSDoc comments for complex functions
Files:
backend/src/core/auth/auth.tsfrontend/src/features/auth/helpers.tsx
backend/src/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
backend/src/**/*.{ts,tsx}: Use async/await for asynchronous operations in the backend
Use Zod schemas for request/response validation
Return consistent API responses using utility functions
Validate all user inputs
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper caching strategies (server-side)
Files:
backend/src/core/auth/auth.ts
backend/src/{controllers,core}/**/*.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Implement proper database transaction handling
Files:
backend/src/core/auth/auth.ts
**/*.{tsx,ts}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
React components and TypeScript types/interfaces must use PascalCase
Files:
backend/src/core/auth/auth.tsfrontend/src/features/auth/helpers.tsx
**/[a-z][a-z0-9-]*.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Utility files should use kebab-case or camelCase (kebab-case validated here)
Files:
backend/src/core/auth/auth.ts
frontend/src/**/*.{tsx,ts}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
frontend/src/**/*.{tsx,ts}: Use functional React components with hooks exclusively
Use Radix UI primitives for accessibility
Optimize React component re-renders
Files:
frontend/src/features/auth/helpers.tsx
frontend/src/**/*.tsx
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
frontend/src/**/*.tsx: Implement TypeScript interfaces/types for all component props
Follow component composition patterns; keep components focused and single-purpose
Implement proper loading and error states in UI
Use a consistent icon set from lucide-react
Files:
frontend/src/features/auth/helpers.tsx
frontend/src/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
frontend/src/**/*.{ts,tsx}: Use TanStack Query for server state management
Use React Hook Form for form handling with Zod validation
Optimize bundle size with proper imports
Files:
frontend/src/features/auth/helpers.tsx
🧠 Learnings (1)
📚 Learning: 2025-10-15T18:18:47.519Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.519Z
Learning: Applies to backend/src/api/**/*.ts : Implement authentication and error-handling middleware
Applied to files:
backend/src/core/auth/auth.ts
🧬 Code graph analysis (1)
backend/src/core/auth/auth.ts (6)
backend/src/types/auth.ts (1)
XUserInfo(129-136)backend/src/core/auth/oauth.config.ts (1)
OAuthConfigService(26-464)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)shared-schemas/src/auth-api.schema.ts (1)
CreateSessionResponse(324-324)
🔇 Additional comments (9)
frontend/src/features/auth/helpers.tsx (2)
8-8: LGTM!The X logo import follows the established pattern for other OAuth provider logos.
68-74: LGTM!The X OAuth provider entry is well-structured and consistent with existing provider patterns.
backend/src/core/auth/auth.ts (7)
38-38: LGTM!The XUserInfo import is correctly added and necessary for X OAuth implementation.
702-702: LGTM!XUserInfo correctly added to the union type for third-party OAuth identity data.
808-808: LGTM!XUserInfo correctly added to maintain consistency with the findOrCreateThirdPartyUser signature.
1658-1680: LGTM!The X user info retrieval correctly uses Twitter API v2 and requests appropriate user fields.
1726-1727: LGTM!The 'x' provider case is correctly integrated into the OAuth URL generation routing.
1738-1738: LGTM!Adding state to the payload type is necessary for X OAuth's PKCE flow and aligns with OAuth best practices.
1765-1766: LGTM!The 'x' provider case is correctly integrated into the OAuth callback handling routing.
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (2)
backend/src/core/auth/auth.ts (2)
1570-1574: Remove redundant state validation.State is already validated at lines 1562-1564, making this second check inside the
useSharedKeyblock redundant.Apply this diff:
if (config?.useSharedKey) { - if (!state) { - logger.warn('Shared X OAuth called without state parameter'); - throw new Error('State parameter is required for shared X OAuth'); - } - // Use shared keys if configured
1685-1687: Add fallback for missing username and name.If both
xUserInfo.usernameandxUserInfo.nameare undefined or empty strings,userNamewill be undefined, resulting in an invalid email like[email protected]. While the type definition showsnameas required, defensive coding is warranted.Apply this diff to add a proper fallback:
async findOrCreateXUser(xUserInfo: XUserInfo): Promise<CreateSessionResponse> { - const userName = xUserInfo.username || xUserInfo.name; + const userName = xUserInfo.username || xUserInfo.name || `user${xUserInfo.id.substring(0, 8)}`; const email = `${userName}@users.noreply.x.local`;
🧹 Nitpick comments (1)
backend/src/core/auth/auth.ts (1)
1553-1558: Consider moving PKCE generation after config validation.The PKCE verifier and challenge are generated before checking if the X OAuth config exists. If the config is missing, this wastes cryptographic entropy and CPU cycles.
Consider this refactor:
async generateXOAuthUrl(state?: string): Promise<string> { const oauthConfigService = OAuthConfigService.getInstance(); const config = await oauthConfigService.getConfigByProvider('x'); - const verifier = crypto.randomBytes(32).toString('base64url'); - const challenge = crypto.createHash('sha256').update(verifier).digest('base64url'); if (!config) { throw new Error('X OAuth not configured'); } + + const verifier = crypto.randomBytes(32).toString('base64url'); + const challenge = crypto.createHash('sha256').update(verifier).digest('base64url'); const selfBaseUrl = getApiBaseUrl();
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
backend/src/api/routes/auth.oauth.ts(2 hunks)backend/src/core/auth/auth.ts(10 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- backend/src/api/routes/auth.oauth.ts
🧰 Additional context used
📓 Path-based instructions (5)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
**/*.{ts,tsx}: Use TypeScript for all code files
Use ES modules (import/export syntax)
Prefer descriptive, unabbreviated variable and function names
Implement proper error handling with try-catch blocks and logging where appropriate
Use single quotes for strings
Include semicolons at the end of statements
Use arrow functions for callbacks and inline functions
Prefer const over let; avoid var
Use template literals for string interpolation
Maintain 2-space indentation
Format code with the repository Prettier configuration
Variables, parameters, properties, and functions must use camelCase
Constants and enum members must use UPPER_CASE
Include JSDoc comments for complex functions
Files:
backend/src/core/auth/auth.ts
backend/src/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
backend/src/**/*.{ts,tsx}: Use async/await for asynchronous operations in the backend
Use Zod schemas for request/response validation
Return consistent API responses using utility functions
Validate all user inputs
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper caching strategies (server-side)
Files:
backend/src/core/auth/auth.ts
backend/src/{controllers,core}/**/*.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Implement proper database transaction handling
Files:
backend/src/core/auth/auth.ts
**/*.{tsx,ts}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
React components and TypeScript types/interfaces must use PascalCase
Files:
backend/src/core/auth/auth.ts
**/[a-z][a-z0-9-]*.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Utility files should use kebab-case or camelCase (kebab-case validated here)
Files:
backend/src/core/auth/auth.ts
🧠 Learnings (1)
📚 Learning: 2025-10-15T18:18:47.519Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.519Z
Learning: Applies to backend/src/api/**/*.ts : Implement authentication and error-handling middleware
Applied to files:
backend/src/core/auth/auth.ts
🧬 Code graph analysis (1)
backend/src/core/auth/auth.ts (4)
backend/src/types/auth.ts (1)
XUserInfo(129-136)backend/src/core/auth/oauth.config.ts (1)
OAuthConfigService(26-464)backend/src/app.config.ts (1)
config(30-54)backend/src/utils/environment.ts (1)
getApiBaseUrl(39-41)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: CI Pre-merge Check
- GitHub Check: E2E Tests
🔇 Additional comments (6)
backend/src/core/auth/auth.ts (6)
702-702: LGTM!XUserInfo correctly added to union types, consistent with other OAuth providers.
Also applies to: 808-808
1612-1656: LGTM!PKCE code exchange implementation is correct:
- Retrieves and validates verifier by state
- Immediately deletes verifier to prevent replay attacks
- Uses proper Twitter OAuth 2.0 token endpoint with Basic auth
- Includes required PKCE code_verifier parameter
1658-1680: LGTM!Twitter user info retrieval is correctly implemented using the v2 API endpoint with appropriate fields.
1726-1727: LGTM!X OAuth case correctly integrated into the provider switch statement.
1738-1738: LGTM!State parameter correctly added to payload signature (required for PKCE), and X OAuth case properly integrated.
Also applies to: 1765-1766
1857-1872: LGTM!X OAuth callback handler correctly implemented:
- Validates required code and state parameters
- Exchanges authorization code for token using PKCE verifier
- Fetches and processes user info
- Integrates with existing user creation flow
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (5)
backend/src/core/auth/auth.ts (5)
1577-1577: Verify shared key endpoint path.Line 1577 uses
/oauth/twitterbut other providers follow the/auth/v1/shared/{provider}pattern (e.g., GitHub uses/auth/v1/shared/githubat line 900). Verify this is the correct endpoint or update to match the pattern.
61-62: Fix capitalization: "Oauth" should be "OAuth".The comment uses "Oauth" but standard capitalization is "OAuth" (capital A and capital H).
Apply this diff:
- // OAuth helper for X(Twitter) + // OAuth helper for X(Twitter)Also applies to line 96.
96-97: In-memory PKCE verifier storage unsuitable for production.The
verifierCodesMap stores PKCE verifiers in-memory, which will fail in multi-instance or load-balanced deployments where the callback request might be handled by a different instance that doesn't have the verifier.Consider using Redis or a database table with TTL support for production environments.
1567-1571: Remove redundant state validation.State is already validated at lines 1559-1561, making the second check inside the
if (config?.useSharedKey)block at lines 1568-1571 redundant.Apply this diff:
}, 600000); if (config?.useSharedKey) { - if (!state) { - logger.warn('Shared X OAuth called without state parameter'); - throw new Error('State parameter is required for shared X OAuth'); - } - // Use shared keys if configured const cloudBasedUrl = process.env.CLOUD_API_HOST || 'https://api.insforge.dev';
1603-1605: Remove duplicate state parameter setting.The
stateparameter is set twice: once at line 1599 withstate ?? ''and again at lines 1603-1605 conditionally. Since state is validated as non-null at line 1559-1561, the second assignment is redundant.Apply this diff:
authUrl.searchParams.set('state', state ?? ''); authUrl.searchParams.set('code_challenge', challenge); authUrl.searchParams.set('code_challenge_method', 'S256'); - if (state) { - authUrl.searchParams.set('state', state); - } return authUrl.toString();
🧹 Nitpick comments (1)
backend/src/core/auth/auth.ts (1)
1550-1553: Move PKCE generation after config validation.The PKCE verifier and challenge are generated at lines 1550-1551 before checking if the X OAuth configuration exists at line 1553. If the config is missing, these crypto operations are wasted.
Apply this diff:
async generateXOAuthUrl(state?: string): Promise<string> { const oauthConfigService = OAuthConfigService.getInstance(); const config = await oauthConfigService.getConfigByProvider('x'); - const verifier = crypto.randomBytes(32).toString('base64url'); - const challenge = crypto.createHash('sha256').update(verifier).digest('base64url'); if (!config) { throw new Error('X OAuth not configured'); } + const verifier = crypto.randomBytes(32).toString('base64url'); + const challenge = crypto.createHash('sha256').update(verifier).digest('base64url'); + const selfBaseUrl = getApiBaseUrl();
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
backend/src/core/auth/auth.ts(10 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
**/*.{ts,tsx}: Use TypeScript for all code files
Use ES modules (import/export syntax)
Prefer descriptive, unabbreviated variable and function names
Implement proper error handling with try-catch blocks and logging where appropriate
Use single quotes for strings
Include semicolons at the end of statements
Use arrow functions for callbacks and inline functions
Prefer const over let; avoid var
Use template literals for string interpolation
Maintain 2-space indentation
Format code with the repository Prettier configuration
Variables, parameters, properties, and functions must use camelCase
Constants and enum members must use UPPER_CASE
Include JSDoc comments for complex functions
Files:
backend/src/core/auth/auth.ts
backend/src/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
backend/src/**/*.{ts,tsx}: Use async/await for asynchronous operations in the backend
Use Zod schemas for request/response validation
Return consistent API responses using utility functions
Validate all user inputs
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper caching strategies (server-side)
Files:
backend/src/core/auth/auth.ts
backend/src/{controllers,core}/**/*.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Implement proper database transaction handling
Files:
backend/src/core/auth/auth.ts
**/*.{tsx,ts}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
React components and TypeScript types/interfaces must use PascalCase
Files:
backend/src/core/auth/auth.ts
**/[a-z][a-z0-9-]*.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Utility files should use kebab-case or camelCase (kebab-case validated here)
Files:
backend/src/core/auth/auth.ts
🧠 Learnings (1)
📚 Learning: 2025-10-15T18:18:47.519Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.519Z
Learning: Applies to backend/src/api/**/*.ts : Implement authentication and error-handling middleware
Applied to files:
backend/src/core/auth/auth.ts
🧬 Code graph analysis (1)
backend/src/core/auth/auth.ts (6)
backend/src/types/auth.ts (1)
XUserInfo(129-136)backend/src/core/auth/oauth.config.ts (1)
OAuthConfigService(26-464)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)shared-schemas/src/auth-api.schema.ts (1)
CreateSessionResponse(324-324)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: CI Pre-merge Check
- GitHub Check: E2E Tests
🔇 Additional comments (8)
backend/src/core/auth/auth.ts (8)
702-702: LGTM: Type unions properly extended.The
XUserInfotype is correctly added to the union types for bothfindOrCreateThirdPartyUserandcreateThirdPartyUser, following the existing pattern for other OAuth providers.Also applies to: 808-808
1609-1653: LGTM: PKCE token exchange correctly implemented.The token exchange flow properly:
- Retrieves and validates the PKCE verifier
- Immediately deletes the verifier to prevent replay attacks
- Includes the
code_verifierin the token request- Uses Basic authentication as required by Twitter OAuth 2.0
- Handles errors appropriately
1655-1677: LGTM: User info retrieval correctly implemented.The method correctly uses Twitter API v2 to fetch user information with appropriate fields and returns data matching the
XUserInfotype structure.
1679-1694: LGTM: User creation logic properly implemented.The username fallback logic correctly handles cases where
usernameornamemight be missing, providing a sensible default. The implementation follows the existing pattern used by other OAuth providers.
1723-1724: LGTM: OAuth URL generation routing updated.The case for provider 'x' is correctly added and delegates to the X-specific OAuth URL generation method, following the pattern used by other providers.
1735-1735: LGTM: Payload type extended for PKCE support.Adding
stateto the payload type is necessary for X OAuth's PKCE flow, where the state parameter is used to retrieve the corresponding code verifier.
1762-1763: LGTM: OAuth callback routing updated.The case for provider 'x' is correctly added and delegates to the X-specific callback handler, following the pattern used by other providers.
1854-1869: LGTM: X OAuth callback handler correctly implemented.The callback handler properly validates that both
codeandstateare present (required for PKCE), exchanges the authorization code for an access token, fetches user information, and creates or finds the user record. The implementation follows the established pattern.
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
backend/src/api/routes/auth.oauth.ts (1)
480-517: Validate verifier presence for X provider.The current implementation defaults
verifierto an empty string whencodeVerifieris missing from the state (line 489). For the X provider, which requires PKCE, an empty verifier will cause authentication to fail. Additionally, the verifier is passed to all providers (line 517), even though only the X provider needs it.Consider validating that verifier is present when the provider is 'x', or handle the empty verifier case explicitly in the X callback handler.
Example approach - validate in the X callback:
// In the provider callback validation section (after line 512) if (validatedProvider === 'x' && !verifier) { throw new AppError( 'PKCE verifier is required for X OAuth', 400, ERROR_CODES.INVALID_INPUT ); }
🧹 Nitpick comments (1)
backend/src/core/auth/auth.ts (1)
1545-1591: Review required parameters enforcement.Lines 1555-1557 throw an error if
stateorchallengeare missing. However, this breaks the optional pattern used by other OAuth providers (e.g., GitHub, Discord at lines 913-915, 970-972). While X requires PKCE, the error handling could be more specific and the parameters should remain optional in the signature for consistency.Consider making the validation more specific:
- if (!state || !challenge) { - throw new Error('State and Challenge parameter is required.'); + if (!state) { + throw new Error('State parameter is required for X OAuth.'); + } + if (!challenge) { + throw new Error('PKCE challenge is required for X OAuth.'); }However, since the route handler always provides these for provider 'x', this validation may be defensive. Consider whether throwing here is the right approach or if the calling code should guarantee these values.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
backend/src/api/routes/auth.oauth.ts(5 hunks)backend/src/core/auth/auth.ts(9 hunks)frontend/src/features/auth/components/OAuthConfigDialog.tsx(2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- frontend/src/features/auth/components/OAuthConfigDialog.tsx
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
**/*.{ts,tsx}: Use TypeScript for all code files
Use ES modules (import/export syntax)
Prefer descriptive, unabbreviated variable and function names
Implement proper error handling with try-catch blocks and logging where appropriate
Use single quotes for strings
Include semicolons at the end of statements
Use arrow functions for callbacks and inline functions
Prefer const over let; avoid var
Use template literals for string interpolation
Maintain 2-space indentation
Format code with the repository Prettier configuration
Variables, parameters, properties, and functions must use camelCase
Constants and enum members must use UPPER_CASE
Include JSDoc comments for complex functions
Files:
backend/src/api/routes/auth.oauth.tsbackend/src/core/auth/auth.ts
backend/src/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
backend/src/**/*.{ts,tsx}: Use async/await for asynchronous operations in the backend
Use Zod schemas for request/response validation
Return consistent API responses using utility functions
Validate all user inputs
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper caching strategies (server-side)
Files:
backend/src/api/routes/auth.oauth.tsbackend/src/core/auth/auth.ts
backend/src/api/**/*.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
backend/src/api/**/*.ts: Implement authentication and error-handling middleware
Follow RESTful conventions for API endpoints
Implement rate limiting for API endpoints
Files:
backend/src/api/routes/auth.oauth.ts
**/*.{tsx,ts}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
React components and TypeScript types/interfaces must use PascalCase
Files:
backend/src/api/routes/auth.oauth.tsbackend/src/core/auth/auth.ts
**/[a-z][a-z0-9-]*.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Utility files should use kebab-case or camelCase (kebab-case validated here)
Files:
backend/src/api/routes/auth.oauth.tsbackend/src/core/auth/auth.ts
backend/src/{controllers,core}/**/*.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Implement proper database transaction handling
Files:
backend/src/core/auth/auth.ts
🧠 Learnings (1)
📚 Learning: 2025-10-15T18:18:47.519Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.519Z
Learning: Applies to backend/src/api/**/*.ts : Implement authentication and error-handling middleware
Applied to files:
backend/src/api/routes/auth.oauth.tsbackend/src/core/auth/auth.ts
🧬 Code graph analysis (1)
backend/src/core/auth/auth.ts (4)
backend/src/types/auth.ts (1)
XUserInfo(129-136)backend/src/core/auth/oauth.config.ts (1)
OAuthConfigService(26-464)backend/src/utils/environment.ts (1)
getApiBaseUrl(39-41)backend/src/utils/logger.ts (1)
logger(6-29)
⏰ 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 (11)
backend/src/api/routes/auth.oauth.ts (3)
11-11: LGTM!The crypto import is needed for PKCE verifier and challenge generation in the X OAuth flow.
273-288: LGTM!The PKCE implementation correctly follows RFC 7636:
- 32-byte random verifier with base64url encoding provides sufficient entropy
- SHA-256 challenge derivation matches the S256 method
- Verifier is properly embedded in the state JWT for retrieval during callback
295-295: LGTM!The challenge parameter is correctly passed only for the X provider, remaining undefined for other OAuth providers that don't require PKCE.
backend/src/core/auth/auth.ts (8)
38-38: LGTM!The XUserInfo type import is correctly added alongside other OAuth provider types.
697-697: LGTM!XUserInfo is correctly added to the identity data union type, maintaining consistency with other OAuth providers.
803-803: LGTM!XUserInfo is correctly added to the identity data union type in the createThirdPartyUser method, consistent with findOrCreateThirdPartyUser.
1593-1628: LGTM!The X token exchange implementation correctly follows Twitter API v2 OAuth 2.0 with PKCE:
- Includes
code_verifierparameter as required by PKCE flow- Uses Basic authentication with client credentials
- Posts to the correct Twitter API v2 token endpoint
1630-1652: LGTM!The X user info retrieval correctly uses Twitter API v2:
- Fetches from
/2/users/meendpoint with Bearer token- Requests appropriate user fields
- Correctly accesses the nested data structure (
response.data.data)
1654-1669: LGTM!The X user creation logic correctly handles optional username and follows the pattern established by other OAuth providers (GitHub, Discord) for generating local email addresses when real emails aren't available.
1682-1703: LGTM!The OAuth URL generation is correctly updated to support PKCE for X while maintaining backward compatibility with other providers that don't require a challenge parameter.
1833-1849: LGTM with dependency on verifier type fix.The X OAuth callback handler correctly implements the PKCE flow by validating both code and verifier, then exchanging them for an access token. The implementation follows the same pattern as other provider callbacks.
Note: This is contingent on making the
verifierparameter optional in thehandleOAuthCallbacksignature and updating the validation logic as suggested in the previous comment.
There was a problem hiding this comment.
Actionable comments posted: 2
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
backend/src/api/routes/auth.oauth.ts(5 hunks)backend/src/core/auth/auth.ts(9 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
**/*.{ts,tsx}: Use TypeScript for all code files
Use ES modules (import/export syntax)
Prefer descriptive, unabbreviated variable and function names
Implement proper error handling with try-catch blocks and logging where appropriate
Use single quotes for strings
Include semicolons at the end of statements
Use arrow functions for callbacks and inline functions
Prefer const over let; avoid var
Use template literals for string interpolation
Maintain 2-space indentation
Format code with the repository Prettier configuration
Variables, parameters, properties, and functions must use camelCase
Constants and enum members must use UPPER_CASE
Include JSDoc comments for complex functions
Files:
backend/src/api/routes/auth.oauth.tsbackend/src/core/auth/auth.ts
backend/src/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
backend/src/**/*.{ts,tsx}: Use async/await for asynchronous operations in the backend
Use Zod schemas for request/response validation
Return consistent API responses using utility functions
Validate all user inputs
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper caching strategies (server-side)
Files:
backend/src/api/routes/auth.oauth.tsbackend/src/core/auth/auth.ts
backend/src/api/**/*.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
backend/src/api/**/*.ts: Implement authentication and error-handling middleware
Follow RESTful conventions for API endpoints
Implement rate limiting for API endpoints
Files:
backend/src/api/routes/auth.oauth.ts
**/*.{tsx,ts}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
React components and TypeScript types/interfaces must use PascalCase
Files:
backend/src/api/routes/auth.oauth.tsbackend/src/core/auth/auth.ts
**/[a-z][a-z0-9-]*.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Utility files should use kebab-case or camelCase (kebab-case validated here)
Files:
backend/src/api/routes/auth.oauth.tsbackend/src/core/auth/auth.ts
backend/src/{controllers,core}/**/*.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Implement proper database transaction handling
Files:
backend/src/core/auth/auth.ts
🧠 Learnings (1)
📚 Learning: 2025-10-15T18:18:47.519Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.519Z
Learning: Applies to backend/src/api/**/*.ts : Implement authentication and error-handling middleware
Applied to files:
backend/src/api/routes/auth.oauth.tsbackend/src/core/auth/auth.ts
🧬 Code graph analysis (1)
backend/src/core/auth/auth.ts (4)
backend/src/types/auth.ts (1)
XUserInfo(129-136)backend/src/core/auth/oauth.config.ts (1)
OAuthConfigService(26-464)backend/src/app.config.ts (1)
config(30-54)backend/src/utils/environment.ts (1)
getApiBaseUrl(39-41)
⏰ 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
| let jwtPayload: Record<string, unknown> = { | ||
| provider: validatedProvider, | ||
| redirectUri: redirect_uri ? (redirect_uri as string) : undefined, | ||
| createdAt: Date.now(), | ||
| }; | ||
| let challenge: string | undefined; | ||
|
|
||
| // For X (Twitter) only — generate PKCE verifier/challenge and embed verifier in state | ||
| if (validatedProvider === 'x') { | ||
| const verifier = crypto.randomBytes(32).toString('base64url'); | ||
| challenge = crypto.createHash('sha256').update(verifier).digest('base64url'); | ||
| jwtPayload = { | ||
| ...jwtPayload, | ||
| codeVerifier: verifier, // add PKCE verifier | ||
| }; | ||
| } |
There was a problem hiding this comment.
PKCE verifier must stay server-side
Adding codeVerifier to the signed state means the browser (and any interceptor) can base64-decode the JWT payload and recover it. An attacker who steals the authorization code now also has the verifier, defeating PKCE’s protection. Persist the verifier entirely on the server instead (e.g., short-lived store keyed by state), omit it from the JWT, and load it in the callback before exchanging the code. Also update the callback flow to consume that stored verifier rather than trusting a front-channel value.
🤖 Prompt for AI Agents
In backend/src/api/routes/auth.oauth.ts around lines 273 to 288, do not embed
the PKCE codeVerifier in the signed JWT/state because that exposes the verifier
to the browser and defeats PKCE; instead generate the verifier on the server as
you do now, remove codeVerifier from jwtPayload, persist the verifier
server-side in a short-lived store keyed by the state (or a separate random
server-side key tied to the state), and update the callback flow to retrieve and
consume that stored verifier when exchanging the authorization code; ensure the
stored verifier is deleted after use and set a tight TTL to limit exposure.
|
In-memory PKCE storage won't scale across instances. Would using the database for short-lived verifier records be an acceptable approach? |
You are definitely right. We are going to use PKCE for all of our authentication system in the next patch, and at that time we will have a database table for it. For now, I think storing it in memory is fine. Also, do you mind solve the merge conflict? We are actually refactoring all oauth into individual files, so putting all relevant logic into a file called oauth.x.ts would be nice (just like oauth.google.ts in the main branch). Thanks for your work! |
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
backend/src/core/auth/oauth.x.ts (1)
29-81: PKCE implementation looks correct.The PKCE flow is properly implemented with secure verifier generation, SHA256 challenge computation, and appropriate URL parameters. The state parameter is correctly required for security.
One minor optimization: the verifier is stored at lines 44-47 before checking if the shared key flow will be used (line 49). In the shared key flow, the locally stored verifier won't be used since the cloud service handles PKCE. Consider moving the verifier storage after the shared key check to avoid unnecessary Map entries:
const selfBaseUrl = getApiBaseUrl(); if (!state) { throw new Error('State parameter is required.'); } - this.verifierCodes.set(state, verifier); - setTimeout(() => { - this.verifierCodes.delete(state); - }, 600000); if (config?.useSharedKey) { // Use shared keys if configured const cloudBasedUrl = process.env.CLOUD_API_HOST || 'https://api.insforge.dev'; const redirectUri = `${selfBaseUrl}/api/auth/oauth/shared/callback/${state}`; const response = await axios.get( `${cloudBasedUrl}/oauth/twitter?redirect_uri=${encodeURIComponent(redirectUri)}`, { headers: { 'Content-Type': 'application/json', }, } ); return response.data.auth_url || response.data.url || ''; } + this.verifierCodes.set(state, verifier); + setTimeout(() => { + this.verifierCodes.delete(state); + }, 600000); + logger.debug('X OAuth Config (fresh from DB):', {
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
backend/src/api/routes/auth.oauth.ts(3 hunks)backend/src/core/auth/auth.ts(6 hunks)backend/src/core/auth/oauth.x.ts(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- backend/src/api/routes/auth.oauth.ts
🧰 Additional context used
🧬 Code graph analysis (2)
backend/src/core/auth/auth.ts (2)
backend/src/types/auth.ts (1)
XUserInfo(129-136)backend/src/core/auth/oauth.x.ts (1)
XOAuthService(10-187)
backend/src/core/auth/oauth.x.ts (5)
backend/src/app.config.ts (1)
config(30-54)backend/src/utils/environment.ts (1)
getApiBaseUrl(39-41)backend/src/utils/logger.ts (1)
logger(6-29)backend/src/types/auth.ts (1)
XUserInfo(129-136)shared-schemas/src/auth-api.schema.ts (1)
CreateSessionResponse(324-324)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: E2E Tests
🔇 Additional comments (7)
backend/src/core/auth/auth.ts (3)
38-38: LGTM!The imports for XUserInfo and XOAuthService are correctly placed and follow the existing patterns used for other OAuth providers.
Also applies to: 45-45
685-699: LGTM!The XUserInfo type is correctly added to the identityData union in both
findOrCreateThirdPartyUserandcreateThirdPartyUsermethods. This maintains consistency with other OAuth providers and enables X user data to flow through the existing user provisioning pipeline.Also applies to: 792-805
1554-1577: LGTM!The X OAuth integration follows the established pattern used for other providers (particularly Google's delegated service approach). The addition of
state?: stringto the payload type is necessary for PKCE support, and both the URL generation and callback handling correctly delegate to XOAuthService.Also applies to: 1582-1618
backend/src/core/auth/oauth.x.ts (4)
10-24: LGTM!The singleton pattern is correctly implemented with proper initialization of the verifierCodes Map. The in-memory storage for PKCE verifiers was already discussed in past reviews, and the team has acknowledged this as an acceptable temporary solution until a system-wide PKCE database table is implemented in a future patch.
86-127: LGTM!The token exchange correctly implements PKCE security:
- Verifier retrieved server-side using the state parameter (never exposed to client)
- Immediate deletion after retrieval prevents replay attacks
- Proper use of Twitter API v2 OAuth 2.0 token endpoint with PKCE verifier and Basic authentication
132-151: LGTM!The user info retrieval correctly uses the Twitter API v2
/users/meendpoint with appropriate fields and properly handles the nested response structure. The returned data matches the XUserInfo type definition.
156-186: LGTM!Both methods correctly implement the X OAuth user provisioning flow:
findOrCreateXUserconstructs a synthetic email and delegates to AuthService's shared third-party user logic, following the pattern used by GitHub and Discord providershandleXCallbackproperly validates required parameters (code and state), orchestrates the token exchange, user info retrieval, and user provisioning in the correct sequence
Summary
Closes: #387
Added X (Twitter) OAuth Support
Added X (Twitter) OAuth integration following the same pattern as existing Google, GitHub, and Discord flows.
Developers can now enable Twitter login using either custom credentials or shared application keys.
Backend Changes
generateXOAuthUrl,exchangeXCodeForToken,findOrCreateXUser,getXUserInfo,handleXCallbackmethods to handle full PKCE-based (mandatory by X) OAuth flow.AuthService.generateOAuthUrl()andAuthService.handleOAuthCallback()to include'x'as a valid provider.tweet.read users.read.Frontend Changes
'x'inOAuthProvidersSchema.Client ID,Client Secret.How Did You Test This Change?
docker compose up.http://localhost:7131.access_tokenfrom Twitter.id,name,username,profile_image_url) imported correctly._accountsand_account_providers.x.mp4
Summary by CodeRabbit
New Feature
UI/UX Updates
Documentation
X_CLIENT_IDandX_CLIENT_SECRETplaceholders.Summary by CodeRabbit
New Features
UI
Chores