Repository navigation
feat : #384 - mircrosoft oauth support added - #436
Conversation
WalkthroughAdds 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
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20-30 minutes Possibly related PRs
Suggested reviewers
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: CodeRabbit UI Review profile: CHILL Plan: Pro 📒 Files selected for processing (1)
🧰 Additional context used📓 Path-based instructions (6)**/*.{ts,tsx}📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Files:
frontend/src/**/*.{tsx,ts}📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Files:
frontend/src/**/*.tsx📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Files:
frontend/src/**/*.{ts,tsx}📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Files:
**/*.{tsx,ts}📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Files:
frontend/src/**/[A-Z]*.tsx📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Files:
🔇 Additional comments (1)
Comment |
There was a problem hiding this comment.
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 checkThe shared callback still rejects any provider not in
['google', 'github'], so Microsoft flows will always raiseInvalid provider in statebefore your new branch can execute. Extend the allowlist to includemicrosoft; 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: AlignMicrosoftUserInfowith actual Graph payload
getMicrosoftUserInfo(and the identity data we persist) exposeid,displayName, anduserPrincipalName, notsub/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
⛔ Files ignored due to path filters (1)
frontend/src/assets/logos/microsoft.svgis 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.tsfrontend/src/features/auth/components/AddOAuthDialog.tsxbackend/src/core/auth/auth.tsbackend/src/core/auth/oauth.tsshared-schemas/src/auth.schema.tsbackend/src/api/routes/auth.oauth.tsfrontend/src/features/auth/components/AuthMethodTab.tsx
backend/src/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
backend/src/**/*.{ts,tsx}: Use async/await for asynchronous operations in the backend
Use Zod schemas for request/response validation
Return consistent API responses using utility functions
Validate all user inputs
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper caching strategies (server-side)
Files:
backend/src/types/auth.tsbackend/src/core/auth/auth.tsbackend/src/core/auth/oauth.tsbackend/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.tsfrontend/src/features/auth/components/AddOAuthDialog.tsxbackend/src/core/auth/auth.tsbackend/src/core/auth/oauth.tsshared-schemas/src/auth.schema.tsbackend/src/api/routes/auth.oauth.tsfrontend/src/features/auth/components/AuthMethodTab.tsx
**/[a-z][a-z0-9-]*.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Utility files should use kebab-case or camelCase (kebab-case validated here)
Files:
backend/src/types/auth.tsbackend/src/core/auth/auth.tsbackend/src/core/auth/oauth.tsshared-schemas/src/auth.schema.tsbackend/src/api/routes/auth.oauth.ts
frontend/src/**/*.{tsx,ts}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
frontend/src/**/*.{tsx,ts}: Use functional React components with hooks exclusively
Use Radix UI primitives for accessibility
Optimize React component re-renders
Files:
frontend/src/features/auth/components/AddOAuthDialog.tsxfrontend/src/features/auth/components/AuthMethodTab.tsx
frontend/src/**/*.tsx
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
frontend/src/**/*.tsx: Implement TypeScript interfaces/types for all component props
Follow component composition patterns; keep components focused and single-purpose
Implement proper loading and error states in UI
Use a consistent icon set from lucide-react
Files:
frontend/src/features/auth/components/AddOAuthDialog.tsxfrontend/src/features/auth/components/AuthMethodTab.tsx
frontend/src/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
frontend/src/**/*.{ts,tsx}: Use TanStack Query for server state management
Use React Hook Form for form handling with Zod validation
Optimize bundle size with proper imports
Files:
frontend/src/features/auth/components/AddOAuthDialog.tsxfrontend/src/features/auth/components/AuthMethodTab.tsx
frontend/src/**/[A-Z]*.tsx
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Component files must use PascalCase filenames (e.g., DataGrid.tsx)
Files:
frontend/src/features/auth/components/AddOAuthDialog.tsxfrontend/src/features/auth/components/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.tsbackend/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)
| scopes = ['openid', 'email', 'profile']; | ||
| } |
There was a problem hiding this comment.
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.
| 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.
|
Great work! Would love to see a video demo of the configuration working as intented! |
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (4)
examples/oauth/test-microsoft-oauth.html (2)
55-58: SimplifysetTextlogic; current check is ambiguous.Line 57's condition
el.value ? el.value = text : el.textContent = text;is confusing and incorrect. It checks the truthiness ofel.value, not whether the element has avalueproperty. 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 bothaccess_tokenandtokenparameters are accepted.Line 111 accepts both
access_tokenandtokenas 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 parameterIf 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:
- JSDoc comment: Add documentation similar to other OAuth methods for consistency.
- Avatar URL: Currently empty because Microsoft Graph
/medoesn't return the photo URL. If avatars are important, you could enhance this by making a separate call to/me/photo/$valueor/me/photos/48x48/$valueto retrieve the profile picture.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 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
MicrosoftUserInfois 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
findOrCreateThirdPartyUserand correctly supports Microsoft OAuth.
| 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 | ||
| }; | ||
| } |
There was a problem hiding this comment.
Add code deduplication and error handling consistent with Google OAuth.
This method is missing critical safeguards present in exchangeCodeToTokenByGoogle:
-
Missing code deduplication (lines 556-562, 573, 600-606 in Google implementation): Without the
processedCodesSet andtokenCacheMap, concurrent requests with the same code can cause race conditions. -
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.
-
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.
| 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'; | ||
| } |
There was a problem hiding this comment.
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.
| 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'; | |
| } |
| 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; | ||
| } | ||
| } |
There was a problem hiding this comment.
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.
| 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.
| 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 }); |
There was a problem hiding this comment.
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.
2279ae8705af408980334c273cfeeb99.mp4Hi @tonychang04 , found couple of things while testing which i have fixed |
There was a problem hiding this comment.
@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?
There was a problem hiding this comment.
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
📒 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.
There was a problem hiding this comment.
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:
Missing code deduplication: Without
processedCodesSet andtokenCacheMap (present inexchangeCodeToTokenByGooglelines 610-660), concurrent requests with the same authorization code can cause race conditions.Missing error handling: No try-catch block to handle axios errors, clean up
processedCodes, or provide structured error messages.Unnecessary
scopeparameter (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.Inconsistent base URL: Line 860 uses
process.env.API_BASE_URLdirectly instead of thegetApiBaseUrl()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:
Invalid blob URL on server (lines 903-908):
URL.createObjectURLcreates process-localblob://URLs that cannot be fetched by clients. The avatar URL will be unusable.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.
Inconsistent HTTP client: Uses
fetchfor photo butaxiosfor 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: Makenameoptional to align with other providers and Microsoft Graph API behavior.The
namefield is marked as required, but other providers (Google, LinkedIn) define it as optional. Microsoft Graph API may returnnullfordisplayNameif not set by the user, which would cause type errors.Additionally, consider adding an
email_verifiedfield (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: UsegetApiBaseUrl()helper for consistency.Line 834 uses
process.env.API_BASE_URL || 'http://localhost:7130'directly, while other OAuth methods in this file use thegetApiBaseUrl()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
📒 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.tsbackend/src/types/auth.tsfrontend/src/features/auth/components/AddOAuthDialog.tsxfrontend/src/features/auth/components/AuthMethodTab.tsxbackend/src/core/auth/auth.ts
backend/src/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
backend/src/**/*.{ts,tsx}: Use async/await for asynchronous operations in the backend
Use Zod schemas for request/response validation
Return consistent API responses using utility functions
Validate all user inputs
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper caching strategies (server-side)
Files:
backend/src/api/routes/auth.oauth.tsbackend/src/types/auth.tsbackend/src/core/auth/auth.ts
backend/src/api/**/*.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
backend/src/api/**/*.ts: Implement authentication and error-handling middleware
Follow RESTful conventions for API endpoints
Implement rate limiting for API endpoints
Files:
backend/src/api/routes/auth.oauth.ts
**/*.{tsx,ts}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
React components and TypeScript types/interfaces must use PascalCase
Files:
backend/src/api/routes/auth.oauth.tsbackend/src/types/auth.tsfrontend/src/features/auth/components/AddOAuthDialog.tsxfrontend/src/features/auth/components/AuthMethodTab.tsxbackend/src/core/auth/auth.ts
**/[a-z][a-z0-9-]*.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Utility files should use kebab-case or camelCase (kebab-case validated here)
Files:
backend/src/api/routes/auth.oauth.tsbackend/src/types/auth.tsbackend/src/core/auth/auth.ts
frontend/src/**/*.{tsx,ts}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
frontend/src/**/*.{tsx,ts}: Use functional React components with hooks exclusively
Use Radix UI primitives for accessibility
Optimize React component re-renders
Files:
frontend/src/features/auth/components/AddOAuthDialog.tsxfrontend/src/features/auth/components/AuthMethodTab.tsx
frontend/src/**/*.tsx
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
frontend/src/**/*.tsx: Implement TypeScript interfaces/types for all component props
Follow component composition patterns; keep components focused and single-purpose
Implement proper loading and error states in UI
Use a consistent icon set from lucide-react
Files:
frontend/src/features/auth/components/AddOAuthDialog.tsxfrontend/src/features/auth/components/AuthMethodTab.tsx
frontend/src/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
frontend/src/**/*.{ts,tsx}: Use TanStack Query for server state management
Use React Hook Form for form handling with Zod validation
Optimize bundle size with proper imports
Files:
frontend/src/features/auth/components/AddOAuthDialog.tsxfrontend/src/features/auth/components/AuthMethodTab.tsx
frontend/src/**/[A-Z]*.tsx
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Component files must use PascalCase filenames (e.g., DataGrid.tsx)
Files:
frontend/src/features/auth/components/AddOAuthDialog.tsxfrontend/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, andselectProviderhave 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
OAuthProviderInfointerface,enabledProvidersmemo, andhandleConfirmSelectedfunction 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
MicrosoftUserInfointo the authentication flow, consistent with other OAuth providers.Also applies to: 292-292, 377-377
| } 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); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
This comment should be addressed, mixing sub/id could lead to type issues. Can you unify them?
There was a problem hiding this comment.
🧩 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: numberfrom native API) - Microsoft Graph API (returns
idfield, notsub) - 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:
- Transforming API responses unnecessarily
- Making code inconsistent with the actual Microsoft Graph API schema
- 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).
| // 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 | ||
| ); | ||
| } |
There was a problem hiding this comment.
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.
|
@Fermionic-Lyu Resolved the merge conflicts and added avatar url. Tested again as well |
There was a problem hiding this comment.
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
📒 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
left a comment
There was a problem hiding this comment.
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.
| } 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); |
There was a problem hiding this comment.
This comment should be addressed, mixing sub/id could lead to type issues. Can you unify them?
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
backend/src/types/auth.ts (1)
92-97: Verify required fields and consider addingemail_verified.A few observations about the new
MicrosoftUserInfointerface:
Consistency with other providers: The past review comment noted inconsistency between using
idvssubacross provider interfaces. WhileMicrosoftUserInfousesid(consistent with Discord and GitHub), Google and LinkedIn usesub. This inconsistency remains but likely reflects the actual field names returned by each provider's API.Required fields: The interface makes
namerequired (non-optional). Please verify that Microsoft's Graph API always returns these fields. According to Microsoft's documentation, theMissing
email_verifiedfield: For consistency withGoogleUserInfoandLinkedInUserInfo, consider adding an optionalemail_verified?: booleanfield if Microsoft's API provides this information.Please verify that Microsoft's API guarantees
nameare 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_verifiedfor 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
📒 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
left a comment
There was a problem hiding this comment.
g2m first, we can address remaining issues later
|
please help address the conflists(prob becuz we merged facebook) thanks! @RaghavGanesh7 |
There was a problem hiding this comment.
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:
- Missing code deduplication (lines 612-620 in Google implementation): No
processedCodesSet check to prevent race conditions from concurrent requests.- Missing token caching (lines 656-663 in Google): No
tokenCacheMap for performance.- Missing error handling (lines 666-678 in Google): No try-catch block or axios error handling.
- Unnecessary scope parameter (lines 873-876): Microsoft's token endpoint doesn't require scope—it's established during authorization.
- Inconsistent helper usage (line 865): Uses
process.env.API_BASE_URLdirectly instead ofgetApiBaseUrl().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:
- Lines 914-916:
URL.createObjectURL(blob)creates a process-local blob URL that won't work on the server—clients can't fetchblob://URLs from Node.js processes.- 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
displayNameanduserPrincipalName, but theMicrosoftUserInfointerface (lines 92-97 inbackend/src/types/auth.ts) definesnameinstead. This type mismatch was flagged in previous reviews.The previous review comment provides two options:
- Update this method and
getMicrosoftUserInfoto useMicrosoftUserInfotype withnamefield (recommended for consistency with Google/LinkedIn/Facebook)- Update the interface to include
displayNameanduserPrincipalNamePlease ensure consistency between the interface definition and all implementations.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 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.tsxbackend/src/api/routes/auth.oauth.tsbackend/src/types/auth.tsbackend/src/core/auth/auth.ts
frontend/src/**/*.{tsx,ts}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
frontend/src/**/*.{tsx,ts}: Use functional React components with hooks exclusively
Use Radix UI primitives for accessibility
Optimize React component re-renders
Files:
frontend/src/features/auth/components/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.tsxbackend/src/api/routes/auth.oauth.tsbackend/src/types/auth.tsbackend/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.tsbackend/src/types/auth.tsbackend/src/core/auth/auth.ts
backend/src/api/**/*.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
backend/src/api/**/*.ts: Implement authentication and error-handling middleware
Follow RESTful conventions for API endpoints
Implement rate limiting for API endpoints
Files:
backend/src/api/routes/auth.oauth.ts
**/[a-z][a-z0-9-]*.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Utility files should use kebab-case or camelCase (kebab-case validated here)
Files:
backend/src/api/routes/auth.oauth.tsbackend/src/types/auth.tsbackend/src/core/auth/auth.ts
backend/src/{controllers,core}/**/*.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Implement proper database transaction handling
Files:
backend/src/core/auth/auth.ts
🧠 Learnings (1)
📚 Learning: 2025-10-15T18:18:47.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(notsub) to match the Microsoft Graph API response format and aligns with theMicrosoftUserInfointerface.
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
MicrosoftUserInfotype 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.
| export interface MicrosoftUserInfo { | ||
| id: string; | ||
| email: string; | ||
| name: string; | ||
| avatar_url?: string; | ||
| } |
There was a problem hiding this comment.
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) returnsdisplayNameanduserPrincipalNamefindOrCreateMicrosoftUser(lines 928-944) expectsdisplayNameanduserPrincipalName
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.
Summary
GET /api/auth/oauth/microsoft(returns consent URL withstate).GET /api/auth/oauth/:provider/callbacknow supportsmicrosoft.backend/src/core/auth/auth.ts:generateMicrosoftAuthUrl,exchangeCodeToTokenByMicrosoft,getMicrosoftUserInfo,findOrCreateMicrosoftUser.backend/src/core/auth/oauth.ts(openid email profile offline_access User.Read).microsoftinshared-schemas/src/auth.schema.ts.AddOAuthDialogandAuthMethodTabprovider types and selection.MICROSOFT_OAUTH_SETUP.md(setup, endpoints, flow).MICROSOFT_CLIENT_IDandMICROSOFT_CLIENT_SECRETfor.env/env.example.How did you test this change?
http://localhost:7130/api/auth/oauth/microsoft/callback.User.Read.AuthMethodTab), added Microsoft OAuth config withclientIdandclientSecret(left scopes blank to use defaults).GET /api/auth/oauth/microsoft?redirect_uri=http://localhost:7131/oauth/callbackand verified a valid Microsoft consent URL was returned.redirect_uriwithaccess_token,user_id,email,namequery params.Summary by CodeRabbit
New Features
Documentation