Repository navigation
Added linkedin oauth provider - #421
Conversation
|
@tonychang04 pls review ! this let me know if anything is needed in this |
|
@HarshSharma0801 Thanks for your PR! It looks decent to me. The add oauth configuration part LGTM. Just wondering if you can show a demo video of login with linkedin in to make sure it is working? i.e. Some boiler plate app that allow user to sign in with Linkedin Oauth. |
|
@Fermionic-Lyu sure ! here's a video demonstrating whole flow Screen.Recording.2025-10-16.at.2.mp4 |
Fermionic-Lyu
left a comment
There was a problem hiding this comment.
We built your PR to a new image and tested internally. It worked smoothly, great work! Just some chore comments here:
From the picture, the 'linkedin' label should be 'Linkedin' for consistentcy, and let's make it linkedin-blue for better visuals.
Also, if a user has many identities, the '+1' badge is too short in width, adding some padding would be great.
WalkthroughAdds LinkedIn OAuth support across backend and frontend: environment example, new Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant Frontend
participant Backend
participant LinkedIn
User->>Frontend: Click "Connect LinkedIn"
Frontend->>Backend: GET /api/auth/oauth/linkedin?redirect_uri=...
Backend->>Backend: create state JWT & generate auth URL
Backend-->>Frontend: Return auth URL
Frontend->>LinkedIn: Redirect user to LinkedIn auth URL
LinkedIn->>User: Consent screen
User->>LinkedIn: Authorize
LinkedIn->>Frontend: Redirect to /callback with code & state
Frontend->>Backend: GET /api/auth/oauth/linkedin/callback?code=...&state=...
Backend->>Backend: Validate state JWT
Backend->>LinkedIn: Exchange code for access_token & id_token
LinkedIn-->>Backend: Return tokens
Backend->>Backend: Verify id_token → linkedinUserInfo
Backend->>Backend: findOrCreateLinkedInUser(linkedinUserInfo)
Backend-->>Frontend: Return session/auth response
Frontend->>User: Login complete
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Poem
Pre-merge checks and finishing touches✅ Passed checks (4 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: CodeRabbit UI Review profile: CHILL Plan: Pro 📒 Files selected for processing (1)
🧰 Additional context used📓 Path-based instructions (5)**/*.{ts,tsx}📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Files:
backend/src/**/*.{ts,tsx}📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Files:
backend/src/{controllers,core}/**/*.ts📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Files:
**/*.{tsx,ts}📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Files:
**/[a-z][a-z0-9-]*.ts📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Files:
🧬 Code graph analysis (1)backend/src/core/auth/auth.ts (2)
🪛 Gitleaks (8.28.0)backend/src/core/auth/auth.ts[high] 924-924: 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)
🔇 Additional comments (4)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 5
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
backend/src/api/routes/auth.oauth.ts (1)
198-204: Stop returning PII in redirect URL.Appending
nameleaks PII via logs/history/referrers. Return only an access token (or a short-lived code) and fetch user info on the client.- finalredirectUri.searchParams.set('user_id', result?.user.id ?? ''); - finalredirectUri.searchParams.set('email', result?.user.email ?? ''); - finalredirectUri.searchParams.set('name', result?.user.name ?? ''); + // Prefer sending only access_token or a one-time code, then fetch user info via API on app load.backend/src/core/auth/auth.ts (1)
619-621: Typo in error message.“conifgured” → “configured”.
- throw new Error('Google Client Secret not conifgured.'); + throw new Error('Google Client Secret not configured.');
🧹 Nitpick comments (10)
backend/src/core/auth/oauth.ts (1)
185-187: Default LinkedIn scopes added — verify against LinkedIn OIDC config and consider centralizing.
- The defaults ['openid', 'profile', 'email'] look right for LinkedIn OIDC, but please confirm your app has OpenID Connect and Email permissions enabled in the LinkedIn dev console. Also ensure downstream logic expects these claims.
- To avoid the growing if/else chain, centralize defaults in a map.
Example refactor:
@@ - if (!scopes) { - const provider = input.provider.toLowerCase(); - if (provider === 'google') { - scopes = ['openid', 'email', 'profile']; - } else if (provider === 'github') { - scopes = ['user:email']; - } else if (provider === 'linkedin') { - scopes = ['openid', 'profile', 'email']; - } - } + if (!scopes) { + const provider = input.provider.toLowerCase(); + const DEFAULT_SCOPES: Record<string, string[]> = { + google: ['openid', 'email', 'profile'], + github: ['user:email'], + linkedin: ['openid', 'profile', 'email'], + }; + scopes = DEFAULT_SCOPES[provider]; + }.env.example (1)
51-54: Add brief guidance for LinkedIn OIDC setup.Consider a short note that the LinkedIn app must have OpenID Connect enabled and the callback URL set to /api/auth/oauth/linkedin/callback to match backend routes.
frontend/src/features/auth/components/UsersDataGrid.tsx (1)
86-88: Use stable React keys.Avoid index as key to prevent reconciliation glitches; use provider string instead.
- {uniqueProviders.slice(0, 2).map((provider: string, index: number) => ( - <ProviderIcon key={index} provider={provider} /> - ))} + {uniqueProviders.slice(0, 2).map((provider: string) => ( + <ProviderIcon key={provider} provider={provider} /> + ))}backend/src/types/auth.ts (1)
92-101: Type duplication with Google OIDC shape — consider a shared OIDC user type.LinkedInUserInfo mirrors GoogleUserInfo fields. Factor a BaseOidcUserInfo to reduce duplication and keep providers aligned.
Example:
export interface BaseOidcUserInfo { sub: string; email: string; email_verified?: boolean; name?: string; picture?: string; given_name?: string; family_name?: string; locale?: string; } export interface GoogleUserInfo extends BaseOidcUserInfo {} export interface LinkedInUserInfo extends BaseOidcUserInfo {}Note: LinkedIn’s email claim is present only when the 'email' scope is granted; handle optionality downstream.
test-linkedin-oauth.html (1)
241-276: Happy-path fetch is fine; optionally prefer relative path and sessionStorage for tests.
- If serving from the same origin, a relative URL avoids mixed-origin quirks.
- For demo pages, sessionStorage reduces persistence of tokens on shared machines.
- const INSFORGE_API = 'http://localhost:7130'; + const INSFORGE_API = window.location.origin === 'null' ? 'http://localhost:7130' : window.location.origin; @@ - const data = await response.json(); + const data = await response.json(); @@ - window.location.href = data.authUrl; + window.location.href = data.authUrl;And where you store the token:
- localStorage.setItem('insforge_token', token); - localStorage.setItem('insforge_user', JSON.stringify(user)); + sessionStorage.setItem('insforge_token', token); + sessionStorage.setItem('insforge_user', JSON.stringify(user));frontend/src/features/auth/components/AddOAuthDialog.tsx (2)
17-19: Deduplicate provider union with a local alias.The 'google' | 'github' | 'linkedin' union is repeated; define a ProviderId alias and reuse across props, state, and helpers.
+type ProviderId = 'google' | 'github' | 'linkedin'; @@ - onConfirm: (selectedId: 'google' | 'github' | 'linkedin') => void; - enabledProviders: Record<'google' | 'github' | 'linkedin', boolean>; + onConfirm: (selectedId: ProviderId) => void; + enabledProviders: Record<ProviderId, boolean>; @@ - const [selectedId, setSelectedId] = useState<'google' | 'github' | 'linkedin' | null>(null); + const [selectedId, setSelectedId] = useState<ProviderId | null>(null); @@ - const selectProvider = (id: 'google' | 'github' | 'linkedin') => { + const selectProvider = (id: ProviderId) => {Also applies to: 28-28, 42-42
64-79: Minor a11y: reflect selection state.Add aria-pressed to the provider button for better screen reader support.
- <button + <button key={p.id} onClick={() => selectProvider(p.id)} + aria-pressed={selectedId === p.id} className={cn(frontend/src/features/auth/components/AuthMethodTab.tsx (1)
45-45: Deduplicate provider ID unions.Extract a shared type (e.g.,
type OAuthProviderId = 'google' | 'github' | 'linkedin') and reuse across props/functions to avoid drift.backend/src/api/routes/auth.oauth.ts (1)
188-196: LinkedIn payload mapping mirrors other providers.Consider validating
payloadshape with Zod before use to guard shared-key responses.backend/src/core/auth/auth.ts (1)
754-802: Consider adding nonce in LinkedIn auth request.OIDC best practice: include a
nonceand later verify it in the ID token.const authUrl = new URL('https://www.linkedin.com/oauth/v2/authorization'); @@ authUrl.searchParams.set('response_type', 'code'); authUrl.searchParams.set( 'scope', config.scopes ? config.scopes.join(' ') : 'openid profile email' ); + // Optional but recommended: + // const nonce = crypto.randomUUID(); + // authUrl.searchParams.set('nonce', nonce); + // Cache `nonce` by state to verify during token validation.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
frontend/src/assets/logos/linkedin.svgis excluded by!**/*.svg
📒 Files selected for processing (9)
.env.example(1 hunks)backend/src/api/routes/auth.oauth.ts(5 hunks)backend/src/core/auth/auth.ts(6 hunks)backend/src/core/auth/oauth.ts(1 hunks)backend/src/types/auth.ts(1 hunks)frontend/src/features/auth/components/AddOAuthDialog.tsx(3 hunks)frontend/src/features/auth/components/AuthMethodTab.tsx(5 hunks)frontend/src/features/auth/components/UsersDataGrid.tsx(3 hunks)test-linkedin-oauth.html(1 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/core/auth/oauth.tsbackend/src/types/auth.tsfrontend/src/features/auth/components/UsersDataGrid.tsxbackend/src/api/routes/auth.oauth.tsfrontend/src/features/auth/components/AddOAuthDialog.tsxbackend/src/core/auth/auth.tsfrontend/src/features/auth/components/AuthMethodTab.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/oauth.tsbackend/src/types/auth.tsbackend/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/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/core/auth/oauth.tsbackend/src/types/auth.tsfrontend/src/features/auth/components/UsersDataGrid.tsxbackend/src/api/routes/auth.oauth.tsfrontend/src/features/auth/components/AddOAuthDialog.tsxbackend/src/core/auth/auth.tsfrontend/src/features/auth/components/AuthMethodTab.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/oauth.tsbackend/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/components/AddOAuthDialog.tsxfrontend/src/features/auth/components/AuthMethodTab.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/components/AddOAuthDialog.tsxfrontend/src/features/auth/components/AuthMethodTab.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/components/AddOAuthDialog.tsxfrontend/src/features/auth/components/AuthMethodTab.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/AddOAuthDialog.tsxfrontend/src/features/auth/components/AuthMethodTab.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
🧠 Learnings (1)
📚 Learning: 2025-10-15T18:18:47.505Z
Learnt from: CR
PR: InsForge/InsForge#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.505Z
Learning: Applies to frontend/src/**/*.tsx : Use a consistent icon set from lucide-react
Applied to files:
frontend/src/features/auth/components/AuthMethodTab.tsx
🧬 Code graph analysis (2)
backend/src/api/routes/auth.oauth.ts (1)
backend/src/api/middleware/error.ts (1)
AppError(7-17)
backend/src/core/auth/auth.ts (2)
backend/src/types/auth.ts (3)
GoogleUserInfo(66-75)GitHubUserInfo(77-83)LinkedInUserInfo(92-101)backend/src/core/auth/oauth.ts (1)
OAuthConfigService(26-400)
🪛 GitHub Actions: Lint and Format Check
test-linkedin-oauth.html
[warning] 1-1: Code style issues found by Prettier. Run 'npx prettier --write test-linkedin-oauth.html' to fix.
🪛 Gitleaks (8.28.0)
backend/src/core/auth/auth.ts
[high] 920-920: 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). (1)
- GitHub Check: E2E Tests
🔇 Additional comments (17)
frontend/src/features/auth/components/UsersDataGrid.tsx (2)
36-41: LinkedIn provider styling — looks good.Consistent label and color palette with existing providers. No issues.
133-133: Column width tweak acknowledged.Increasing identities to 1.5fr improves readability when multiple providers exist.
test-linkedin-oauth.html (1)
1-348: Fix Prettier violations.CI flagged formatting for this file. Please run: npx prettier --write test-linkedin-oauth.html
frontend/src/features/auth/components/AuthMethodTab.tsx (4)
6-6: LGTM on LinkedIn logo import.Matches existing brand-logo approach for Google/GitHub.
35-41: LinkedIn provider entry looks correct.Copy-parity with existing providers; setup URL and icon are fine.
109-109: Enabled state wiring for LinkedIn looks good.
118-129: Selection handler type extension is correct.backend/src/api/routes/auth.oauth.ts (3)
148-151: Provider validation extended correctly.
233-236: Provider list update is correct.
265-283: LinkedIn callback branch wiring is sound.Flow mirrors Google: code→tokens→verify→find/create. Once token verification is hardened in AuthService, this path will be secure.
backend/src/core/auth/auth.ts (7)
22-28: Types import updated to include LinkedIn.
284-285: Third-party user union extended correctly.
363-364: createThirdPartyUser union extended correctly.
453-462: Axios switch for shared Google auth URL is fine.Return extraction from
response.datalooks correct.
505-514: Axios switch for shared GitHub auth URL is fine.
919-931: LinkedIn user creation wrapper looks correct.Username/email mapping matches Google/GitHub patterns.
920-920: No secrets committed—gitleaks false positive.The flagged line 920 is a TypeScript function parameter (
linkedinUserInfo: LinkedInUserInfo), not a secret. Code inspection confirms LinkedIn client secrets are properly retrieved viaOAuthConfigService.getClientSecretByProvider()(line 834) rather than hardcoded, following best practices for secret management. No actionable security concerns found.
| // GET /api/auth/oauth/linkedin - Initialize LinkedIn OAuth flow | ||
| router.get('/linkedin', async (req: Request, res: Response, next: NextFunction) => { | ||
| try { | ||
| const { redirect_uri } = req.query; | ||
| if (!redirect_uri) { | ||
| throw new AppError('Redirect URI is required', 400, ERROR_CODES.INVALID_INPUT); | ||
| } | ||
|
|
||
| const jwtPayload = { | ||
| provider: 'linkedin', | ||
| redirectUri: redirect_uri ? (redirect_uri as string) : undefined, | ||
| createdAt: Date.now(), | ||
| }; | ||
| const state = jwt.sign(jwtPayload, process.env.JWT_SECRET || 'default_secret', { | ||
| algorithm: 'HS256', | ||
| expiresIn: '1h', | ||
| }); | ||
|
|
||
| const authUrl = await authService.generateLinkedInAuthUrl(state); | ||
|
|
||
| res.json({ authUrl }); | ||
| } catch (error) { | ||
| logger.error('LinkedIn OAuth error', { error }); | ||
| next( | ||
| new AppError( | ||
| 'LinkedIn OAuth is not properly configured. Please check your oauth configurations.', | ||
| 500, | ||
| ERROR_CODES.AUTH_OAUTH_CONFIG_ERROR | ||
| ) | ||
| ); | ||
| } | ||
| }); |
There was a problem hiding this comment.
Avoid JWT state fallback secret and validate redirect_uri.
- Using
process.env.JWT_SECRET || 'default_secret'weakens security; fail fast if unset. - Validate
redirect_uriagainst an allowlist/same-origin to prevent open redirects.
router.get('/linkedin', async (req: Request, res: Response, next: NextFunction) => {
try {
const { redirect_uri } = req.query;
if (!redirect_uri) {
throw new AppError('Redirect URI is required', 400, ERROR_CODES.INVALID_INPUT);
}
+ // Enforce JWT secret
+ const jwtSecret = process.env.JWT_SECRET;
+ if (!jwtSecret) {
+ throw new AppError('Server misconfiguration: JWT_SECRET is missing', 500, ERROR_CODES.AUTH_OAUTH_CONFIG_ERROR);
+ }
+ // Optional: restrict redirect to same-origin or configured allowlist
+ // Example (adjust APP_BASE_URL/env as appropriate):
+ // const appBase = new URL(process.env.APP_BASE_URL || 'http://localhost:7131');
+ // const reqRedirect = new URL(redirect_uri as string, appBase.origin);
+ // if (reqRedirect.origin !== appBase.origin) {
+ // throw new AppError('Invalid redirect URI', 400, ERROR_CODES.INVALID_INPUT);
+ // }
const jwtPayload = {
provider: 'linkedin',
redirectUri: redirect_uri ? (redirect_uri as string) : undefined,
createdAt: Date.now(),
};
- const state = jwt.sign(jwtPayload, process.env.JWT_SECRET || 'default_secret', {
+ const state = jwt.sign(jwtPayload, jwtSecret, {
algorithm: 'HS256',
expiresIn: '1h',
});📝 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.
| // GET /api/auth/oauth/linkedin - Initialize LinkedIn OAuth flow | |
| router.get('/linkedin', async (req: Request, res: Response, next: NextFunction) => { | |
| try { | |
| const { redirect_uri } = req.query; | |
| if (!redirect_uri) { | |
| throw new AppError('Redirect URI is required', 400, ERROR_CODES.INVALID_INPUT); | |
| } | |
| const jwtPayload = { | |
| provider: 'linkedin', | |
| redirectUri: redirect_uri ? (redirect_uri as string) : undefined, | |
| createdAt: Date.now(), | |
| }; | |
| const state = jwt.sign(jwtPayload, process.env.JWT_SECRET || 'default_secret', { | |
| algorithm: 'HS256', | |
| expiresIn: '1h', | |
| }); | |
| const authUrl = await authService.generateLinkedInAuthUrl(state); | |
| res.json({ authUrl }); | |
| } catch (error) { | |
| logger.error('LinkedIn OAuth error', { error }); | |
| next( | |
| new AppError( | |
| 'LinkedIn OAuth is not properly configured. Please check your oauth configurations.', | |
| 500, | |
| ERROR_CODES.AUTH_OAUTH_CONFIG_ERROR | |
| ) | |
| ); | |
| } | |
| }); | |
| // GET /api/auth/oauth/linkedin - Initialize LinkedIn OAuth flow | |
| router.get('/linkedin', async (req: Request, res: Response, next: NextFunction) => { | |
| try { | |
| const { redirect_uri } = req.query; | |
| if (!redirect_uri) { | |
| throw new AppError('Redirect URI is required', 400, ERROR_CODES.INVALID_INPUT); | |
| } | |
| // Enforce JWT secret | |
| const jwtSecret = process.env.JWT_SECRET; | |
| if (!jwtSecret) { | |
| throw new AppError('Server misconfiguration: JWT_SECRET is missing', 500, ERROR_CODES.AUTH_OAUTH_CONFIG_ERROR); | |
| } | |
| // Optional: restrict redirect to same-origin or configured allowlist | |
| // Example (adjust APP_BASE_URL/env as appropriate): | |
| // const appBase = new URL(process.env.APP_BASE_URL || 'http://localhost:7131'); | |
| // const reqRedirect = new URL(redirect_uri as string, appBase.origin); | |
| // if (reqRedirect.origin !== appBase.origin) { | |
| // throw new AppError('Invalid redirect URI', 400, ERROR_CODES.INVALID_INPUT); | |
| // } | |
| const jwtPayload = { | |
| provider: 'linkedin', | |
| redirectUri: redirect_uri ? (redirect_uri as string) : undefined, | |
| createdAt: Date.now(), | |
| }; | |
| const state = jwt.sign(jwtPayload, jwtSecret, { | |
| algorithm: 'HS256', | |
| expiresIn: '1h', | |
| }); | |
| const authUrl = await authService.generateLinkedInAuthUrl(state); | |
| res.json({ authUrl }); | |
| } catch (error) { | |
| logger.error('LinkedIn OAuth error', { error }); | |
| next( | |
| new AppError( | |
| 'LinkedIn OAuth is not properly configured. Please check your oauth configurations.', | |
| 500, | |
| ERROR_CODES.AUTH_OAUTH_CONFIG_ERROR | |
| ) | |
| ); | |
| } | |
| }); |
🤖 Prompt for AI Agents
In backend/src/api/routes/auth.oauth.ts around lines 90 to 121, the code
currently falls back to a default JWT secret and does not validate redirect_uri;
change it to first require process.env.JWT_SECRET and throw a clear
configuration error if missing (fail-fast, do not use 'default_secret'), and
validate the incoming redirect_uri against an allowlist or same-origin policy
before including it in the JWT payload (reject requests with absent or
non-allowlisted redirect_uri with a 400 AppError); ensure the error paths log
useful context and return appropriate error codes rather than proceeding with
insecure defaults.
| const clientSecret = await oauthConfigService.getClientSecretByProvider('linkedin'); | ||
| const selfBaseUrl = process.env.API_BASE_URL || 'http://localhost:7130'; | ||
| const response = await axios.post( | ||
| 'https://www.linkedin.com/oauth/v2/accessToken', | ||
| new URLSearchParams({ | ||
| code, | ||
| client_id: config.clientId ?? '', | ||
| client_secret: clientSecret ?? '', | ||
| redirect_uri: `${selfBaseUrl}/api/auth/oauth/linkedin/callback`, | ||
| grant_type: 'authorization_code', | ||
| }), | ||
| { |
There was a problem hiding this comment.
Guard missing LinkedIn client secret before token exchange.
Avoid sending an empty secret; fail fast with a clear error.
- const clientSecret = await oauthConfigService.getClientSecretByProvider('linkedin');
+ const clientSecret = await oauthConfigService.getClientSecretByProvider('linkedin');
+ if (!clientSecret) {
+ throw new Error('LinkedIn Client Secret not configured');
+ }🤖 Prompt for AI Agents
In backend/src/core/auth/auth.ts around lines 834 to 845, the code posts to
LinkedIn's accessToken endpoint even if clientSecret is empty; add a guard
before the axios.post that checks clientSecret (and optionally config.clientId)
and if missing throw or return an explicit error (e.g., throw new Error('Missing
LinkedIn client secret') or return a 400/500 with a clear message) so we fail
fast and avoid sending an empty secret to LinkedIn; ensure the check occurs
before constructing the URLSearchParams and that the error message includes
which credential is missing.
| const deleteOAuthConfig = async ( | ||
| providerId: 'google' | 'github' | 'linkedin', | ||
| providerName: string | ||
| ) => { |
There was a problem hiding this comment.
Ensure deletion errors are caught.
deleteOAuthConfig is async but deleteConfig isn’t awaited; thrown errors may bypass the try/catch.
const deleteOAuthConfig = async (
providerId: 'google' | 'github' | 'linkedin',
providerName: string
) => {
@@
- try {
- deleteConfig(providerId);
+ try {
+ await deleteConfig(providerId);
} catch (error) {
console.error(`Failed to delete ${providerId} OAuth:`, error);
}Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In frontend/src/features/auth/components/AuthMethodTab.tsx around lines 71 to
74, the async function deleteOAuthConfig calls deleteConfig without awaiting it
so exceptions can escape the try/catch; modify the function to await
deleteConfig(...) and keep the call inside the existing try/catch (or return the
awaited promise) so any thrown errors are caught and handled by the catch block.
| // Check if returning from OAuth callback | ||
| const urlParams = new URLSearchParams(window.location.search); | ||
| const token = urlParams.get('token'); | ||
| const userStr = urlParams.get('user'); | ||
| const error = urlParams.get('error'); | ||
|
|
||
| console.log('URL Params:', { token: !!token, user: !!userStr, error }); | ||
|
|
||
| if (error) { | ||
| showError('Authentication failed: ' + error); | ||
| return; | ||
| } | ||
|
|
||
| if (token && userStr) { | ||
| try { | ||
| const user = JSON.parse(decodeURIComponent(userStr)); | ||
| console.log('User data:', user); | ||
| showSuccess(token, user); | ||
|
|
||
| // Store in localStorage | ||
| localStorage.setItem('insforge_token', token); | ||
| localStorage.setItem('insforge_user', JSON.stringify(user)); | ||
| } catch (e) { | ||
| console.error('Parse error:', e); | ||
| showError('Failed to parse user data: ' + e.message); | ||
| } | ||
| } else { |
There was a problem hiding this comment.
Clear sensitive data from URL after OAuth callback.
Token and user are passed via query params; sanitize the address bar to avoid leaking via history/referrers.
- if (token && userStr) {
+ if (token && userStr) {
try {
const user = JSON.parse(decodeURIComponent(userStr));
console.log('User data:', user);
showSuccess(token, user);
// Store in localStorage
- localStorage.setItem('insforge_token', token);
- localStorage.setItem('insforge_user', JSON.stringify(user));
+ localStorage.setItem('insforge_token', token);
+ localStorage.setItem('insforge_user', JSON.stringify(user));
+
+ // Remove sensitive query params from the URL
+ window.history.replaceState(null, '', window.location.href.split('?')[0]);📝 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.
| // Check if returning from OAuth callback | |
| const urlParams = new URLSearchParams(window.location.search); | |
| const token = urlParams.get('token'); | |
| const userStr = urlParams.get('user'); | |
| const error = urlParams.get('error'); | |
| console.log('URL Params:', { token: !!token, user: !!userStr, error }); | |
| if (error) { | |
| showError('Authentication failed: ' + error); | |
| return; | |
| } | |
| if (token && userStr) { | |
| try { | |
| const user = JSON.parse(decodeURIComponent(userStr)); | |
| console.log('User data:', user); | |
| showSuccess(token, user); | |
| // Store in localStorage | |
| localStorage.setItem('insforge_token', token); | |
| localStorage.setItem('insforge_user', JSON.stringify(user)); | |
| } catch (e) { | |
| console.error('Parse error:', e); | |
| showError('Failed to parse user data: ' + e.message); | |
| } | |
| } else { | |
| // Check if returning from OAuth callback | |
| const urlParams = new URLSearchParams(window.location.search); | |
| const token = urlParams.get('token'); | |
| const userStr = urlParams.get('user'); | |
| const error = urlParams.get('error'); | |
| console.log('URL Params:', { token: !!token, user: !!userStr, error }); | |
| if (error) { | |
| showError('Authentication failed: ' + error); | |
| return; | |
| } | |
| if (token && userStr) { | |
| try { | |
| const user = JSON.parse(decodeURIComponent(userStr)); | |
| console.log('User data:', user); | |
| showSuccess(token, user); | |
| // Store in localStorage | |
| localStorage.setItem('insforge_token', token); | |
| localStorage.setItem('insforge_user', JSON.stringify(user)); | |
| // Remove sensitive query params from the URL | |
| window.history.replaceState(null, '', window.location.href.split('?')[0]); | |
| } catch (e) { | |
| console.error('Parse error:', e); | |
| showError('Failed to parse user data: ' + e.message); | |
| } | |
| } else { |
🤖 Prompt for AI Agents
test-linkedin-oauth.html around lines 200 to 226: token and user query params
remain in the address bar after processing which can leak sensitive data; after
you parse/store the token and user (and also in the error branch) call
window.history.replaceState({}, document.title, window.location.pathname +
window.location.hash) to remove the query string without reloading the page so
the sensitive values are cleared from the URL and browser history.
f1f060e to
af31abc
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (4)
frontend/src/features/auth/components/AuthMethodTab.tsx (1)
71-90: Missing await on async deleteConfig call.The
deleteConfigcall on line 85 is not awaited, which means exceptions may bypass the try/catch block. This was flagged in a previous review.Apply this diff:
const deleteOAuthConfig = async ( providerId: 'google' | 'github' | 'linkedin', providerName: string ) => { const shouldDelete = await confirm({ title: `Delete ${providerName} OAuth`, description: `Are you sure you want to delete the ${providerName} configuration? This action cannot be undone.`, confirmText: 'Delete', cancelText: 'Cancel', destructive: true, }); if (shouldDelete) { try { - deleteConfig(providerId); + await deleteConfig(providerId); } catch (error) { console.error(`Failed to delete ${providerId} OAuth:`, error); } } };backend/src/api/routes/auth.oauth.ts (1)
90-121: Critical: Remove JWT_SECRET fallback and validate redirect_uri.The LinkedIn route (and existing Google/GitHub routes) have two security issues:
- Line 103: Using
process.env.JWT_SECRET || 'default_secret'is unsafe. Fail fast if JWT_SECRET is not set.- Lines 93-96: The redirect_uri is not validated against an allowlist, enabling potential open redirect attacks.
These issues were flagged in previous reviews and affect all OAuth initialization routes.
Apply this diff to the LinkedIn route (and similarly to Google/GitHub routes):
router.get('/linkedin', async (req: Request, res: Response, next: NextFunction) => { try { const { redirect_uri } = req.query; if (!redirect_uri) { throw new AppError('Redirect URI is required', 400, ERROR_CODES.INVALID_INPUT); } + + const jwtSecret = process.env.JWT_SECRET; + if (!jwtSecret) { + throw new AppError('Server misconfiguration: JWT_SECRET is missing', 500, ERROR_CODES.AUTH_OAUTH_CONFIG_ERROR); + } + + // Validate redirect_uri against allowlist or same-origin + // Example (adjust based on your security requirements): + // const allowedOrigins = [process.env.APP_BASE_URL || 'http://localhost:7131']; + // const reqRedirect = new URL(redirect_uri as string); + // if (!allowedOrigins.some(origin => reqRedirect.origin === new URL(origin).origin)) { + // throw new AppError('Invalid redirect URI', 400, ERROR_CODES.INVALID_INPUT); + // } const jwtPayload = { provider: 'linkedin', redirectUri: redirect_uri ? (redirect_uri as string) : undefined, createdAt: Date.now(), }; - const state = jwt.sign(jwtPayload, process.env.JWT_SECRET || 'default_secret', { + const state = jwt.sign(jwtPayload, jwtSecret, { algorithm: 'HS256', expiresIn: '1h', });backend/src/core/auth/auth.ts (2)
805-882: Guard against missing LinkedIn client secret.Line 835 retrieves the client secret but doesn't validate it before sending to LinkedIn on line 842. This can result in an empty secret being sent, causing unclear errors. This was flagged in a previous review.
Apply this diff:
logger.info('Exchanging LinkedIn code for tokens', { hasCode: !!code, clientId: config.clientId?.substring(0, 10) + '...', }); const clientSecret = await oauthConfigService.getClientSecretByProvider('linkedin'); + if (!clientSecret) { + throw new Error('LinkedIn Client Secret not configured'); + } + const selfBaseUrl = getApiBaseUrl(); const response = await axios.post( 'https://www.linkedin.com/oauth/v2/accessToken', new URLSearchParams({ code, client_id: config.clientId ?? '', - client_secret: clientSecret ?? '', + client_secret: clientSecret, redirect_uri: `${selfBaseUrl}/api/auth/oauth/linkedin/callback`, grant_type: 'authorization_code', }),
887-915: Critical: Verify LinkedIn ID token signature with JOSE.Using
jwt.decode(line 896) does not verify the token signature or validate claims, enabling token forgery. LinkedIn supports OIDC; you must verify the token against LinkedIn's JWKS endpoint. This was flagged in a previous review.Replace with proper JOSE verification:
+ // Add 'jose' to package.json dependencies first + async verifyLinkedInToken(idToken: string) { const oauthConfigService = OAuthConfigService.getInstance(); const config = await oauthConfigService.getConfigByProvider('linkedin'); if (!config) { throw new Error('LinkedIn OAuth not configured'); } + // Verify with LinkedIn JWKS (OIDC) + const { createRemoteJWKSet, jwtVerify } = await import('jose'); + const JWKS = createRemoteJWKSet(new URL('https://www.linkedin.com/oauth/openid/jwks')); + try { - const decoded = jwt.decode(idToken) as LinkedInUserInfo; - if (!decoded) { - throw new Error('Invalid LinkedIn token payload'); - } - + const { payload } = await jwtVerify(idToken, JWKS, { + issuer: 'https://www.linkedin.com', + audience: config.clientId, + }); + return { - sub: decoded.sub, - email: decoded.email || '', - email_verified: decoded.email_verified || false, - name: decoded.name || '', - picture: decoded.picture || '', - given_name: decoded.given_name || '', - family_name: decoded.family_name || '', - locale: decoded.locale || '', + sub: String(payload.sub), + email: (payload.email as string) || '', + email_verified: Boolean(payload.email_verified), + name: (payload.name as string) || '', + picture: (payload.picture as string) || '', + given_name: (payload.given_name as string) || '', + family_name: (payload.family_name as string) || '', + locale: (payload.locale as string) || '', }; } catch (error) { logger.error('LinkedIn token verification failed:', error); - throw new Error(`LinkedIn token verification failed: ${error}`); + throw new Error('LinkedIn token verification failed'); } }Note: Install
josevianpm install joseand add it to dependencies.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
frontend/src/assets/logos/linkedin.svgis excluded by!**/*.svg
📒 Files selected for processing (8)
.env.example(1 hunks)backend/src/api/routes/auth.oauth.ts(5 hunks)backend/src/core/auth/auth.ts(6 hunks)backend/src/core/auth/oauth.ts(1 hunks)backend/src/types/auth.ts(1 hunks)frontend/src/features/auth/components/AddOAuthDialog.tsx(3 hunks)frontend/src/features/auth/components/AuthMethodTab.tsx(5 hunks)frontend/src/features/auth/components/UsersDataGrid.tsx(3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- .env.example
- backend/src/types/auth.ts
🧰 Additional context used
📓 Path-based instructions (10)
**/*.{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/oauth.tsbackend/src/api/routes/auth.oauth.tsfrontend/src/features/auth/components/AddOAuthDialog.tsxfrontend/src/features/auth/components/UsersDataGrid.tsxfrontend/src/features/auth/components/AuthMethodTab.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/core/auth/oauth.tsbackend/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/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/core/auth/oauth.tsbackend/src/api/routes/auth.oauth.tsfrontend/src/features/auth/components/AddOAuthDialog.tsxfrontend/src/features/auth/components/UsersDataGrid.tsxfrontend/src/features/auth/components/AuthMethodTab.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/core/auth/oauth.tsbackend/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
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/AddOAuthDialog.tsxfrontend/src/features/auth/components/UsersDataGrid.tsxfrontend/src/features/auth/components/AuthMethodTab.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/AddOAuthDialog.tsxfrontend/src/features/auth/components/UsersDataGrid.tsxfrontend/src/features/auth/components/AuthMethodTab.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/AddOAuthDialog.tsxfrontend/src/features/auth/components/UsersDataGrid.tsxfrontend/src/features/auth/components/AuthMethodTab.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/AddOAuthDialog.tsxfrontend/src/features/auth/components/UsersDataGrid.tsxfrontend/src/features/auth/components/AuthMethodTab.tsx
🧠 Learnings (1)
📚 Learning: 2025-10-15T18:18:47.505Z
Learnt from: CR
PR: InsForge/InsForge#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.505Z
Learning: Applies to frontend/src/**/*.tsx : Use a consistent icon set from lucide-react
Applied to files:
frontend/src/features/auth/components/AuthMethodTab.tsx
🧬 Code graph analysis (2)
backend/src/api/routes/auth.oauth.ts (1)
backend/src/api/middleware/error.ts (1)
AppError(7-17)
backend/src/core/auth/auth.ts (3)
backend/src/types/auth.ts (3)
GoogleUserInfo(66-75)GitHubUserInfo(77-83)LinkedInUserInfo(92-101)backend/src/core/auth/oauth.ts (1)
OAuthConfigService(26-400)shared-schemas/src/auth-api.schema.ts (1)
CreateSessionResponse(185-185)
🔇 Additional comments (8)
backend/src/core/auth/oauth.ts (1)
185-186: LGTM!The LinkedIn default scopes follow the existing pattern and are appropriate for LinkedIn's OpenID Connect implementation.
frontend/src/features/auth/components/UsersDataGrid.tsx (2)
36-41: LGTM!The LinkedIn provider rendering follows the existing pattern with appropriate branding colors.
133-133: LGTM!Increasing the column width to 1.5fr provides better space for displaying multiple identity providers.
frontend/src/features/auth/components/AddOAuthDialog.tsx (1)
17-18: LGTM!Type definitions correctly extended to include LinkedIn across all relevant interfaces and state.
Also applies to: 28-28, 42-42
frontend/src/features/auth/components/AuthMethodTab.tsx (1)
6-6: LGTM!LinkedIn provider integration follows the existing pattern for Google and GitHub with appropriate branding and configuration.
Based on learnings
Also applies to: 35-41, 45-45, 109-109, 118-118
backend/src/api/routes/auth.oauth.ts (2)
187-195: LGTM!The LinkedIn payload mapping in the shared callback correctly transforms the provider data into the LinkedInUserInfo format and invokes the appropriate user creation method.
265-282: LGTM!The LinkedIn provider callback handles both token and code flows correctly, following the same pattern as Google.
backend/src/core/auth/auth.ts (1)
917-932: LGTM!The LinkedIn user creation flow correctly maps LinkedIn user info and delegates to the shared third-party user handler.
| /** | ||
| * Generate LinkedIn OAuth authorization URL | ||
| */ | ||
| async generateLinkedInAuthUrl(state?: string): Promise<string | undefined> { | ||
| const oauthConfigService = OAuthConfigService.getInstance(); | ||
| const config = await oauthConfigService.getConfigByProvider('linkedin'); | ||
|
|
||
| if (!config) { | ||
| throw new Error('LinkedIn OAuth not configured'); | ||
| } | ||
|
|
||
| const selfBaseUrl = process.env.API_BASE_URL || 'http://localhost:7130'; | ||
|
|
||
| if (config?.useSharedKey) { | ||
| if (!state) { | ||
| logger.warn('Shared LinkedIn OAuth called without state parameter'); | ||
| throw new Error('State parameter is required for shared LinkedIn 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/linkedin?redirect_uri=${encodeURIComponent(redirectUri)}`, | ||
| { | ||
| headers: { | ||
| 'Content-Type': 'application/json', | ||
| }, | ||
| } | ||
| ); | ||
| return response.data.auth_url || response.data.url || ''; | ||
| } | ||
|
|
||
| logger.debug('LinkedIn OAuth Config (fresh from DB):', { | ||
| clientId: config.clientId ? 'SET' : 'NOT SET', | ||
| }); | ||
|
|
||
| const authUrl = new URL('https://www.linkedin.com/oauth/v2/authorization'); | ||
| authUrl.searchParams.set('client_id', config.clientId ?? ''); | ||
| authUrl.searchParams.set('redirect_uri', `${selfBaseUrl}/api/auth/oauth/linkedin/callback`); | ||
| authUrl.searchParams.set('response_type', 'code'); | ||
| authUrl.searchParams.set( | ||
| 'scope', | ||
| config.scopes ? config.scopes.join(' ') : 'openid profile email' | ||
| ); | ||
| if (state) { | ||
| authUrl.searchParams.set('state', state); | ||
| } | ||
|
|
||
| return authUrl.toString(); | ||
| } |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major
Use getApiBaseUrl() helper for consistency.
Lines 766 and 836 hardcode process.env.API_BASE_URL || 'http://localhost:7130' instead of using the existing getApiBaseUrl() helper (imported on line 30). The Google and GitHub methods use getApiBaseUrl() for consistency.
Apply this diff:
async generateLinkedInAuthUrl(state?: string): Promise<string | undefined> {
const oauthConfigService = OAuthConfigService.getInstance();
const config = await oauthConfigService.getConfigByProvider('linkedin');
if (!config) {
throw new Error('LinkedIn OAuth not configured');
}
- const selfBaseUrl = process.env.API_BASE_URL || 'http://localhost:7130';
+ const selfBaseUrl = getApiBaseUrl();
if (config?.useSharedKey) {And in exchangeCodeToTokenByLinkedIn:
});
const clientSecret = await oauthConfigService.getClientSecretByProvider('linkedin');
- const selfBaseUrl = process.env.API_BASE_URL || 'http://localhost:7130';
+ const selfBaseUrl = getApiBaseUrl();
const response = await axios.post(Committable suggestion skipped: line range outside the PR's diff.
@Fermionic-Lyu fixed the UI and rebased my branch with main Cc: @tonychang04 |
Fermionic-Lyu
left a comment
There was a problem hiding this comment.
Tested and working. LGTM!
|
I have some slight concerns over this code rabbits comment. lmk if you can fix this? otherwise LGTM! |
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (3)
backend/src/core/auth/auth.ts (3)
766-766: UsegetApiBaseUrl()helper for consistency.This hardcoded approach is inconsistent with the Google (line 444) and GitHub (line 496) methods, which use the imported
getApiBaseUrl()helper. This issue was previously flagged but remains unaddressed.Apply this diff:
- const selfBaseUrl = process.env.API_BASE_URL || 'http://localhost:7130'; + const selfBaseUrl = getApiBaseUrl();
836-836: UsegetApiBaseUrl()helper for consistency.Same issue as in
generateLinkedInAuthUrl- this hardcoded approach is inconsistent with Google (line 564) and GitHub (line 682) methods.Apply this diff:
- const selfBaseUrl = process.env.API_BASE_URL || 'http://localhost:7130'; + const selfBaseUrl = getApiBaseUrl();
835-846: Guard missing LinkedIn client secret before token exchange.The code retrieves
clientSecretbut doesn't validate it before constructing the request. Sending an empty or null secret to LinkedIn will fail. This issue was previously flagged but remains unaddressed.Apply this diff:
const clientSecret = await oauthConfigService.getClientSecretByProvider('linkedin'); + if (!clientSecret) { + throw new Error('LinkedIn Client Secret not configured'); + } const selfBaseUrl = process.env.API_BASE_URL || 'http://localhost:7130';
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
package-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (2)
backend/package.json(1 hunks)backend/src/core/auth/auth.ts(6 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
🧬 Code graph analysis (1)
backend/src/core/auth/auth.ts (3)
backend/src/types/auth.ts (3)
GoogleUserInfo(66-75)GitHubUserInfo(77-83)LinkedInUserInfo(92-101)backend/src/core/auth/oauth.ts (1)
OAuthConfigService(26-400)shared-schemas/src/auth-api.schema.ts (1)
CreateSessionResponse(185-185)
🪛 GitHub Actions: Lint and Format Check
backend/src/core/auth/auth.ts
[error] 898-898: prettier/prettier: Delete ······ (unnecessary whitespace) at line 898.
🪛 GitHub Check: lint-and-format
backend/src/core/auth/auth.ts
[failure] 898-898:
Delete ······
🪛 Gitleaks (8.28.0)
backend/src/core/auth/auth.ts
[high] 924-924: 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). (1)
- GitHub Check: E2E Tests
🔇 Additional comments (5)
backend/package.json (1)
52-52: Verify the intent of the jose version bump.The update from
^6.0.12to^6.1.0is a safe, backward-compatible minor version bump within the v6.x line. However, the new features introduced in 6.1.0 (AKP JWKs support and ML-DSA post-quantum algorithms) don't appear directly related to LinkedIn OAuth support. Clarify whether this is a proactive dependency maintenance update or if the LinkedIn OAuth implementation relies on specific 6.1.0 behaviors or fixes.Please verify:
- Whether the version bump is intentional (maintenance) or required by the LinkedIn OAuth changes.
- Whether the new 6.1.0 features (AKP JWKs, ML-DSA PQC algorithms) are utilized anywhere in the OAuth flow or if they are future-proofing.
Based on learnings, v6.1.0 is the latest stable release and has no breaking changes relative to 6.0.x, so the update is safe to proceed with.
backend/src/core/auth/auth.ts (4)
22-28: LGTM! Import added for LinkedIn support.The
LinkedInUserInfoimport is correctly added alongside existing OAuth provider types.
285-285: LGTM! Type signature extended for LinkedIn.The union type correctly includes
LinkedInUserInfoto support the new provider.
920-935: LGTM! LinkedIn user creation follows established pattern.The implementation correctly mirrors the Google and GitHub user creation flows.
Note: The Gitleaks warning on line 924 is a false positive - it's flagging the variable name
linkedinUserInfo, not an actual secret.
896-896: Dependency verified.
joseis installed with version ^6.1.0 in the backend dependencies.
|
@tonychang04 added |

Summary
closes #385
Added LinkedIn OAuth support following the same pattern as Google/GitHub OAuth. Users can now configure LinkedIn authentication in the dashboard with shared keys or custom credentials.
Backend Changes:
openid,profile,email)fetchwithaxiosin all OAuth methodsFrontend Changes:
'linkedin'How did you test this change?
docker compose up_oauth_configstable with correct scopesScreen.Recording.2025-10-14.at.6.mp4
Summary by CodeRabbit
New Features
UI/UX Updates
Documentation
Chores