security: fix open redirect vulnerability in login flow#1179
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Note Other AI code review bot(s) detectedCodeRabbit 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. 📝 WalkthroughWalkthroughThis PR adds path validation security enhancement by introducing a new Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested reviewers
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
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. Comment |
Prevent open redirects in login by validating
|
There was a problem hiding this comment.
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.
apps/web/utils/path.ts
Outdated
|
|
||
| export function isInternalPath(path: string | null | undefined): boolean { | ||
| if (!path) return false; | ||
| return path.startsWith("/") && !path.startsWith("//"); |
There was a problem hiding this comment.
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}`) => {
+
+export function isInternalPath(path: string | null | undefined): boolean {
+ if (!path) return false;
+ return path.startsWith("/") && !path.startsWith("//");
+}
</file context>
| return path.startsWith("/") && !path.startsWith("//"); | |
| return path.startsWith("/") && !path.startsWith("//") && !path.startsWith("/\\"); |
✅ Addressed in b7679f1
There was a problem hiding this comment.
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.
apps/web/app/api/clean/route.test.ts
Outdated
| 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, | ||
| }; | ||
| } |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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'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.
There was a problem hiding this comment.
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:
Lines 129-130: Using
Date.now()as a fallback for missingstart/endtimes 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.Line 122: Defaulting to an empty string for missing
idcould 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
isPremiumfails, and line 49 throws the same message whenhasAiAccessfails. This creates redundancy and may confuse debugging efforts.Consider either:
- Consolidating into a single check if both validations serve the same purpose
- 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
📒 Files selected for processing (10)
apps/web/__tests__/helpers.tsapps/web/app/(app)/[emailAccountId]/calendars/page.tsxapps/web/app/(landing)/login/LoginForm.tsxapps/web/app/(landing)/login/page.tsxapps/web/app/api/clean/route.test.tsapps/web/app/api/clean/route.tsapps/web/utils/calendar/providers/microsoft-events.tsapps/web/utils/organizations/access.tsapps/web/utils/path.tsapps/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 theswrpackage
Useresult?.serverErrorwithtoastErrorfrom@/components/Toastfor 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 conventionuse[FeatureName]Enabledthat return a boolean fromuseFeatureFlagEnabled("flag-key")
For A/B test variant flags, create hooks using the naming conventionuse[FeatureName]Variantthat define variant types, useuseFeatureFlagVariantKey()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
Useas constinstead of literal types and type annotations
Use eitherT[]orArray<T>consistently
Initialize each enum member value explicitly
Useexport typefor types
Use `impo...
Files:
apps/web/utils/user/validate.tsapps/web/utils/organizations/access.tsapps/web/app/(app)/[emailAccountId]/calendars/page.tsxapps/web/__tests__/helpers.tsapps/web/utils/path.tsapps/web/app/api/clean/route.tsapps/web/app/(landing)/login/LoginForm.tsxapps/web/utils/calendar/providers/microsoft-events.tsapps/web/app/(landing)/login/page.tsxapps/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/enumsinstead of@/generated/prisma/clientto avoid Next.js bundling errors in client componentsImport Prisma using the project's centralized utility:
import prisma from '@/utils/prisma'
Files:
apps/web/utils/user/validate.tsapps/web/utils/organizations/access.tsapps/web/app/(app)/[emailAccountId]/calendars/page.tsxapps/web/__tests__/helpers.tsapps/web/utils/path.tsapps/web/app/api/clean/route.tsapps/web/app/(landing)/login/LoginForm.tsxapps/web/utils/calendar/providers/microsoft-events.tsapps/web/app/(landing)/login/page.tsxapps/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.tsapps/web/utils/organizations/access.tsapps/web/app/(app)/[emailAccountId]/calendars/page.tsxapps/web/__tests__/helpers.tsapps/web/utils/path.tsapps/web/app/api/clean/route.tsapps/web/app/(landing)/login/LoginForm.tsxapps/web/utils/calendar/providers/microsoft-events.tsapps/web/app/(landing)/login/page.tsxapps/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'sselectoption. 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. AllfindUnique/findFirstcalls 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
AllfindManyqueries 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.tsapps/web/utils/organizations/access.tsapps/web/__tests__/helpers.tsapps/web/utils/path.tsapps/web/app/api/clean/route.tsapps/web/utils/calendar/providers/microsoft-events.tsapps/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
Usenext/imagepackage for images
For API GET requests to server, use theswrpackage with hooks likeuseSWRto fetch data
For text inputs, use theInputcomponent withregisterPropsfor form integration and error handling
Files:
apps/web/utils/user/validate.tsapps/web/utils/organizations/access.tsapps/web/app/(app)/[emailAccountId]/calendars/page.tsxapps/web/__tests__/helpers.tsapps/web/utils/path.tsapps/web/app/api/clean/route.tsapps/web/app/(landing)/login/LoginForm.tsxapps/web/utils/calendar/providers/microsoft-events.tsapps/web/app/(landing)/login/page.tsxapps/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.tsapps/web/utils/organizations/access.tsapps/web/app/(app)/[emailAccountId]/calendars/page.tsxapps/web/__tests__/helpers.tsapps/web/utils/path.tsapps/web/app/api/clean/route.tsapps/web/app/(landing)/login/LoginForm.tsxapps/web/utils/calendar/providers/microsoft-events.tsapps/web/app/(landing)/login/page.tsxapps/web/app/api/clean/route.test.ts
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)
**/*.{js,jsx,ts,tsx}: Don't useaccessKeyattribute on any HTML element
Don't setaria-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 thescopeprop 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 assigntabIndexto non-interactive HTML elements
Don't use positive integers fortabIndexproperty
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 atitleelement 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
AssigntabIndexto non-interactive HTML elements witharia-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 atypeattribute for button elements
Make elements with interactive roles and handlers focusable
Give heading elements content that's accessible to screen readers (not hidden witharia-hidden)
Always include alangattribute on the html element
Always include atitleattribute for iframe elements
AccompanyonClickwith at least one of:onKeyUp,onKeyDown, oronKeyPress
AccompanyonMouseOver/onMouseOutwithonFocus/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.tsapps/web/utils/organizations/access.tsapps/web/app/(app)/[emailAccountId]/calendars/page.tsxapps/web/__tests__/helpers.tsapps/web/utils/path.tsapps/web/app/api/clean/route.tsapps/web/app/(landing)/login/LoginForm.tsxapps/web/utils/calendar/providers/microsoft-events.tsapps/web/app/(landing)/login/page.tsxapps/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.tsapps/web/utils/organizations/access.tsapps/web/app/(app)/[emailAccountId]/calendars/page.tsxapps/web/__tests__/helpers.tsapps/web/utils/path.tsapps/web/app/api/clean/route.tsapps/web/app/(landing)/login/LoginForm.tsxapps/web/utils/calendar/providers/microsoft-events.tsapps/web/app/(landing)/login/page.tsxapps/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.tsapps/web/utils/organizations/access.tsapps/web/app/(app)/[emailAccountId]/calendars/page.tsxapps/web/__tests__/helpers.tsapps/web/utils/path.tsapps/web/app/api/clean/route.tsapps/web/app/(landing)/login/LoginForm.tsxapps/web/utils/calendar/providers/microsoft-events.tsapps/web/app/(landing)/login/page.tsxapps/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.tsapps/web/utils/organizations/access.tsapps/web/utils/path.tsapps/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.tsapps/web/utils/organizations/access.tsapps/web/app/(app)/[emailAccountId]/calendars/page.tsxapps/web/__tests__/helpers.tsapps/web/utils/path.tsapps/web/app/api/clean/route.tsapps/web/app/(landing)/login/LoginForm.tsxapps/web/utils/calendar/providers/microsoft-events.tsapps/web/app/(landing)/login/page.tsxapps/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.tsapps/web/utils/organizations/access.tsapps/web/app/(app)/[emailAccountId]/calendars/page.tsxapps/web/__tests__/helpers.tsapps/web/utils/path.tsapps/web/app/api/clean/route.tsapps/web/app/(landing)/login/LoginForm.tsxapps/web/utils/calendar/providers/microsoft-events.tsapps/web/app/(landing)/login/page.tsxapps/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, andturbo.json
Files:
apps/web/utils/user/validate.tsapps/web/utils/organizations/access.tsapps/web/__tests__/helpers.tsapps/web/utils/path.tsapps/web/app/api/clean/route.tsapps/web/utils/calendar/providers/microsoft-events.tsapps/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 inpage.tsx, or in theapps/web/app/(app)/PAGE_NAMEfolder
If we're in a deeply nested component we will useswrto fetch via API
If you need to useonClickin a component, that component is a client component and file must start withuse client
Files:
apps/web/app/(app)/[emailAccountId]/calendars/page.tsx
**/*.tsx
📄 CodeRabbit inference engine (.cursor/rules/ui-components.mdc)
**/*.tsx: Use theLoadingContentcomponent to handle loading states instead of manual loading state management
For text areas, use theInputcomponent withtype='text',autosizeTextareaprop set to true, andregisterPropsfor form integration
Files:
apps/web/app/(app)/[emailAccountId]/calendars/page.tsxapps/web/app/(landing)/login/LoginForm.tsxapps/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 bothchildrenanddangerouslySetInnerHTMLprops 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 usetarget="_blank"withoutrel="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.tsxapps/web/app/(landing)/login/LoginForm.tsxapps/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.tsxapps/web/app/api/clean/route.tsapps/web/app/(landing)/login/LoginForm.tsxapps/web/app/(landing)/login/page.tsxapps/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
Useresult?.serverErrorwithtoastErrorandtoastSuccessfor error handling in forms
Files:
apps/web/app/(app)/[emailAccountId]/calendars/page.tsxapps/web/app/(landing)/login/LoginForm.tsxapps/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, andapps/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 usingwithAuthorwithEmailAccountmiddleware inapps/web/app/api/*/route.ts, export response types asGetExampleResponsetype alias for client-side type safety
Always export response types from GET routes asGet[Feature]Responseusing type inference from the data fetching function for type-safe client consumption
Do NOT use POST API routes for mutations - always use server actions withnext-safe-actioninstead
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 withwithAuthorwithEmailAccountmiddleware for consistent error handling and authentication in Next.js App Router
Infer and export response type for GET API routes usingAwaited<ReturnType<typeof functionName>>pattern in Next.js
Use Prisma for database queries in GET API routes
Return responses usingNextResponse.json()in GET API routes
Do not use try/catch blocks in GET API route handlers when usingwithAuthorwithEmailAccountmiddleware, 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 usewithAuth,withEmailAccount, orwithErrormiddleware for authentication
All database queries must include user scoping withemailAccountIdoruserIdfiltering 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; throwSafeErrorinstead of exposing user IDs, resource IDs, or system information
API routes should only return necessary fields usingselectin database queries to prevent unintended information disclosure
Cron endpoints must usehasCronSecretorhasPostCronSecretto 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.tsapps/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: usewithEmailAccountfor email-scoped operations, usewithAuthfor user-scoped operations, or usewithErrorwith proper validation for public/custom auth endpoints
UsewithEmailAccountmiddleware for operations scoped to a specific email account, including reading/writing emails, rules, schedules, or any operation usingemailAccountId
UsewithAuthmiddleware for user-level operations such as user settings, API keys, and referrals that use onlyuserId
UsewithErrormiddleware only for public endpoints, custom authentication logic, or cron endpoints. For cron endpoints, MUST usehasCronSecret()orhasPostCronSecret()validation
Cron endpoints without proper authentication can be triggered by anyone. CRITICAL: All cron endpoints MUST validate cron secret usinghasCronSecret(request)orhasPostCronSecret(request)and capture unauthorized attempts withcaptureException()
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.tsapps/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 withwithAuthorwithEmailAccountmiddleware for fetching data
Export response types from GET API routes usingexport type GetXResponse = Awaited<ReturnType<typeof getData>>
Files:
apps/web/app/api/clean/route.tsapps/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}: Usevitestas the testing framework
Colocate test files next to the tested file with.test.tsor.test.tsxnaming convention (e.g.,dir/format.tsanddir/format.test.ts)
Mockserver-onlyusingvi.mock("server-only", () => ({}))
Mock Prisma usingvi.mock("@/utils/prisma")and the provided mock from@/utils/__mocks__/prisma
Use test helper functionsgetEmail,getEmailAccount, andgetRulefrom@/__tests__/helpersfor creating mock data
Clear all mocks between tests usingbeforeEach(() => { 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.tsapps/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.tsapps/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.tsapps/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.tsapps/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.tsxapps/web/utils/path.tsapps/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.tsxapps/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.tsxapps/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.tsxapps/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.tsxapps/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.tsxapps/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.tsapps/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.tsapps/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.tsapps/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.tsapps/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.tsapps/web/app/api/clean/route.tsapps/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
MicrosoftEventtype 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/eventsto/me/calendar/calendarViewwithstartDateTime/endDateTimequery parameters correctly addresses overlap-based event retrieval. The approach of fetchingmaxResults * 3events before filtering by attendee is appropriate given API limitations.
100-117: LGTM! Sensible default for time range.The 30-day default for
effectiveTimeMaxwhentimeMaxis 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
getMemberEmailAccountandgetCallerEmailAccountwhich already use this patternThe 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
isInternalPathutility, 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
nextparameter points to an internal path before redirecting. Previously, an attacker could craft a malicious URL like/login?next=https://evil.comto redirect users to an external site after authentication.The fallback to
WELCOME_PATHensures users are redirected to a safe location when thenextparameter 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
nextparameter is an internal path before using it as thecallbackURL. 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
cleanThreadallows 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
breakafter 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
labelIdsandattachmentsparameters togetMockMessageenables more realistic test scenarios while maintaining backward compatibility with sensible defaults. This supports the newcleanThreadtest cases that validate label-based and attachment-based skip conditions.apps/web/app/api/clean/route.test.ts (1)
113-264: Incorrect usage ofgetMockMessagehelper.All test cases pass a
headersobject togetMockMessage, but the helper function doesn't accept aheadersparameter. According to the helper signature inapps/web/__tests__/helpers.ts, it expects flat parameters (from,to,subject) not a nestedheadersobject.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
headersparameter 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 helpersLearnt 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 dataLearnt 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 callsLearnt 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 callsLearnt 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
There was a problem hiding this comment.
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
📒 Files selected for processing (2)
apps/web/app/api/clean/route.test.tsapps/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 theswrpackage
Useresult?.serverErrorwithtoastErrorfrom@/components/Toastfor 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 conventionuse[FeatureName]Enabledthat return a boolean fromuseFeatureFlagEnabled("flag-key")
For A/B test variant flags, create hooks using the naming conventionuse[FeatureName]Variantthat define variant types, useuseFeatureFlagVariantKey()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
Useas constinstead of literal types and type annotations
Use eitherT[]orArray<T>consistently
Initialize each enum member value explicitly
Useexport typefor 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/enumsinstead of@/generated/prisma/clientto avoid Next.js bundling errors in client componentsImport 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'sselectoption. 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. AllfindUnique/findFirstcalls 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
AllfindManyqueries 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
Usenext/imagepackage for images
For API GET requests to server, use theswrpackage with hooks likeuseSWRto fetch data
For text inputs, use theInputcomponent withregisterPropsfor 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 useaccessKeyattribute on any HTML element
Don't setaria-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 thescopeprop 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 assigntabIndexto non-interactive HTML elements
Don't use positive integers fortabIndexproperty
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 atitleelement 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
AssigntabIndexto non-interactive HTML elements witharia-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 atypeattribute for button elements
Make elements with interactive roles and handlers focusable
Give heading elements content that's accessible to screen readers (not hidden witharia-hidden)
Always include alangattribute on the html element
Always include atitleattribute for iframe elements
AccompanyonClickwith at least one of:onKeyUp,onKeyDown, oronKeyPress
AccompanyonMouseOver/onMouseOutwithonFocus/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, andturbo.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}: Usevitestas the testing framework
Colocate test files next to the tested file with.test.tsor.test.tsxnaming convention (e.g.,dir/format.tsanddir/format.test.ts)
Mockserver-onlyusingvi.mock("server-only", () => ({}))
Mock Prisma usingvi.mock("@/utils/prisma")and the provided mock from@/utils/__mocks__/prisma
Use test helper functionsgetEmail,getEmailAccount, andgetRulefrom@/__tests__/helpersfor creating mock data
Clear all mocks between tests usingbeforeEach(() => { 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.
User description
Validate the 'next' query parameter to ensure only internal paths are allowed for redirects, preventing open redirect attacks.
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:13pxImplement a security fix to prevent open redirect vulnerabilities by validating the
nextquery parameter in the login flow and calendar redirection. Introduce a newisInternalPathutility function to ensure all redirects lead to internal application paths.getMockMessageutility, improving test code reusability and maintainability.Modified files (2)
Latest Contributors(1)
nextquery parameter in login and calendar redirection flows to prevent open redirect vulnerabilities by ensuring only internal paths are used.Modified files (5)
Latest Contributors(2)
Summary by CodeRabbit
Bug Fixes
Tests
✏️ Tip: You can customize this high-level summary in your review settings.