Skip to content

Comments

fix: Fix microsoft account link for new accounts#731

Merged
elie222 merged 6 commits intoelie222:mainfrom
edulelis:fix-microsoft-account-link
Aug 29, 2025
Merged

fix: Fix microsoft account link for new accounts#731
elie222 merged 6 commits intoelie222:mainfrom
edulelis:fix-microsoft-account-link

Conversation

@edulelis
Copy link
Collaborator

@edulelis edulelis commented Aug 29, 2025

Summary by CodeRabbit

  • New Features

    • Streamlined Microsoft account connection with explicit "Create" or "Merge" actions.
    • Automatic profile image retrieval for newly linked Microsoft accounts.
    • Clearer success and error outcomes during Microsoft linking, improving guidance when accounts aren’t found for merge.
  • Refactor

    • Consolidated Microsoft linking into a single, parameterized flow.
    • Connect flow now obtains an authorization URL from the backend before redirecting; Google flow unchanged.

@vercel
Copy link

vercel bot commented Aug 29, 2025

@edulelis is attempting to deploy a commit to the Inbox Zero OSS Program Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 29, 2025

Walkthrough

Consolidated Microsoft linking: frontend requests a backend auth URL with an action ("create" or "merge") and redirects; backend encodes action into OAuth state and returns the URL; callback decodes action and either merges or creates+links an account (optionally fetching profile image).

Changes

Cohort / File(s) Summary
Frontend: AddAccount Microsoft linking
apps/web/app/(app)/accounts/AddAccount.tsx
Replaced signIn.social Microsoft flow with a unified handleConnectMicrosoft(action) that GETs /api/outlook/linking/auth-url?action={action} and redirects. Added handleCreateMicrosoft and handleMergeMicrosoft. Google flow unchanged.
Backend: Outlook linking API
apps/web/app/api/outlook/linking/auth-url/route.ts, apps/web/app/api/outlook/linking/callback/route.ts
Auth-url route accepts action, encodes {userId, action, nonce} as base64url state and returns { url }; callback decodes state (with action) and branches: existing-account merge path preserved; if no account and action==="create" it creates/link a Microsoft OIDC account, persists tokens, optionally fetches profile photo, creates emailAccount, and redirects with success; added decode error handling and logging.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor U as User
  participant W as Web App (AddAccount)
  participant A as API /api/outlook/linking/auth-url
  participant MS as Microsoft OAuth
  participant C as API /api/outlook/linking/callback
  participant DB as Database

  U->>W: Click "Connect Microsoft" (create/merge)
  W->>A: GET auth-url?action={action}
  A->>A: Build state {userId, action, nonce} (base64url)
  A->>W: { url }
  W->>MS: Redirect to OAuth authorize URL

  MS-->>C: Redirect with code & state
  C->>C: Decode/validate state (userId, action, nonce)

  alt Existing MS-linked account found
    C->>DB: Update/link existing account (merge)
    C-->>U: Redirect success (merged)
  else No existing account
    alt action == "merge"
      C-->>U: Redirect error account_not_found_for_merge
    else action == "create"
      C->>MS: (opt) GET profile photo using access token
      C->>DB: Create OIDC account + emailAccount, persist tokens & metadata
      C-->>U: Redirect success account_created_and_linked
    end
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

A rabbit taps the merge-or-make key,
Hops to the backend for an auth URL spree.
State bears action, nonce tucked tight,
Back comes a token, avatar in light.
Burrows linked, new accounts delight — hop! 🥕✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

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

⚠️ Outside diff range comments (3)
apps/web/app/api/outlook/linking/auth-url/route.ts (1)

9-17: Validate and narrow action; use Zod + literal union.

Per guidelines, validate query params. Also tighten the type of action across the boundary.

+import { z } from "zod";
+
+const ActionSchema = z.enum(["merge", "create"]);
-const getAuthUrl = ({ userId, action }: { userId: string; action: string }) => {
+const getAuthUrl = ({
+  userId,
+  action,
+}: {
+  userId: string;
+  action: z.infer<typeof ActionSchema>;
+}) => {
   const stateObject = { userId, action, nonce: crypto.randomUUID() };
   const state = Buffer.from(JSON.stringify(stateObject)).toString("base64url");
   …
   return { url, state };
 };
 …
-  const url = new URL(request.url);
-  const action = url.searchParams.get("action") || "merge";
+  const url = new URL(request.url);
+  const action = ActionSchema.parse(url.searchParams.get("action") ?? "merge");
   const { url: authUrl, state } = getAuthUrl({ userId, action });

Also applies to: 21-24

apps/web/app/api/outlook/linking/callback/route.ts (2)

35-45: Validate decoded state with Zod and restrict action to enum.

Guarantees shape and allowed values before branching.

+import { z } from "zod";-  let decodedState: { userId: string; action: string; nonce: string };
+  const StateSchema = z.object({
+    userId: z.string().min(1),
+    action: z.enum(["merge", "create"]).default("merge"),
+    nonce: z.string().min(1),
+  });
+  let decodedState: z.infer<typeof StateSchema>;
   try {
-    decodedState = JSON.parse(
-      Buffer.from(storedState, "base64url").toString("utf8"),
-    );
+    const raw = JSON.parse(
+      Buffer.from(storedState, "base64url").toString("utf8"),
+    );
+    decodedState = StateSchema.parse(raw);
   } catch (error) {
     logger.error("Failed to decode state", { error });
     redirectUrl.searchParams.set("error", "invalid_state_format");
     response.cookies.delete(OUTLOOK_LINKING_STATE_COOKIE_NAME);
     return NextResponse.redirect(redirectUrl, { headers: response.headers });
   }
 …
-  const { userId: targetUserId, action } = decodedState;
+  const { userId: targetUserId, action } = decodedState;

Also applies to: 49-50


238-255: Don’t use any in catch; sanitize error description returned to the client.

Avoid leaking internals in URLs; keep details in logs.

-} catch (error: any) {
-  logger.error("Error in Outlook linking callback:", { error });
+} catch (error: unknown) {
+  logger.error("Error in Outlook linking callback:", { error });
   let errorCode = "link_failed";
-  if (error.message?.includes("Failed to exchange code")) {
+  const message = error instanceof Error ? error.message : String(error);
+  if (message.includes("Failed to exchange code")) {
     errorCode = "token_exchange_failed";
-  } else if (error.message?.includes("Failed to fetch user profile")) {
+  } else if (message.includes("Failed to fetch user profile")) {
     errorCode = "profile_fetch_failed";
-  } else if (error.message?.includes("Profile missing required")) {
+  } else if (message.includes("Profile missing required")) {
     errorCode = "incomplete_profile";
   }
   redirectUrl.searchParams.set("error", errorCode);
-  redirectUrl.searchParams.set(
-    "error_description",
-    error.message || "Unknown error",
-  );
+  redirectUrl.searchParams.set("error_description", "Linking failed. Please try again.");
   response.cookies.delete(OUTLOOK_LINKING_STATE_COOKIE_NAME);
   return NextResponse.redirect(redirectUrl, { headers: response.headers });
 }
🧹 Nitpick comments (4)
apps/web/app/api/outlook/linking/auth-url/route.ts (1)

25-26: Prevent caching of one-time auth URL responses.

Set no-store to avoid intermediaries caching the redirect URL.

-  const response = NextResponse.json({ url: authUrl });
+  const response = NextResponse.json({ url: authUrl });
+  response.headers.set("Cache-Control", "no-store");
apps/web/app/(app)/accounts/AddAccount.tsx (2)

28-37: Mirror the same error handling for Google merge.

   const handleMergeGoogle = async () => {
-    const response = await fetch("/api/google/linking/auth-url", {
-      method: "GET",
-      headers: { "Content-Type": "application/json" },
-    });
-    const data: GetAuthLinkUrlResponse = await response.json();
-    window.location.href = data.url;
+    const response = await fetch("/api/google/linking/auth-url");
+    if (!response.ok) {
+      toastError({
+        title: "Error initiating Google link",
+        description: "Please try again or contact support",
+      });
+      return;
+    }
+    const data: GetAuthLinkUrlResponse = await response.json();
+    window.location.href = data.url;
   };

128-131: Provide meaningful alt text for accessibility.

Empty alt violates a11y guidance; use a descriptive alt.

-          <Image src={image} alt="" width={24} height={24} unoptimized />
+          <Image src={image} alt={`${name} logo`} width={24} height={24} unoptimized />
apps/web/app/api/outlook/linking/callback/route.ts (1)

57-96: Add timeouts to external fetch calls (token, profile, photo).

Prevent hanging on slow providers; use AbortController with a sane timeout.

-    const tokenResponse = await fetch(
+    const tokenController = new AbortController();
+    const tokenTimeout = setTimeout(() => tokenController.abort(), 10000);
+    const tokenResponse = await fetch(
       "https://login.microsoftonline.com/common/oauth2/v2.0/token",
       {
         method: "POST",
         headers: {
           "Content-Type": "application/x-www-form-urlencoded",
         },
         body: new URLSearchParams({
           client_id: env.MICROSOFT_CLIENT_ID,
           client_secret: env.MICROSOFT_CLIENT_SECRET,
           code,
           grant_type: "authorization_code",
           redirect_uri: `${env.NEXT_PUBLIC_BASE_URL}/api/outlook/linking/callback`,
         }),
+        signal: tokenController.signal,
       },
     );
+    clearTimeout(tokenTimeout);-    const profileResponse = await fetch("https://graph.microsoft.com/v1.0/me", {
+    const profileController = new AbortController();
+    const profileTimeout = setTimeout(() => profileController.abort(), 10000);
+    const profileResponse = await fetch("https://graph.microsoft.com/v1.0/me", {
       headers: {
         Authorization: `Bearer ${tokens.access_token}`,
       },
+      signal: profileController.signal,
     });
+    clearTimeout(profileTimeout);

And similarly for the photo request inside the try/catch:

-          const photoResponse = await fetch(
+          const photoController = new AbortController();
+          const photoTimeout = setTimeout(() => photoController.abort(), 8000);
+          const photoResponse = await fetch(
             "https://graph.microsoft.com/v1.0/me/photo/$value",
             {
               headers: {
                 Authorization: `Bearer ${tokens.access_token}`,
               },
+              signal: photoController.signal,
             },
           );
+          clearTimeout(photoTimeout);

Also applies to: 102-115

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 1b02c91 and 994dc97.

📒 Files selected for processing (3)
  • apps/web/app/(app)/accounts/AddAccount.tsx (2 hunks)
  • apps/web/app/api/outlook/linking/auth-url/route.ts (2 hunks)
  • apps/web/app/api/outlook/linking/callback/route.ts (3 hunks)
🧰 Additional context used
📓 Path-based instructions (18)
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

apps/web/**/*.{ts,tsx}: Use TypeScript with strict null checks
Path aliases: Use @/ for imports from project root
Use proper error handling with try/catch blocks
Format code with Prettier
Leverage TypeScript inference for better DX

Files:

  • apps/web/app/api/outlook/linking/callback/route.ts
  • apps/web/app/(app)/accounts/AddAccount.tsx
  • apps/web/app/api/outlook/linking/auth-url/route.ts
apps/web/app/**

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

NextJS app router structure with (app) directory

Files:

  • apps/web/app/api/outlook/linking/callback/route.ts
  • apps/web/app/(app)/accounts/AddAccount.tsx
  • apps/web/app/api/outlook/linking/auth-url/route.ts
apps/web/app/api/**/route.ts

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

apps/web/app/api/**/route.ts: Use withAuth for user-level operations
Use withEmailAccount for email-account-level operations
Do NOT use POST API routes for mutations - use server actions instead
No need for try/catch in GET routes when using middleware
Export response types from GET routes

apps/web/app/api/**/route.ts: Wrap all GET API route handlers with withAuth or withEmailAccount middleware for authentication and authorization.
Export response types from GET API routes for type-safe client usage.
Do not use try/catch in GET API routes when using authentication middleware; rely on centralized error handling.

Files:

  • apps/web/app/api/outlook/linking/callback/route.ts
  • apps/web/app/api/outlook/linking/auth-url/route.ts
!{.cursor/rules/*.mdc}

📄 CodeRabbit inference engine (.cursor/rules/cursor-rules.mdc)

Never place rule files in the project root, in subdirectories outside .cursor/rules, or in any other location

Files:

  • apps/web/app/api/outlook/linking/callback/route.ts
  • apps/web/app/(app)/accounts/AddAccount.tsx
  • apps/web/app/api/outlook/linking/auth-url/route.ts
**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/form-handling.mdc)

**/*.ts: The same validation should be done in the server action too
Define validation schemas using Zod

Files:

  • apps/web/app/api/outlook/linking/callback/route.ts
  • apps/web/app/api/outlook/linking/auth-url/route.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/logging.mdc)

**/*.{ts,tsx}: Use createScopedLogger for logging in backend TypeScript files
Typically add the logger initialization at the top of the file when using createScopedLogger
Only use .with() on a logger instance within a specific function, not for a global logger

Import Prisma in the project using import prisma from "@/utils/prisma";

**/*.{ts,tsx}: Don't use TypeScript enums.
Don't use TypeScript const enum.
Don't use the TypeScript directive @ts-ignore.
Don't use primitive type aliases or misleading types.
Don't use empty type parameters in type aliases and interfaces.
Don't use any or unknown as type constraints.
Don't use implicit any type on variable declarations.
Don't let variables evolve into any type through reassignments.
Don't use non-null assertions with the ! postfix operator.
Don't misuse the non-null assertion operator (!) in TypeScript files.
Don't use user-defined types.
Use as const instead of literal types and type annotations.
Use export type for types.
Use import type for types.
Don't declare empty interfaces.
Don't merge interfaces and classes unsafely.
Don't use overload signatures that aren't next to each other.
Use the namespace keyword instead of the module keyword to declare TypeScript namespaces.
Don't use TypeScript namespaces.
Don't export imported variables.
Don't add type annotations to variables, parameters, and class properties that are initialized with literal expressions.
Don't use parameter properties in class constructors.
Use either T[] or Array consistently.
Initialize each enum member value explicitly.
Make sure all enum members are literal values.

Files:

  • apps/web/app/api/outlook/linking/callback/route.ts
  • apps/web/app/(app)/accounts/AddAccount.tsx
  • apps/web/app/api/outlook/linking/auth-url/route.ts
**/api/**/route.ts

📄 CodeRabbit inference engine (.cursor/rules/security.mdc)

**/api/**/route.ts: ALL API routes that handle user data MUST use appropriate authentication and authorization middleware (withAuth or withEmailAccount).
ALL database queries in API routes MUST be scoped to the authenticated user/account (e.g., include userId or emailAccountId in query filters).
Always validate that resources belong to the authenticated user before performing operations (resource ownership validation).
Use withEmailAccount middleware for API routes that operate on a specific email account (i.e., use or require emailAccountId).
Use withAuth middleware for API routes that operate at the user level (i.e., use or require only userId).
Use withError middleware (with proper validation) for public endpoints, custom authentication, or cron endpoints.
Cron endpoints MUST use withError middleware and validate the cron secret using hasCronSecret(request) or hasPostCronSecret(request).
Cron endpoints MUST capture unauthorized attempts with captureException and return a 401 status for unauthorized requests.
All parameters in API routes MUST be validated for type, format, and length before use.
Request bodies in API routes MUST be validated using Zod schemas before use.
All Prisma queries in API routes MUST only return necessary fields and never expose sensitive data.
Error messages in API routes MUST not leak internal information or sensitive data; use generic error messages and SafeError where appropriate.
API routes MUST use a consistent error response format, returning JSON with an error message and status code.
All findUnique and findFirst Prisma calls in API routes MUST include ownership filters (e.g., userId or emailAccountId).
All findMany Prisma calls in API routes MUST be scoped to the authenticated user's data.
Never use direct object references in API routes without ownership checks (prevent IDOR vulnerabilities).
Prevent mass assignment vulnerabilities by only allowing explicitly whitelisted fields in update operations in AP...

Files:

  • apps/web/app/api/outlook/linking/callback/route.ts
  • apps/web/app/api/outlook/linking/auth-url/route.ts
apps/web/app/api/**/*.{ts,js}

📄 CodeRabbit inference engine (.cursor/rules/security-audit.mdc)

apps/web/app/api/**/*.{ts,js}: All API route handlers in 'apps/web/app/api/' must use authentication middleware: withAuth, withEmailAccount, or withError (with custom authentication logic).
All Prisma queries in API routes must include user/account filtering (e.g., emailAccountId or userId in WHERE clauses) to prevent unauthorized data access.
All parameters used in API routes must be validated before use; do not use parameters from 'params' or request bodies directly in queries without validation.
Request bodies in API routes should use Zod schemas for validation.
API routes should only return necessary fields using Prisma's 'select' and must not include sensitive data in error messages.
Error messages in API routes must not reveal internal details; use generic errors and SafeError for user-facing errors.
All QStash endpoints (API routes called via publishToQstash or publishToQstashQueue) must use verifySignatureAppRouter to verify request authenticity.
All cron endpoints in API routes must use hasCronSecret or hasPostCronSecret for authentication.
Do not hardcode weak or plaintext secrets in API route files; secrets must not be directly assigned as string literals.
Review all new withError usage in API routes to ensure custom authentication is implemented where required.

Files:

  • apps/web/app/api/outlook/linking/callback/route.ts
  • apps/web/app/api/outlook/linking/auth-url/route.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{js,jsx,ts,tsx}: Don't use elements in Next.js projects.
Don't use elements in Next.js projects.
Don't use namespace imports.
Don't access namespace imports dynamically.
Don't use global eval().
Don't use console.
Don't use debugger.
Don't use var.
Don't use with statements in non-strict contexts.
Don't use the arguments object.
Don't use consecutive spaces in regular expression literals.
Don't use the comma operator.
Don't use unnecessary boolean casts.
Don't use unnecessary callbacks with flatMap.
Use for...of statements instead of Array.forEach.
Don't create classes that only have static members (like a static namespace).
Don't use this and super in static contexts.
Don't use unnecessary catch clauses.
Don't use unnecessary constructors.
Don't use unnecessary continue statements.
Don't export empty modules that don't change anything.
Don't use unnecessary escape sequences in regular expression literals.
Don't use unnecessary labels.
Don't use unnecessary nested block statements.
Don't rename imports, exports, and destructured assignments to the same name.
Don't use unnecessary string or template literal concatenation.
Don't use String.raw in template literals when there are no escape sequences.
Don't use useless case statements in switch statements.
Don't use ternary operators when simpler alternatives exist.
Don't use useless this aliasing.
Don't initialize variables to undefined.
Don't use the void operators (they're not familiar).
Use arrow functions instead of function expressions.
Use Date.now() to get milliseconds since the Unix Epoch.
Use .flatMap() instead of map().flat() when possible.
Use literal property access instead of computed property access.
Don't use parseInt() or Number.parseInt() when binary, octal, or hexadecimal literals work.
Use concise optional chaining instead of chained logical expressions.
Use regular expression literals instead of the RegExp constructor when possible.
Don't use number literal object member names th...

Files:

  • apps/web/app/api/outlook/linking/callback/route.ts
  • apps/web/app/(app)/accounts/AddAccount.tsx
  • apps/web/app/api/outlook/linking/auth-url/route.ts
!pages/_document.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

!pages/_document.{js,jsx,ts,tsx}: Don't import next/document outside of pages/_document.jsx in Next.js projects.
Don't import next/document outside of pages/_document.jsx in Next.js projects.

Files:

  • apps/web/app/api/outlook/linking/callback/route.ts
  • apps/web/app/(app)/accounts/AddAccount.tsx
  • apps/web/app/api/outlook/linking/auth-url/route.ts
apps/web/**/*.tsx

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

apps/web/**/*.tsx: Follow tailwindcss patterns with prettier-plugin-tailwindcss
Prefer functional components with hooks
Use shadcn/ui components when available
Ensure responsive design with mobile-first approach
Follow consistent naming conventions (PascalCase for components)
Use LoadingContent component for async data
Use result?.serverError with toastError and toastSuccess
Use LoadingContent component to handle loading and error states consistently
Pass loading, error, and children props to LoadingContent

Files:

  • apps/web/app/(app)/accounts/AddAccount.tsx
**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/form-handling.mdc)

**/*.tsx: Use React Hook Form with Zod for validation
Validate form inputs before submission
Show validation errors inline next to form fields

Files:

  • apps/web/app/(app)/accounts/AddAccount.tsx
apps/web/app/(app)/*/**

📄 CodeRabbit inference engine (.cursor/rules/page-structure.mdc)

Components for the page are either put in page.tsx, or in the apps/web/app/(app)/PAGE_NAME folder

Files:

  • apps/web/app/(app)/accounts/AddAccount.tsx
apps/web/app/(app)/*/**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/page-structure.mdc)

If you need to use onClick in a component, that component is a client component and file must start with 'use client'

Files:

  • apps/web/app/(app)/accounts/AddAccount.tsx
apps/web/app/(app)/*/**/**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/page-structure.mdc)

If we're in a deeply nested component we will use swr to fetch via API

Files:

  • apps/web/app/(app)/accounts/AddAccount.tsx
apps/web/app/**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)

Components with onClick must be client components with use client directive

Files:

  • apps/web/app/(app)/accounts/AddAccount.tsx
**/*.{jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{jsx,tsx}: Don't destructure props inside JSX components in Solid projects.
Don't use both children and dangerouslySetInnerHTML props on the same element.
Don't use Array index in keys.
Don't assign to React component props.
Don't define React components inside other components.
Don't use event handlers on non-interactive elements.
Don't assign JSX properties multiple times.
Don't add extra closing tags for components without children.
Use <>...</> instead of ....
Don't insert comments as text nodes.
Don't use the return value of React.render.
Make sure all dependencies are correctly specified in React hooks.
Make sure all React hooks are called from the top level of component functions.
Don't use unnecessary fragments.
Don't pass children as props.
Use semantic elements instead of role attributes in JSX.

Files:

  • apps/web/app/(app)/accounts/AddAccount.tsx
**/*.{html,jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{html,jsx,tsx}: Don't use or elements.
Don't use accessKey attribute on any HTML element.
Don't set aria-hidden="true" on focusable elements.
Don't add ARIA roles, states, and properties to elements that don't support them.
Only use the scope prop on elements.
Don't assign non-interactive ARIA roles to interactive HTML elements.
Make sure label elements have text content and are associated with an input.
Don't assign interactive ARIA roles to non-interactive HTML elements.
Don't assign tabIndex to non-interactive HTML elements.
Don't use positive integers for tabIndex property.
Don't include "image", "picture", or "photo" in img alt prop.
Don't use explicit role property that's the same as the implicit/default role.
Make static elements with click handlers use a valid role attribute.
Always include a title element for SVG elements.
Give all elements requiring alt text meaningful information for screen readers.
Make sure anchors have content that's accessible to screen readers.
Assign tabIndex to non-interactive HTML elements with aria-activedescendant.
Include all required ARIA attributes for elements with ARIA roles.
Make sure ARIA properties are valid for the element's supported roles.
Always include a type attribute for button elements.
Make elements with interactive roles and handlers focusable.
Give heading elements content that's accessible to screen readers (not hidden with aria-hidden).
Always include a lang attribute on the html element.
Always include a title attribute for iframe elements.
Accompany onClick with at least one of: onKeyUp, onKeyDown, or onKeyPress.
Accompany onMouseOver/onMouseOut with onFocus/onBlur.
Include caption tracks for audio and video elements.
Make sure all anchors are valid and navigable.
Ensure all ARIA properties (aria-*) are valid.
Use valid, non-abstract ARIA roles for elements with ARIA roles.
Use valid ARIA state and property values.
Use valid values for the autocomplete attribute on input eleme...

Files:

  • apps/web/app/(app)/accounts/AddAccount.tsx
🧬 Code graph analysis (1)
apps/web/app/(app)/accounts/AddAccount.tsx (1)
apps/web/app/api/outlook/linking/auth-url/route.ts (1)
  • GetOutlookAuthLinkUrlResponse (7-7)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Static Code Analysis Js
  • GitHub Check: Jit Security
🔇 Additional comments (1)
apps/web/app/(app)/accounts/AddAccount.tsx (1)

53-55: Wrapper approach looks good.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Caution

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

⚠️ Outside diff range comments (4)
apps/web/app/api/outlook/linking/callback/route.ts (4)

206-248: Gate the merge path by action to prevent unintended account reassignment.

Currently, merge executes even when action !== "merge". This can reassign and delete users when the intention was “create”.

Apply this diff:

   if (existingAccount.userId === targetUserId) {
     logger.warn(
       "Microsoft account is already linked to the correct user. Merge action unnecessary.",
       { email: providerEmail, targetUserId },
     );
     redirectUrl.searchParams.set("error", "already_linked_to_self");
     return NextResponse.redirect(redirectUrl, {
       headers: response.headers,
     });
   }
 
+  if (action !== "merge") {
+    logger.warn("Merge not requested; account exists under a different user.", {
+      email: providerEmail,
+      targetUserId,
+      sourceUserId: existingAccount.userId,
+    });
+    redirectUrl.searchParams.set("error", "account_exists_for_another_user");
+    return NextResponse.redirect(redirectUrl, { headers: response.headers });
+  }
+
   logger.info("Merging Microsoft account linked to user.", {
     email: providerEmail,
     targetUserId,
   });

35-45: Harden state decoding/validation and guarantee Node runtime for Buffer.

Validate structure and allowed actions with Zod; avoid silent acceptance of unknown actions. Also ensure this route runs on Node (Buffer isn’t available on Edge by default).

Apply this diff to replace the block:

-let decodedState: { userId: string; action: string; nonce: string };
-try {
-  decodedState = JSON.parse(
-    Buffer.from(storedState, "base64url").toString("utf8"),
-  );
-} catch (error) {
-  logger.error("Failed to decode state", { error });
-  redirectUrl.searchParams.set("error", "invalid_state_format");
-  response.cookies.delete(OUTLOOK_LINKING_STATE_COOKIE_NAME);
-  return NextResponse.redirect(redirectUrl, { headers: response.headers });
-}
+const parsed = StateSchema.safeParse(
+  JSON.parse(Buffer.from(storedState, "base64url").toString("utf8")),
+);
+if (!parsed.success) {
+  logger.error("Failed to decode/validate state", {
+    issues: parsed.error.issues,
+  });
+  redirectUrl.searchParams.set("error", "invalid_state_format");
+  response.cookies.delete(OUTLOOK_LINKING_STATE_COOKIE_NAME);
+  return NextResponse.redirect(redirectUrl, { headers: response.headers });
+}
+const decodedState = parsed.data;

Add these supporting changes outside the block:

// at top-level imports
import { z } from "zod";

// explicitly set runtime
export const runtime = "nodejs";

// near logger declaration
const StateSchema = z.object({
  userId: z.string().min(1),
  action: z.enum(["merge", "create"]).default("create"),
  nonce: z.string().min(1),
});

102-114: Match existing accounts by providerAccountId (primary) with email as fallback, not email-only.

Email-based lookup risks false matches; providerAccountId is the stable identifier.

Apply this diff:

-const existingAccount = await prisma.account.findFirst({
-  where: {
-    provider: "microsoft",
-    user: {
-      email: providerEmail.trim().toLowerCase(),
-    },
-  },
+const existingAccount = await prisma.account.findFirst({
+  where: {
+    provider: "microsoft",
+    OR: [
+      { providerAccountId: profile.id },
+      { user: { email: normalizedEmail } },
+    ],
+  },
   select: {
     id: true,
     userId: true,
     user: { select: { name: true, email: true } },
   },
 });

Add this supporting line right after the providerEmail null-check:

const normalizedEmail = providerEmail.trim().toLowerCase();

249-263: Do not leak raw error.message to clients; return sanitized messages.

Project guidelines forbid exposing internal details. Map to friendly strings.

Apply this diff:

-redirectUrl.searchParams.set(
-  "error_description",
-  error.message || "Unknown error",
-);
+const messageByCode: Record<string, string> = {
+  token_exchange_failed: "Unable to sign in with Microsoft. Please try again.",
+  profile_fetch_failed: "We couldn't access your Microsoft profile.",
+  incomplete_profile: "Your Microsoft account has no email address.",
+};
+redirectUrl.searchParams.set(
+  "error_description",
+  messageByCode[errorCode] ?? "Microsoft linking failed.",
+);
♻️ Duplicate comments (1)
apps/web/app/api/outlook/linking/callback/route.ts (1)

135-144: Good fix on expires_in vs expires_at; also guard against NaN/invalid values.

Compute a capped, finite expiresAt to avoid storing invalid dates.

Apply this diff:

-} else if (tokens.expires_in) {
-  const expiresInSeconds =
-    typeof tokens.expires_in === "string"
-      ? Number.parseInt(tokens.expires_in, 10)
-      : tokens.expires_in;
-  expiresAt = new Date(Date.now() + expiresInSeconds * 1000);
-}
+} else if (tokens.expires_in) {
+  const expiresInSeconds =
+    typeof tokens.expires_in === "string"
+      ? Number.parseInt(tokens.expires_in, 10)
+      : tokens.expires_in;
+  if (Number.isFinite(expiresInSeconds) && expiresInSeconds > 0) {
+    const ONE_YEAR_S = 365 * 24 * 60 * 60;
+    const capped = Math.min(expiresInSeconds, ONE_YEAR_S);
+    expiresAt = new Date(Date.now() + capped * 1000);
+  } else {
+    expiresAt = null;
+  }
+}
🧹 Nitpick comments (4)
apps/web/app/api/outlook/linking/callback/route.ts (4)

171-176: Validate photo content-type before using bytes.

Avoid treating non-image responses as images (e.g., HTML error bodies).

Apply this diff:

- if (photoResponse.ok) {
+ if (
+   photoResponse.ok &&
+   photoResponse.headers.get("content-type")?.startsWith("image/")
+ ) {
    const photoBuffer = await photoResponse.arrayBuffer();
    const photoBase64 = Buffer.from(photoBuffer).toString("base64");
    profileImage = `data:image/jpeg;base64,${photoBase64}`;
  }

181-183: Normalize stored email to lower-case to prevent duplicates.

Ensure consistent casing at write-time.

Apply this diff:

-            email: providerEmail,
+            email: normalizedEmail,

Supporting line already suggested: define normalizedEmail after verifying providerEmail exists.


59-74: Add short fetch timeouts to external calls.

Protect the callback from hanging on Microsoft endpoints.

Example (helper outside these blocks):

const withTimeout = (ms: number, signal?: AbortSignal) => {
  const ctrl = new AbortController();
  const id = setTimeout(() => ctrl.abort(), ms);
  return { signal: signal ? AbortSignal.any([signal, ctrl.signal]) : ctrl.signal, clear: () => clearTimeout(id) };
};

Usage:

const t1 = withTimeout(10_000);
const tokenResponse = await fetch(url, { method: "POST", headers, body, signal: t1.signal }).finally(t1.clear);

const t2 = withTimeout(10_000);
const profileResponse = await fetch("https://graph.microsoft.com/v1.0/me", { headers, signal: t2.signal }).finally(t2.clear);

const t3 = withTimeout(7_000);
const photoResponse = await fetch("https://graph.microsoft.com/v1.0/me/photo/$value", { headers, signal: t3.signal }).finally(t3.clear);

Also applies to: 85-90, 162-169


1-10: Export response type for this GET route (even if it always redirects).

Keeps client usage type-safe per guidelines.

Add:

export type OutlookLinkingCallbackResponse = never;
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 994dc97 and 9f62408.

📒 Files selected for processing (2)
  • apps/web/app/(app)/accounts/AddAccount.tsx (2 hunks)
  • apps/web/app/api/outlook/linking/callback/route.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/web/app/(app)/accounts/AddAccount.tsx
🧰 Additional context used
📓 Path-based instructions (10)
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

apps/web/**/*.{ts,tsx}: Use TypeScript with strict null checks
Path aliases: Use @/ for imports from project root
Use proper error handling with try/catch blocks
Format code with Prettier
Leverage TypeScript inference for better DX

Files:

  • apps/web/app/api/outlook/linking/callback/route.ts
apps/web/app/**

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

NextJS app router structure with (app) directory

Files:

  • apps/web/app/api/outlook/linking/callback/route.ts
apps/web/app/api/**/route.ts

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

apps/web/app/api/**/route.ts: Use withAuth for user-level operations
Use withEmailAccount for email-account-level operations
Do NOT use POST API routes for mutations - use server actions instead
No need for try/catch in GET routes when using middleware
Export response types from GET routes

apps/web/app/api/**/route.ts: Wrap all GET API route handlers with withAuth or withEmailAccount middleware for authentication and authorization.
Export response types from GET API routes for type-safe client usage.
Do not use try/catch in GET API routes when using authentication middleware; rely on centralized error handling.

Files:

  • apps/web/app/api/outlook/linking/callback/route.ts
!{.cursor/rules/*.mdc}

📄 CodeRabbit inference engine (.cursor/rules/cursor-rules.mdc)

Never place rule files in the project root, in subdirectories outside .cursor/rules, or in any other location

Files:

  • apps/web/app/api/outlook/linking/callback/route.ts
**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/form-handling.mdc)

**/*.ts: The same validation should be done in the server action too
Define validation schemas using Zod

Files:

  • apps/web/app/api/outlook/linking/callback/route.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/logging.mdc)

**/*.{ts,tsx}: Use createScopedLogger for logging in backend TypeScript files
Typically add the logger initialization at the top of the file when using createScopedLogger
Only use .with() on a logger instance within a specific function, not for a global logger

Import Prisma in the project using import prisma from "@/utils/prisma";

**/*.{ts,tsx}: Don't use TypeScript enums.
Don't use TypeScript const enum.
Don't use the TypeScript directive @ts-ignore.
Don't use primitive type aliases or misleading types.
Don't use empty type parameters in type aliases and interfaces.
Don't use any or unknown as type constraints.
Don't use implicit any type on variable declarations.
Don't let variables evolve into any type through reassignments.
Don't use non-null assertions with the ! postfix operator.
Don't misuse the non-null assertion operator (!) in TypeScript files.
Don't use user-defined types.
Use as const instead of literal types and type annotations.
Use export type for types.
Use import type for types.
Don't declare empty interfaces.
Don't merge interfaces and classes unsafely.
Don't use overload signatures that aren't next to each other.
Use the namespace keyword instead of the module keyword to declare TypeScript namespaces.
Don't use TypeScript namespaces.
Don't export imported variables.
Don't add type annotations to variables, parameters, and class properties that are initialized with literal expressions.
Don't use parameter properties in class constructors.
Use either T[] or Array consistently.
Initialize each enum member value explicitly.
Make sure all enum members are literal values.

Files:

  • apps/web/app/api/outlook/linking/callback/route.ts
**/api/**/route.ts

📄 CodeRabbit inference engine (.cursor/rules/security.mdc)

**/api/**/route.ts: ALL API routes that handle user data MUST use appropriate authentication and authorization middleware (withAuth or withEmailAccount).
ALL database queries in API routes MUST be scoped to the authenticated user/account (e.g., include userId or emailAccountId in query filters).
Always validate that resources belong to the authenticated user before performing operations (resource ownership validation).
Use withEmailAccount middleware for API routes that operate on a specific email account (i.e., use or require emailAccountId).
Use withAuth middleware for API routes that operate at the user level (i.e., use or require only userId).
Use withError middleware (with proper validation) for public endpoints, custom authentication, or cron endpoints.
Cron endpoints MUST use withError middleware and validate the cron secret using hasCronSecret(request) or hasPostCronSecret(request).
Cron endpoints MUST capture unauthorized attempts with captureException and return a 401 status for unauthorized requests.
All parameters in API routes MUST be validated for type, format, and length before use.
Request bodies in API routes MUST be validated using Zod schemas before use.
All Prisma queries in API routes MUST only return necessary fields and never expose sensitive data.
Error messages in API routes MUST not leak internal information or sensitive data; use generic error messages and SafeError where appropriate.
API routes MUST use a consistent error response format, returning JSON with an error message and status code.
All findUnique and findFirst Prisma calls in API routes MUST include ownership filters (e.g., userId or emailAccountId).
All findMany Prisma calls in API routes MUST be scoped to the authenticated user's data.
Never use direct object references in API routes without ownership checks (prevent IDOR vulnerabilities).
Prevent mass assignment vulnerabilities by only allowing explicitly whitelisted fields in update operations in AP...

Files:

  • apps/web/app/api/outlook/linking/callback/route.ts
apps/web/app/api/**/*.{ts,js}

📄 CodeRabbit inference engine (.cursor/rules/security-audit.mdc)

apps/web/app/api/**/*.{ts,js}: All API route handlers in 'apps/web/app/api/' must use authentication middleware: withAuth, withEmailAccount, or withError (with custom authentication logic).
All Prisma queries in API routes must include user/account filtering (e.g., emailAccountId or userId in WHERE clauses) to prevent unauthorized data access.
All parameters used in API routes must be validated before use; do not use parameters from 'params' or request bodies directly in queries without validation.
Request bodies in API routes should use Zod schemas for validation.
API routes should only return necessary fields using Prisma's 'select' and must not include sensitive data in error messages.
Error messages in API routes must not reveal internal details; use generic errors and SafeError for user-facing errors.
All QStash endpoints (API routes called via publishToQstash or publishToQstashQueue) must use verifySignatureAppRouter to verify request authenticity.
All cron endpoints in API routes must use hasCronSecret or hasPostCronSecret for authentication.
Do not hardcode weak or plaintext secrets in API route files; secrets must not be directly assigned as string literals.
Review all new withError usage in API routes to ensure custom authentication is implemented where required.

Files:

  • apps/web/app/api/outlook/linking/callback/route.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{js,jsx,ts,tsx}: Don't use elements in Next.js projects.
Don't use elements in Next.js projects.
Don't use namespace imports.
Don't access namespace imports dynamically.
Don't use global eval().
Don't use console.
Don't use debugger.
Don't use var.
Don't use with statements in non-strict contexts.
Don't use the arguments object.
Don't use consecutive spaces in regular expression literals.
Don't use the comma operator.
Don't use unnecessary boolean casts.
Don't use unnecessary callbacks with flatMap.
Use for...of statements instead of Array.forEach.
Don't create classes that only have static members (like a static namespace).
Don't use this and super in static contexts.
Don't use unnecessary catch clauses.
Don't use unnecessary constructors.
Don't use unnecessary continue statements.
Don't export empty modules that don't change anything.
Don't use unnecessary escape sequences in regular expression literals.
Don't use unnecessary labels.
Don't use unnecessary nested block statements.
Don't rename imports, exports, and destructured assignments to the same name.
Don't use unnecessary string or template literal concatenation.
Don't use String.raw in template literals when there are no escape sequences.
Don't use useless case statements in switch statements.
Don't use ternary operators when simpler alternatives exist.
Don't use useless this aliasing.
Don't initialize variables to undefined.
Don't use the void operators (they're not familiar).
Use arrow functions instead of function expressions.
Use Date.now() to get milliseconds since the Unix Epoch.
Use .flatMap() instead of map().flat() when possible.
Use literal property access instead of computed property access.
Don't use parseInt() or Number.parseInt() when binary, octal, or hexadecimal literals work.
Use concise optional chaining instead of chained logical expressions.
Use regular expression literals instead of the RegExp constructor when possible.
Don't use number literal object member names th...

Files:

  • apps/web/app/api/outlook/linking/callback/route.ts
!pages/_document.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

!pages/_document.{js,jsx,ts,tsx}: Don't import next/document outside of pages/_document.jsx in Next.js projects.
Don't import next/document outside of pages/_document.jsx in Next.js projects.

Files:

  • apps/web/app/api/outlook/linking/callback/route.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Static Code Analysis Js
  • GitHub Check: Jit Security
🔇 Additional comments (1)
apps/web/app/api/outlook/linking/callback/route.ts (1)

11-14: Confirm try/catch necessity alongside withError.

Guidelines suggest avoiding try/catch in GET with middleware; if custom redirects per error are required, keep as-is. Otherwise, let withError handle.

Would you prefer central handling (throw SafeError with codes) and move mapping to middleware?

@elie222
Copy link
Owner

elie222 commented Aug 29, 2025

@claude review

@claude
Copy link

claude bot commented Aug 29, 2025

Claude encountered an error —— View job

Failed with exit code 128

I'll analyze this and get back to you.

@elie222 elie222 merged commit df211b0 into elie222:main Aug 29, 2025
9 of 11 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Sep 9, 2025
@coderabbitai coderabbitai bot mentioned this pull request Sep 17, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants