Skip to content

feat : #384 - mircrosoft oauth support added - #436

Merged
tonychang04 merged 10 commits into
InsForge:mainfrom
RaghavGanesh7:feat/#384-microsoft-oauth
Oct 21, 2025
Merged

tonychang04 merged 10 commits into
InsForge:mainfrom
RaghavGanesh7:feat/#384-microsoft-oauth

Conversation

@RaghavGanesh7

@RaghavGanesh7 RaghavGanesh7 commented Oct 15, 2025 •

Copy link
Copy Markdown
Contributor

Summary

  • Added Microsoft OAuth as a first-class provider.
    • Backend
      • New route: GET /api/auth/oauth/microsoft (returns consent URL with state).
      • Extended callback: GET /api/auth/oauth/:provider/callback now supports microsoft.
      • New helpers in backend/src/core/auth/auth.ts: generateMicrosoftAuthUrl, exchangeCodeToTokenByMicrosoft, getMicrosoftUserInfo, findOrCreateMicrosoftUser.
      • Default scopes for Microsoft in backend/src/core/auth/oauth.ts (openid email profile offline_access User.Read).
    • Schemas
      • Extended provider enum to include microsoft in shared-schemas/src/auth.schema.ts.
    • Frontend (admin)
      • Enabled Microsoft in AddOAuthDialog and AuthMethodTab provider types and selection.
      • Added Microsoft logo asset.
    • Docs
      • New MICROSOFT_OAUTH_SETUP.md (setup, endpoints, flow).
    • Env
      • Documented MICROSOFT_CLIENT_ID and MICROSOFT_CLIENT_SECRET for .env/env.example.

How did you test this change?

  • Configuration
    • Created Azure app registration; added Web redirect URI http://localhost:7130/api/auth/oauth/microsoft/callback.
    • Granted Microsoft Graph delegated permission User.Read.
    • In admin UI (AuthMethodTab), added Microsoft OAuth config with clientId and clientSecret (left scopes blank to use defaults).
  • Auth URL
    • Called GET /api/auth/oauth/microsoft?redirect_uri=http://localhost:7131/oauth/callback and verified a valid Microsoft consent URL was returned.
  • Login flow
    • Navigated to the returned consent URL, signed in, and confirmed the backend callback redirected to redirect_uri with access_token, user_id, email, name query params.

Summary by CodeRabbit

  • New Features

    • Microsoft OAuth authentication is now supported — users can sign in and link Microsoft accounts alongside Google, GitHub, Discord, LinkedIn, and Facebook.
    • Microsoft appears in OAuth setup and provider selection UIs and dialogs.
  • Documentation

    • Environment example updated with Microsoft OAuth variables (client ID and secret).

@coderabbitai

coderabbitai Bot commented Oct 15, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds Microsoft OAuth across the stack: environment variables, backend routes and auth service methods/types, OAuth config defaults, and frontend UI/components to enable Microsoft account authentication and session creation.

Changes

Cohort / File(s) Summary
Configuration & Environment
\.env.example``
Adds MICROSOFT_CLIENT_ID and MICROSOFT_CLIENT_SECRET variables with an explanatory comment.
Type Definitions
backend/src/types/auth.ts
Adds exported MicrosoftUserInfo interface: id: string, email: string, name: string, optional avatar_url?: string.
Backend OAuth Routes
backend/src/api/routes/auth.oauth.ts
Adds GET /api/auth/oauth/microsoft endpoint to initialize Microsoft OAuth (validate redirect_uri, create state JWT, generate auth URL); extends callback handling, provider validation, token exchange, user info retrieval, and maps payload to findOrCreateMicrosoftUser; updates error handling for Microsoft flows.
Backend OAuth Configuration
backend/src/core/auth/oauth.ts
Adds default OAuth scope ['User.Read'] for provider microsoft when scopes are not provided.
Backend Authentication Service
backend/src/core/auth/auth.ts
Imports MicrosoftUserInfo; extends findOrCreateThirdPartyUser and createThirdPartyUser signatures to accept MicrosoftUserInfo; adds methods: generateMicrosoftAuthUrl(state?), exchangeCodeToTokenByMicrosoft(code), getMicrosoftUserInfo(accessToken), findOrCreateMicrosoftUser(msUserInfo).
Frontend OAuth Dialog
frontend/src/features/auth/components/AddOAuthDialog.tsx
Expands provider unions and internal state to include 'microsoft'; updates onConfirm and enabledProviders prop types and selectProvider handler types.
Frontend Authentication Methods
frontend/src/features/auth/components/AuthMethodTab.tsx
Adds Microsoft provider entry (id 'microsoft', icon, description, setup URL); extends OAuthProviderInfo id union; updates deleteOAuthConfig, handleConfirmSelected, enabled/provider checks and UI rendering to include Microsoft.

Sequence Diagram(s)

sequenceDiagram
    participant User as User
    participant Frontend as Frontend
    participant Backend as Backend
    participant Microsoft as Microsoft OAuth
    participant DB as Database

    User->>Frontend: Click "Add Microsoft OAuth"
    Frontend->>Backend: GET /api/auth/oauth/microsoft?redirect_uri=...
    Backend->>Backend: validate redirect_uri & create state JWT
    Backend->>Microsoft: build auth URL (state)
    Microsoft-->>Backend: auth URL
    Backend-->>Frontend: return auth URL
    Frontend->>Microsoft: Redirect user to auth URL
    Microsoft->>User: login & consent
    Microsoft->>Frontend: Redirect back with code & state
    Frontend->>Backend: POST/GET /api/auth/callback?code=...&state=...
    Backend->>Backend: verify state JWT
    Backend->>Microsoft: exchange code for token
    Microsoft-->>Backend: access token (+id_token?)
    Backend->>Microsoft: fetch user info (User.Read)
    Microsoft-->>Backend: user info (id, email, name, avatar)
    Backend->>DB: findOrCreate user using MicrosoftUserInfo
    DB-->>Backend: user record
    Backend-->>Frontend: create session / return user
    Frontend-->>User: authenticated
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20-30 minutes

Possibly related PRs

Suggested reviewers

  • tonychang04
  • Fermionic-Lyu

Poem

🐰 I hopped through code with eager paws,

Brought Microsoft keys and OAuth laws,
From .env seeds to callback trails,
Tokens, users, session details,
A rabbit cheers — auth now scales! ✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The pull request title "feat : #384 - mircrosoft oauth support added" is directly related to the main changes in the changeset. The PR comprehensively adds Microsoft OAuth support across the backend (new routes, helper methods, token exchange), frontend (UI extensions), type definitions (MicrosoftUserInfo interface), and configuration (environment variables). The title accurately captures this primary objective and would be immediately understandable to a teammate scanning the project history. While the title contains a minor typo ("mircrosoft" instead of "microsoft") and some formatting verbosity, these issues do not obscure the core message or mislead about the changeset's purpose.
✨ 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 215b783 and dae5947.

📒 Files selected for processing (1)
  • frontend/src/features/auth/components/AddOAuthDialog.tsx (3 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx}: Use TypeScript for all code files
Use ES modules (import/export syntax)
Prefer descriptive, unabbreviated variable and function names
Implement proper error handling with try-catch blocks and logging where appropriate
Use single quotes for strings
Include semicolons at the end of statements
Use arrow functions for callbacks and inline functions
Prefer const over let; avoid var
Use template literals for string interpolation
Maintain 2-space indentation
Format code with the repository Prettier configuration
Variables, parameters, properties, and functions must use camelCase
Constants and enum members must use UPPER_CASE
Include JSDoc comments for complex functions

Files:

  • frontend/src/features/auth/components/AddOAuthDialog.tsx
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/**/*.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/**/*.{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
**/*.{tsx,ts}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

React components and TypeScript types/interfaces must use PascalCase

Files:

  • frontend/src/features/auth/components/AddOAuthDialog.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
🔇 Additional comments (1)
frontend/src/features/auth/components/AddOAuthDialog.tsx (1)

47-47: No type safety issues found.

The verification confirms that OAuthProviderInfo.id and all related code are properly typed. The enabledProviders Record uses matching key types, and selectProvider accepts the correct union type. Lines 47 and 75 are type-safe.


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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
backend/src/api/routes/auth.oauth.ts (1)

147-150: Allow microsoft in shared callback provider check

The shared callback still rejects any provider not in ['google', 'github'], so Microsoft flows will always raise Invalid provider in state before your new branch can execute. Extend the allowlist to include microsoft; otherwise the new OAuth path is broken.

-    if (!['google', 'github'].includes(provider)) {
+    if (!['google', 'github', 'microsoft'].includes(provider)) {
🧹 Nitpick comments (1)
backend/src/types/auth.ts (1)

92-97: Align MicrosoftUserInfo with actual Graph payload

getMicrosoftUserInfo (and the identity data we persist) expose id, displayName, and userPrincipalName, not sub/name. Keeping the interface in this mismatched shape undermines type-safety for any downstream consumer. Please update the interface to mirror the real payload (or adjust the helper to emit the defined shape). For example:

-export interface MicrosoftUserInfo {
-  sub: string;
-  email: string;
-  name: string;
-  avatar_url?: string;
-}
+export interface MicrosoftUserInfo {
+  id: string;
+  email: string;
+  displayName?: string;
+  userPrincipalName?: string;
+  avatar_url?: string;
+}
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e7ed615 and cbda6bb.

⛔ Files ignored due to path filters (1)
  • frontend/src/assets/logos/microsoft.svg is excluded by !**/*.svg
📒 Files selected for processing (9)
  • .env.example (1 hunks)
  • MICROSOFT_OAUTH_SETUP.md (1 hunks)
  • backend/src/api/routes/auth.oauth.ts (4 hunks)
  • backend/src/core/auth/auth.ts (4 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)
  • shared-schemas/src/auth.schema.ts (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/types/auth.ts
  • frontend/src/features/auth/components/AddOAuthDialog.tsx
  • backend/src/core/auth/auth.ts
  • backend/src/core/auth/oauth.ts
  • shared-schemas/src/auth.schema.ts
  • backend/src/api/routes/auth.oauth.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/types/auth.ts
  • backend/src/core/auth/auth.ts
  • backend/src/core/auth/oauth.ts
  • backend/src/api/routes/auth.oauth.ts
**/*.{tsx,ts}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

React components and TypeScript types/interfaces must use PascalCase

Files:

  • backend/src/types/auth.ts
  • frontend/src/features/auth/components/AddOAuthDialog.tsx
  • backend/src/core/auth/auth.ts
  • backend/src/core/auth/oauth.ts
  • shared-schemas/src/auth.schema.ts
  • backend/src/api/routes/auth.oauth.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/types/auth.ts
  • backend/src/core/auth/auth.ts
  • backend/src/core/auth/oauth.ts
  • shared-schemas/src/auth.schema.ts
  • 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/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/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/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/AuthMethodTab.tsx
backend/src/{controllers,core}/**/*.ts

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Implement proper database transaction handling

Files:

  • backend/src/core/auth/auth.ts
  • backend/src/core/auth/oauth.ts
**/.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/core/auth/auth.ts (2)
backend/src/types/auth.ts (1)
  • MicrosoftUserInfo (92-97)
backend/src/core/auth/oauth.ts (1)
  • OAuthConfigService (26-400)
backend/src/api/routes/auth.oauth.ts (1)
backend/src/api/middleware/error.ts (1)
  • AppError (7-17)
🪛 LanguageTool
MICROSOFT_OAUTH_SETUP.md

[grammar] ~6-~6: There might be a mistake here.
Context: .... ## Environment Variable Configuration Add these to your .env (or environment...

(QB_NEW_EN)


[grammar] ~21-~21: There might be a mistake here.
Context: ...ated → add: - User.Read 5. Save your: - Application (client) ID → `MICROSOFT_CLI...

(QB_NEW_EN)


[grammar] ~22-~22: There might be a mistake here.
Context: ...ve your: - Application (client) ID → MICROSOFT_CLIENT_ID - Client secret → `MICROSOFT_CLIENT_SECRET...

(QB_NEW_EN)


[grammar] ~25-~25: There might be a mistake here.
Context: ...LIENT_SECRET Authorized redirect URIs: - Development:http://localhost:7130/api/...

(QB_NEW_EN)


[grammar] ~26-~26: There might be a mistake here.
Context: ...uthorized redirect URIs: - Development: http://localhost:7130/api/auth/oauth/microsoft/callback - Production: `https://yourdomain.com/api/...

(QB_NEW_EN)


[grammar] ~44-~44: There might be a mistake here.
Context: ...### 2) Microsoft OAuth Callback Handling Endpoint: `GET /api/auth/oauth/microsoft...

(QB_NEW_EN)


[grammar] ~51-~51: There might be a mistake here.
Context: ...fo (id, email, displayName). 4. Find or create local user and issue our app JWT. 5. Re...

(QB_NEW_EN)


[grammar] ~51-~51: There might be a mistake here.
Context: ...create local user and issue our app JWT. 5. Redirect to the original redirect_uri ...

(QB_NEW_EN)

Comment thread backend/src/core/auth/oauth.ts Outdated
Comment on lines 186 to 187
scopes = ['openid', 'email', 'profile'];
}

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 | 🔴 Critical

Microsoft defaults miss User.Read, breaking /me call

If an admin creates the Microsoft config without custom scopes, we persist ['openid','email','profile']. Later, generateMicrosoftAuthUrl reuses that list, so the consent flow omits User.Read. When we afterwards call https://graph.microsoft.com/v1.0/me, Microsoft responds 403 (insufficient privileges), and the login fails outright. Please align the stored defaults with the scopes we need for Graph:

-        } else if (provider === 'microsoft') {
-          scopes = ['openid', 'email', 'profile'];
+        } else if (provider === 'microsoft') {
+          scopes = ['openid', 'email', 'profile', 'offline_access', 'User.Read'];
📝 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
scopes = ['openid', 'email', 'profile'];
}
} else if (provider === 'microsoft') {
scopes = ['openid', 'email', 'profile', 'offline_access', 'User.Read'];
}
🤖 Prompt for AI Agents
In backend/src/core/auth/oauth.ts around lines 186-187, the default Microsoft
scopes are set to ['openid','email','profile'] which omits the Graph scope
needed for /me; update the default to include 'User.Read' (e.g.
['openid','email','profile','User.Read']) so stored configs and subsequent
generateMicrosoftAuthUrl flows request Graph consent and allow calls to
https://graph.microsoft.com/v1.0/me.

@tonychang04

Copy link
Copy Markdown
Member

Great work! Would love to see a video demo of the configuration working as intented!

@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

🧹 Nitpick comments (4)
examples/oauth/test-microsoft-oauth.html (2)

55-58: Simplify setText logic; current check is ambiguous.

Line 57's condition el.value ? el.value = text : el.textContent = text; is confusing and incorrect. It checks the truthiness of el.value, not whether the element has a value property. This could fail silently if an input field is empty (falsy value).

Apply this diff for clarity and correctness:

    function setText(id, text) {
      const el = document.getElementById(id);
-     if (el) el.value ? el.value = text : el.textContent = text;
+     if (!el) return;
+     if ('value' in el) {
+       el.value = text;
+     } else {
+       el.textContent = text;
+     }
    }

This checks for the property's existence rather than its truthiness.


111-111: Clarify why both access_token and token parameters are accepted.

Line 111 accepts both access_token and token as parameter names with a comment "be tolerant". This permissiveness could mask upstream issues if the backend changes or is inconsistent. Document the expected parameter name or refactor to enforce a single contract.

Either document why both are supported or standardize on one parameter name:

      // Backend appends access_token, user_id, email, name
-     const token = p.get('access_token') || p.get('token'); // be tolerant
+     const token = p.get('access_token'); // Backend provides access_token parameter

If fallback is intentional, add an explanatory comment about backward compatibility or alternative OAuth providers.

backend/src/core/auth/auth.ts (2)

772-794: Consider adding JSDoc comment for consistency.

The method logic is correct and follows the established pattern for OAuth authorization URL generation. However, consider adding a JSDoc comment similar to the other OAuth methods for consistency and maintainability.

Example:

+/**
+ * Generate Microsoft OAuth authorization URL
+ */
 async generateMicrosoftAuthUrl(state?: string): Promise<string> {

857-872: LGTM! Consider optional enhancements.

The method correctly follows the established OAuth pattern. Two optional enhancements to consider:

  1. JSDoc comment: Add documentation similar to other OAuth methods for consistency.
  2. Avatar URL: Currently empty because Microsoft Graph /me doesn't return the photo URL. If avatars are important, you could enhance this by making a separate call to /me/photo/$value or /me/photos/48x48/$value to retrieve the profile picture.
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cbda6bb and 4d0c8c9.

📒 Files selected for processing (3)
  • backend/src/core/auth/auth.ts (4 hunks)
  • backend/src/core/auth/oauth.ts (1 hunks)
  • examples/oauth/test-microsoft-oauth.html (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • backend/src/core/auth/oauth.ts
🧰 Additional context used
📓 Path-based instructions (5)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx}: Use TypeScript for all code files
Use ES modules (import/export syntax)
Prefer descriptive, unabbreviated variable and function names
Implement proper error handling with try-catch blocks and logging where appropriate
Use single quotes for strings
Include semicolons at the end of statements
Use arrow functions for callbacks and inline functions
Prefer const over let; avoid var
Use template literals for string interpolation
Maintain 2-space indentation
Format code with the repository Prettier configuration
Variables, parameters, properties, and functions must use camelCase
Constants and enum members must use UPPER_CASE
Include JSDoc comments for complex functions

Files:

  • backend/src/core/auth/auth.ts
backend/src/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

backend/src/**/*.{ts,tsx}: Use async/await for asynchronous operations in the backend
Use Zod schemas for request/response validation
Return consistent API responses using utility functions
Validate all user inputs
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper caching strategies (server-side)

Files:

  • backend/src/core/auth/auth.ts
backend/src/{controllers,core}/**/*.ts

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Implement proper database transaction handling

Files:

  • backend/src/core/auth/auth.ts
**/*.{tsx,ts}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

React components and TypeScript types/interfaces must use PascalCase

Files:

  • backend/src/core/auth/auth.ts
**/[a-z][a-z0-9-]*.ts

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Utility files should use kebab-case or camelCase (kebab-case validated here)

Files:

  • backend/src/core/auth/auth.ts
🧬 Code graph analysis (1)
backend/src/core/auth/auth.ts (3)
backend/src/types/auth.ts (1)
  • MicrosoftUserInfo (92-97)
backend/src/core/auth/oauth.ts (1)
  • OAuthConfigService (26-400)
shared-schemas/src/auth-api.schema.ts (1)
  • CreateSessionResponse (185-185)
🔇 Additional comments (3)
backend/src/core/auth/auth.ts (3)

22-28: LGTM!

The import of MicrosoftUserInfo is correctly added and needed for the new Microsoft OAuth functionality.


284-284: LGTM!

The type signature correctly extends the union to include MicrosoftUserInfo, maintaining consistency with the existing OAuth provider pattern.


363-363: LGTM!

The type signature update is consistent with the change in findOrCreateThirdPartyUser and correctly supports Microsoft OAuth.

Comment thread backend/src/core/auth/auth.ts Outdated
Comment on lines +797 to +832
async exchangeCodeToTokenByMicrosoft(
code: string
): Promise<{ access_token: string; id_token?: string }> {
const oauthConfigService = OAuthConfigService.getInstance();
const config = await oauthConfigService.getConfigByProvider('microsoft');
if (!config) {
throw new Error('Microsoft OAuth not configured');
}
const clientSecret = await oauthConfigService.getClientSecretByProvider('microsoft');
const selfBaseUrl = process.env.API_BASE_URL || 'http://localhost:7130';

const body = new URLSearchParams({
client_id: config.clientId ?? '',
client_secret: clientSecret ?? '',
code,
redirect_uri: `${selfBaseUrl}/api/auth/oauth/microsoft/callback`,
grant_type: 'authorization_code',
scope: (config.scopes && config.scopes.length > 0)
? config.scopes.join(' ')
: 'openid email profile offline_access User.Read',
});

const response = await axios.post(
'https://login.microsoftonline.com/common/oauth2/v2.0/token',
body.toString(),
{ headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
);

if (!response.data.access_token) {
throw new Error('Failed to get access token from Microsoft');
}
return {
access_token: response.data.access_token,
id_token: response.data.id_token, // optional
};
}

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

Add code deduplication and error handling consistent with Google OAuth.

This method is missing critical safeguards present in exchangeCodeToTokenByGoogle:

  1. Missing code deduplication (lines 556-562, 573, 600-606 in Google implementation): Without the processedCodes Set and tokenCache Map, concurrent requests with the same code can cause race conditions.

  2. Missing error handling and logging (lines 609-621 in Google implementation): No try-catch block, axios error handling, or logging for debugging failed token exchanges.

  3. Unnecessary scope parameter (lines 814-816): Microsoft's token endpoint doesn't require the scope parameter—it's already established during authorization. This is non-standard and could cause issues.

Apply this diff to add the missing safeguards:

 async exchangeCodeToTokenByMicrosoft(
   code: string
 ): Promise<{ access_token: string; id_token?: string }> {
+  // Check cache first
+  if (this.processedCodes.has(code)) {
+    const cachedTokens = this.tokenCache.get(code);
+    if (cachedTokens) {
+      logger.debug('Returning cached tokens for already processed code.');
+      return { access_token: cachedTokens.access_token, id_token: cachedTokens.id_token };
+    }
+    throw new Error('Authorization code is currently being processed.');
+  }
+
   const oauthConfigService = OAuthConfigService.getInstance();
   const config = await oauthConfigService.getConfigByProvider('microsoft');
   if (!config) {
     throw new Error('Microsoft OAuth not configured');
   }
-  const clientSecret = await oauthConfigService.getClientSecretByProvider('microsoft');
-  const selfBaseUrl = process.env.API_BASE_URL || 'http://localhost:7130';
-  
-  const body = new URLSearchParams({
-    client_id: config.clientId ?? '',
-    client_secret: clientSecret ?? '',
-    code,
-    redirect_uri: `${selfBaseUrl}/api/auth/oauth/microsoft/callback`,
-    grant_type: 'authorization_code',
-    scope: (config.scopes && config.scopes.length > 0)
-      ? config.scopes.join(' ')
-      : 'openid email profile offline_access User.Read',
-  });
-
-  const response = await axios.post(
-    'https://login.microsoftonline.com/common/oauth2/v2.0/token',
-    body.toString(),
-    { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
-  );
-
-  if (!response.data.access_token) {
-    throw new Error('Failed to get access token from Microsoft');
-  }
-  return {
-    access_token: response.data.access_token,
-    id_token: response.data.id_token, // optional
-  };
+
+  try {
+    this.processedCodes.add(code);
+
+    logger.info('Exchanging Microsoft code for tokens', {
+      hasCode: !!code,
+      clientId: config.clientId?.substring(0, 10) + '...',
+    });
+
+    const clientSecret = await oauthConfigService.getClientSecretByProvider('microsoft');
+    const selfBaseUrl = process.env.API_BASE_URL || 'http://localhost:7130';
+    
+    const body = new URLSearchParams({
+      client_id: config.clientId ?? '',
+      client_secret: clientSecret ?? '',
+      code,
+      redirect_uri: `${selfBaseUrl}/api/auth/oauth/microsoft/callback`,
+      grant_type: 'authorization_code',
+    });
+
+    const response = await axios.post(
+      'https://login.microsoftonline.com/common/oauth2/v2.0/token',
+      body.toString(),
+      { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
+    );
+
+    if (!response.data.access_token) {
+      throw new Error('Failed to get access token from Microsoft');
+    }
+
+    const result = {
+      access_token: response.data.access_token,
+      id_token: response.data.id_token,
+    };
+
+    // Cache the successful token exchange
+    this.tokenCache.set(code, result);
+
+    // Set a timeout to clear the code and cache to prevent memory leaks
+    setTimeout(() => {
+      this.processedCodes.delete(code);
+      this.tokenCache.delete(code);
+    }, 60000); // 1 minute timeout
+
+    return result;
+  } catch (error) {
+    // If the request fails, remove the code immediately to allow for a retry
+    this.processedCodes.delete(code);
+
+    if (axios.isAxiosError(error) && error.response) {
+      logger.error('Microsoft token exchange failed', {
+        status: error.response.status,
+        error: error.response.data,
+      });
+      throw new Error(`Microsoft OAuth error: ${JSON.stringify(error.response.data)}`);
+    }
+    throw error;
+  }
 }
🤖 Prompt for AI Agents
In backend/src/core/auth/auth.ts around lines 797 to 832, the Microsoft token
exchange lacks the deduplication, caching and robust error handling used by the
Google implementation: add use of the module-level processedCodes Set to
short-circuit repeated processing of the same code and a tokenCache Map to cache
and immediately return in-flight/previously fetched tokens for that code; remove
the scope field from the POST body (do not send scope to Microsoft's token
endpoint); wrap the axios.post call and response handling in a try-catch that
logs errors (using the same logger used in Google flow) and normalizes
axios/network errors to throw the same structured Error used by Google
exchangeCodeToTokenByGoogle; ensure processedCodes is cleaned up and tokenCache
is populated/cleared consistently to avoid leaks and race conditions.

Comment on lines +67 to +76
function showUser(user) {
const el = document.getElementById('user');
el.innerHTML = `
<div><strong>ID:</strong> ${user.id || ''}</div>
<div><strong>Email:</strong> ${user.email || ''}</div>
<div><strong>Name:</strong> ${user.name || ''}</div>
<div style="margin-top:8px;"><strong>JWT (localStorage):</strong> <code>${(localStorage.getItem('auth_token')||'').slice(0,24)}...</code></div>
`;
el.style.display = 'block';
}

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

Sanitize user data before rendering to prevent XSS.

User-controlled fields (email, name) are inserted directly via innerHTML without sanitization. While this test page is for internal development, best practice is to use textContent or sanitize HTML entities.

Apply this diff to safely render user data:

    function showUser(user) {
      const el = document.getElementById('user');
-     el.innerHTML = `
-       <div><strong>ID:</strong> ${user.id || ''}</div>
-       <div><strong>Email:</strong> ${user.email || ''}</div>
-       <div><strong>Name:</strong> ${user.name || ''}</div>
-       <div style="margin-top:8px;"><strong>JWT (localStorage):</strong> <code>${(localStorage.getItem('auth_token')||'').slice(0,24)}...</code></div>
-     `;
+     el.textContent = '';
+     const formatField = (label, value) => {
+       const div = document.createElement('div');
+       const strong = document.createElement('strong');
+       strong.textContent = label;
+       div.appendChild(strong);
+       div.appendChild(document.createTextNode(': ' + (value || '')));
+       el.appendChild(div);
+     };
+     formatField('ID', user.id);
+     formatField('Email', user.email);
+     formatField('Name', user.name);
+     const tokenDiv = document.createElement('div');
+     tokenDiv.style.marginTop = '8px';
+     const tokenStrong = document.createElement('strong');
+     tokenStrong.textContent = 'JWT (localStorage): ';
+     const tokenCode = document.createElement('code');
+     tokenCode.textContent = (localStorage.getItem('auth_token') || '').slice(0, 24) + '...';
+     tokenDiv.appendChild(tokenStrong);
+     tokenDiv.appendChild(tokenCode);
+     el.appendChild(tokenDiv);
📝 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
function showUser(user) {
const el = document.getElementById('user');
el.innerHTML = `
<div><strong>ID:</strong> ${user.id || ''}</div>
<div><strong>Email:</strong> ${user.email || ''}</div>
<div><strong>Name:</strong> ${user.name || ''}</div>
<div style="margin-top:8px;"><strong>JWT (localStorage):</strong> <code>${(localStorage.getItem('auth_token')||'').slice(0,24)}...</code></div>
`;
el.style.display = 'block';
}
function showUser(user) {
const el = document.getElementById('user');
el.textContent = '';
const formatField = (label, value) => {
const div = document.createElement('div');
const strong = document.createElement('strong');
strong.textContent = label;
div.appendChild(strong);
div.appendChild(document.createTextNode(': ' + (value || '')));
el.appendChild(div);
};
formatField('ID', user.id);
formatField('Email', user.email);
formatField('Name', user.name);
const tokenDiv = document.createElement('div');
tokenDiv.style.marginTop = '8px';
const tokenStrong = document.createElement('strong');
tokenStrong.textContent = 'JWT (localStorage): ';
const tokenCode = document.createElement('code');
tokenCode.textContent = (localStorage.getItem('auth_token') || '').slice(0, 24) + '...';
tokenDiv.appendChild(tokenStrong);
tokenDiv.appendChild(tokenCode);
el.appendChild(tokenDiv);
el.style.display = 'block';
}

Comment on lines +78 to +106
async function initiateMicrosoftLogin() {
const btn = document.getElementById('msLoginBtn');
const original = btn.textContent;
try {
btn.disabled = true;
btn.textContent = 'Getting authorization link...';

// FIX: Use the current page URL on port 7131
const redirect = "http://localhost/"; // This will be http://localhost:7131/...
setText('redirectUrl', redirect);

showStatus('Requesting Microsoft authorization URL...', 'info');

// Call backend API on 7130
const res = await fetch(`${API_BASE}/auth/oauth/microsoft?redirect_uri=${encodeURIComponent(redirect)}`);
const data = await res.json();
console.log('Microsoft OAuth response:', data);
if (data.authUrl) {
showStatus('Redirecting to Microsoft...', 'info');
window.location.href = data.authUrl;
} else {
throw new Error(data?.error?.message || 'Failed to get authorization link');
}
} catch (e) {
showStatus(`Error: ${e.message}`, 'error');
btn.disabled = false;
btn.textContent = original;
}
}

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 | 🔴 Critical

Redirect URL is hardcoded and non-functional.

Line 86 hardcodes redirect = "http://localhost/" with a comment claiming it should be http://localhost:7131/..., but the actual value won't work for the OAuth callback. The redirect must be a valid, full URL pointing to where this test page is being served (typically on port 7131), so the backend can redirect back after authentication.

Apply this diff to dynamically construct the redirect URL:

    // FIX: Use the current page URL on port 7131
-   const redirect = "http://localhost/"; // This will be http://localhost:7131/...
+   const redirect = `http://${window.location.hostname}:7131${window.location.pathname}`;

This assumes the test page is served on port 7131; adjust if running on a different port.

📝 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
async function initiateMicrosoftLogin() {
const btn = document.getElementById('msLoginBtn');
const original = btn.textContent;
try {
btn.disabled = true;
btn.textContent = 'Getting authorization link...';
// FIX: Use the current page URL on port 7131
const redirect = "http://localhost/"; // This will be http://localhost:7131/...
setText('redirectUrl', redirect);
showStatus('Requesting Microsoft authorization URL...', 'info');
// Call backend API on 7130
const res = await fetch(`${API_BASE}/auth/oauth/microsoft?redirect_uri=${encodeURIComponent(redirect)}`);
const data = await res.json();
console.log('Microsoft OAuth response:', data);
if (data.authUrl) {
showStatus('Redirecting to Microsoft...', 'info');
window.location.href = data.authUrl;
} else {
throw new Error(data?.error?.message || 'Failed to get authorization link');
}
} catch (e) {
showStatus(`Error: ${e.message}`, 'error');
btn.disabled = false;
btn.textContent = original;
}
}
async function initiateMicrosoftLogin() {
const btn = document.getElementById('msLoginBtn');
const original = btn.textContent;
try {
btn.disabled = true;
btn.textContent = 'Getting authorization link...';
// FIX: Use the current page URL on port 7131
const redirect = `http://${window.location.hostname}:7131${window.location.pathname}`;
setText('redirectUrl', redirect);
showStatus('Requesting Microsoft authorization URL...', 'info');
// Call backend API on 7130
const res = await fetch(`${API_BASE}/auth/oauth/microsoft?redirect_uri=${encodeURIComponent(redirect)}`);
const data = await res.json();
console.log('Microsoft OAuth response:', data);
if (data.authUrl) {
showStatus('Redirecting to Microsoft...', 'info');
window.location.href = data.authUrl;
} else {
throw new Error(data?.error?.message || 'Failed to get authorization link');
}
} catch (e) {
showStatus(`Error: ${e.message}`, 'error');
btn.disabled = false;
btn.textContent = original;
}
}
🤖 Prompt for AI Agents
In examples/oauth/test-microsoft-oauth.html around lines 78 to 106 the redirect
URL is hardcoded to "http://localhost/" which is invalid for the OAuth callback;
replace the hardcoded value with a dynamically constructed full URL that targets
this test page on port 7131 (e.g. derive protocol and hostname from
window.location and set port to 7131, preserving the current path or using '/'
as appropriate), assign that constructed URL to the redirect variable and pass
it to setText('redirectUrl', redirect) so the backend receives a valid
redirect_uri for Microsoft OAuth.

Comment on lines +125 to +131
if (token && userId) {
localStorage.setItem('auth_token', token);
localStorage.setItem('user_id', userId);
localStorage.setItem('user_email', email || '');
localStorage.setItem('user_name', name || '');
showStatus('Login successful!', 'success');
showUser({ id: userId, email, name });

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

Document security implications of localStorage for sensitive tokens.

The test page stores authentication tokens and user data in browser localStorage, which is vulnerable to XSS attacks and persists across page reloads. For a development/test page this may be acceptable, but add a prominent comment warning developers against using this approach in production.

Consider adding a security notice at the top of the file or as an inline comment:

  <script>
    const API_BASE = 'http://localhost:7130/api';
+   // ⚠️ WARNING: This test page stores auth tokens in localStorage.
+   // localStorage is NOT secure against XSS attacks. This is for development/testing only.
+   // Never use this pattern in production; prefer httpOnly, secure cookies instead.

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In examples/oauth/test-microsoft-oauth.html around lines 125-131, the code
stores auth tokens and user info in localStorage which is insecure for
production; add a prominent comment (either at the top of the file and/or
directly above this block) warning developers that localStorage is vulnerable to
XSS and should not be used for sensitive tokens in production, and recommend
safer alternatives (HttpOnly secure cookies, encrypted storage, or
platform-specific secure stores) and that this pattern is only acceptable for
local development/testing.

@RaghavGanesh7

Copy link
Copy Markdown
Contributor Author
2279ae8705af408980334c273cfeeb99.mp4

Hi @tonychang04 , found couple of things while testing which i have fixed

@Fermionic-Lyu
Fermionic-Lyu self-requested a review October 18, 2025 17:29

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

@RaghavGanesh7
I built your PR into a new image and tested internally. It worked well, great job!
Could you kindly resolve the conflicts and fix the eslint issues? Then I'll do a final check and approve this PR. Thanks!

edit: I think the user avatar url is missing. Can you add it?

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

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

363-364: Same typing concern as above.


797-832: Token exchange: add dedup/cache + robust error handling and remove scope.

This repeats issues previously flagged: no processedCodes/tokenCache protection, no try/catch with logging, and scope is incorrectly sent to the token endpoint. Also, guard missing client secret. Apply the following:

-async exchangeCodeToTokenByMicrosoft(
-  code: string
-): Promise<{ access_token: string; id_token?: string }> {
-  const oauthConfigService = OAuthConfigService.getInstance();
-  const config = await oauthConfigService.getConfigByProvider('microsoft');
-  if (!config) {
-    throw new Error('Microsoft OAuth not configured');
-  }
-  const clientSecret = await oauthConfigService.getClientSecretByProvider('microsoft');
-  const selfBaseUrl = process.env.API_BASE_URL || 'http://localhost:7130';
-  
-  const body = new URLSearchParams({
-    client_id: config.clientId ?? '',
-    client_secret: clientSecret ?? '',
-    code,
-    redirect_uri: `${selfBaseUrl}/api/auth/oauth/microsoft/callback`,
-    grant_type: 'authorization_code',
-    scope: (config.scopes && config.scopes.length > 0)
-      ? config.scopes.join(' ')
-      : 'openid email profile offline_access User.Read',
-  });
-
-  const response = await axios.post(
-    'https://login.microsoftonline.com/common/oauth2/v2.0/token',
-    body.toString(),
-    { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
-  );
-
-  if (!response.data.access_token) {
-    throw new Error('Failed to get access token from Microsoft');
-  }
-  return {
-    access_token: response.data.access_token,
-    id_token: response.data.id_token, // optional
-  };
-}
+async exchangeCodeToTokenByMicrosoft(
+  code: string
+): Promise<{ access_token: string; id_token?: string }> {
+  // Short‑circuit duplicate/in‑flight codes
+  if (this.processedCodes.has(code)) {
+    const cached = this.tokenCache.get(code);
+    if (cached) {
+      logger.debug('Returning cached tokens for already processed Microsoft code.');
+      return cached;
+    }
+    throw new Error('Authorization code is currently being processed.');
+  }
+
+  const oauthConfigService = OAuthConfigService.getInstance();
+  const config = await oauthConfigService.getConfigByProvider('microsoft');
+  if (!config) {
+    throw new Error('Microsoft OAuth not configured');
+  }
+  const clientSecret = await oauthConfigService.getClientSecretByProvider('microsoft');
+  if (!clientSecret) {
+    throw new Error('Microsoft Client Secret not configured');
+  }
+  const selfBaseUrl = process.env.API_BASE_URL || 'http://localhost:7130';
+
+  try {
+    this.processedCodes.add(code);
+
+    logger.info('Exchanging Microsoft code for tokens', {
+      hasCode: !!code,
+      clientId: (config.clientId ?? '').substring(0, 10) + '...',
+    });
+
+    const body = new URLSearchParams({
+      client_id: config.clientId ?? '',
+      client_secret: clientSecret ?? '',
+      code,
+      redirect_uri: `${selfBaseUrl}/api/auth/oauth/microsoft/callback`,
+      grant_type: 'authorization_code',
+    });
+
+    const response = await axios.post(
+      'https://login.microsoftonline.com/common/oauth2/v2.0/token',
+      body.toString(),
+      { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
+    );
+
+    if (!response.data?.access_token) {
+      throw new Error('Failed to get access token from Microsoft');
+    }
+
+    const result = {
+      access_token: response.data.access_token as string,
+      id_token: response.data.id_token as string | undefined,
+    };
+
+    this.tokenCache.set(code, result);
+    setTimeout(() => {
+      this.processedCodes.delete(code);
+      this.tokenCache.delete(code);
+    }, 60000);
+
+    return result;
+  } catch (error) {
+    this.processedCodes.delete(code);
+    if (axios.isAxiosError(error) && error.response) {
+      logger.error('Microsoft token exchange failed', {
+        status: error.response.status,
+        error: error.response.data,
+      });
+      throw new Error(`Microsoft OAuth error: ${JSON.stringify(error.response.data)}`);
+    }
+    throw error;
+  }
+}

Supporting change outside this hunk (to allow optional id_token in the cache):

-  private tokenCache: Map<string, { access_token: string; id_token: string }>;
+  private tokenCache: Map<string, { access_token: string; id_token?: string }>;

As per coding guidelines.

🧹 Nitpick comments (3)
backend/src/core/auth/auth.ts (3)

284-285: Unify Microsoft identityData typing (shape mismatch).

You pass Microsoft Graph-shaped objects elsewhere (id/displayName/userPrincipalName), but the MicrosoftUserInfo type (sub/name/email) differs. This compiles only due to Record<string, unknown> in the union, weakening type safety. Map to MicrosoftUserInfo before persistence or align the interface.

As per coding guidelines.


771-795: Auth URL is fine; consider PKCE + enforced state (optional).

For parity and CSRF hardening, consider requiring state (like shared Google/GitHub flow) and adding PKCE support for public clients.

As per coding guidelines.


866-882: Normalize and pass a typed MicrosoftUserInfo object.

Map Graph fields to MicrosoftUserInfo before calling findOrCreateThirdPartyUser; keeps provider_data consistent and typed.

-async findOrCreateMicrosoftUser(msUserInfo: {
+async findOrCreateMicrosoftUser(msUserInfo: {
   id: string;
   displayName?: string;
   userPrincipalName?: string;
   email: string;
   avatar_url?: string;
 }): Promise<CreateSessionResponse> {
-  const userName = msUserInfo.displayName || (msUserInfo.email.split('@')[0] || 'user');
-  return this.findOrCreateThirdPartyUser(
+  const userName = msUserInfo.displayName || (msUserInfo.email.split('@')[0] || 'user');
+  const microsoftIdentity: MicrosoftUserInfo = {
+    sub: msUserInfo.id,
+    email: msUserInfo.email,
+    name: userName,
+    avatar_url: msUserInfo.avatar_url || '',
+  };
+  return this.findOrCreateThirdPartyUser(
     'microsoft',
     msUserInfo.id,
     msUserInfo.email,
     userName,
-    msUserInfo.avatar_url || '',
-    msUserInfo
+    microsoftIdentity.avatar_url || '',
+    microsoftIdentity
   );
 }

As per coding guidelines.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4d0c8c9 and 400647e.

📒 Files selected for processing (1)
  • backend/src/core/auth/auth.ts (4 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)
  • MicrosoftUserInfo (92-97)
backend/src/core/auth/oauth.ts (1)
  • OAuthConfigService (26-400)
🔇 Additional comments (1)
backend/src/core/auth/auth.ts (1)

22-28: Imports look good.

No issues spotted with the new types import.

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

@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: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
backend/src/api/routes/auth.oauth.ts (1)

213-213: Add 'microsoft' to the allowed providers array.

The validation on line 213 rejects 'microsoft' as an invalid provider, but Microsoft handling is implemented in lines 252-260. This will cause Microsoft OAuth via the shared callback path to fail.

Apply this diff:

-    if (!['google', 'github', 'discord', 'linkedin'].includes(provider)) {
+    if (!['google', 'github', 'discord', 'linkedin', 'microsoft'].includes(provider)) {
       logger.warn('Invalid provider in state', { provider });
       throw new AppError('Invalid provider in state', 400, ERROR_CODES.INVALID_INPUT);
     }
♻️ Duplicate comments (2)
backend/src/core/auth/auth.ts (2)

850-886: CRITICAL: Past review issues remain unresolved.

This method still has the critical issues flagged in previous reviews:

  1. Missing code deduplication: Without processedCodes Set and tokenCache Map (present in exchangeCodeToTokenByGoogle lines 610-660), concurrent requests with the same authorization code can cause race conditions.

  2. Missing error handling: No try-catch block to handle axios errors, clean up processedCodes, or provide structured error messages.

  3. Unnecessary scope parameter (lines 868-870): Microsoft's token endpoint doesn't require the scope parameter—scopes are established during authorization. This is non-standard and could cause token exchange failures.

  4. Inconsistent base URL: Line 860 uses process.env.API_BASE_URL directly instead of the getApiBaseUrl() helper used by other methods.

Apply this diff to address all issues:

 async exchangeCodeToTokenByMicrosoft(
   code: string
 ): Promise<{ access_token: string; id_token?: string }> {
+  // Check cache first
+  if (this.processedCodes.has(code)) {
+    const cachedTokens = this.tokenCache.get(code);
+    if (cachedTokens) {
+      logger.debug('Returning cached tokens for already processed code.');
+      return { access_token: cachedTokens.access_token, id_token: cachedTokens.id_token };
+    }
+    throw new Error('Authorization code is currently being processed.');
+  }
+
   const oauthConfigService = OAuthConfigService.getInstance();
   const config = await oauthConfigService.getConfigByProvider('microsoft');
   if (!config) {
     throw new Error('Microsoft OAuth not configured');
   }
-  const clientSecret = await oauthConfigService.getClientSecretByProvider('microsoft');
-  const selfBaseUrl = process.env.API_BASE_URL || 'http://localhost:7130';
-  
-  const body = new URLSearchParams({
-    client_id: config.clientId ?? '',
-    client_secret: clientSecret ?? '',
-    code,
-    redirect_uri: `${selfBaseUrl}/api/auth/oauth/microsoft/callback`,
-    grant_type: 'authorization_code',
-    scope: (config.scopes && config.scopes.length > 0)
-      ? config.scopes.join(' ')
-      : 'openid email profile offline_access User.Read',
-  });
-
-  const response = await axios.post(
-    'https://login.microsoftonline.com/common/oauth2/v2.0/token',
-    body.toString(),
-    { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
-  );
-
-  if (!response.data.access_token) {
-    throw new Error('Failed to get access token from Microsoft');
-  }
-  return {
-    access_token: response.data.access_token,
-    id_token: response.data.id_token, // optional
-  };
+
+  try {
+    this.processedCodes.add(code);
+
+    logger.info('Exchanging Microsoft code for tokens', {
+      hasCode: !!code,
+      clientId: config.clientId?.substring(0, 10) + '...',
+    });
+
+    const clientSecret = await oauthConfigService.getClientSecretByProvider('microsoft');
+    const selfBaseUrl = getApiBaseUrl();
+    
+    const body = new URLSearchParams({
+      client_id: config.clientId ?? '',
+      client_secret: clientSecret ?? '',
+      code,
+      redirect_uri: `${selfBaseUrl}/api/auth/oauth/microsoft/callback`,
+      grant_type: 'authorization_code',
+    });
+
+    const response = await axios.post(
+      'https://login.microsoftonline.com/common/oauth2/v2.0/token',
+      body.toString(),
+      { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
+    );
+
+    if (!response.data.access_token) {
+      throw new Error('Failed to get access token from Microsoft');
+    }
+
+    const result = {
+      access_token: response.data.access_token,
+      id_token: response.data.id_token,
+    };
+
+    // Cache the successful token exchange
+    this.tokenCache.set(code, result);
+
+    // Set a timeout to clear the code and cache to prevent memory leaks
+    setTimeout(() => {
+      this.processedCodes.delete(code);
+      this.tokenCache.delete(code);
+    }, 60000); // 1 minute timeout
+
+    return result;
+  } catch (error) {
+    // If the request fails, remove the code immediately to allow for a retry
+    this.processedCodes.delete(code);
+
+    if (axios.isAxiosError(error) && error.response) {
+      logger.error('Microsoft token exchange failed', {
+        status: error.response.status,
+        error: error.response.data,
+      });
+      throw new Error(`Microsoft OAuth error: ${JSON.stringify(error.response.data)}`);
+    }
+    throw error;
+  }
 }

888-917: CRITICAL: Server-side blob URL and missing error handling remain unresolved.

This method still has critical issues flagged in previous reviews:

  1. Invalid blob URL on server (lines 903-908): URL.createObjectURL creates process-local blob:// URLs that cannot be fetched by clients. The avatar URL will be unusable.

  2. Missing error handling: No try-catch blocks around the Microsoft Graph API calls. A 404 on the photo endpoint (common for users without profile photos) will crash the entire authentication flow.

  3. Inconsistent HTTP client: Uses fetch for photo but axios for user info.

Apply this diff to fix all issues:

 async getMicrosoftUserInfo(accessToken: string) {
-  const userResp = await axios.get('https://graph.microsoft.com/v1.0/me', {
-    headers: { Authorization: `Bearer ${accessToken}` },
-  });
-
-  const data = userResp.data as {
-    id: string;
-    displayName?: string;
-    userPrincipalName?: string;
-    mail?: string | null;
-  };
-
-  const email = data.userPrincipalName || data.mail || `${data.id}@users.noreply.microsoft.com`;
-
-  const response = await fetch('https://graph.microsoft.com/v1.0/me/photo/$value', {
-    headers: { 'Authorization': `Bearer ${accessToken}` }
-  });
-  const blob = await response.blob();
-  const url = URL.createObjectURL(blob);
-  logger.info('Microsoft user avatar URL', { url});
-
-  return {
-    id: data.id,
-    displayName: data.displayName || '', 
-    userPrincipalName: data.userPrincipalName || '',
-    email,
-    avatar_url: url,
-  };
+  try {
+    const userResp = await axios.get('https://graph.microsoft.com/v1.0/me', {
+      headers: { Authorization: `Bearer ${accessToken}` },
+    });
+
+    const data = userResp.data as {
+      id: string;
+      displayName?: string;
+      userPrincipalName?: string;
+      mail?: string | null;
+    };
+
+    const email =
+      data.userPrincipalName || data.mail || `${data.id}@users.noreply.microsoft.com`;
+
+    // Best-effort fetch of profile photo; non-fatal on 404/errors
+    let avatarUrl = '';
+    try {
+      const photoResp = await axios.get('https://graph.microsoft.com/v1.0/me/photo/$value', {
+        headers: { Authorization: `Bearer ${accessToken}` },
+        responseType: 'arraybuffer',
+      });
+      const contentType = photoResp.headers['content-type'] || 'image/jpeg';
+      const base64 = Buffer.from(photoResp.data as ArrayBuffer).toString('base64');
+      avatarUrl = `data:${contentType};base64,${base64}`;
+    } catch (err) {
+      if (axios.isAxiosError(err) && err.response?.status !== 404) {
+        logger.warn('Microsoft photo fetch failed', {
+          status: err.response?.status,
+          error: err.response?.data,
+        });
+      }
+      // 404 is expected for users without photos; silently continue
+    }
+
+    return {
+      id: data.id,
+      displayName: data.displayName || '',
+      userPrincipalName: data.userPrincipalName || '',
+      email,
+      avatar_url: avatarUrl,
+    };
+  } catch (error) {
+    if (axios.isAxiosError(error) && error.response) {
+      logger.error('Microsoft user info fetch failed', {
+        status: error.response.status,
+        error: error.response.data,
+      });
+      throw new Error(`Microsoft Graph error: ${JSON.stringify(error.response.data)}`);
+    }
+    logger.error('Microsoft user info fetch failed', error);
+    throw error;
+  }
 }

As per coding guidelines.

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

92-97: Make name optional to align with other providers and Microsoft Graph API behavior.

The name field is marked as required, but other providers (Google, LinkedIn) define it as optional. Microsoft Graph API may return null for displayName if not set by the user, which would cause type errors.

Additionally, consider adding an email_verified field (optional) for consistency with Google and LinkedIn, as Microsoft returns this in some flows.

Apply this diff:

 export interface MicrosoftUserInfo {
   sub: string;
   email: string;
-  name: string;
+  name?: string;
   avatar_url?: string;
+  email_verified?: boolean;
 }
backend/src/api/routes/auth.oauth.ts (1)

348-357: Add blank line for consistency.

The Microsoft callback handling is correct, but there's a minor formatting inconsistency: a blank line is missing before the else if (provider === 'discord') statement on line 357, which breaks the visual separation pattern used elsewhere in the file.

Apply this diff:

       const accessToken = await authService.exchangeCodeToTokenByMicrosoft(code as string);
       const microsoftUserInfo = await authService.getMicrosoftUserInfo(accessToken.access_token);
       result = await authService.findOrCreateMicrosoftUser(microsoftUserInfo);
-    }
-    else if (provider === 'discord') {
+    } else if (provider === 'discord') {
       if (!code) {
backend/src/core/auth/auth.ts (1)

826-848: Use getApiBaseUrl() helper for consistency.

Line 834 uses process.env.API_BASE_URL || 'http://localhost:7130' directly, while other OAuth methods in this file use the getApiBaseUrl() helper (imported at line 32 and used throughout). This inconsistency could lead to configuration issues.

Apply this diff:

 async generateMicrosoftAuthUrl(state?: string): Promise<string> {
   const oauthConfigService = OAuthConfigService.getInstance();
   const config = await oauthConfigService.getConfigByProvider('microsoft');
   if (!config) {
     throw new Error('Microsoft OAuth not configured');
   }
 
-  const selfBaseUrl = process.env.API_BASE_URL || 'http://localhost:7130';
+  const selfBaseUrl = getApiBaseUrl();
 
   // Note: shared-keys path not implemented for Microsoft; configure local keys
   const authUrl = new URL('https://login.microsoftonline.com/common/oauth2/v2.0/authorize');
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 400647e and 15a79fe.

📒 Files selected for processing (7)
  • .env.example (1 hunks)
  • backend/src/api/routes/auth.oauth.ts (4 hunks)
  • backend/src/core/auth/auth.ts (4 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 (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • backend/src/core/auth/oauth.ts
  • .env.example
🧰 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/api/routes/auth.oauth.ts
  • backend/src/types/auth.ts
  • frontend/src/features/auth/components/AddOAuthDialog.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/api/routes/auth.oauth.ts
  • backend/src/types/auth.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
**/*.{tsx,ts}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

React components and TypeScript types/interfaces must use PascalCase

Files:

  • backend/src/api/routes/auth.oauth.ts
  • backend/src/types/auth.ts
  • frontend/src/features/auth/components/AddOAuthDialog.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/api/routes/auth.oauth.ts
  • backend/src/types/auth.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/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/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/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/AddOAuthDialog.tsx
  • frontend/src/features/auth/components/AuthMethodTab.tsx
backend/src/{controllers,core}/**/*.ts

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Implement proper database transaction handling

Files:

  • backend/src/core/auth/auth.ts
🧠 Learnings (1)
📚 Learning: 2025-10-15T18:18:47.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 (1)
  • MicrosoftUserInfo (92-97)
backend/src/core/auth/oauth.ts (1)
  • OAuthConfigService (26-404)
shared-schemas/src/auth-api.schema.ts (1)
  • CreateSessionResponse (185-185)
🪛 Biome (2.1.2)
frontend/src/features/auth/components/AuthMethodTab.tsx

[error] 88-88: Expected a parameter but instead found '| 'microsoft''.

Expected a parameter here.

(parse)

🔇 Additional comments (5)
frontend/src/features/auth/components/AddOAuthDialog.tsx (1)

17-18: LGTM! Microsoft provider type integration is consistent.

The type definitions for onConfirm, enabledProviders, selectedId, and selectProvider have been properly extended to include 'microsoft' as a valid provider option. The implementation is consistent throughout the component.

Also applies to: 28-30, 44-46

frontend/src/features/auth/components/AuthMethodTab.tsx (2)

6-6: LGTM! Microsoft provider configuration follows established patterns.

The Microsoft logo import and provider configuration are consistent with existing providers. The setup URL correctly points to the Azure portal for OAuth application registration.

Also applies to: 37-43


61-61: LGTM! Type definitions and state management properly updated.

The OAuthProviderInfo interface, enabledProviders memo, and handleConfirmSelected function signature have been correctly extended to support Microsoft as a provider option. Changes are consistent with the AddOAuthDialog component.

Also applies to: 127-127, 136-136

backend/src/api/routes/auth.oauth.ts (1)

156-186: LGTM!

The Microsoft OAuth initialization endpoint follows the established pattern for other providers, with consistent error handling and state management.

backend/src/core/auth/auth.ts (1)

26-26: LGTM!

The import and type union updates correctly integrate MicrosoftUserInfo into the authentication flow, consistent with other OAuth providers.

Also applies to: 292-292, 377-377

Comment on lines +252 to +260
} else if (provider === 'microsoft') {
// Handle Microsoft OAuth payload
const microsoftUserInfo = {
id: payloadData.providerId,
email: payloadData.email,
name: payloadData.name || '',
avatar_url: payloadData.avatar || '',
};
result = await authService.findOrCreateMicrosoftUser(microsoftUserInfo);

@coderabbitai coderabbitai Bot Oct 19, 2025 •

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 | 🔴 Critical

Fix type mismatch: use sub instead of id.

The microsoftUserInfo object uses an id field (line 255), but the MicrosoftUserInfo interface in backend/src/types/auth.ts expects sub: string. This causes a type mismatch and breaks the Microsoft OAuth flow.

Apply this diff:

     } else if (provider === 'microsoft') {
       // Handle Microsoft OAuth payload
       const microsoftUserInfo = {
-        id: payloadData.providerId,
+        sub: payloadData.providerId,
         email: payloadData.email,
         name: payloadData.name || '',
         avatar_url: payloadData.avatar || '',
       };
       result = await authService.findOrCreateMicrosoftUser(microsoftUserInfo);
🤖 Prompt for AI Agents
In backend/src/api/routes/auth.oauth.ts around lines 252 to 260, the
microsoftUserInfo object uses an id property but the MicrosoftUserInfo interface
expects sub: string; change the object to use sub: payloadData.providerId
(remove id), keep email, name and avatar_url as-is and ensure the object shape
matches the MicrosoftUserInfo type before passing it to
authService.findOrCreateMicrosoftUser so the type mismatch is resolved.

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.

This comment should be addressed, mixing sub/id could lead to type issues. Can you unify them?

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.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash

# Check the MicrosoftUserInfo type definition
echo "=== MicrosoftUserInfo Type Definition ==="
rg -A 5 "interface MicrosoftUserInfo" backend/src/types/auth.ts

echo -e "\n=== All places constructing microsoftUserInfo objects ==="
# Search for microsoftUserInfo object constructions
rg -n -B 2 -A 6 "microsoftUserInfo\s*=" backend/

echo -e "\n=== Check for 'id:' usage in Microsoft OAuth context ==="
# Look for potential id: usage in Microsoft-related code
rg -n -B 3 -A 3 "microsoft.*id:|id:.*microsoft" --ignore-case backend/src/api/routes/auth.oauth.ts backend/src/core/auth/

echo -e "\n=== Check getMicrosoftUserInfo return type ==="
# Look at the getMicrosoftUserInfo implementation
ast-grep --pattern "getMicrosoftUserInfo($_) {
  $$$
}"

Length of output: 1849


🏁 Script executed:

#!/bin/bash

# Get the full getMicrosoftUserInfo implementation
echo "=== getMicrosoftUserInfo implementation ==="
rg -n -A 20 "async getMicrosoftUserInfo\(accessToken: string\)" backend/src/core/auth/auth.ts

# Check how other providers handle this in shared callback
echo -e "\n=== How Google handles it in shared callback ==="
rg -n -B 2 -A 7 "provider === 'google'" backend/src/api/routes/auth.oauth.ts | head -20

echo -e "\n=== How GitHub handles it in shared callback ==="
rg -n -B 2 -A 7 "provider === 'github'" backend/src/api/routes/auth.oauth.ts | head -20

Length of output: 2645


🏁 Script executed:

#!/bin/bash

# Get the complete getMicrosoftUserInfo including its return statement
echo "=== Complete getMicrosoftUserInfo implementation ==="
rg -n -A 30 "async getMicrosoftUserInfo\(accessToken: string\)" backend/src/core/auth/auth.ts

# Check the findOrCreateMicrosoftUser signature and what it expects
echo -e "\n=== findOrCreateMicrosoftUser signature ==="
rg -n -B 2 -A 15 "async findOrCreateMicrosoftUser" backend/src/core/auth/auth.ts

Length of output: 1772


🏁 Script executed:

#!/bin/bash

# Check GitHubUserInfo type definition to understand the pattern
echo "=== GitHubUserInfo Type Definition ==="
rg -B 2 -A 6 "interface GitHubUserInfo" backend/src/types/auth.ts

# Check GoogleUserInfo type definition
echo -e "\n=== GoogleUserInfo Type Definition ==="
rg -B 2 -A 6 "interface GoogleUserInfo" backend/src/types/auth.ts

# Verify what findOrCreateThirdPartyUser signature expects
echo -e "\n=== findOrCreateThirdPartyUser signature ==="
rg -n -A 8 "async findOrCreateThirdPartyUser" backend/src/core/auth/auth.ts | head -15

Length of output: 693


@Fermionic-Lyu, you're absolutely right - there's a type inconsistency that needs to be fixed. Let me show you the complete picture:


🏁 Script executed:

#!/bin/bash

echo "=== ISSUE SUMMARY ==="
echo "The MicrosoftUserInfo type definition is inconsistent with its implementation."
echo ""

echo "1. Type definition (WRONG - says 'sub'):"
rg -n -A 4 "export interface MicrosoftUserInfo" backend/src/types/auth.ts

echo -e "\n2. Implementation (uses 'id'):"
echo "   - getMicrosoftUserInfo returns: { id: data.id, ... }"
rg -n "id: data.id" backend/src/core/auth/auth.ts

echo -e "\n3. findOrCreateMicrosoftUser expects: { id: string, ... }"
rg -n -A 2 "async findOrCreateMicrosoftUser\(msUserInfo: {" backend/src/core/auth/auth.ts

echo -e "\n4. Shared callback uses: { id: payloadData.providerId, ... }"
rg -n "id: payloadData.providerId" backend/src/api/routes/auth.oauth.ts

echo -e "\n=== COMPARISON WITH OTHER PROVIDERS ==="
echo "GitHub uses 'id' (native API field):"
rg -n "interface GitHubUserInfo" -A 3 backend/src/types/auth.ts

echo -e "\nGoogle uses 'sub' (OIDC standard):"
rg -n "interface GoogleUserInfo" -A 3 backend/src/types/auth.ts

Length of output: 1087


@Fermionic-Lyu, excellent catch! The issue is actually the opposite of what CodeRabbit suggested. The type definition is wrong, not the implementation code.

Root Cause

The MicrosoftUserInfo type definition incorrectly uses sub (OIDC standard), but Microsoft Graph API actually returns id (like GitHub's API). The entire implementation consistently uses id:

  • ✅ getMicrosoftUserInfo() returns { id: data.id, ... }
  • ✅ findOrCreateMicrosoftUser() expects { id: string, ... }
  • ✅ Shared callback constructs { id: payloadData.providerId, ... }
  • ❌ Type definition says sub: string ← This is the bug

The Correct Fix

Fix the type definition in backend/src/types/auth.ts:

export interface MicrosoftUserInfo {
-  sub: string;
+  id: string;
  email: string;
  name: string;
  avatar_url?: string;
}

This aligns with:

  • GitHub pattern (uses id: number from native API)
  • Microsoft Graph API (returns id field, not sub)
  • Current implementation (everywhere uses id)

Why Not Change to sub?

Google uses sub because it's an OIDC-compliant provider. Microsoft Graph API is not OIDC - it's a REST API that returns an id field. Changing everything to sub would require:

  1. Transforming API responses unnecessarily
  2. Making code inconsistent with the actual Microsoft Graph API schema
  3. More changes across multiple files

The minimal fix is to update the type definition to match reality. 🐰


🧬 Code Graph Analysis Results

[summary] backend/src/api/routes/auth.oauth.ts: Shared OAuth callback for Google currently maps payloadData.providerId to sub when constructing googleUserInfo, which introduces inconsistency between user identifiers (sub vs id) used elsewhere. This could lead to type mismatches when downstream code expects a unified user identifier field.

[summary] backend/src/core/auth/auth.ts: Token and user shape conventions:

  • generateToken(payload: TokenPayloadSchema): string signs a JWT with sub, email, and role fields; token consumer expects sub as the user id.
  • verifyToken(token: string): returns an object with sub, email, and role, where role defaults to 'authenticated' if missing.
  • Admin login uses a token containing sub: ADMIN_ID and role: 'project_admin'; the API user object uses id (separate from sub) in its schema.
    These illustrate the current sub vs id usage pattern and potential inconsistency between token payloads (sub) and API user objects (id).

Comment thread backend/src/core/auth/auth.ts Outdated
Comment on lines +919 to +936
// NEW: Find or create Microsoft user
async findOrCreateMicrosoftUser(msUserInfo: {
id: string;
displayName?: string;
userPrincipalName?: string;
email: string;
avatar_url?: string;
}): Promise<CreateSessionResponse> {
const userName = msUserInfo.displayName || (msUserInfo.email.split('@')[0] || 'user');
return this.findOrCreateThirdPartyUser(
'microsoft',
msUserInfo.id,
msUserInfo.email,
userName,
msUserInfo.avatar_url || '',
msUserInfo
);
}

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

Fix parameter type to match MicrosoftUserInfo interface.

The parameter signature uses fields like id, displayName, and userPrincipalName, but the MicrosoftUserInfo interface (lines 92-97 in backend/src/types/auth.ts) expects sub, name, and email. Additionally, the return value from getMicrosoftUserInfo (lines 910-916) uses id instead of sub.

Either map the fields correctly or update the interface and all usages to be consistent.

Apply this diff to align with the interface:

-async findOrCreateMicrosoftUser(msUserInfo: {
-  id: string;
-  displayName?: string;
-  userPrincipalName?: string;
-  email: string;
-  avatar_url?: string;
-}): Promise<CreateSessionResponse> {
-  const userName = msUserInfo.displayName || (msUserInfo.email.split('@')[0] || 'user');
+async findOrCreateMicrosoftUser(msUserInfo: MicrosoftUserInfo): Promise<CreateSessionResponse> {
+  const userName = msUserInfo.name || msUserInfo.email.split('@')[0];
   return this.findOrCreateThirdPartyUser(
     'microsoft',
-    msUserInfo.id,
+    msUserInfo.sub,
     msUserInfo.email,
     userName,
     msUserInfo.avatar_url || '',
     msUserInfo
   );
 }

Then update getMicrosoftUserInfo to return the correct shape:

     return {
-      id: data.id,
-      displayName: data.displayName || '',
-      userPrincipalName: data.userPrincipalName || '',
+      sub: data.id,
       email,
+      name: data.displayName || '',
       avatar_url: avatarUrl,
     };
🤖 Prompt for AI Agents
In backend/src/core/auth/auth.ts around lines 919-936, the method signature and
field usage for Microsoft user info do not match the MicrosoftUserInfo interface
(which uses sub, name, email); change the parameter type to MicrosoftUserInfo
(or update the interface consistently) and update the body to use msUserInfo.sub
as the provider ID, msUserInfo.name as displayName, and msUserInfo.email as
email (and msUserInfo.picture/avatar if present); also update
getMicrosoftUserInfo to return the correct shape (sub instead of id) or ensure
you map id -> sub before calling findOrCreateMicrosoftUser so field names are
consistent across all usages.

@RaghavGanesh7

Copy link
Copy Markdown
Contributor Author

@Fermionic-Lyu Resolved the merge conflicts and added avatar url. Tested again as well

@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: 0

🧹 Nitpick comments (1)
frontend/src/features/auth/components/AuthMethodTab.tsx (1)

88-88: Consider deriving the provider type to reduce duplication.

The provider union type 'google' | 'github' | 'linkedin' | 'discord' | 'microsoft' is repeated in multiple locations (lines 61, 88, 136). When adding new providers, all these locations must be updated manually.

Consider extracting the type from OAuthProviderInfo:

type ProviderId = OAuthProviderInfo['id'];

const deleteOAuthConfig = async (
  providerId: ProviderId,
  providerName: string
) => {
  // ...
};

const handleConfirmSelected = (selectedId: ProviderId) => {
  // ...
};

This ensures type consistency and reduces maintenance overhead when adding new providers.

Also applies to: 136-136

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 15a79fe and fdfef3b.

📒 Files selected for processing (1)
  • frontend/src/features/auth/components/AuthMethodTab.tsx (6 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx}: Use TypeScript for all code files
Use ES modules (import/export syntax)
Prefer descriptive, unabbreviated variable and function names
Implement proper error handling with try-catch blocks and logging where appropriate
Use single quotes for strings
Include semicolons at the end of statements
Use arrow functions for callbacks and inline functions
Prefer const over let; avoid var
Use template literals for string interpolation
Maintain 2-space indentation
Format code with the repository Prettier configuration
Variables, parameters, properties, and functions must use camelCase
Constants and enum members must use UPPER_CASE
Include JSDoc comments for complex functions

Files:

  • frontend/src/features/auth/components/AuthMethodTab.tsx
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/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/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/AuthMethodTab.tsx
**/*.{tsx,ts}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

React components and TypeScript types/interfaces must use PascalCase

Files:

  • 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/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
🔇 Additional comments (1)
frontend/src/features/auth/components/AuthMethodTab.tsx (1)

88-88: Good fix! The syntax error has been resolved.

The type union is now correct with no misplaced comma before the pipe operator.

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

Changes LGTM, just some additional comments that need to be addressed. Also the eslint check is still failing, let me know if you need help on this.

Comment thread MICROSOFT_OAUTH_SETUP.md Resolved
Comment on lines +252 to +260
} else if (provider === 'microsoft') {
// Handle Microsoft OAuth payload
const microsoftUserInfo = {
id: payloadData.providerId,
email: payloadData.email,
name: payloadData.name || '',
avatar_url: payloadData.avatar || '',
};
result = await authService.findOrCreateMicrosoftUser(microsoftUserInfo);

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.

This comment should be addressed, mixing sub/id could lead to type issues. Can you unify them?

Comment thread backend/src/types/auth.ts Resolved

@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: 0

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

92-97: Verify required fields and consider adding email_verified.

A few observations about the new MicrosoftUserInfo interface:

  1. Consistency with other providers: The past review comment noted inconsistency between using id vs sub across provider interfaces. While MicrosoftUserInfo uses id (consistent with Discord and GitHub), Google and LinkedIn use sub. This inconsistency remains but likely reflects the actual field names returned by each provider's API.

  2. Required fields: The interface makes email and name required (non-optional). Please verify that Microsoft's Graph API always returns these fields. According to Microsoft's documentation, the mail field can be null for users without an email configured, which would cause runtime errors if the code expects a required string.

  3. Missing email_verified field: For consistency with GoogleUserInfo and LinkedInUserInfo, consider adding an optional email_verified?: boolean field if Microsoft's API provides this information.

Please verify that Microsoft's API guarantees email and name are always present. If not, consider making them optional:

 export interface MicrosoftUserInfo {
   id: string;
-  email: string;
-  name: string;
+  email?: string;
+  name?: string;
   avatar_url?: string;
 }

Optionally, add email_verified for consistency:

 export interface MicrosoftUserInfo {
   id: string;
   email?: string;
+  email_verified?: boolean;
   name?: string;
   avatar_url?: string;
 }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1b16d74 and 2241111.

📒 Files selected for processing (1)
  • backend/src/types/auth.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx}: Use TypeScript for all code files
Use ES modules (import/export syntax)
Prefer descriptive, unabbreviated variable and function names
Implement proper error handling with try-catch blocks and logging where appropriate
Use single quotes for strings
Include semicolons at the end of statements
Use arrow functions for callbacks and inline functions
Prefer const over let; avoid var
Use template literals for string interpolation
Maintain 2-space indentation
Format code with the repository Prettier configuration
Variables, parameters, properties, and functions must use camelCase
Constants and enum members must use UPPER_CASE
Include JSDoc comments for complex functions

Files:

  • backend/src/types/auth.ts
backend/src/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

backend/src/**/*.{ts,tsx}: Use async/await for asynchronous operations in the backend
Use Zod schemas for request/response validation
Return consistent API responses using utility functions
Validate all user inputs
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper caching strategies (server-side)

Files:

  • backend/src/types/auth.ts
**/*.{tsx,ts}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

React components and TypeScript types/interfaces must use PascalCase

Files:

  • backend/src/types/auth.ts
**/[a-z][a-z0-9-]*.ts

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Utility files should use kebab-case or camelCase (kebab-case validated here)

Files:

  • backend/src/types/auth.ts

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

g2m first, we can address remaining issues later

@tonychang04 tonychang04 linked an issue Oct 21, 2025 that may be closed by this pull request
@tonychang04

Copy link
Copy Markdown
Member

please help address the conflists(prob becuz we merged facebook) thanks! @RaghavGanesh7

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
backend/src/api/routes/auth.oauth.ts (1)

245-245: Add 'microsoft' to the allowed providers list.

The shared callback validation is missing 'microsoft', but it's included in the main callback validation (line 357) and has a handler at lines 284-292. This inconsistency will cause Microsoft OAuth to fail when using the shared callback route.

Apply this diff:

-    if (!['google', 'github', 'facebook', 'discord', 'linkedin'].includes(provider)) {
+    if (!['google', 'github', 'facebook', 'discord', 'linkedin', 'microsoft'].includes(provider)) {
       logger.warn('Invalid provider in state', { provider });
       throw new AppError('Invalid provider in state', 400, ERROR_CODES.INVALID_INPUT);
     }
♻️ Duplicate comments (3)
backend/src/core/auth/auth.ts (3)

856-894: Add deduplication, caching, error handling, and fix scope parameter.

This method has several issues that were flagged in previous reviews:

  1. Missing code deduplication (lines 612-620 in Google implementation): No processedCodes Set check to prevent race conditions from concurrent requests.
  2. Missing token caching (lines 656-663 in Google): No tokenCache Map for performance.
  3. Missing error handling (lines 666-678 in Google): No try-catch block or axios error handling.
  4. Unnecessary scope parameter (lines 873-876): Microsoft's token endpoint doesn't require scope—it's established during authorization.
  5. Inconsistent helper usage (line 865): Uses process.env.API_BASE_URL directly instead of getApiBaseUrl().

Please refer to the detailed diff in the previous review comment that shows how to add these safeguards following the Google implementation pattern.


897-925: Replace URL.createObjectURL with base64 data URI and add error handling.

This method has critical issues flagged in previous reviews:

  1. Lines 914-916: URL.createObjectURL(blob) creates a process-local blob URL that won't work on the server—clients can't fetch blob:// URLs from Node.js processes.
  2. Missing error handling: No try-catch blocks for the Graph API call or photo fetch.

The previous review comment provides a complete diff showing how to:

  • Convert the photo to a base64 data URI (data:image/jpeg;base64,...)
  • Add try-catch blocks with proper logging
  • Handle 404 responses gracefully (many users don't have profile photos)
  • Wrap the entire method in error handling

928-944: Fix parameter type to match MicrosoftUserInfo interface.

The parameter signature uses an inline type with displayName and userPrincipalName, but the MicrosoftUserInfo interface (lines 92-97 in backend/src/types/auth.ts) defines name instead. This type mismatch was flagged in previous reviews.

The previous review comment provides two options:

  1. Update this method and getMicrosoftUserInfo to use MicrosoftUserInfo type with name field (recommended for consistency with Google/LinkedIn/Facebook)
  2. Update the interface to include displayName and userPrincipalName

Please ensure consistency between the interface definition and all implementations.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2241111 and 215b783.

📒 Files selected for processing (6)
  • backend/src/api/routes/auth.oauth.ts (4 hunks)
  • backend/src/core/auth/auth.ts (4 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 (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • frontend/src/features/auth/components/AddOAuthDialog.tsx
  • backend/src/core/auth/oauth.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:

  • frontend/src/features/auth/components/AuthMethodTab.tsx
  • backend/src/api/routes/auth.oauth.ts
  • backend/src/types/auth.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/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/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/AuthMethodTab.tsx
**/*.{tsx,ts}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

React components and TypeScript types/interfaces must use PascalCase

Files:

  • frontend/src/features/auth/components/AuthMethodTab.tsx
  • backend/src/api/routes/auth.oauth.ts
  • backend/src/types/auth.ts
  • backend/src/core/auth/auth.ts
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/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/api/routes/auth.oauth.ts
  • backend/src/types/auth.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
**/[a-z][a-z0-9-]*.ts

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Utility files should use kebab-case or camelCase (kebab-case validated here)

Files:

  • backend/src/api/routes/auth.oauth.ts
  • backend/src/types/auth.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/auth.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 (2)
backend/src/api/middleware/error.ts (1)
  • AppError (7-17)
backend/src/utils/logger.ts (1)
  • logger (6-29)
backend/src/core/auth/auth.ts (5)
backend/src/types/auth.ts (1)
  • MicrosoftUserInfo (92-97)
backend/src/core/auth/oauth.ts (1)
  • OAuthConfigService (26-406)
backend/src/utils/environment.ts (1)
  • getApiBaseUrl (39-41)
backend/src/utils/logger.ts (1)
  • logger (6-29)
shared-schemas/src/auth-api.schema.ts (1)
  • CreateSessionResponse (185-185)
🔇 Additional comments (9)
backend/src/api/routes/auth.oauth.ts (3)

188-218: LGTM!

The Microsoft OAuth initialization endpoint follows the established pattern used by other providers (Google, GitHub, Facebook) with proper validation, state management, and error handling.


284-292: LGTM!

The Microsoft OAuth payload handling correctly uses id (not sub) to match the Microsoft Graph API response format and aligns with the MicrosoftUserInfo interface.


397-404: LGTM!

The Microsoft callback handling follows the established pattern and correctly chains the token exchange, user info fetch, and user provisioning steps.

frontend/src/features/auth/components/AuthMethodTab.tsx (3)

6-6: LGTM!

The Microsoft provider entry follows the established pattern with appropriate logo import, configuration details, and setup URL pointing to the Azure portal.

Also applies to: 38-44


69-69: LGTM!

The interface correctly extends the provider type union to include 'microsoft'.


96-96: LGTM!

All function parameter type unions are consistently updated to include 'microsoft', maintaining type safety throughout the component.

Also applies to: 135-135, 146-146

backend/src/core/auth/auth.ts (3)

27-27: LGTM!

The import is correctly placed alongside other OAuth provider type imports.


293-293: LGTM!

The MicrosoftUserInfo type is correctly added to the identity data union types, maintaining consistency with other OAuth providers.

Also applies to: 379-379


828-853: LGTM!

The Microsoft auth URL generation follows the established pattern, uses the getApiBaseUrl() helper correctly, and sets appropriate default scopes for Microsoft Graph API access.

Comment thread backend/src/types/auth.ts
Comment on lines +92 to +97
export interface MicrosoftUserInfo {
id: string;
email: string;
name: string;
avatar_url?: 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 | 🟠 Major

Type mismatch: interface doesn't match implementation.

The MicrosoftUserInfo interface defines name: string, but the actual implementation in backend/src/core/auth/auth.ts uses different fields:

  • getMicrosoftUserInfo (lines 897-925) returns displayName and userPrincipalName
  • findOrCreateMicrosoftUser (lines 928-944) expects displayName and userPrincipalName

Apply this diff to align the interface with the implementation:

 export interface MicrosoftUserInfo {
   id: string;
   email: string;
-  name: string;
+  displayName?: string;
+  userPrincipalName?: string;
   avatar_url?: string;
 }

Alternatively, update the implementation to use name instead of displayName for consistency with other OAuth provider interfaces (Google, LinkedIn, Facebook all use name).

🤖 Prompt for AI Agents
In backend/src/types/auth.ts around lines 92-97, the MicrosoftUserInfo interface
is inconsistent with the auth implementation (which uses displayName and
userPrincipalName). Update the interface to match the implementation by
replacing the name field with displayName: string and adding userPrincipalName:
string (keep id, email and avatar_url as appropriate); then run/find TypeScript
errors and adjust any call sites if needed to use the new field names or add a
mapping layer if you prefer to keep the existing name property.

@tonychang04
tonychang04 merged commit a8f673c into InsForge:main Oct 21, 2025
This was referenced Oct 22, 2025
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 Microsoft Oauth

3 participants