Skip to content

Comments

security: fix open redirect vulnerability in login flow#1179

Merged
elie222 merged 5 commits intomainfrom
fix/open-redirect-vulnerability
Jan 3, 2026
Merged

security: fix open redirect vulnerability in login flow#1179
elie222 merged 5 commits intomainfrom
fix/open-redirect-vulnerability

Conversation

@elie222
Copy link
Owner

@elie222 elie222 commented Jan 2, 2026

User description

Validate the 'next' query parameter to ensure only internal paths are allowed for redirects, preventing open redirect attacks.

  • Added isInternalPath utility to apps/web/utils/path.ts
  • Validated next parameter in apps/web/app/(landing)/login/page.tsx
  • Validated next parameter in apps/web/app/(landing)/login/LoginForm.tsx for social sign-in callbacks
  • Refactored apps/web/app/(app)/[emailAccountId]/calendars/page.tsx to use the shared utility

Generated description

Below is a concise technical summary of the changes proposed in this PR:

graph LR
AuthenticationPage_("AuthenticationPage"):::modified
isInternalPath_("isInternalPath"):::added
LoginForm_handleGoogleSignIn_("LoginForm.handleGoogleSignIn"):::modified
LoginForm_handleMicrosoftSignIn_("LoginForm.handleMicrosoftSignIn"):::modified
CalendarsPage_("CalendarsPage"):::modified
SIGN_IN_SOCIAL_("SIGN_IN_SOCIAL"):::modified
GOOGLE_OAUTH_("GOOGLE_OAUTH"):::modified
MICROSOFT_OAUTH_("MICROSOFT_OAUTH"):::modified
AuthenticationPage_ -- "Validates 'next' is internal before redirecting." --> isInternalPath_
LoginForm_handleGoogleSignIn_ -- "Validates 'next' before using it as callbackURL." --> isInternalPath_
LoginForm_handleMicrosoftSignIn_ -- "Validates 'next' before using it as callbackURL." --> isInternalPath_
CalendarsPage_ -- "Ensures returnPath cookie points to an internal route." --> isInternalPath_
LoginForm_handleGoogleSignIn_ -- "Passes validated callbackURL to SIGN_IN_SOCIAL." --> SIGN_IN_SOCIAL_
LoginForm_handleGoogleSignIn_ -- "Uses Google OAuth with validated callbackURL." --> GOOGLE_OAUTH_
LoginForm_handleMicrosoftSignIn_ -- "Passes validated callbackURL to SIGN_IN_SOCIAL." --> SIGN_IN_SOCIAL_
LoginForm_handleMicrosoftSignIn_ -- "Uses Microsoft OAuth with validated callbackURL." --> MICROSOFT_OAUTH_
classDef added stroke:#15AA7A
classDef removed stroke:#CD5270
classDef modified stroke:#EDAC4C
linkStyle default stroke:#CBD5E1,font-size:13px
Loading

Implement a security fix to prevent open redirect vulnerabilities by validating the next query parameter in the login flow and calendar redirection. Introduce a new isInternalPath utility function to ensure all redirects lead to internal application paths.

TopicDetails
Refactor Test Utils Refactor test helper functions to use a shared getMockMessage utility, improving test code reusability and maintainability.
Modified files (2)
  • apps/web/app/api/clean/route.test.ts
  • apps/web/__tests__/helpers.ts
Latest Contributors(1)
UserCommitDate
elie222fix-properly-merge-hea...January 02, 2026
Fix Open Redirect Validate the next query parameter in login and calendar redirection flows to prevent open redirect vulnerabilities by ensuring only internal paths are used.
Modified files (5)
  • apps/web/utils/path.ts
  • apps/web/utils/path.test.ts
  • apps/web/app/(landing)/login/page.tsx
  • apps/web/app/(landing)/login/LoginForm.tsx
  • apps/web/app/(app)/[emailAccountId]/calendars/page.tsx
Latest Contributors(2)
UserCommitDate
elie222adjust-calendar-page-uxDecember 30, 2025
eduardoleliss@gmail.comUse-outlook-endpointOctober 09, 2025
This pull request is reviewed by Baz. Review like a pro on (Baz).

Summary by CodeRabbit

  • Bug Fixes

    • Improved validation of redirect paths in login flows and calendar navigation to better distinguish internal routes from external URLs.
    • Enhanced callback URL handling during authentication sign-in flows.
  • Tests

    • Added comprehensive test coverage for path validation logic.
    • Updated test infrastructure with enhanced mock message creation.

✏️ Tip: You can customize this high-level summary in your review settings.

@vercel
Copy link

vercel bot commented Jan 2, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Review Updated (UTC)
inbox-zero Ready Ready Preview Jan 3, 2026 4:41pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 2, 2026

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

📝 Walkthrough

Walkthrough

This PR adds path validation security enhancement by introducing a new isInternalPath utility function and applying it across authentication and navigation flows to prevent open redirects. Test mock helpers are updated to support flexible label and attachment configuration.

Changes

Cohort / File(s) Summary
Path Validation Utility
apps/web/utils/path.ts, apps/web/utils/path.test.ts
New isInternalPath() function validates whether paths are internal (start with single /, reject //, /\, external URLs, and null/undefined). Comprehensive test suite covering valid paths, external URLs, protocol-relative URLs, and edge cases.
Authentication Pages
apps/web/app/(landing)/login/page.tsx, apps/web/app/(landing)/login/LoginForm.tsx
Integrated isInternalPath checks to redirect only to validated internal paths; fallback to WELCOME_PATH for external or invalid next parameters.
Calendar Page
apps/web/app/(app)/[emailAccountId]/calendars/page.tsx
Replaced inline path validation logic with isInternalPath() utility call.
Test Utilities & Tests
apps/web/__tests__/helpers.ts, apps/web/app/api/clean/route.test.ts
Enhanced getMockMessage to accept optional labelIds and attachments parameters, replacing hardcoded defaults. Updated test file to use the improved helper instead of local createMockMessage.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • Outlook refactor & Delayed Actions fixes #595: Updates attachment detection and label handling in message processing; aligns with enhanced mock message helper that now supports flexible attachments and labelIds configuration for testing.

Suggested reviewers

  • anakarentorosserrano-star

Poem

🐰 With paths now clear and safe to roam,
No open redirects lead away from home,
The rabbit hops through validated shores,
Where internal paths unlock the doors!
✨ A hop of security, through and through,
The tests and helpers now all anew!

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly and concisely summarizes the main change: fixing an open redirect vulnerability in the login flow by validating internal paths.
✨ Finishing touches
  • 📝 Generate docstrings

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

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

@macroscopeapp
Copy link
Contributor

macroscopeapp bot commented Jan 2, 2026

Prevent open redirects in login by validating isInternalPath in LoginForm.handleGoogleSignIn, LoginForm.handleMicrosoftSignIn, and (landing)/login/page.tsx, and gate cookie-based redirects in (app)/[emailAccountId]/calendars/page.tsx

Introduce utils/path.isInternalPath and use it to validate next and cookie return paths in login and calendar redirect flows; add unit tests for isInternalPath and update tests to use __tests__/helpers.getMockMessage. See apps/web/utils/path.ts.

📍Where to Start

Start with isInternalPath in apps/web/utils/path.ts, then review its usage in apps/web/app/(landing)/login/LoginForm.tsx and apps/web/app/(landing)/login/page.tsx.


Macroscope summarized 7c855d2.

Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

1 issue found across 9 files

Prompt for AI agents (all issues)

Check if these issues are valid — if so, understand the root cause of each and fix them.


<file name="apps/web/utils/path.ts">

<violation number="1" location="apps/web/utils/path.ts:8">
P1: Open redirect bypass: The backslash variant `/\evil.com` bypasses this check. Browsers normalize backslashes to forward slashes, so `/\evil.com` becomes `//evil.com` and redirects to `evil.com`. Add a check for `/\` to fully prevent open redirects.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.


export function isInternalPath(path: string | null | undefined): boolean {
if (!path) return false;
return path.startsWith("/") && !path.startsWith("//");
Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot Jan 2, 2026

Choose a reason for hiding this comment

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

P1: Open redirect bypass: The backslash variant /\evil.com bypasses this check. Browsers normalize backslashes to forward slashes, so /\evil.com becomes //evil.com and redirects to evil.com. Add a check for /\ to fully prevent open redirects.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/web/utils/path.ts, line 8:

<comment>Open redirect bypass: The backslash variant `/\evil.com` bypasses this check. Browsers normalize backslashes to forward slashes, so `/\evil.com` becomes `//evil.com` and redirects to `evil.com`. Add a check for `/\` to fully prevent open redirects.</comment>

<file context>
@@ -2,3 +2,8 @@ export const prefixPath = (emailAccountId: string, path: `/${string}`) =&gt; {
+
+export function isInternalPath(path: string | null | undefined): boolean {
+  if (!path) return false;
+  return path.startsWith(&quot;/&quot;) &amp;&amp; !path.startsWith(&quot;//&quot;);
+}
</file context>
Suggested change
return path.startsWith("/") && !path.startsWith("//");
return path.startsWith("/") && !path.startsWith("//") && !path.startsWith("/\\");

✅ Addressed in b7679f1

Copy link
Contributor

Choose a reason for hiding this comment

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

Commit b7679f1 addressed this comment by adding the exact security fix that was requested. The new code includes !path.startsWith("/\\") as an additional condition, which prevents the backslash bypass vulnerability where /\evil.com could be normalized by browsers to //evil.com and cause an open redirect.

Comment on lines 68 to 111
function createMockMessage(
overrides: Partial<ParsedMessage> & { labelIds?: string[] } = {},
): ParsedMessage {
return {
id: overrides.id || "msg-1",
threadId: "thread-1",
historyId: "12345",
snippet: "Test snippet",
subject: overrides.headers?.subject || "Test Subject",
date: new Date().toISOString(),
internalDate: String(Date.now()),
inline: [],
headers: {
from: "sender@example.com",
to: "user@example.com",
subject: "Test Subject",
date: new Date().toISOString(),
...overrides.headers,
},
labelIds: overrides.labelIds || [],
attachments: overrides.attachments || [],
...overrides,
};
}

function getDefaultParams() {
return {
emailAccountId: "email-account-id",
threadId: "thread-1",
markedDoneLabelId: "marked-done-label",
processedLabelId: "processed-label",
jobId: "job-1",
action: CleanAction.ARCHIVE,
skips: {
reply: true,
starred: true,
calendar: true,
receipt: true,
attachment: true,
conversation: true,
},
logger: mockLogger as any,
};
}
Copy link
Contributor

Choose a reason for hiding this comment

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

The new tests define createMockMessage/getDefaultParams inline at lines 68‑111 instead of reusing the shared helpers from apps/web/__tests__/helpers.ts (getMockMessage, getEmail, etc.). .cursor/rules/testing.mdc explicitly requires email/account mock data to come from the shared helpers so tests don't drift, so this duplication violates the team guideline and should be replaced with the canonical helpers plus tailored overrides (e.g., overriding labelIds/attachments).


Finding type: AI Coding Guidelines

Copy link
Contributor

Choose a reason for hiding this comment

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

Commit b7679f1 addressed this comment by removing the duplicated createMockMessage function entirely and replacing all its usages with the canonical getMockMessage helper from the shared test helpers. The commit also added the proper import for getMockMessage from @/__tests__/helpers, which aligns with the team guideline requiring email/account mock data to come from shared helpers.

Copy link
Owner Author

Choose a reason for hiding this comment

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

Addressed. I've replaced the inline 'createMockMessage' with the shared 'getMockMessage' helper and updated the calls to use flat parameters ('from', 'to', 'subject') as expected by the helper. Tests are now correctly using the intended test data.

Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

1 issue found across 3 files (changes from recent commits).

Prompt for AI agents (all issues)

Check if these issues are valid — if so, understand the root cause of each and fix them.


<file name="apps/web/app/api/clean/route.test.ts">

<violation number="1" location="apps/web/app/api/clean/route.test.ts:115">
P1: `getMockMessage` doesn&#39;t accept a `headers` object. It expects `from`, `to`, `subject` as flat parameters. These tests will use default values instead of the intended test data, causing tests to not validate what they should.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

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 (1)
apps/web/utils/calendar/providers/microsoft-events.ts (1)

120-137: Consider stricter validation for critical event fields.

The fallback values for missing critical fields could mask data quality issues:

  1. Lines 129-130: Using Date.now() as a fallback for missing start/end times creates events with incorrect timestamps. If the Microsoft API omits these fields, it indicates a serious data issue that should be surfaced rather than silently substituted.

  2. Line 122: Defaulting to an empty string for missing id could cause problems if IDs are used for deduplication, as keys, or for event matching.

🔎 Suggested approach: Add validation or logging

Consider one of these approaches:

Option 1: Throw errors for missing critical fields

 private parseEvent(event: MicrosoftEvent) {
+  if (!event.id || !event.start?.dateTime || !event.end?.dateTime) {
+    this.logger.error("Microsoft event missing critical fields", { event });
+    throw new Error("Microsoft event missing required fields");
+  }
+
   return {
-    id: event.id || "",
+    id: event.id,
     title: event.subject || "Untitled",
     description: event.bodyPreview || undefined,
     location: event.location?.displayName || undefined,
     eventUrl: event.webLink || undefined,
     videoConferenceLink:
       event.onlineMeeting?.joinUrl || event.onlineMeetingUrl || undefined,
-    startTime: new Date(event.start?.dateTime || Date.now()),
-    endTime: new Date(event.end?.dateTime || Date.now()),
+    startTime: new Date(event.start.dateTime),
+    endTime: new Date(event.end.dateTime),
     attendees:
       event.attendees?.map((attendee) => ({
         email: attendee.emailAddress?.address || "",
         name: attendee.emailAddress?.name ?? undefined,
       })) || [],
   };
 }

Option 2: Log warnings but keep defensive fallbacks

 private parseEvent(event: MicrosoftEvent) {
+  if (!event.id) {
+    this.logger.warn("Microsoft event missing id", { event });
+  }
+  if (!event.start?.dateTime || !event.end?.dateTime) {
+    this.logger.warn("Microsoft event missing date fields", { event });
+  }
+
   return {
     id: event.id || "",
     // ... rest unchanged
   };
 }
🧹 Nitpick comments (1)
apps/web/utils/user/validate.ts (1)

39-49: Consider consolidating or differentiating error messages for premium checks.

The function now performs two consecutive premium validations with identical error messages. Line 43 throws "Please upgrade for AI access" when isPremium fails, and line 49 throws the same message when hasAiAccess fails. This creates redundancy and may confuse debugging efforts.

Consider either:

  1. Consolidating into a single check if both validations serve the same purpose
  2. Using distinct error messages to clarify which validation failed (e.g., "Active subscription required for AI access" vs. "AI access tier required")
🔎 Option 1: Consolidate checks into single validation
- const isUserPremium = isPremium(
-   emailAccount.user.premium?.lemonSqueezyRenewsAt || null,
-   emailAccount.user.premium?.stripeSubscriptionStatus || null,
- );
- if (!isUserPremium) throw new SafeError("Please upgrade for AI access");
-
  const userHasAiAccess = hasAiAccess(
    emailAccount.user.premium?.tier || null,
    emailAccount.user.aiApiKey,
  );
  if (!userHasAiAccess) throw new SafeError("Please upgrade for AI access");

Option 2: Use distinct error messages

  const isUserPremium = isPremium(
    emailAccount.user.premium?.lemonSqueezyRenewsAt || null,
    emailAccount.user.premium?.stripeSubscriptionStatus || null,
  );
- if (!isUserPremium) throw new SafeError("Please upgrade for AI access");
+ if (!isUserPremium) throw new SafeError("Active subscription required for AI access");

  const userHasAiAccess = hasAiAccess(
    emailAccount.user.premium?.tier || null,
    emailAccount.user.aiApiKey,
  );
- if (!userHasAiAccess) throw new SafeError("Please upgrade for AI access");
+ if (!userHasAiAccess) throw new SafeError("AI tier or API key required for AI access");
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 345ea28 and b7679f1.

📒 Files selected for processing (10)
  • apps/web/__tests__/helpers.ts
  • apps/web/app/(app)/[emailAccountId]/calendars/page.tsx
  • apps/web/app/(landing)/login/LoginForm.tsx
  • apps/web/app/(landing)/login/page.tsx
  • apps/web/app/api/clean/route.test.ts
  • apps/web/app/api/clean/route.ts
  • apps/web/utils/calendar/providers/microsoft-events.ts
  • apps/web/utils/organizations/access.ts
  • apps/web/utils/path.ts
  • apps/web/utils/user/validate.ts
🧰 Additional context used
📓 Path-based instructions (33)
**/*.{ts,tsx}

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

**/*.{ts,tsx}: For API GET requests to server, use the swr package
Use result?.serverError with toastError from @/components/Toast for error handling in async operations

**/*.{ts,tsx}: Use wrapper functions for Gmail message operations (get, list, batch, etc.) from @/utils/gmail/message.ts instead of direct API calls
Use wrapper functions for Gmail thread operations from @/utils/gmail/thread.ts instead of direct API calls
Use wrapper functions for Gmail label operations from @/utils/gmail/label.ts instead of direct API calls

**/*.{ts,tsx}: For early access feature flags, create hooks using the naming convention use[FeatureName]Enabled that return a boolean from useFeatureFlagEnabled("flag-key")
For A/B test variant flags, create hooks using the naming convention use[FeatureName]Variant that define variant types, use useFeatureFlagVariantKey() with type casting, and provide a default "control" fallback
Use kebab-case for PostHog feature flag keys (e.g., inbox-cleaner, pricing-options-2)
Always define types for A/B test variant flags (e.g., type PricingVariant = "control" | "variant-a" | "variant-b") and provide type safety through type casting

**/*.{ts,tsx}: Don't use primitive type aliases or misleading types
Don't use empty type parameters in type aliases and interfaces
Don't use this and super in static contexts
Don't use any or unknown as type constraints
Don't use the TypeScript directive @ts-ignore
Don't use TypeScript enums
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 TypeScript namespaces
Don't use non-null assertions with the ! postfix operator
Don't use parameter properties in class constructors
Don't use user-defined types
Use as const instead of literal types and type annotations
Use either T[] or Array<T> consistently
Initialize each enum member value explicitly
Use export type for types
Use `impo...

Files:

  • apps/web/utils/user/validate.ts
  • apps/web/utils/organizations/access.ts
  • apps/web/app/(app)/[emailAccountId]/calendars/page.tsx
  • apps/web/__tests__/helpers.ts
  • apps/web/utils/path.ts
  • apps/web/app/api/clean/route.ts
  • apps/web/app/(landing)/login/LoginForm.tsx
  • apps/web/utils/calendar/providers/microsoft-events.ts
  • apps/web/app/(landing)/login/page.tsx
  • apps/web/app/api/clean/route.test.ts
**/*.{ts,tsx,js,jsx}

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

Always import Prisma enums from @/generated/prisma/enums instead of @/generated/prisma/client to avoid Next.js bundling errors in client components

Import Prisma using the project's centralized utility: import prisma from '@/utils/prisma'

Files:

  • apps/web/utils/user/validate.ts
  • apps/web/utils/organizations/access.ts
  • apps/web/app/(app)/[emailAccountId]/calendars/page.tsx
  • apps/web/__tests__/helpers.ts
  • apps/web/utils/path.ts
  • apps/web/app/api/clean/route.ts
  • apps/web/app/(landing)/login/LoginForm.tsx
  • apps/web/utils/calendar/providers/microsoft-events.ts
  • apps/web/app/(landing)/login/page.tsx
  • apps/web/app/api/clean/route.test.ts
apps/web/**/*.{ts,tsx}

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

Import specific lodash functions rather than entire lodash library to minimize bundle size (e.g., import groupBy from 'lodash/groupBy')

apps/web/**/*.{ts,tsx}: Use TypeScript with strict null checks
Do not export types/interfaces that are only used within the same file. Export later if needed

Files:

  • apps/web/utils/user/validate.ts
  • apps/web/utils/organizations/access.ts
  • apps/web/app/(app)/[emailAccountId]/calendars/page.tsx
  • apps/web/__tests__/helpers.ts
  • apps/web/utils/path.ts
  • apps/web/app/api/clean/route.ts
  • apps/web/app/(landing)/login/LoginForm.tsx
  • apps/web/utils/calendar/providers/microsoft-events.ts
  • apps/web/app/(landing)/login/page.tsx
  • apps/web/app/api/clean/route.test.ts
**/*.ts

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

**/*.ts: ALL database queries MUST be scoped to the authenticated user/account by including user/account filtering in WHERE clauses to prevent unauthorized data access
Always validate that resources belong to the authenticated user before performing operations, using ownership checks in WHERE clauses or relationships
Always validate all input parameters for type, format, and length before using them in database queries
Use SafeError for error responses to prevent information disclosure. Generic error messages should not reveal internal IDs, logic, or resource ownership details
Only return necessary fields in API responses using Prisma's select option. Never expose sensitive data such as password hashes, private keys, or system flags
Prevent Insecure Direct Object References (IDOR) by validating resource ownership before operations. All findUnique/findFirst calls MUST include ownership filters
Prevent mass assignment vulnerabilities by explicitly whitelisting allowed fields in update operations instead of accepting all user-provided data
Prevent privilege escalation by never allowing users to modify system fields, ownership fields, or admin-only attributes through user input
All findMany queries MUST be scoped to the user's data by including appropriate WHERE filters to prevent returning data from other users
Use Prisma relationships for access control by leveraging nested where clauses (e.g., emailAccount: { id: emailAccountId }) to validate ownership

Files:

  • apps/web/utils/user/validate.ts
  • apps/web/utils/organizations/access.ts
  • apps/web/__tests__/helpers.ts
  • apps/web/utils/path.ts
  • apps/web/app/api/clean/route.ts
  • apps/web/utils/calendar/providers/microsoft-events.ts
  • apps/web/app/api/clean/route.test.ts
**/*.{tsx,ts}

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

**/*.{tsx,ts}: Use Shadcn UI and Tailwind for components and styling
Use next/image package for images
For API GET requests to server, use the swr package with hooks like useSWR to fetch data
For text inputs, use the Input component with registerProps for form integration and error handling

Files:

  • apps/web/utils/user/validate.ts
  • apps/web/utils/organizations/access.ts
  • apps/web/app/(app)/[emailAccountId]/calendars/page.tsx
  • apps/web/__tests__/helpers.ts
  • apps/web/utils/path.ts
  • apps/web/app/api/clean/route.ts
  • apps/web/app/(landing)/login/LoginForm.tsx
  • apps/web/utils/calendar/providers/microsoft-events.ts
  • apps/web/app/(landing)/login/page.tsx
  • apps/web/app/api/clean/route.test.ts
**/*.{tsx,ts,css}

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

Implement responsive design with Tailwind CSS using a mobile-first approach

Files:

  • apps/web/utils/user/validate.ts
  • apps/web/utils/organizations/access.ts
  • apps/web/app/(app)/[emailAccountId]/calendars/page.tsx
  • apps/web/__tests__/helpers.ts
  • apps/web/utils/path.ts
  • apps/web/app/api/clean/route.ts
  • apps/web/app/(landing)/login/LoginForm.tsx
  • apps/web/utils/calendar/providers/microsoft-events.ts
  • apps/web/app/(landing)/login/page.tsx
  • apps/web/app/api/clean/route.test.ts
**/*.{js,jsx,ts,tsx}

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

**/*.{js,jsx,ts,tsx}: 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
Don't use distracting elements like <marquee> or <blink>
Only use the scope prop on <th> 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
Use semantic elements instead of role attributes in JSX
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 AR...

Files:

  • apps/web/utils/user/validate.ts
  • apps/web/utils/organizations/access.ts
  • apps/web/app/(app)/[emailAccountId]/calendars/page.tsx
  • apps/web/__tests__/helpers.ts
  • apps/web/utils/path.ts
  • apps/web/app/api/clean/route.ts
  • apps/web/app/(landing)/login/LoginForm.tsx
  • apps/web/utils/calendar/providers/microsoft-events.ts
  • apps/web/app/(landing)/login/page.tsx
  • apps/web/app/api/clean/route.test.ts
!(pages/_document).{jsx,tsx}

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

Don't use the next/head module in pages/_document.js on Next.js projects

Files:

  • apps/web/utils/user/validate.ts
  • apps/web/utils/organizations/access.ts
  • apps/web/app/(app)/[emailAccountId]/calendars/page.tsx
  • apps/web/__tests__/helpers.ts
  • apps/web/utils/path.ts
  • apps/web/app/api/clean/route.ts
  • apps/web/app/(landing)/login/LoginForm.tsx
  • apps/web/utils/calendar/providers/microsoft-events.ts
  • apps/web/app/(landing)/login/page.tsx
  • apps/web/app/api/clean/route.test.ts
**/*.{js,ts,jsx,tsx}

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

**/*.{js,ts,jsx,tsx}: Use lodash utilities for common operations (arrays, objects, strings)
Import specific lodash functions to minimize bundle size (e.g., import groupBy from 'lodash/groupBy')

Files:

  • apps/web/utils/user/validate.ts
  • apps/web/utils/organizations/access.ts
  • apps/web/app/(app)/[emailAccountId]/calendars/page.tsx
  • apps/web/__tests__/helpers.ts
  • apps/web/utils/path.ts
  • apps/web/app/api/clean/route.ts
  • apps/web/app/(landing)/login/LoginForm.tsx
  • apps/web/utils/calendar/providers/microsoft-events.ts
  • apps/web/app/(landing)/login/page.tsx
  • apps/web/app/api/clean/route.test.ts
**/{utils,helpers,lib}/**/*.{ts,tsx}

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

Logger should be passed as a parameter to helper functions instead of creating their own logger instances

Files:

  • apps/web/utils/user/validate.ts
  • apps/web/utils/organizations/access.ts
  • apps/web/utils/path.ts
  • apps/web/utils/calendar/providers/microsoft-events.ts
apps/web/**/*.{ts,tsx,js,jsx}

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

apps/web/**/*.{ts,tsx,js,jsx}: Use @/ path aliases for imports from project root
Prefer self-documenting code over comments; use descriptive variable and function names instead of explaining intent with comments
Add helper functions to the bottom of files, not the top
All imports go at the top of files, no mid-file dynamic imports

Files:

  • apps/web/utils/user/validate.ts
  • apps/web/utils/organizations/access.ts
  • apps/web/app/(app)/[emailAccountId]/calendars/page.tsx
  • apps/web/__tests__/helpers.ts
  • apps/web/utils/path.ts
  • apps/web/app/api/clean/route.ts
  • apps/web/app/(landing)/login/LoginForm.tsx
  • apps/web/utils/calendar/providers/microsoft-events.ts
  • apps/web/app/(landing)/login/page.tsx
  • apps/web/app/api/clean/route.test.ts
apps/web/**/*.{ts,tsx,js,jsx,json,css}

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

Format code with Prettier

Files:

  • apps/web/utils/user/validate.ts
  • apps/web/utils/organizations/access.ts
  • apps/web/app/(app)/[emailAccountId]/calendars/page.tsx
  • apps/web/__tests__/helpers.ts
  • apps/web/utils/path.ts
  • apps/web/app/api/clean/route.ts
  • apps/web/app/(landing)/login/LoginForm.tsx
  • apps/web/utils/calendar/providers/microsoft-events.ts
  • apps/web/app/(landing)/login/page.tsx
  • apps/web/app/api/clean/route.test.ts
apps/web/**/*.{example,ts,json}

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

Add environment variables to .env.example, env.ts, and turbo.json

Files:

  • apps/web/utils/user/validate.ts
  • apps/web/utils/organizations/access.ts
  • apps/web/__tests__/helpers.ts
  • apps/web/utils/path.ts
  • apps/web/app/api/clean/route.ts
  • apps/web/utils/calendar/providers/microsoft-events.ts
  • apps/web/app/api/clean/route.test.ts
apps/web/app/(app)/**/*.{ts,tsx}

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

apps/web/app/(app)/**/*.{ts,tsx}: Components for the page are either put in page.tsx, or in the apps/web/app/(app)/PAGE_NAME folder
If we're in a deeply nested component we will use swr to fetch via API
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)/[emailAccountId]/calendars/page.tsx
**/*.tsx

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

**/*.tsx: Use the LoadingContent component to handle loading states instead of manual loading state management
For text areas, use the Input component with type='text', autosizeTextarea prop set to true, and registerProps for form integration

Files:

  • apps/web/app/(app)/[emailAccountId]/calendars/page.tsx
  • apps/web/app/(landing)/login/LoginForm.tsx
  • apps/web/app/(landing)/login/page.tsx
**/*.{jsx,tsx}

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

**/*.{jsx,tsx}: Don't use unnecessary fragments
Don't pass children as props
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 forget key props in iterators and collection literals
Don't define React components inside other components
Don't use event handlers on non-interactive elements
Don't assign to React component props
Don't use both children and dangerouslySetInnerHTML props on the same element
Don't use dangerous JSX props
Don't use Array index in keys
Don't insert comments as text nodes
Don't assign JSX properties multiple times
Don't add extra closing tags for components without children
Use <>...</> instead of <Fragment>...</Fragment>
Watch out for possible "wrong" semicolons inside JSX elements
Make sure void (self-closing) elements don't have children
Don't use target="_blank" without rel="noopener"
Don't use <img> elements in Next.js projects
Don't use <head> elements in Next.js projects

Files:

  • apps/web/app/(app)/[emailAccountId]/calendars/page.tsx
  • apps/web/app/(landing)/login/LoginForm.tsx
  • apps/web/app/(landing)/login/page.tsx
apps/web/app/**/*.{ts,tsx}

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

Follow NextJS app router structure with (app) directory

Files:

  • apps/web/app/(app)/[emailAccountId]/calendars/page.tsx
  • apps/web/app/api/clean/route.ts
  • apps/web/app/(landing)/login/LoginForm.tsx
  • apps/web/app/(landing)/login/page.tsx
  • apps/web/app/api/clean/route.test.ts
apps/web/**/*.{tsx,jsx}

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

apps/web/**/*.{tsx,jsx}: Follow tailwindcss patterns with prettier-plugin-tailwindcss for class sorting
Prefer functional components with hooks in React
Use shadcn/ui components when available
Ensure responsive design with mobile-first approach in components
Follow consistent naming conventions using PascalCase for components
Use LoadingContent component for async data with loading and error states
Use React Hook Form with Zod validation for form handling
Use result?.serverError with toastError and toastSuccess for error handling in forms

Files:

  • apps/web/app/(app)/[emailAccountId]/calendars/page.tsx
  • apps/web/app/(landing)/login/LoginForm.tsx
  • apps/web/app/(landing)/login/page.tsx
apps/web/{utils/ai,utils/llms,__tests__}/**/*.ts

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

LLM-related code must be organized in specific directories: apps/web/utils/ai/ for main implementations, apps/web/utils/llms/ for core utilities and configurations, and apps/web/__tests__/ for LLM-specific tests

Files:

  • apps/web/__tests__/helpers.ts
**/{scripts,tests,__tests__}/**/*.{ts,tsx}

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

Use createScopedLogger only for code that doesn't run within a middleware chain, such as standalone scripts or tests

Files:

  • apps/web/__tests__/helpers.ts
**/__tests__/**/*.{ts,tsx}

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

Place AI tests in the __tests__ directory and do not run them by default as they use a real LLM

Files:

  • apps/web/__tests__/helpers.ts
apps/web/app/api/**/route.ts

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

apps/web/app/api/**/route.ts: Create GET API routes using withAuth or withEmailAccount middleware in apps/web/app/api/*/route.ts, export response types as GetExampleResponse type alias for client-side type safety
Always export response types from GET routes as Get[Feature]Response using type inference from the data fetching function for type-safe client consumption
Do NOT use POST API routes for mutations - always use server actions with next-safe-action instead

Files:

  • apps/web/app/api/clean/route.ts
**/app/**/route.ts

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

**/app/**/route.ts: Always wrap GET API route handlers with withAuth or withEmailAccount middleware for consistent error handling and authentication in Next.js App Router
Infer and export response type for GET API routes using Awaited<ReturnType<typeof functionName>> pattern in Next.js
Use Prisma for database queries in GET API routes
Return responses using NextResponse.json() in GET API routes
Do not use try/catch blocks in GET API route handlers when using withAuth or withEmailAccount middleware, as the middleware handles error handling

Files:

  • apps/web/app/api/clean/route.ts
apps/web/app/**/[!.]*/route.{ts,tsx}

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

Use kebab-case for route directories in Next.js App Router (e.g., api/hello-world/route)

Files:

  • apps/web/app/api/clean/route.ts
apps/web/app/api/**/*.{ts,tsx}

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

apps/web/app/api/**/*.{ts,tsx}: API routes must use withAuth, withEmailAccount, or withError middleware for authentication
All database queries must include user scoping with emailAccountId or userId filtering in WHERE clauses
Request parameters must be validated before use; avoid direct parameter usage without type checking
Use generic error messages instead of revealing internal details; throw SafeError instead of exposing user IDs, resource IDs, or system information
API routes should only return necessary fields using select in database queries to prevent unintended information disclosure
Cron endpoints must use hasCronSecret or hasPostCronSecret to validate cron requests and prevent unauthorized access
Request bodies should use Zod schemas for validation to ensure type safety and prevent injection attacks

Files:

  • apps/web/app/api/clean/route.ts
  • apps/web/app/api/clean/route.test.ts
**/app/api/**/*.ts

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

**/app/api/**/*.ts: ALL API routes that handle user data MUST use appropriate middleware: use withEmailAccount for email-scoped operations, use withAuth for user-scoped operations, or use withError with proper validation for public/custom auth endpoints
Use withEmailAccount middleware for operations scoped to a specific email account, including reading/writing emails, rules, schedules, or any operation using emailAccountId
Use withAuth middleware for user-level operations such as user settings, API keys, and referrals that use only userId
Use withError middleware only for public endpoints, custom authentication logic, or cron endpoints. For cron endpoints, MUST use hasCronSecret() or hasPostCronSecret() validation
Cron endpoints without proper authentication can be triggered by anyone. CRITICAL: All cron endpoints MUST validate cron secret using hasCronSecret(request) or hasPostCronSecret(request) and capture unauthorized attempts with captureException()
Always validate request bodies using Zod schemas to ensure type safety and prevent invalid data from reaching database operations
Maintain consistent error response format across all API routes to avoid information disclosure while providing meaningful error feedback

Files:

  • apps/web/app/api/clean/route.ts
  • apps/web/app/api/clean/route.test.ts
**/{app,pages}/**/{route,+page}.{ts,tsx}

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

**/{app,pages}/**/{route,+page}.{ts,tsx}: Use middleware wrappers (withError, withAuth, withEmailAccount, withEmailProvider) that automatically create loggers with request context in API routes
Enrich logger context within route handlers using logger.with() to add request-specific fields like messageId

Files:

  • apps/web/app/api/clean/route.ts
apps/web/app/api/**/*.ts

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

apps/web/app/api/**/*.ts: Create GET API routes wrapped with withAuth or withEmailAccount middleware for fetching data
Export response types from GET API routes using export type GetXResponse = Awaited<ReturnType<typeof getData>>

Files:

  • apps/web/app/api/clean/route.ts
  • apps/web/app/api/clean/route.test.ts
**/*Form.{ts,tsx}

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

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

Files:

  • apps/web/app/(landing)/login/LoginForm.tsx
**/*.{test,spec}.{js,jsx,ts,tsx}

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

**/*.{test,spec}.{js,jsx,ts,tsx}: Don't nest describe() blocks too deeply in test files
Don't use callbacks in asynchronous tests and hooks
Don't have duplicate hooks in describe blocks
Don't use export or module.exports in test files
Don't use focused tests
Make sure the assertion function, like expect, is placed inside an it() function call
Don't use disabled tests

Files:

  • apps/web/app/api/clean/route.test.ts
apps/web/**/*.test.{ts,tsx}

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

Co-locate test files next to source files (e.g., utils/example.test.ts). Only E2E and AI tests go in __tests__/

Files:

  • apps/web/app/api/clean/route.test.ts
**/*.test.{js,jsx,ts,tsx}

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

Co-locate test files next to source files (e.g., utils/example.test.ts). Only E2E and AI tests go in __tests__/

Files:

  • apps/web/app/api/clean/route.test.ts
**/*.test.{ts,tsx}

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

**/*.test.{ts,tsx}: Use vitest as the testing framework
Colocate test files next to the tested file with .test.ts or .test.tsx naming convention (e.g., dir/format.ts and dir/format.test.ts)
Mock server-only using vi.mock("server-only", () => ({}))
Mock Prisma using vi.mock("@/utils/prisma") and the provided mock from @/utils/__mocks__/prisma
Use test helper functions getEmail, getEmailAccount, and getRule from @/__tests__/helpers for creating mock data
Clear all mocks between tests using beforeEach(() => { vi.clearAllMocks(); })
Use descriptive test names that clearly indicate what is being tested
Do not mock the Logger in tests

Files:

  • apps/web/app/api/clean/route.test.ts
🧠 Learnings (45)
📚 Learning: 2025-11-25T14:38:07.606Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-11-25T14:38:07.606Z
Learning: Applies to apps/web/utils/ai/**/*.ts : LLM feature functions must import from `zod` for schema validation, use `createScopedLogger` from `@/utils/logger`, `chatCompletionObject` and `createGenerateObject` from `@/utils/llms`, and import `EmailAccountWithAI` type from `@/utils/llms/types`

Applied to files:

  • apps/web/utils/user/validate.ts
  • apps/web/app/api/clean/route.test.ts
📚 Learning: 2025-11-25T14:38:07.606Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-11-25T14:38:07.606Z
Learning: Applies to apps/web/utils/ai/**/*.ts : Implement early returns for invalid LLM inputs, use proper error types and logging, implement fallbacks for AI failures, and add retry logic for transient failures using `withRetry`

Applied to files:

  • apps/web/utils/user/validate.ts
📚 Learning: 2025-11-25T14:39:23.326Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:23.326Z
Learning: Applies to app/api/**/*.ts : All input parameters must be validated - check for presence, type, and format before use; use Zod schemas to validate request bodies with type guards and constraints

Applied to files:

  • apps/web/utils/user/validate.ts
📚 Learning: 2025-11-25T14:39:23.326Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:23.326Z
Learning: Applies to **/*.ts : Always validate that resources belong to the authenticated user before any operation - use ownership checks in queries (e.g., `emailAccount: { id: emailAccountId }`) and throw `SafeError` if validation fails

Applied to files:

  • apps/web/utils/user/validate.ts
  • apps/web/utils/organizations/access.ts
📚 Learning: 2025-11-25T14:39:23.326Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:23.326Z
Learning: Applies to app/api/**/*.ts : Use `SafeError` for error responses to prevent information disclosure - provide generic messages (e.g., 'Rule not found' not 'Rule {id} does not exist for user {userId}') without revealing internal IDs or ownership details

Applied to files:

  • apps/web/utils/user/validate.ts
  • apps/web/utils/organizations/access.ts
📚 Learning: 2025-11-25T14:39:08.150Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security-audit.mdc:0-0
Timestamp: 2025-11-25T14:39:08.150Z
Learning: Applies to apps/web/app/api/**/*.{ts,tsx} : Use generic error messages instead of revealing internal details; throw `SafeError` instead of exposing user IDs, resource IDs, or system information

Applied to files:

  • apps/web/utils/user/validate.ts
📚 Learning: 2025-11-25T14:39:23.326Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:23.326Z
Learning: Applies to app/api/**/*.ts : Use `withError` middleware only for public endpoints or custom authentication logic - cron endpoints MUST validate with `hasCronSecret(request)` or `hasPostCronSecret(request)` and capture unauthorized attempts with `captureException`

Applied to files:

  • apps/web/utils/user/validate.ts
📚 Learning: 2025-11-25T14:39:27.909Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:27.909Z
Learning: Applies to **/app/api/**/*.ts : Use `withError` middleware only for public endpoints, custom authentication logic, or cron endpoints. For cron endpoints, MUST use `hasCronSecret()` or `hasPostCronSecret()` validation

Applied to files:

  • apps/web/utils/user/validate.ts
📚 Learning: 2025-11-25T14:39:23.326Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:23.326Z
Learning: Applies to app/api/**/*.ts : Use `withEmailAccount` middleware for operations scoped to a specific email account (reading/writing emails, rules, schedules, etc.) - provides `emailAccountId`, `userId`, and `email` in `request.auth`

Applied to files:

  • apps/web/utils/user/validate.ts
  • apps/web/utils/organizations/access.ts
📚 Learning: 2025-11-25T14:39:08.150Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security-audit.mdc:0-0
Timestamp: 2025-11-25T14:39:08.150Z
Learning: Applies to apps/web/app/api/**/*.{ts,tsx} : All database queries must include user scoping with `emailAccountId` or `userId` filtering in WHERE clauses

Applied to files:

  • apps/web/utils/organizations/access.ts
📚 Learning: 2025-11-25T14:39:23.326Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:23.326Z
Learning: Applies to **/*.ts : Prevent Insecure Direct Object References (IDOR) by validating resource ownership in all queries - always include ownership filters (e.g., `emailAccount: { id: emailAccountId }`) when accessing user-specific resources

Applied to files:

  • apps/web/utils/organizations/access.ts
📚 Learning: 2025-11-25T14:39:27.909Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:27.909Z
Learning: Applies to **/app/api/**/*.ts : Use `withEmailAccount` middleware for operations scoped to a specific email account, including reading/writing emails, rules, schedules, or any operation using `emailAccountId`

Applied to files:

  • apps/web/utils/organizations/access.ts
📚 Learning: 2025-11-25T14:39:49.448Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/server-actions.mdc:0-0
Timestamp: 2025-11-25T14:39:49.448Z
Learning: Applies to apps/web/utils/actions/*.ts : Use `adminActionClient` for actions restricted to admin users

Applied to files:

  • apps/web/utils/organizations/access.ts
📚 Learning: 2025-12-21T12:21:37.794Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-12-21T12:21:37.794Z
Learning: Applies to apps/web/**/*.{ts,tsx,js,jsx} : Use `@/` path aliases for imports from project root

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/calendars/page.tsx
  • apps/web/utils/path.ts
  • apps/web/app/(landing)/login/page.tsx
📚 Learning: 2025-11-25T14:37:22.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Applies to **/{pages,routes,components}/**/*.{ts,tsx} : Never call Gmail API directly from routes or components - always use wrapper functions from the utils folder

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/calendars/page.tsx
📚 Learning: 2025-11-25T14:38:23.265Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/page-structure.mdc:0-0
Timestamp: 2025-11-25T14:38:23.265Z
Learning: Applies to apps/web/app/(app)/*/page.tsx : Create new pages at `apps/web/app/(app)/PAGE_NAME/page.tsx`

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/calendars/page.tsx
  • apps/web/app/(landing)/login/page.tsx
📚 Learning: 2025-12-17T02:38:41.499Z
Learnt from: elie222
Repo: elie222/inbox-zero PR: 1103
File: apps/web/utils/actions/rule.ts:447-457
Timestamp: 2025-12-17T02:38:41.499Z
Learning: In apps/web/utils/actions/rule.ts, revalidatePath is not needed for toggleAllRulesAction because rules data is fetched client-side using SWR, not server-side. Server-side cache revalidation is only needed when using Next.js server components or server-side data fetching.

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/calendars/page.tsx
  • apps/web/app/(landing)/login/page.tsx
📚 Learning: 2025-12-21T12:21:37.794Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-12-21T12:21:37.794Z
Learning: Applies to apps/web/utils/actions/**/*.ts : Use `revalidatePath` in server actions for cache invalidation after mutations

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/calendars/page.tsx
📚 Learning: 2025-11-25T14:38:18.874Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/page-structure.mdc:0-0
Timestamp: 2025-11-25T14:38:18.874Z
Learning: Applies to apps/web/app/(app)/**/page.tsx : Create new pages at `apps/web/app/(app)/PAGE_NAME/page.tsx`

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/calendars/page.tsx
  • apps/web/app/(landing)/login/page.tsx
📚 Learning: 2025-11-25T14:38:23.265Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/page-structure.mdc:0-0
Timestamp: 2025-11-25T14:38:23.265Z
Learning: Applies to apps/web/app/(app)/**/*.{ts,tsx} : Components for the page are either put in `page.tsx`, or in the `apps/web/app/(app)/PAGE_NAME` folder

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/calendars/page.tsx
  • apps/web/app/(landing)/login/page.tsx
📚 Learning: 2025-11-25T14:38:18.874Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/page-structure.mdc:0-0
Timestamp: 2025-11-25T14:38:18.874Z
Learning: Applies to apps/web/app/(app)/**/*.tsx : Components for pages are either put in `page.tsx`, or in the `apps/web/app/(app)/PAGE_NAME` folder

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/calendars/page.tsx
  • apps/web/app/(landing)/login/page.tsx
📚 Learning: 2025-11-25T14:37:56.430Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-11-25T14:37:56.430Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Prefer using existing helpers from `@/__tests__/helpers.ts` (`getEmailAccount`, `getEmail`, `getRule`, `getMockMessage`, `getMockExecutedRule`) instead of creating custom test data helpers

Applied to files:

  • apps/web/__tests__/helpers.ts
  • apps/web/app/api/clean/route.test.ts
📚 Learning: 2026-01-01T10:42:29.775Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2026-01-01T10:42:29.775Z
Learning: Applies to **/*.test.{ts,tsx} : Use test helper functions `getEmail`, `getEmailAccount`, and `getRule` from `@/__tests__/helpers` for creating mock data

Applied to files:

  • apps/web/__tests__/helpers.ts
  • apps/web/app/api/clean/route.test.ts
📚 Learning: 2025-11-25T14:37:22.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Applies to **/*.{ts,tsx} : Use wrapper functions for Gmail label operations from @/utils/gmail/label.ts instead of direct API calls

Applied to files:

  • apps/web/__tests__/helpers.ts
  • apps/web/app/api/clean/route.test.ts
📚 Learning: 2025-11-25T14:37:22.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Applies to **/*.{ts,tsx} : Use wrapper functions for Gmail message operations (get, list, batch, etc.) from @/utils/gmail/message.ts instead of direct API calls

Applied to files:

  • apps/web/__tests__/helpers.ts
  • apps/web/app/api/clean/route.test.ts
📚 Learning: 2025-11-25T14:37:22.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Applies to **/*.{ts,tsx} : Use wrapper functions for Gmail thread operations from @/utils/gmail/thread.ts instead of direct API calls

Applied to files:

  • apps/web/__tests__/helpers.ts
  • apps/web/app/api/clean/route.ts
  • apps/web/app/api/clean/route.test.ts
📚 Learning: 2025-07-08T13:14:07.449Z
Learnt from: elie222
Repo: elie222/inbox-zero PR: 537
File: apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx:30-34
Timestamp: 2025-07-08T13:14:07.449Z
Learning: The clean onboarding page in apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx is intentionally Gmail-specific and should show an error for non-Google email accounts rather than attempting to support multiple providers.

Applied to files:

  • apps/web/app/(landing)/login/LoginForm.tsx
📚 Learning: 2025-11-25T14:36:36.276Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/data-fetching.mdc:0-0
Timestamp: 2025-11-25T14:36:36.276Z
Learning: Applies to **/*.{ts,tsx} : Import error and success toast utilities from '@/components/Toast' for displaying notifications

Applied to files:

  • apps/web/app/(landing)/login/LoginForm.tsx
📚 Learning: 2025-12-21T12:21:37.794Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-12-21T12:21:37.794Z
Learning: Applies to apps/web/app/**/*.{ts,tsx} : Follow NextJS app router structure with (app) directory

Applied to files:

  • apps/web/app/(landing)/login/page.tsx
📚 Learning: 2025-11-25T14:42:08.869Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/ultracite.mdc:0-0
Timestamp: 2025-11-25T14:42:08.869Z
Learning: Applies to pages/_document.{jsx,tsx} : Don't import next/document outside of pages/_document.jsx in Next.js projects

Applied to files:

  • apps/web/app/(landing)/login/page.tsx
📚 Learning: 2025-11-25T14:38:56.992Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/project-structure.mdc:0-0
Timestamp: 2025-11-25T14:38:56.992Z
Learning: Applies to apps/web/app/(app)/*/page.tsx : Create new pages at `apps/web/app/(app)/PAGE_NAME/page.tsx` with components either colocated in the same folder or in `page.tsx`

Applied to files:

  • apps/web/app/(landing)/login/page.tsx
📚 Learning: 2025-11-25T14:38:56.992Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/project-structure.mdc:0-0
Timestamp: 2025-11-25T14:38:56.992Z
Learning: Applies to apps/web/app/**/[!.]*/route.{ts,tsx} : Use kebab-case for route directories in Next.js App Router (e.g., `api/hello-world/route`)

Applied to files:

  • apps/web/app/(landing)/login/page.tsx
📚 Learning: 2025-08-10T22:03:30.507Z
Learnt from: elie222
Repo: elie222/inbox-zero PR: 667
File: apps/web/app/(app)/[emailAccountId]/onboarding/page.tsx:18-25
Timestamp: 2025-08-10T22:03:30.507Z
Learning: In Next.js 15, both `params` and `searchParams` passed to page components in the App Router are Promises that need to be awaited. They should be typed as `Promise<{...}>` and accessed using `await` in server components or React's `use()` hook in client components. This is different from Next.js 14 where they were plain objects.

Applied to files:

  • apps/web/app/(landing)/login/page.tsx
📚 Learning: 2025-06-05T09:49:12.168Z
Learnt from: elie222
Repo: elie222/inbox-zero PR: 485
File: apps/web/app/(landing)/login/page.tsx:41-43
Timestamp: 2025-06-05T09:49:12.168Z
Learning: In Next.js App Router, components that use the `useSearchParams` hook require a Suspense boundary to handle the asynchronous nature of search parameter access. The Suspense wrapper is necessary and should not be removed when a component uses useSearchParams.

Applied to files:

  • apps/web/app/(landing)/login/page.tsx
📚 Learning: 2026-01-01T10:42:29.775Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2026-01-01T10:42:29.775Z
Learning: Applies to **/*.test.{ts,tsx} : Use descriptive test names that clearly indicate what is being tested

Applied to files:

  • apps/web/app/api/clean/route.test.ts
📚 Learning: 2025-11-25T14:37:56.430Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-11-25T14:37:56.430Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Use `describe.runIf(isAiTest)` with environment variable `RUN_AI_TESTS === "true"` to conditionally run LLM tests

Applied to files:

  • apps/web/app/api/clean/route.test.ts
📚 Learning: 2025-12-21T12:21:37.794Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-12-21T12:21:37.794Z
Learning: Applies to apps/web/**/*.test.{ts,tsx} : Co-locate test files next to source files (e.g., `utils/example.test.ts`). Only E2E and AI tests go in `__tests__/`

Applied to files:

  • apps/web/app/api/clean/route.test.ts
📚 Learning: 2026-01-01T10:42:29.775Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2026-01-01T10:42:29.775Z
Learning: Applies to **/__tests__/**/*.{ts,tsx} : Place AI tests in the `__tests__` directory and do not run them by default as they use a real LLM

Applied to files:

  • apps/web/app/api/clean/route.test.ts
📚 Learning: 2025-11-25T14:37:56.430Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-11-25T14:37:56.430Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Place all LLM-related tests in `apps/web/__tests__/` directory

Applied to files:

  • apps/web/app/api/clean/route.test.ts
📚 Learning: 2025-11-25T14:39:23.326Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:23.326Z
Learning: Applies to **/*.test.ts : Include security tests in test suites to verify: authentication is required, IDOR protection works (other users cannot access resources), parameter validation rejects invalid inputs, and error messages don't leak information

Applied to files:

  • apps/web/app/api/clean/route.test.ts
📚 Learning: 2025-11-25T14:37:56.430Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-11-25T14:37:56.430Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Use `console.debug()` for outputting generated LLM content in tests, e.g., `console.debug("Generated content:\n", result.content);`

Applied to files:

  • apps/web/app/api/clean/route.test.ts
📚 Learning: 2025-11-25T14:38:07.606Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-11-25T14:38:07.606Z
Learning: Applies to apps/web/utils/ai/**/*.ts : LLM feature functions must follow a standard structure: accept options with `inputData` and `emailAccount` parameters, implement input validation with early returns, define separate system and user prompts, create a Zod schema for response validation, and use `createGenerateObject` to execute the LLM call

Applied to files:

  • apps/web/app/api/clean/route.test.ts
📚 Learning: 2025-11-25T14:38:07.606Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-11-25T14:38:07.606Z
Learning: Applies to apps/web/utils/ai/**/*.ts : User prompts must contain the actual data and context, and should be kept separate from system prompts

Applied to files:

  • apps/web/app/api/clean/route.test.ts
📚 Learning: 2025-11-25T14:37:22.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Applies to apps/web/utils/gmail/**/*.{ts,tsx} : Always use wrapper functions from @/utils/gmail/ for Gmail API operations instead of direct provider API calls

Applied to files:

  • apps/web/app/api/clean/route.test.ts
📚 Learning: 2025-11-25T14:38:07.606Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-11-25T14:38:07.606Z
Learning: Applies to apps/web/{utils/ai,utils/llms,__tests__}/**/*.ts : LLM-related code must be organized in specific directories: `apps/web/utils/ai/` for main implementations, `apps/web/utils/llms/` for core utilities and configurations, and `apps/web/__tests__/` for LLM-specific tests

Applied to files:

  • apps/web/app/api/clean/route.test.ts
🧬 Code graph analysis (5)
apps/web/utils/user/validate.ts (2)
apps/web/utils/premium/index.ts (1)
  • isPremium (16-26)
apps/web/utils/error.ts (1)
  • SafeError (87-97)
apps/web/utils/organizations/access.ts (2)
apps/web/utils/organizations/roles.ts (1)
  • ADMIN_ROLES (1-1)
apps/web/utils/error.ts (1)
  • SafeError (87-97)
apps/web/app/(app)/[emailAccountId]/calendars/page.tsx (2)
apps/web/utils/calendar/constants.ts (1)
  • CALENDAR_ONBOARDING_RETURN_COOKIE (2-2)
apps/web/utils/path.ts (1)
  • isInternalPath (6-11)
apps/web/app/(landing)/login/LoginForm.tsx (2)
apps/web/utils/path.ts (1)
  • isInternalPath (6-11)
apps/web/utils/config.ts (1)
  • WELCOME_PATH (24-24)
apps/web/app/(landing)/login/page.tsx (1)
apps/web/utils/path.ts (1)
  • isInternalPath (6-11)
⏰ 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). (4)
  • GitHub Check: Socket Security: Pull Request Alerts
  • GitHub Check: cubic · AI code reviewer
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Macroscope - Correctness Check
🔇 Additional comments (13)
apps/web/utils/calendar/providers/microsoft-events.ts (3)

16-29: LGTM! Well-structured type definition.

The MicrosoftEvent type comprehensively models the Microsoft Graph API response with appropriate optional fields.


63-86: Correct use of calendarView endpoint for overlap filtering.

The switch from /me/calendar/events to /me/calendar/calendarView with startDateTime/endDateTime query parameters correctly addresses overlap-based event retrieval. The approach of fetching maxResults * 3 events before filtering by attendee is appropriate given API limitations.


100-117: LGTM! Sensible default for time range.

The 30-day default for effectiveTimeMax when timeMax is not provided is reasonable and appropriately documented. The calendarView endpoint requires both start and end times, so this default is necessary.

apps/web/utils/organizations/access.ts (1)

64-77: LGTM! Excellent refactoring to database-level filtering.

This change improves both security and performance by:

  • Moving admin role validation from application logic to the database query (line 68)
  • Eliminating a separate role check step
  • Providing a unified error message that doesn't leak membership information
  • Making the function consistent with getMemberEmailAccount and getCallerEmailAccount which already use this pattern

The consolidated error message appropriately prevents information disclosure about organization membership.

apps/web/app/(app)/[emailAccountId]/calendars/page.tsx (1)

9-19: LGTM! Improved security with centralized path validation.

The change replaces inline path validation with the isInternalPath utility, which provides enhanced protection against open redirect attacks by also checking for backslash-prefixed paths (/\\) that could bypass the original validation. This centralizes the validation logic and makes it consistent with other redirect points in the application.

apps/web/app/(landing)/login/page.tsx (1)

26-30: LGTM! Critical security fix for open redirect vulnerability.

This change prevents open redirect attacks in the login flow by validating that the next parameter points to an internal path before redirecting. Previously, an attacker could craft a malicious URL like /login?next=https://evil.com to redirect users to an external site after authentication.

The fallback to WELCOME_PATH ensures users are redirected to a safe location when the next parameter is missing or external.

apps/web/app/(landing)/login/LoginForm.tsx (2)

29-37: LGTM! Critical security fix for OAuth callback redirect vulnerability.

This change prevents open redirect attacks in the OAuth callback flow by validating that the next parameter is an internal path before using it as the callbackURL. Previously, an attacker could exploit OAuth flows with a malicious URL like /login?next=https://evil.com, causing the user to be redirected to an external site after authentication.

This is particularly important for OAuth callbacks because:

  • Users trust redirects following legitimate OAuth flows
  • Session tokens could be exposed to external sites through referrer headers
  • The vulnerability affects both authentication providers consistently

49-57: LGTM! Consistent security fix for Microsoft OAuth flow.

The Microsoft sign-in handler applies the same open redirect protection as the Google sign-in handler, ensuring consistent security across all OAuth providers.

apps/web/utils/path.ts (1)

6-11: LGTM - Security fix correctly implemented.

The function properly validates internal paths by rejecting both protocol-relative URLs (//) and the backslash bypass variant (/\). The null/undefined check and single-slash requirement ensure only safe relative paths are accepted.

apps/web/app/api/clean/route.ts (2)

48-48: LGTM - Export enables unit testing.

Exporting cleanThread allows the new test suite to validate the thread evaluation logic, improving test coverage for this critical AI cleaning flow.


164-174: LGTM - Correct fix for thread evaluation logic.

Removing the early break after detecting a maybe-receipt is the correct behavior. The function now continues evaluating all messages in the thread for skip conditions (starred, sent, attachments) before deciding whether to invoke the LLM. This prevents incorrectly archiving receipts that should be skipped due to other criteria. The new test suite validates this behavior comprehensively.

apps/web/__tests__/helpers.ts (1)

139-183: LGTM - Test helper enhancement.

Adding optional labelIds and attachments parameters to getMockMessage enables more realistic test scenarios while maintaining backward compatibility with sensible defaults. This supports the new cleanThread test cases that validate label-based and attachment-based skip conditions.

apps/web/app/api/clean/route.test.ts (1)

113-264: Incorrect usage of getMockMessage helper.

All test cases pass a headers object to getMockMessage, but the helper function doesn't accept a headers parameter. According to the helper signature in apps/web/__tests__/helpers.ts, it expects flat parameters (from, to, subject) not a nested headers object.

Current (incorrect):

getMockMessage({
  id: "msg-1",
  headers: {  // ❌ Not in function signature
    from: "store@example.com",
    to: "user@example.com",
    subject: "Payment confirmation",
    date: new Date().toISOString(),
  },
  labelIds: [],
})

Should be:

getMockMessage({
  id: "msg-1",
  from: "store@example.com",
  to: "user@example.com",
  subject: "Payment confirmation",
  labelIds: [],
})

The headers parameter will be ignored, and the mock will use default values instead of your intended test data. This affects all four test cases.

🔎 Proposed fix for all test cases
     it("should skip thread when message 1 is maybe-receipt but message 2 is starred", async () => {
       const messages = [
         getMockMessage({
           id: "msg-1",
-          headers: {
-            from: "store@example.com",
-            to: "user@example.com",
-            subject: "Payment confirmation",
-            date: new Date().toISOString(),
-          },
+          from: "store@example.com",
+          to: "user@example.com",
+          subject: "Payment confirmation",
           labelIds: [],
         }),
         getMockMessage({
           id: "msg-2",
-          headers: {
-            from: "user@example.com",
-            to: "store@example.com",
-            subject: "Re: Payment confirmation",
-            date: new Date().toISOString(),
-          },
+          from: "user@example.com",
+          to: "store@example.com",
+          subject: "Re: Payment confirmation",
           labelIds: [GmailLabel.STARRED],
         }),
       ];

Apply the same pattern to all test cases (lines 149-183, 185-233, 235-264).

⛔ Skipped due to learnings
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-11-25T14:37:56.430Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Prefer using existing helpers from `@/__tests__/helpers.ts` (`getEmailAccount`, `getEmail`, `getRule`, `getMockMessage`, `getMockExecutedRule`) instead of creating custom test data helpers
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2026-01-01T10:42:29.775Z
Learning: Applies to **/*.test.{ts,tsx} : Use test helper functions `getEmail`, `getEmailAccount`, and `getRule` from `@/__tests__/helpers` for creating mock data
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Applies to **/*.{ts,tsx} : Use wrapper functions for Gmail message operations (get, list, batch, etc.) from @/utils/gmail/message.ts instead of direct API calls
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Applies to **/*.{ts,tsx} : Use wrapper functions for Gmail thread operations from @/utils/gmail/thread.ts instead of direct API calls
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Applies to **/*.{ts,tsx} : Use wrapper functions for Gmail label operations from @/utils/gmail/label.ts instead of direct API calls

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

🧹 Nitpick comments (1)
apps/web/utils/path.test.ts (1)

4-39: Excellent security test coverage for open redirect prevention!

The test suite comprehensively covers the critical bypass techniques for open redirects:

  • Protocol-relative URLs (//example.com)
  • Backslash confusion attacks (/\example.com)
  • External URL protocols (http://, https://, javascript:)
  • Edge cases (null, undefined, empty strings)

Test names are clear and descriptive, making the security requirements explicit.

Optional: Additional edge cases to document behavior

Consider adding tests for these edge cases to further document the expected behavior, though the current implementation already handles them correctly:

+  it("should return true for paths with query strings and fragments", () => {
+    expect(isInternalPath("/path?query=value")).toBe(true);
+    expect(isInternalPath("/path#fragment")).toBe(true);
+    expect(isInternalPath("/path?query=value#fragment")).toBe(true);
+  });
+
+  it("should return false for triple-slash URLs", () => {
+    expect(isInternalPath("///example.com")).toBe(false);
+  });

These additions would make the test suite even more comprehensive, but they are not essential since the current implementation correctly handles these cases.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b7679f1 and 7c855d2.

📒 Files selected for processing (2)
  • apps/web/app/api/clean/route.test.ts
  • apps/web/utils/path.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/web/app/api/clean/route.test.ts
🧰 Additional context used
📓 Path-based instructions (17)
**/*.{ts,tsx}

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

**/*.{ts,tsx}: For API GET requests to server, use the swr package
Use result?.serverError with toastError from @/components/Toast for error handling in async operations

**/*.{ts,tsx}: Use wrapper functions for Gmail message operations (get, list, batch, etc.) from @/utils/gmail/message.ts instead of direct API calls
Use wrapper functions for Gmail thread operations from @/utils/gmail/thread.ts instead of direct API calls
Use wrapper functions for Gmail label operations from @/utils/gmail/label.ts instead of direct API calls

**/*.{ts,tsx}: For early access feature flags, create hooks using the naming convention use[FeatureName]Enabled that return a boolean from useFeatureFlagEnabled("flag-key")
For A/B test variant flags, create hooks using the naming convention use[FeatureName]Variant that define variant types, use useFeatureFlagVariantKey() with type casting, and provide a default "control" fallback
Use kebab-case for PostHog feature flag keys (e.g., inbox-cleaner, pricing-options-2)
Always define types for A/B test variant flags (e.g., type PricingVariant = "control" | "variant-a" | "variant-b") and provide type safety through type casting

**/*.{ts,tsx}: Don't use primitive type aliases or misleading types
Don't use empty type parameters in type aliases and interfaces
Don't use this and super in static contexts
Don't use any or unknown as type constraints
Don't use the TypeScript directive @ts-ignore
Don't use TypeScript enums
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 TypeScript namespaces
Don't use non-null assertions with the ! postfix operator
Don't use parameter properties in class constructors
Don't use user-defined types
Use as const instead of literal types and type annotations
Use either T[] or Array<T> consistently
Initialize each enum member value explicitly
Use export type for types
Use `impo...

Files:

  • apps/web/utils/path.test.ts
**/*.{ts,tsx,js,jsx}

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

Always import Prisma enums from @/generated/prisma/enums instead of @/generated/prisma/client to avoid Next.js bundling errors in client components

Import Prisma using the project's centralized utility: import prisma from '@/utils/prisma'

Files:

  • apps/web/utils/path.test.ts
apps/web/**/*.{ts,tsx}

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

Import specific lodash functions rather than entire lodash library to minimize bundle size (e.g., import groupBy from 'lodash/groupBy')

apps/web/**/*.{ts,tsx}: Use TypeScript with strict null checks
Do not export types/interfaces that are only used within the same file. Export later if needed

Files:

  • apps/web/utils/path.test.ts
**/*.ts

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

**/*.ts: ALL database queries MUST be scoped to the authenticated user/account by including user/account filtering in WHERE clauses to prevent unauthorized data access
Always validate that resources belong to the authenticated user before performing operations, using ownership checks in WHERE clauses or relationships
Always validate all input parameters for type, format, and length before using them in database queries
Use SafeError for error responses to prevent information disclosure. Generic error messages should not reveal internal IDs, logic, or resource ownership details
Only return necessary fields in API responses using Prisma's select option. Never expose sensitive data such as password hashes, private keys, or system flags
Prevent Insecure Direct Object References (IDOR) by validating resource ownership before operations. All findUnique/findFirst calls MUST include ownership filters
Prevent mass assignment vulnerabilities by explicitly whitelisting allowed fields in update operations instead of accepting all user-provided data
Prevent privilege escalation by never allowing users to modify system fields, ownership fields, or admin-only attributes through user input
All findMany queries MUST be scoped to the user's data by including appropriate WHERE filters to prevent returning data from other users
Use Prisma relationships for access control by leveraging nested where clauses (e.g., emailAccount: { id: emailAccountId }) to validate ownership

Files:

  • apps/web/utils/path.test.ts
**/*.{tsx,ts}

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

**/*.{tsx,ts}: Use Shadcn UI and Tailwind for components and styling
Use next/image package for images
For API GET requests to server, use the swr package with hooks like useSWR to fetch data
For text inputs, use the Input component with registerProps for form integration and error handling

Files:

  • apps/web/utils/path.test.ts
**/*.{tsx,ts,css}

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

Implement responsive design with Tailwind CSS using a mobile-first approach

Files:

  • apps/web/utils/path.test.ts
**/*.{js,jsx,ts,tsx}

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

**/*.{js,jsx,ts,tsx}: 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
Don't use distracting elements like <marquee> or <blink>
Only use the scope prop on <th> 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
Use semantic elements instead of role attributes in JSX
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 AR...

Files:

  • apps/web/utils/path.test.ts
**/*.{test,spec}.{js,jsx,ts,tsx}

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

**/*.{test,spec}.{js,jsx,ts,tsx}: Don't nest describe() blocks too deeply in test files
Don't use callbacks in asynchronous tests and hooks
Don't have duplicate hooks in describe blocks
Don't use export or module.exports in test files
Don't use focused tests
Make sure the assertion function, like expect, is placed inside an it() function call
Don't use disabled tests

Files:

  • apps/web/utils/path.test.ts
!(pages/_document).{jsx,tsx}

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

Don't use the next/head module in pages/_document.js on Next.js projects

Files:

  • apps/web/utils/path.test.ts
**/*.{js,ts,jsx,tsx}

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

**/*.{js,ts,jsx,tsx}: Use lodash utilities for common operations (arrays, objects, strings)
Import specific lodash functions to minimize bundle size (e.g., import groupBy from 'lodash/groupBy')

Files:

  • apps/web/utils/path.test.ts
**/{utils,helpers,lib}/**/*.{ts,tsx}

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

Logger should be passed as a parameter to helper functions instead of creating their own logger instances

Files:

  • apps/web/utils/path.test.ts
apps/web/**/*.{ts,tsx,js,jsx}

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

apps/web/**/*.{ts,tsx,js,jsx}: Use @/ path aliases for imports from project root
Prefer self-documenting code over comments; use descriptive variable and function names instead of explaining intent with comments
Add helper functions to the bottom of files, not the top
All imports go at the top of files, no mid-file dynamic imports

Files:

  • apps/web/utils/path.test.ts
apps/web/**/*.{ts,tsx,js,jsx,json,css}

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

Format code with Prettier

Files:

  • apps/web/utils/path.test.ts
apps/web/**/*.test.{ts,tsx}

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

Co-locate test files next to source files (e.g., utils/example.test.ts). Only E2E and AI tests go in __tests__/

Files:

  • apps/web/utils/path.test.ts
apps/web/**/*.{example,ts,json}

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

Add environment variables to .env.example, env.ts, and turbo.json

Files:

  • apps/web/utils/path.test.ts
**/*.test.{js,jsx,ts,tsx}

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

Co-locate test files next to source files (e.g., utils/example.test.ts). Only E2E and AI tests go in __tests__/

Files:

  • apps/web/utils/path.test.ts
**/*.test.{ts,tsx}

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

**/*.test.{ts,tsx}: Use vitest as the testing framework
Colocate test files next to the tested file with .test.ts or .test.tsx naming convention (e.g., dir/format.ts and dir/format.test.ts)
Mock server-only using vi.mock("server-only", () => ({}))
Mock Prisma using vi.mock("@/utils/prisma") and the provided mock from @/utils/__mocks__/prisma
Use test helper functions getEmail, getEmailAccount, and getRule from @/__tests__/helpers for creating mock data
Clear all mocks between tests using beforeEach(() => { vi.clearAllMocks(); })
Use descriptive test names that clearly indicate what is being tested
Do not mock the Logger in tests

Files:

  • apps/web/utils/path.test.ts
🧠 Learnings (13)
📓 Common learnings
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:23.326Z
Learning: Applies to **/*.ts : Prevent Insecure Direct Object References (IDOR) by validating resource ownership in all queries - always include ownership filters (e.g., `emailAccount: { id: emailAccountId }`) when accessing user-specific resources
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:23.326Z
Learning: Applies to **/*.test.ts : Include security tests in test suites to verify: authentication is required, IDOR protection works (other users cannot access resources), parameter validation rejects invalid inputs, and error messages don't leak information
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security-audit.mdc:0-0
Timestamp: 2025-11-25T14:39:04.892Z
Learning: Verify during code review that all new routes follow established security patterns: middleware usage, database query scoping, input validation, and proper error handling
📚 Learning: 2025-12-21T12:21:37.794Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-12-21T12:21:37.794Z
Learning: Applies to apps/web/**/*.test.{ts,tsx} : Co-locate test files next to source files (e.g., `utils/example.test.ts`). Only E2E and AI tests go in `__tests__/`

Applied to files:

  • apps/web/utils/path.test.ts
📚 Learning: 2025-11-25T14:37:56.430Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-11-25T14:37:56.430Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Place all LLM-related tests in `apps/web/__tests__/` directory

Applied to files:

  • apps/web/utils/path.test.ts
📚 Learning: 2025-11-25T14:39:23.326Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:23.326Z
Learning: Applies to **/*.test.ts : Include security tests in test suites to verify: authentication is required, IDOR protection works (other users cannot access resources), parameter validation rejects invalid inputs, and error messages don't leak information

Applied to files:

  • apps/web/utils/path.test.ts
📚 Learning: 2025-11-25T14:38:07.606Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-11-25T14:38:07.606Z
Learning: Applies to apps/web/{utils/ai,utils/llms,__tests__}/**/*.ts : LLM-related code must be organized in specific directories: `apps/web/utils/ai/` for main implementations, `apps/web/utils/llms/` for core utilities and configurations, and `apps/web/__tests__/` for LLM-specific tests

Applied to files:

  • apps/web/utils/path.test.ts
📚 Learning: 2025-12-21T12:21:44.259Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/notes.mdc:0-0
Timestamp: 2025-12-21T12:21:44.259Z
Learning: Applies to **/*.test.{js,jsx,ts,tsx} : Co-locate test files next to source files (e.g., `utils/example.test.ts`). Only E2E and AI tests go in `__tests__/`

Applied to files:

  • apps/web/utils/path.test.ts
📚 Learning: 2025-12-21T12:21:37.794Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-12-21T12:21:37.794Z
Learning: Applies to apps/web/**/*.{ts,tsx,js,jsx} : Use `@/` path aliases for imports from project root

Applied to files:

  • apps/web/utils/path.test.ts
📚 Learning: 2025-11-25T14:37:56.430Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-11-25T14:37:56.430Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Use vitest imports (`describe`, `expect`, `test`, `vi`, `beforeEach`) in LLM test files

Applied to files:

  • apps/web/utils/path.test.ts
📚 Learning: 2026-01-01T10:42:29.775Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2026-01-01T10:42:29.775Z
Learning: Applies to **/__tests__/**/*.{ts,tsx} : Place AI tests in the `__tests__` directory and do not run them by default as they use a real LLM

Applied to files:

  • apps/web/utils/path.test.ts
📚 Learning: 2025-11-25T14:37:56.430Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-11-25T14:37:56.430Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Use `describe.runIf(isAiTest)` with environment variable `RUN_AI_TESTS === "true"` to conditionally run LLM tests

Applied to files:

  • apps/web/utils/path.test.ts
📚 Learning: 2025-11-25T14:37:56.430Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-11-25T14:37:56.430Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Use `console.debug()` for outputting generated LLM content in tests, e.g., `console.debug("Generated content:\n", result.content);`

Applied to files:

  • apps/web/utils/path.test.ts
📚 Learning: 2025-11-25T14:42:08.869Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/ultracite.mdc:0-0
Timestamp: 2025-11-25T14:42:08.869Z
Learning: Applies to **/*.{test,spec}.{js,jsx,ts,tsx} : Make sure the assertion function, like expect, is placed inside an it() function call

Applied to files:

  • apps/web/utils/path.test.ts
📚 Learning: 2026-01-01T10:42:29.775Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2026-01-01T10:42:29.775Z
Learning: Applies to **/*.test.{ts,tsx} : Use `vitest` as the testing framework

Applied to files:

  • apps/web/utils/path.test.ts
🧬 Code graph analysis (1)
apps/web/utils/path.test.ts (1)
apps/web/utils/path.ts (1)
  • isInternalPath (6-11)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: test
🔇 Additional comments (1)
apps/web/utils/path.test.ts (1)

1-2: LGTM! Correct imports for security testing.

The imports follow project guidelines by using Vitest as the testing framework and properly importing the utility under test.

@elie222 elie222 merged commit 17ff08c into main Jan 3, 2026
15 of 16 checks passed
@elie222 elie222 deleted the fix/open-redirect-vulnerability branch January 3, 2026 16:42
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.

1 participant