Skip to content

Added linkedin oauth provider - #421

Merged
tonychang04 merged 6 commits into
InsForge:mainfrom
HarshSharma0801:harsh/feat/385/linkedin-oauth
Oct 17, 2025
Merged

tonychang04 merged 6 commits into
InsForge:mainfrom
HarshSharma0801:harsh/feat/385/linkedin-oauth

Conversation

@HarshSharma0801

@HarshSharma0801 HarshSharma0801 commented Oct 14, 2025 •

Copy link
Copy Markdown
Contributor

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:

  • Added LinkedIn OAuth methods (generate auth URL, exchange tokens, verify tokens, create/find users)
  • Added LinkedIn routes and callbacks
  • Added LinkedIn type definitions and default scopes (openid, profile, email)
  • Fixed code consistency: replaced fetch with axios in all OAuth methods

Frontend Changes:

  • Added LinkedIn logo and provider option in Auth Method settings
  • Updated type definitions to include 'linkedin'
  • LinkedIn appears in "Add Auth" dialog with same UI as Google/GitHub

How did you test this change?

  1. Started InsForge with docker compose up
  2. Accessed dashboard at http://localhost:7131
  3. Navigated to Settings → Authentication → Auth Method
  4. Clicked "Add Auth" → Selected LinkedIn
  5. Configured with shared keys → Received 200 OK
  6. Verified LinkedIn OAuth card appears in UI
  7. Tested Edit/Delete functionality
  8. Verified database entry in _oauth_configs table with correct scopes
Screen.Recording.2025-10-14.at.6.mp4

Summary by CodeRabbit

  • New Features

    • LinkedIn OAuth authentication is now available as a supported provider.
  • UI/UX Updates

    • LinkedIn added to OAuth setup dialogs and authentication method selection.
    • LinkedIn appears in user management with branding and icon.
    • Identities list layout improved (wider column and refined badge styling).
  • Documentation

    • Environment example updated to include LinkedIn credential placeholders.
  • Chores

    • Backend dependency updated.

@HarshSharma0801

Copy link
Copy Markdown
Contributor Author

@tonychang04 pls review ! this let me know if anything is needed in this

@Fermionic-Lyu
Fermionic-Lyu self-requested a review October 15, 2025 20:24
@Fermionic-Lyu

Copy link
Copy Markdown
Member

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

@HarshSharma0801

Copy link
Copy Markdown
Contributor Author

@Fermionic-Lyu sure ! here's a video demonstrating whole flow

Screen.Recording.2025-10-16.at.2.mp4

@Fermionic-Lyu Fermionic-Lyu left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We built your PR to a new image and tested internally. It worked smoothly, great work! Just some chore comments here:

Image

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.

Comment thread backend/src/core/auth/auth.ts Resolved
@coderabbitai

coderabbitai Bot commented Oct 17, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds LinkedIn OAuth support across backend and frontend: environment example, new LinkedInUserInfo type, auth service methods and routes for LinkedIn (init + callback + token exchange/verify), default scopes, frontend provider UI/dialog updates, small users-grid layout/styling change, and a dependency bump.

Changes

Cohort / File(s) Summary
Configuration & Types
\.env\.example, backend/src/types/auth.ts
Adds LINKEDIN_CLIENT_ID / LINKEDIN_CLIENT_SECRET to env example and introduces exported LinkedInUserInfo interface (sub, email, optional email_verified, name, picture, given_name, family_name, locale).
Backend — OAuth Routes
backend/src/api/routes/auth.oauth.ts
Adds GET /api/auth/oauth/linkedin init endpoint; extends shared and provider callback handlers to include "linkedin", maps LinkedIn payload to linkedinUserInfo, and invokes authService.findOrCreateLinkedInUser.
Backend — Auth Service
backend/src/core/auth/auth.ts
Exposes LinkedIn methods: generateLinkedInAuthUrl, exchangeCodeToTokenByLinkedIn, verifyLinkedInToken, findOrCreateLinkedInUser; expands findOrCreateThirdPartyUser / createThirdPartyUser parameter unions to include LinkedInUserInfo; adds LinkedIn-specific token exchange/verify and logging.
Backend — OAuth Config
backend/src/core/auth/oauth.ts
Sets default scopes for linkedin to ['openid','profile','email'] when no scopes provided.
Frontend — OAuth Dialog
frontend/src/features/auth/components/AddOAuthDialog.tsx
Expands onConfirm prop, enabledProviders, and internal selection state to accept 'linkedin'.
Frontend — Auth Methods UI
frontend/src/features/auth/components/AuthMethodTab.tsx
Adds LinkedIn provider entry (logo, name, description, setup URL), updates OAuthProviderInfo.id, deleteOAuthConfig, and selection handlers to include 'linkedin'.
Frontend — Users Grid
frontend/src/features/auth/components/UsersDataGrid.tsx
Renders LinkedIn provider icon/label in provider badges; adjusts identities badge padding and increases identities column width from 1fr → 1.5fr.
Deps
backend/package.json
Bumps jose dependency from ^6.0.12 → ^6.1.0.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 I hopped through envs and endpoint trees,
LinkedIn joins our circle, strings and keys.
Codes exchanged and tokens flown,
Profiles stitched and sessions sown.
✨🔗

Pre-merge checks and finishing touches

✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The pull request title "Added linkedin oauth provider" directly describes the main objective and primary change of this changeset. The title is concise, clear, and accurately summarizes that LinkedIn OAuth provider support has been added to the system. A developer scanning the repository history would immediately understand that this PR introduces LinkedIn as a new OAuth provider alongside existing ones like Google and GitHub.
Out of Scope Changes Check ✅ Passed All code changes in this PR are directly related to implementing LinkedIn OAuth support as specified in issue #385. The environment configuration additions, backend OAuth methods and routes, type definitions, and frontend UI components all serve the core objective of adding LinkedIn as a supported provider. The jose dependency update from ^6.0.12 to ^6.1.0 appears to be a necessary supporting change for proper LinkedIn JWT token verification and handling. No changes appear to address requirements outside the scope of implementing LinkedIn OAuth support.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2cee090 and 610cefe.

📒 Files selected for processing (1)
  • 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 (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)
🪛 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)
  • GitHub Check: CI Pre-merge Check
  • GitHub Check: E2E Tests
🔇 Additional comments (4)
backend/src/core/auth/auth.ts (4)

22-28: LGTM: Import changes are correct.

The LinkedInUserInfo import follows the existing pattern for other OAuth providers.


285-285: LGTM: Type signature correctly updated.

The LinkedInUserInfo union type is consistent with other OAuth providers.


364-364: LGTM: Type signature correctly updated.

The LinkedInUserInfo union type is consistent with other OAuth providers.


920-935: LGTM: LinkedIn user creation follows established pattern.

The implementation correctly mirrors the Google and GitHub user creation flows.


Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 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 email and name leaks 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 payload shape 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 nonce and 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

📥 Commits

Reviewing files that changed from the base of the PR and between 078de82 and f1f060e.

⛔ Files ignored due to path filters (1)
  • frontend/src/assets/logos/linkedin.svg is 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.ts
  • backend/src/types/auth.ts
  • frontend/src/features/auth/components/UsersDataGrid.tsx
  • backend/src/api/routes/auth.oauth.ts
  • frontend/src/features/auth/components/AddOAuthDialog.tsx
  • backend/src/core/auth/auth.ts
  • frontend/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.ts
  • backend/src/types/auth.ts
  • backend/src/api/routes/auth.oauth.ts
  • 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/oauth.ts
  • 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/oauth.ts
  • backend/src/types/auth.ts
  • frontend/src/features/auth/components/UsersDataGrid.tsx
  • backend/src/api/routes/auth.oauth.ts
  • frontend/src/features/auth/components/AddOAuthDialog.tsx
  • backend/src/core/auth/auth.ts
  • frontend/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.ts
  • backend/src/types/auth.ts
  • backend/src/api/routes/auth.oauth.ts
  • 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/components/UsersDataGrid.tsx
  • frontend/src/features/auth/components/AddOAuthDialog.tsx
  • frontend/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.tsx
  • frontend/src/features/auth/components/AddOAuthDialog.tsx
  • frontend/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.tsx
  • frontend/src/features/auth/components/AddOAuthDialog.tsx
  • frontend/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.tsx
  • frontend/src/features/auth/components/AddOAuthDialog.tsx
  • frontend/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.data looks 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 via OAuthConfigService.getClientSecretByProvider() (line 834) rather than hardcoded, following best practices for secret management. No actionable security concerns found.

Comment on lines +90 to +121
// 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
)
);
}
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Avoid JWT state fallback secret and validate redirect_uri.

  • Using process.env.JWT_SECRET || 'default_secret' weakens security; fail fast if unset.
  • Validate redirect_uri against 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.

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

Comment on lines +834 to +845
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',
}),
{

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

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.

Comment on lines +71 to +74
const deleteOAuthConfig = async (
providerId: 'google' | 'github' | 'linkedin',
providerName: string
) => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

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.

Comment thread test-linkedin-oauth.html Outdated
Comment on lines +200 to +226
// 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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

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.

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

@HarshSharma0801
HarshSharma0801 force-pushed the harsh/feat/385/linkedin-oauth branch from f1f060e to af31abc Compare October 17, 2025 10:59

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (4)
frontend/src/features/auth/components/AuthMethodTab.tsx (1)

71-90: Missing await on async deleteConfig call.

The deleteConfig call 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:

  1. Line 103: Using process.env.JWT_SECRET || 'default_secret' is unsafe. Fail fast if JWT_SECRET is not set.
  2. 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 jose via npm install jose and add it to dependencies.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f1f060e and af31abc.

⛔ Files ignored due to path filters (1)
  • frontend/src/assets/logos/linkedin.svg is 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.ts
  • backend/src/api/routes/auth.oauth.ts
  • frontend/src/features/auth/components/AddOAuthDialog.tsx
  • frontend/src/features/auth/components/UsersDataGrid.tsx
  • frontend/src/features/auth/components/AuthMethodTab.tsx
  • 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/oauth.ts
  • backend/src/api/routes/auth.oauth.ts
  • 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/oauth.ts
  • 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/oauth.ts
  • backend/src/api/routes/auth.oauth.ts
  • frontend/src/features/auth/components/AddOAuthDialog.tsx
  • frontend/src/features/auth/components/UsersDataGrid.tsx
  • frontend/src/features/auth/components/AuthMethodTab.tsx
  • 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/oauth.ts
  • backend/src/api/routes/auth.oauth.ts
  • backend/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.tsx
  • frontend/src/features/auth/components/UsersDataGrid.tsx
  • frontend/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.tsx
  • frontend/src/features/auth/components/UsersDataGrid.tsx
  • frontend/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.tsx
  • frontend/src/features/auth/components/UsersDataGrid.tsx
  • frontend/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.tsx
  • frontend/src/features/auth/components/UsersDataGrid.tsx
  • frontend/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.

Comment on lines +755 to +803
/**
* 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();
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ 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.

@HarshSharma0801

Copy link
Copy Markdown
Contributor Author
Screenshot 2025-10-17 at 4 17 08 PM

@Fermionic-Lyu fixed the UI and rebased my branch with main Cc: @tonychang04

@Fermionic-Lyu Fermionic-Lyu left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tested and working. LGTM!

@tonychang04

tonychang04 commented Oct 17, 2025 •

Copy link
Copy Markdown
Member

#421 (comment)

I have some slight concerns over this code rabbits comment. lmk if you can fix this?

otherwise LGTM!

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (3)
backend/src/core/auth/auth.ts (3)

766-766: Use getApiBaseUrl() 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: Use getApiBaseUrl() 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 clientSecret but 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

📥 Commits

Reviewing files that changed from the base of the PR and between af31abc and 2cee090.

⛔ Files ignored due to path filters (1)
  • package-lock.json is 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.12 to ^6.1.0 is 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:

  1. Whether the version bump is intentional (maintenance) or required by the LinkedIn OAuth changes.
  2. 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 LinkedInUserInfo import is correctly added alongside existing OAuth provider types.


285-285: LGTM! Type signature extended for LinkedIn.

The union type correctly includes LinkedInUserInfo to 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.

jose is installed with version ^6.1.0 in the backend dependencies.

Comment thread backend/src/core/auth/auth.ts Resolved
@HarshSharma0801

Copy link
Copy Markdown
Contributor Author

@tonychang04 added jose for linkedin's jwks verification

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: Support Linkedin Oauth

3 participants