Skip to content

adjust logger#882

Merged
elie222 merged 5 commits intomainfrom
feat/privacy
Oct 31, 2025
Merged

adjust logger#882
elie222 merged 5 commits intomainfrom
feat/privacy

Conversation

@elie222
Copy link
Owner

@elie222 elie222 commented Oct 31, 2025

Note

Adds an admin UI/action to generate email hashes and updates hashing to HMAC-SHA256 with a salt.

  • Admin UI
    • Adds AdminHashEmail component to generate/copy hashed values; integrated into app/(app)/admin/page.tsx.
  • Actions
    • Introduces adminHashEmailAction using hashEmailBody validation.
  • Utils
    • Updates utils/hash.ts to use HMAC-SHA256 with env.EMAIL_ENCRYPT_SALT for hashing.
  • Version
    • Bumps to v2.17.19.

Written by Cursor Bugbot for commit 8ecd8ae. Configure here.

Summary by CodeRabbit

  • New Features
    • Admin "Hash for Log Search" tool: enter an email, generate a hash, view it read-only, and copy to clipboard with loading and toast feedback.
  • UI Updates
    • Admin page now includes the hash tool.
    • Settings section text updated to "Manage Team Access" with refreshed description.
  • Chores
    • Version bumped to v2.17.19.

@vercel
Copy link

vercel bot commented Oct 31, 2025

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

Project Deployment Preview Updated (UTC)
inbox-zero Ready Ready Preview Oct 31, 2025 3:40pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 31, 2025

Warning

Rate limit exceeded

@elie222 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 10 minutes and 36 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between b9abfec and 27bf82d.

📒 Files selected for processing (2)
  • apps/web/app/(app)/[emailAccountId]/settings/MultiAccountSection.tsx (3 hunks)
  • apps/web/utils/actions/premium.ts (2 hunks)

Walkthrough

Adds an admin UI and server action to hash emails, switches hashing to HMAC with an env salt, refactors email-account Prisma projection and related field access, adds a messages GET route and renames getMessages parameter to email, and bumps the version.

Changes

Cohort / File(s) Summary
Admin Email Hashing Feature
apps/web/app/(app)/admin/AdminHashEmail.tsx, apps/web/app/(app)/admin/page.tsx, apps/web/utils/actions/admin.ts, apps/web/utils/actions/admin.validation.ts
New client component AdminHashEmail (form + copy UI). Added adminHashEmailAction server action and Zod schema hashEmailBody. Admin page now renders the new component.
Hashing Implementation
apps/web/utils/hash.ts
Replaced plain SHA-256 digest with HMAC-SHA256 using env.EMAIL_ENCRYPT_SALT; preserves input normalization and export surface.
Email Account Query & Field Access
apps/web/app/api/user/email-account/route.ts, apps/web/hooks/useOrgAccess.ts
Prisma email-account query changed from include-based relation to a select projection (user sub-object removed; scalars moved up). useOrgAccess now uses emailAccount.userId instead of emailAccount.user.id.
Messages API Route & getMessages
apps/web/app/api/messages/route.ts
Added GET route via withEmailProvider. Renamed getMessages parameter userEmailemail and updated internal calls; replaced direct "google" check with isGoogleProvider.
UI Copy/Text Update
apps/web/app/(app)/[emailAccountId]/settings/MultiAccountSection.tsx
Changed section title/subtext from "Share Premium" to "Manage Team Access" and updated description text.
Version Bump
version.txt
Version updated from v2.17.18 to v2.17.19.

Sequence Diagram(s)

sequenceDiagram
    actor Admin
    participant AdminUI as AdminHashEmail
    participant Action as adminHashEmailAction
    participant HashUtil as hash util (HMAC)

    Admin->>AdminUI: enter email & submit
    AdminUI->>Action: invoke action(email)
    Action->>HashUtil: compute HMAC(email, salt)
    HashUtil-->>Action: return hashed value
    Action-->>AdminUI: respond { hash }
    AdminUI->>AdminUI: display hash (readonly)
    Admin->>AdminUI: click Copy
    AdminUI->>AdminUI: write to clipboard & show toast
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

  • Pay attention to:
    • apps/web/utils/hash.ts — verify HMAC usage, env salt presence, and compatibility with stored hashes.
    • apps/web/app/api/user/email-account/route.ts and apps/web/hooks/useOrgAccess.ts — ensure all callsites handle the new projection and userId access pattern.
    • apps/web/app/api/messages/route.ts — confirm userEmailemail rename did not miss external callers and that isGoogleProvider semantics match previous checks.

Possibly related PRs

  • Adjust pricing seats #763 — Modifies the same MultiAccountSection UI file; likely related to the section title/text changes.
  • Logger adjustments #881 — Changes hashing implementation in apps/web/utils/hash.ts; directly related to the HMAC vs SHA-256 adjustments.

Poem

🐇 I nibbled at bytes beneath the moon's pale light,
I salted whispers, turned digests to HMAC bright,
Admin taps keys, a hash appears in view,
I copy with a hop — secured and true! ✨

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Title Check ⚠️ Warning The pull request title "adjust logger" does not clearly relate to the actual changeset. The primary changes include adding an admin UI component for hashing emails (AdminHashEmail.tsx), introducing an adminHashEmailAction, updating the hashing algorithm to use HMAC-SHA256 with a salt in hash.ts, refactoring database queries to use select projections, and updating UI labels. The title makes no mention of these core changes and uses a vague term "logger" that does not appear in any of the modified files or accurately describe the purpose of the changeset. The title should be revised to accurately reflect the main objective of the pull request. A more descriptive title such as "Add admin email hashing feature and switch to HMAC-SHA256" or "Update email hashing to use HMAC with salt" would clearly communicate the primary changes to reviewers and better serve the purpose of a meaningful commit history.
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 (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

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.

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.

No issues found across 6 files

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 (4)
apps/web/utils/actions/admin.validation.ts (1)

3-5: Tighten the schema to reject blank or malformed emails.

Right now whitespace strings satisfy min(1) and you'll hash an empty string after the downstream trim(), producing a misleading digest. Trimming and validating as an email keeps the admin tool aligned with its intent and prevents accidental bad inputs.

Apply this diff:

 export const hashEmailBody = z.object({
-  email: z.string().min(1, "Value is required"),
+  email: z
+    .string()
+    .trim()
+    .email("Enter a valid email address"),
 });
apps/web/utils/actions/admin.ts (1)

192-198: Consider adding logging for admin audit trail.

The action implementation is correct and follows the safe-action pattern. However, other admin actions in this file (e.g., adminDeleteAccountAction at line 70, adminSyncStripeForAllUsersAction at line 88) use the logger from context for audit trails. Consider adding logging here for consistency and traceability of admin operations.

Apply this diff to add logging:

 export const adminHashEmailAction = adminActionClient
   .metadata({ name: "adminHashEmail" })
   .schema(hashEmailBody)
-  .action(async ({ parsedInput: { email } }) => {
+  .action(async ({ parsedInput: { email }, ctx: { logger } }) => {
+    logger.info("Admin hashing email", { email });
     const hashed = hash(email);
     return { hash: hashed };
   });
apps/web/app/(app)/admin/AdminHashEmail.tsx (2)

44-51: Wrap copyToClipboard in useCallback for consistency.

While not critical, wrapping this function in useCallback would be consistent with the onSubmit handler and prevent unnecessary re-creation on every render.

Apply this diff:

-  const copyToClipboard = () => {
+  const copyToClipboard = useCallback(() => {
     if (result.data?.hash) {
       navigator.clipboard.writeText(result.data.hash);
       toastSuccess({
         description: "Hash copied to clipboard",
       });
     }
-  };
+  }, [result.data?.hash]);

72-92: Consider simplifying the read-only hash display.

Using registerProps for a read-only display field (lines 79-82) is unconventional. The registerProps pattern is typically for actual form inputs that need validation and state management. For a read-only display, you could simply pass the value and readOnly props directly to the Input component without wrapping them in registerProps.

Apply this diff:

           <div className="flex-1">
             <Input
               type="text"
               name="hashedValue"
               label="Hashed Value"
-              registerProps={{
-                value: result.data.hash,
-                readOnly: true,
-              }}
+              value={result.data.hash}
+              readOnly={true}
               className="font-mono text-xs"
             />
           </div>
📜 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 05c2702 and 1496bc2.

📒 Files selected for processing (8)
  • apps/web/app/(app)/admin/AdminHashEmail.tsx (1 hunks)
  • apps/web/app/(app)/admin/page.tsx (2 hunks)
  • apps/web/app/api/user/email-account/route.ts (1 hunks)
  • apps/web/hooks/useOrgAccess.ts (1 hunks)
  • apps/web/utils/actions/admin.ts (2 hunks)
  • apps/web/utils/actions/admin.validation.ts (1 hunks)
  • apps/web/utils/hash.ts (2 hunks)
  • version.txt (1 hunks)
🧰 Additional context used
📓 Path-based instructions (28)
apps/web/**/*.{ts,tsx}

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

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

Files:

  • apps/web/app/(app)/admin/AdminHashEmail.tsx
  • apps/web/utils/hash.ts
  • apps/web/app/api/user/email-account/route.ts
  • apps/web/utils/actions/admin.ts
  • apps/web/hooks/useOrgAccess.ts
  • apps/web/utils/actions/admin.validation.ts
  • apps/web/app/(app)/admin/page.tsx
apps/web/app/**

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

NextJS app router structure with (app) directory

Files:

  • apps/web/app/(app)/admin/AdminHashEmail.tsx
  • apps/web/app/api/user/email-account/route.ts
  • apps/web/app/(app)/admin/page.tsx
apps/web/**/*.tsx

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

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

Files:

  • apps/web/app/(app)/admin/AdminHashEmail.tsx
  • apps/web/app/(app)/admin/page.tsx
!{.cursor/rules/*.mdc}

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

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

Files:

  • apps/web/app/(app)/admin/AdminHashEmail.tsx
  • apps/web/utils/hash.ts
  • version.txt
  • apps/web/app/api/user/email-account/route.ts
  • apps/web/utils/actions/admin.ts
  • apps/web/hooks/useOrgAccess.ts
  • apps/web/utils/actions/admin.validation.ts
  • apps/web/app/(app)/admin/page.tsx
**/*.tsx

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

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

Files:

  • apps/web/app/(app)/admin/AdminHashEmail.tsx
  • apps/web/app/(app)/admin/page.tsx
**/*.{ts,tsx}

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

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

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

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

Files:

  • apps/web/app/(app)/admin/AdminHashEmail.tsx
  • apps/web/utils/hash.ts
  • apps/web/app/api/user/email-account/route.ts
  • apps/web/utils/actions/admin.ts
  • apps/web/hooks/useOrgAccess.ts
  • apps/web/utils/actions/admin.validation.ts
  • apps/web/app/(app)/admin/page.tsx
apps/web/app/(app)/*/**

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

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

Files:

  • apps/web/app/(app)/admin/AdminHashEmail.tsx
  • apps/web/app/(app)/admin/page.tsx
apps/web/app/(app)/*/**/*.tsx

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

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

Files:

  • apps/web/app/(app)/admin/AdminHashEmail.tsx
  • apps/web/app/(app)/admin/page.tsx
apps/web/app/(app)/*/**/**/*.tsx

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

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

Files:

  • apps/web/app/(app)/admin/AdminHashEmail.tsx
  • apps/web/app/(app)/admin/page.tsx
apps/web/app/**/*.tsx

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

Components with onClick must be client components with use client directive

Files:

  • apps/web/app/(app)/admin/AdminHashEmail.tsx
  • apps/web/app/(app)/admin/page.tsx
**/*.{js,jsx,ts,tsx}

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

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

Files:

  • apps/web/app/(app)/admin/AdminHashEmail.tsx
  • apps/web/utils/hash.ts
  • apps/web/app/api/user/email-account/route.ts
  • apps/web/utils/actions/admin.ts
  • apps/web/hooks/useOrgAccess.ts
  • apps/web/utils/actions/admin.validation.ts
  • apps/web/app/(app)/admin/page.tsx
!pages/_document.{js,jsx,ts,tsx}

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

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

Files:

  • apps/web/app/(app)/admin/AdminHashEmail.tsx
  • apps/web/utils/hash.ts
  • version.txt
  • apps/web/app/api/user/email-account/route.ts
  • apps/web/utils/actions/admin.ts
  • apps/web/hooks/useOrgAccess.ts
  • apps/web/utils/actions/admin.validation.ts
  • apps/web/app/(app)/admin/page.tsx
**/*.{jsx,tsx}

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

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

Files:

  • apps/web/app/(app)/admin/AdminHashEmail.tsx
  • apps/web/app/(app)/admin/page.tsx
**/*.{html,jsx,tsx}

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

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

Files:

  • apps/web/app/(app)/admin/AdminHashEmail.tsx
  • apps/web/app/(app)/admin/page.tsx
**/*.ts

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

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

Files:

  • apps/web/utils/hash.ts
  • apps/web/app/api/user/email-account/route.ts
  • apps/web/utils/actions/admin.ts
  • apps/web/hooks/useOrgAccess.ts
  • apps/web/utils/actions/admin.validation.ts
apps/web/utils/**

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

Create utility functions in utils/ folder for reusable logic

Files:

  • apps/web/utils/hash.ts
  • apps/web/utils/actions/admin.ts
  • apps/web/utils/actions/admin.validation.ts
apps/web/utils/**/*.ts

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

apps/web/utils/**/*.ts: Use lodash utilities for common operations (arrays, objects, strings)
Import specific lodash functions to minimize bundle size

Files:

  • apps/web/utils/hash.ts
  • apps/web/utils/actions/admin.ts
  • apps/web/utils/actions/admin.validation.ts
apps/web/app/api/**/route.ts

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

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

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

Files:

  • apps/web/app/api/user/email-account/route.ts
**/api/**/route.ts

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

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

Files:

  • apps/web/app/api/user/email-account/route.ts
apps/web/app/api/**/*.{ts,js}

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

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

Files:

  • apps/web/app/api/user/email-account/route.ts
apps/web/utils/actions/**/*.ts

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

apps/web/utils/actions/**/*.ts: Use server actions for all mutations (create/update/delete operations)
next-safe-action provides centralized error handling
Use Zod schemas for validation on both client and server
Use revalidatePath in server actions for cache invalidation

apps/web/utils/actions/**/*.ts: Use server actions (with next-safe-action) for all mutations (create/update/delete operations); do NOT use POST API routes for mutations.
Use revalidatePath in server actions to invalidate cache after mutations.

Files:

  • apps/web/utils/actions/admin.ts
  • apps/web/utils/actions/admin.validation.ts
apps/web/utils/actions/*.ts

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

apps/web/utils/actions/*.ts: Implement all server actions using the next-safe-action library for type safety, input validation, context management, and error handling. Refer to apps/web/utils/actions/safe-action.ts for client definitions (actionClient, actionClientUser, adminActionClient).
Use actionClientUser when only authenticated user context (userId) is needed.
Use actionClient when both authenticated user context and a specific emailAccountId are needed. The emailAccountId must be bound when calling the action from the client.
Use adminActionClient for actions restricted to admin users.
Access necessary context (like userId, emailAccountId, etc.) provided by the safe action client via the ctx object in the .action() handler.
Server Actions are strictly for mutations (operations that change data, e.g., creating, updating, deleting). Do NOT use Server Actions for data fetching (GET operations). For data fetching, use dedicated GET API Routes combined with SWR Hooks.
Use SafeError for expected/handled errors within actions if needed. next-safe-action provides centralized error handling.
Use the .metadata({ name: "actionName" }) method to provide a meaningful name for monitoring. Sentry instrumentation is automatically applied via withServerActionInstrumentation within the safe action clients.
If an action modifies data displayed elsewhere, use revalidatePath or revalidateTag from next/cache within the action handler as needed.

Server action files must start with use server

Files:

  • apps/web/utils/actions/admin.ts
  • apps/web/utils/actions/admin.validation.ts
apps/web/hooks/**/*.ts

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

Use SWR for efficient data fetching and caching

apps/web/hooks/**/*.ts: Use SWR for client-side data fetching and caching.
Call mutate() after successful mutations to refresh SWR data on the client.

Files:

  • apps/web/hooks/useOrgAccess.ts
apps/web/hooks/**/*.{ts,tsx}

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

Call mutate() after successful mutations to refresh data

Files:

  • apps/web/hooks/useOrgAccess.ts
apps/web/hooks/**/*.{js,jsx,ts,tsx}

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

Place custom hooks in the apps/web/hooks/ directory.

Files:

  • apps/web/hooks/useOrgAccess.ts
apps/web/hooks/use*.{js,jsx,ts,tsx}

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

apps/web/hooks/use*.{js,jsx,ts,tsx}: Name custom hooks with the use prefix (e.g., useAccounts.ts).
For fetching data from API endpoints in custom hooks, prefer using useSWR.
Create dedicated hooks for specific data types (e.g., useAccounts, useLabels).
Custom hooks should encapsulate reusable stateful logic, especially for data fetching or complex UI interactions.
Keep custom hooks focused on a single responsibility.

Files:

  • apps/web/hooks/useOrgAccess.ts
apps/web/utils/actions/*.validation.ts

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

Define Zod schemas for validation in dedicated files and use them for both client and server validation.

Define input validation schemas using Zod in the corresponding .validation.ts file. These schemas are used by next-safe-action (.schema()) and can also be reused on the client for form validation.

Files:

  • apps/web/utils/actions/admin.validation.ts
apps/web/app/(app)/*/page.tsx

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

apps/web/app/(app)/*/page.tsx: Create new pages at: apps/web/app/(app)/PAGE_NAME/page.tsx
Pages are Server components so you can load data into them directly

apps/web/app/(app)/*/page.tsx: Create new pages at: apps/web/app/(app)/PAGE_NAME/page.tsx
Pages are Server components for direct data loading

Files:

  • apps/web/app/(app)/admin/page.tsx
🧠 Learnings (39)
📚 Learning: 2025-07-18T17:27:58.249Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/server-actions.mdc:0-0
Timestamp: 2025-07-18T17:27:58.249Z
Learning: Applies to apps/web/utils/actions/*.ts : Use `adminActionClient` for actions restricted to admin users.

Applied to files:

  • apps/web/app/(app)/admin/AdminHashEmail.tsx
  • apps/web/utils/actions/admin.ts
  • apps/web/app/(app)/admin/page.tsx
📚 Learning: 2025-07-18T15:04:30.467Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-18T15:04:30.467Z
Learning: Applies to apps/web/components/**/*.tsx : Use React Hook Form with Zod validation for form handling

Applied to files:

  • apps/web/app/(app)/admin/AdminHashEmail.tsx
  • apps/web/utils/actions/admin.validation.ts
📚 Learning: 2025-07-18T17:27:58.249Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/server-actions.mdc:0-0
Timestamp: 2025-07-18T17:27:58.249Z
Learning: Applies to apps/web/utils/actions/*.ts : Use `actionClient` when both authenticated user context and a specific `emailAccountId` are needed. The `emailAccountId` must be bound when calling the action from the client.

Applied to files:

  • apps/web/app/(app)/admin/AdminHashEmail.tsx
  • apps/web/app/api/user/email-account/route.ts
  • apps/web/utils/actions/admin.ts
  • apps/web/hooks/useOrgAccess.ts
📚 Learning: 2025-07-18T15:05:16.146Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/fullstack-workflow.mdc:0-0
Timestamp: 2025-07-18T15:05:16.146Z
Learning: Applies to apps/web/components/**/*Form.tsx : Use React Hook Form with Zod resolver for form handling and validation.

Applied to files:

  • apps/web/app/(app)/admin/AdminHashEmail.tsx
📚 Learning: 2025-07-18T15:05:16.146Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/fullstack-workflow.mdc:0-0
Timestamp: 2025-07-18T15:05:16.146Z
Learning: Applies to apps/web/components/**/*Form.tsx : Use `result?.serverError` with `toastError` and `toastSuccess` for error and success notifications in form submission handlers.

Applied to files:

  • apps/web/app/(app)/admin/AdminHashEmail.tsx
📚 Learning: 2025-07-18T15:04:57.115Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/form-handling.mdc:0-0
Timestamp: 2025-07-18T15:04:57.115Z
Learning: Applies to **/*.tsx : Validate form inputs before submission

Applied to files:

  • apps/web/app/(app)/admin/AdminHashEmail.tsx
📚 Learning: 2025-07-18T15:04:57.115Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/form-handling.mdc:0-0
Timestamp: 2025-07-18T15:04:57.115Z
Learning: Applies to **/*.tsx : Use React Hook Form with Zod for validation

Applied to files:

  • apps/web/app/(app)/admin/AdminHashEmail.tsx
📚 Learning: 2025-07-18T17:27:58.249Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/server-actions.mdc:0-0
Timestamp: 2025-07-18T17:27:58.249Z
Learning: Applies to apps/web/utils/actions/*.ts : Implement all server actions using the `next-safe-action` library for type safety, input validation, context management, and error handling. Refer to `apps/web/utils/actions/safe-action.ts` for client definitions (`actionClient`, `actionClientUser`, `adminActionClient`).

Applied to files:

  • apps/web/app/(app)/admin/AdminHashEmail.tsx
  • apps/web/utils/actions/admin.ts
📚 Learning: 2025-07-19T17:50:22.078Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/ui-components.mdc:0-0
Timestamp: 2025-07-19T17:50:22.078Z
Learning: Applies to components/**/*.tsx : Use the `Input` component for text inputs, passing `registerProps` and `error` props for form handling

Applied to files:

  • apps/web/app/(app)/admin/AdminHashEmail.tsx
📚 Learning: 2025-07-18T15:04:30.467Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-18T15:04:30.467Z
Learning: Applies to apps/web/app/api/**/route.ts : Use `withEmailAccount` for email-account-level operations

Applied to files:

  • apps/web/app/api/user/email-account/route.ts
  • apps/web/hooks/useOrgAccess.ts
📚 Learning: 2025-07-20T09:00:41.968Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security-audit.mdc:0-0
Timestamp: 2025-07-20T09:00:41.968Z
Learning: Applies to apps/web/app/api/**/*.{ts,js} : All Prisma queries in API routes must include user/account filtering (e.g., emailAccountId or userId in WHERE clauses) to prevent unauthorized data access.

Applied to files:

  • apps/web/app/api/user/email-account/route.ts
  • apps/web/hooks/useOrgAccess.ts
📚 Learning: 2025-07-18T17:27:46.389Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-07-18T17:27:46.389Z
Learning: Applies to **/api/**/route.ts : Use `withEmailAccount` middleware for API routes that operate on a specific email account (i.e., use or require `emailAccountId`).

Applied to files:

  • apps/web/app/api/user/email-account/route.ts
  • apps/web/hooks/useOrgAccess.ts
📚 Learning: 2025-07-20T09:00:41.968Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security-audit.mdc:0-0
Timestamp: 2025-07-20T09:00:41.968Z
Learning: Applies to apps/web/app/api/**/*.{ts,js} : API routes should only return necessary fields using Prisma's 'select' and must not include sensitive data in error messages.

Applied to files:

  • apps/web/app/api/user/email-account/route.ts
📚 Learning: 2025-07-18T17:27:46.389Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-07-18T17:27:46.389Z
Learning: Applies to **/api/**/route.ts : ALL database queries in API routes MUST be scoped to the authenticated user/account (e.g., include userId or emailAccountId in query filters).

Applied to files:

  • apps/web/app/api/user/email-account/route.ts
  • apps/web/hooks/useOrgAccess.ts
📚 Learning: 2025-07-18T17:27:46.389Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-07-18T17:27:46.389Z
Learning: Applies to **/api/**/route.ts : All Prisma queries in API routes MUST only return necessary fields and never expose sensitive data.

Applied to files:

  • apps/web/app/api/user/email-account/route.ts
📚 Learning: 2025-07-18T17:27:46.389Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-07-18T17:27:46.389Z
Learning: Applies to **/api/**/route.ts : All `findUnique` and `findFirst` Prisma calls in API routes MUST include ownership filters (e.g., userId or emailAccountId).

Applied to files:

  • apps/web/app/api/user/email-account/route.ts
📚 Learning: 2025-07-18T15:05:26.713Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-07-18T15:05:26.713Z
Learning: Applies to app/api/**/route.ts : Always wrap the handler with `withAuth` or `withEmailAccount` for consistent error handling and authentication in GET API routes.

Applied to files:

  • apps/web/app/api/user/email-account/route.ts
📚 Learning: 2025-07-18T15:05:26.713Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-07-18T15:05:26.713Z
Learning: Applies to app/api/**/route.ts : Do not use try/catch in GET API route handlers, as `withAuth` and `withEmailAccount` handle error catching.

Applied to files:

  • apps/web/app/api/user/email-account/route.ts
📚 Learning: 2025-07-18T15:05:26.713Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-07-18T15:05:26.713Z
Learning: Applies to app/api/**/route.ts : Use Prisma for database queries in GET API routes.

Applied to files:

  • apps/web/app/api/user/email-account/route.ts
📚 Learning: 2025-09-20T18:24:34.280Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-09-20T18:24:34.280Z
Learning: Applies to **/*.test.{ts,tsx} : Use provided helpers for mocks: import `{ getEmail, getEmailAccount, getRule }` from `@/__tests__/helpers`

Applied to files:

  • apps/web/app/api/user/email-account/route.ts
📚 Learning: 2025-07-18T15:04:30.467Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-18T15:04:30.467Z
Learning: Applies to apps/web/utils/actions/**/*.ts : Use server actions for all mutations (create/update/delete operations)

Applied to files:

  • apps/web/utils/actions/admin.ts
📚 Learning: 2025-07-18T15:05:16.146Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/fullstack-workflow.mdc:0-0
Timestamp: 2025-07-18T15:05:16.146Z
Learning: Applies to apps/web/utils/actions/**/*.ts : Use server actions (with `next-safe-action`) for all mutations (create/update/delete operations); do NOT use POST API routes for mutations.

Applied to files:

  • apps/web/utils/actions/admin.ts
📚 Learning: 2025-07-18T17:27:58.249Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/server-actions.mdc:0-0
Timestamp: 2025-07-18T17:27:58.249Z
Learning: Applies to apps/web/utils/actions/*.ts : Access necessary context (like `userId`, `emailAccountId`, etc.) provided by the safe action client via the `ctx` object in the `.action()` handler.

Applied to files:

  • apps/web/utils/actions/admin.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/hooks/useOrgAccess.ts
📚 Learning: 2025-07-18T15:05:16.146Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/fullstack-workflow.mdc:0-0
Timestamp: 2025-07-18T15:05:16.146Z
Learning: Applies to apps/web/utils/actions/*.validation.ts : Define Zod schemas for validation in dedicated files and use them for both client and server validation.

Applied to files:

  • apps/web/utils/actions/admin.validation.ts
📚 Learning: 2025-07-18T15:04:30.467Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-18T15:04:30.467Z
Learning: Applies to apps/web/utils/actions/**/*.ts : Use Zod schemas for validation on both client and server

Applied to files:

  • apps/web/utils/actions/admin.validation.ts
📚 Learning: 2025-07-18T17:27:58.249Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/server-actions.mdc:0-0
Timestamp: 2025-07-18T17:27:58.249Z
Learning: Applies to apps/web/utils/actions/*.validation.ts : Define input validation schemas using Zod in the corresponding `.validation.ts` file. These schemas are used by `next-safe-action` (`.schema()`) and can also be reused on the client for form validation.

Applied to files:

  • apps/web/utils/actions/admin.validation.ts
📚 Learning: 2025-09-17T22:05:28.646Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-09-17T22:05:28.646Z
Learning: Applies to apps/web/utils/ai/**/*.{ts,tsx} : Always define a Zod schema for response validation

Applied to files:

  • apps/web/utils/actions/admin.validation.ts
📚 Learning: 2025-07-18T15:04:57.115Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/form-handling.mdc:0-0
Timestamp: 2025-07-18T15:04:57.115Z
Learning: Applies to **/*.ts : Define validation schemas using Zod

Applied to files:

  • apps/web/utils/actions/admin.validation.ts
📚 Learning: 2025-07-20T09:00:41.968Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security-audit.mdc:0-0
Timestamp: 2025-07-20T09:00:41.968Z
Learning: Applies to apps/web/app/api/**/*.{ts,js} : Request bodies in API routes should use Zod schemas for validation.

Applied to files:

  • apps/web/utils/actions/admin.validation.ts
📚 Learning: 2025-09-17T22:05:28.646Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-09-17T22:05:28.646Z
Learning: Applies to apps/web/utils/ai/**/*.{ts,tsx} : Make Zod schemas as specific as possible to guide LLM output

Applied to files:

  • apps/web/utils/actions/admin.validation.ts
📚 Learning: 2025-07-18T17:27:46.389Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-07-18T17:27:46.389Z
Learning: Applies to **/api/**/route.ts : Request bodies in API routes MUST be validated using Zod schemas before use.

Applied to files:

  • apps/web/utils/actions/admin.validation.ts
📚 Learning: 2025-09-17T22:05:28.646Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-09-17T22:05:28.646Z
Learning: Applies to apps/web/utils/ai/**/*.{ts,tsx} : LLM feature functions should follow the provided TypeScript pattern (separate system/user prompts, use createGenerateObject, Zod schema validation, early validation, return result.object)

Applied to files:

  • apps/web/utils/actions/admin.validation.ts
📚 Learning: 2025-07-17T04:19:57.099Z
Learnt from: edulelis
Repo: elie222/inbox-zero PR: 576
File: packages/resend/emails/digest.tsx:78-83
Timestamp: 2025-07-17T04:19:57.099Z
Learning: In packages/resend/emails/digest.tsx, the DigestEmailProps type uses `[key: string]: DigestItem[] | undefined | string | Date | undefined` instead of intersection types like `& Record<string, DigestItem[] | undefined>` due to implementation constraints. This was the initial implementation approach and cannot be changed to more restrictive typing.

Applied to files:

  • apps/web/utils/actions/admin.validation.ts
📚 Learning: 2025-07-20T09:00:16.505Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/project-structure.mdc:0-0
Timestamp: 2025-07-20T09:00:16.505Z
Learning: Applies to apps/web/app/(app)/*/ : Components for the page are either in `page.tsx` or in the `apps/web/app/(app)/PAGE_NAME` folder

Applied to files:

  • apps/web/app/(app)/admin/page.tsx
📚 Learning: 2025-07-20T09:00:16.505Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/project-structure.mdc:0-0
Timestamp: 2025-07-20T09:00:16.505Z
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)/admin/page.tsx
📚 Learning: 2025-07-18T15:07:00.269Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/page-structure.mdc:0-0
Timestamp: 2025-07-18T15:07:00.269Z
Learning: Applies to apps/web/app/(app)/*/** : 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)/admin/page.tsx
📚 Learning: 2025-07-18T15:07:00.269Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/page-structure.mdc:0-0
Timestamp: 2025-07-18T15:07:00.269Z
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)/admin/page.tsx
📚 Learning: 2025-07-20T09:00:16.505Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/project-structure.mdc:0-0
Timestamp: 2025-07-20T09:00:16.505Z
Learning: Applies to apps/web/app/(app)/*/page.tsx : Pages are Server components for direct data loading

Applied to files:

  • apps/web/app/(app)/admin/page.tsx
🧬 Code graph analysis (4)
apps/web/app/(app)/admin/AdminHashEmail.tsx (2)
apps/web/utils/actions/admin.ts (1)
  • adminHashEmailAction (192-198)
apps/web/utils/actions/admin.validation.ts (2)
  • HashEmailBody (6-6)
  • hashEmailBody (3-5)
apps/web/utils/hash.ts (1)
apps/web/env.ts (1)
  • env (16-242)
apps/web/utils/actions/admin.ts (3)
apps/web/utils/actions/safe-action.ts (1)
  • adminActionClient (142-151)
apps/web/utils/actions/admin.validation.ts (1)
  • hashEmailBody (3-5)
apps/web/utils/hash.ts (1)
  • hash (10-20)
apps/web/app/(app)/admin/page.tsx (1)
apps/web/app/(app)/admin/AdminHashEmail.tsx (1)
  • AdminHashEmail (16-95)
⏰ 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). (5)
  • GitHub Check: Static Code Analysis Js
  • GitHub Check: cubic · AI code reviewer
  • GitHub Check: Jit Security
  • GitHub Check: test
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (4)
apps/web/utils/hash.ts (1)

17-19: Great to move hashing to HMAC with the env key.

Using createHmac with EMAIL_ENCRYPT_SALT keeps the log hashes environment-specific without touching call sites—nice upgrade.

apps/web/utils/actions/admin.ts (1)

12-13: LGTM!

The imports are correctly structured and necessary for the new hashing functionality.

apps/web/app/(app)/admin/AdminHashEmail.tsx (2)

1-15: LGTM!

The imports and setup are correct. The component properly uses "use client" directive as required for interactive form handling.


16-42: LGTM!

The hooks are correctly implemented following React Hook Form and next-safe-action patterns. The error handling via onError callback and form validation with zodResolver follow the project's coding guidelines.

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.

No issues found across 2 files

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/app/api/messages/route.ts (1)

75-89: Consider using a helper function for Microsoft provider check.

Line 75 uses the isGoogleProvider helper for consistency and maintainability, but line 86 still uses a direct string comparison for the Microsoft provider. Consider creating and using a similar isMicrosoftProvider helper for consistency.

If you'd like, you can add a helper function to apps/web/utils/email/provider-types.ts:

export function isMicrosoftProvider(provider: string | null | undefined) {
  return provider === "microsoft";
}

Then update this code:

-      } else if (emailProvider.name === "microsoft") {
+      } else if (isMicrosoftProvider(emailProvider.name)) {
📜 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 1496bc2 and 882df4e.

📒 Files selected for processing (1)
  • apps/web/app/api/messages/route.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (10)
apps/web/**/*.{ts,tsx}

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

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

Files:

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

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

NextJS app router structure with (app) directory

Files:

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

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

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

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

Files:

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

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

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

Files:

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

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

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

Files:

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

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

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

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

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

Files:

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

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

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

Files:

  • apps/web/app/api/messages/route.ts
apps/web/app/api/**/*.{ts,js}

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

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

Files:

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

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

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

Files:

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

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

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

Files:

  • apps/web/app/api/messages/route.ts
🧠 Learnings (11)
📚 Learning: 2025-07-18T15:04:30.467Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-18T15:04:30.467Z
Learning: Applies to apps/web/app/api/**/route.ts : Use `withEmailAccount` for email-account-level operations

Applied to files:

  • apps/web/app/api/messages/route.ts
📚 Learning: 2025-07-18T15:05:26.713Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-07-18T15:05:26.713Z
Learning: Applies to app/api/**/route.ts : Always wrap the handler with `withAuth` or `withEmailAccount` for consistent error handling and authentication in GET API routes.

Applied to files:

  • apps/web/app/api/messages/route.ts
📚 Learning: 2025-07-18T17:27:46.389Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-07-18T17:27:46.389Z
Learning: Applies to **/api/**/route.ts : Use `withEmailAccount` middleware for API routes that operate on a specific email account (i.e., use or require `emailAccountId`).

Applied to files:

  • apps/web/app/api/messages/route.ts
📚 Learning: 2025-07-18T15:05:16.146Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/fullstack-workflow.mdc:0-0
Timestamp: 2025-07-18T15:05:16.146Z
Learning: Applies to apps/web/app/api/**/route.ts : Wrap all GET API route handlers with `withAuth` or `withEmailAccount` middleware for authentication and authorization.

Applied to files:

  • apps/web/app/api/messages/route.ts
📚 Learning: 2025-07-18T15:05:26.713Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-07-18T15:05:26.713Z
Learning: Applies to app/api/**/route.ts : Do not use try/catch in GET API route handlers, as `withAuth` and `withEmailAccount` handle error catching.

Applied to files:

  • apps/web/app/api/messages/route.ts
📚 Learning: 2025-07-18T15:05:34.899Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-07-18T15:05:34.899Z
Learning: Applies to apps/web/utils/gmail/**/*.ts : Keep provider-specific implementation details isolated in the appropriate utils subfolder (e.g., 'apps/web/utils/gmail/')

Applied to files:

  • apps/web/app/api/messages/route.ts
📚 Learning: 2025-10-02T23:23:48.064Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-10-02T23:23:48.064Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Prefer existing helpers from @/__tests__/helpers.ts (getEmailAccount, getEmail, getRule, getMockMessage, getMockExecutedRule) over custom helpers

Applied to files:

  • apps/web/app/api/messages/route.ts
📚 Learning: 2025-07-20T09:00:41.968Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security-audit.mdc:0-0
Timestamp: 2025-07-20T09:00:41.968Z
Learning: Applies to apps/web/app/api/**/*.{ts,js} : Review all new withError usage in API routes to ensure custom authentication is implemented where required.

Applied to files:

  • apps/web/app/api/messages/route.ts
📚 Learning: 2025-07-18T17:27:46.389Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-07-18T17:27:46.389Z
Learning: Applies to **/api/**/route.ts : ALL API routes that handle user data MUST use appropriate authentication and authorization middleware (withAuth or withEmailAccount).

Applied to files:

  • apps/web/app/api/messages/route.ts
📚 Learning: 2025-09-20T18:24:34.280Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-09-20T18:24:34.280Z
Learning: Applies to **/*.test.{ts,tsx} : Use provided helpers for mocks: import `{ getEmail, getEmailAccount, getRule }` from `@/__tests__/helpers`

Applied to files:

  • apps/web/app/api/messages/route.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/api/messages/route.ts
🧬 Code graph analysis (1)
apps/web/app/api/messages/route.ts (4)
apps/web/utils/middleware.ts (1)
  • withEmailProvider (301-305)
apps/web/app/api/messages/validation.ts (1)
  • messageQuerySchema (3-6)
apps/web/utils/email/types.ts (1)
  • EmailProvider (44-230)
apps/web/utils/email/provider-types.ts (1)
  • isGoogleProvider (1-3)
⏰ 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: cubic · AI code reviewer
🔇 Additional comments (2)
apps/web/app/api/messages/route.ts (2)

34-46: LGTM! Parameter rename improves consistency.

The rename from userEmail to email throughout the function signature and implementation is a good consistency improvement that aligns with the updated API surface.


14-32: Verify that withEmailProvider includes proper authentication.

After reviewing the middleware implementations in apps/web/utils/middleware.ts, I can confirm that withEmailProvider includes robust authentication and authorization checks:

  1. Authentication chain: withEmailProvideremailProviderMiddlewareemailAccountMiddlewareauthMiddleware, ensuring the user is authenticated.

  2. Authorization (ownership validation):

    • emailAccountMiddleware validates that the emailAccountId from the request header belongs to the authenticated user via the getEmailAccount call
    • emailProviderMiddleware performs an additional ownership check by querying Prisma with both id and userId filters (line 240-241), ensuring the account belongs to the authenticated user

In fact, withEmailProvider is more secure than withEmailAccount alone, as it adds an extra validation layer in the database query. The route correctly operates on messages for a specific email account with proper user scoping.

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.

No issues found across 1 file

@elie222 elie222 merged commit 111523a into main Oct 31, 2025
12 of 13 checks passed
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.

No issues found across 2 files

@aminmoghtader
Copy link

Great work — this is a very practical admin feature and the HMAC-SHA256 change is a sensible move. A few suggestions/questions:
please confirm EMAIL_ENCRYPT_SALT is only provided via environment (secrets manager) and not committed anywhere. Consider documenting rotation guidance (what happens to existing hashes if salt rotates).
are existing hashes compatible after the switch to HMAC-SHA256? If not, we should include a migration plan or note in the changelog.
can we add unit tests for adminHashEmailAction and utils/hash.ts, plus an integration/e2e test for the AdminHashEmail clipboard flow (including toast/loading states)?
ensure hashEmailBody covers odd inputs (capitalization, whitespace, unicode/IDN emails). Consider normalizing emails (lowercase/trim) before hashing if intent is case-insensitive search.
the copy-to-clipboard control should have an accessible label and keyboard support — nice to add aria-live or similar for toast feedback.

Overall this looks solid — thanks for the clear UI feedback and version bump. Once the above is clarified/covered, I’m happy to approve.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

Comments