Only allow clean if active premium account#795
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
There was a problem hiding this comment.
1 issue found across 5 files
Prompt for AI agents (all 1 issues)
Understand the root cause of the following 1 issues and fix them.
<file name="apps/web/utils/user/get.ts">
<violation number="1" location="apps/web/utils/user/get.ts:111">
Using || here converts false to null; use nullish coalescing to preserve false.</violation>
</file>
React with 👍 or 👎 to teach cubic. Mention @cubic-dev-ai to give feedback, ask questions, or re-run the review.
|
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. WalkthroughAdds active premium gating across clean flows. Introduces isActivePremium and getUserPremium utilities. Enforces premium checks in API route and server action before Gmail operations. Updates PremiumAlert to support activeOnly and trial handling. Adds PremiumAlert to Clean Intro UI and tweaks spacing in Automation page. Bumps version. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant U as User
participant API as /api/clean
participant DB as getUserPremium
participant Prem as isActivePremium
participant G as Gmail Client
participant S as Cleaner
U->>API: POST clean
API->>DB: Fetch premium by userId
DB-->>API: premium|null
API->>Prem: Check active
Prem-->>API: true/false
alt Not premium or inactive
API-->>U: SafeError("User not premium/active")
else Active
API->>G: Create client
API->>S: Execute clean
API-->>U: Success response
end
sequenceDiagram
autonumber
participant UI as Client
participant ACT as cleanInboxAction
participant DB as getUserPremium
participant Prem as isActivePremium
participant G as Gmail Client
participant L as Label Setup
participant Q as Queue (Qstash)
UI->>ACT: Invoke with { emailAccountId, provider, userId }
ACT->>ACT: Validate provider=google
ACT->>DB: Fetch premium
DB-->>ACT: premium|null
ACT->>Prem: isActivePremium(premium)
Prem-->>ACT: true/false
alt Not premium or inactive
ACT-->>UI: SafeError
else Active
ACT->>G: Create client
ACT->>L: Ensure labels
ACT->>Q: Publish clean job
ACT-->>UI: Job enqueued
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests
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 |
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
apps/web/utils/user/get.ts (1)
111-111: Use nullish coalescing instead of || to preserve falsy-but-valid values.Prevents accidental coercion.
Apply:
- return user?.premium || null; + return user?.premium ?? null;
🧹 Nitpick comments (7)
apps/web/utils/user/get.ts (1)
1-4: Add explicit return type and type import for stronger typings.Clarifies API and aids inference across call sites.
Apply:
import prisma from "@/utils/prisma"; import type { EmailAccountWithAI } from "@/utils/llms/types"; -import type { Prisma } from "@prisma/client"; +import type { Prisma, Premium } from "@prisma/client"; @@ -export async function getUserPremium({ userId }: { userId: string }) { +export async function getUserPremium({ + userId, +}: { + userId: string; +}): Promise<Premium | null> { const user = await prisma.user.findUnique({ where: { id: userId }, select: { premium: true }, }); - return user?.premium || null; + return user?.premium ?? null; }Also applies to: 105-112
apps/web/utils/actions/clean.ts (2)
134-139: Log uses stalenextPageTokenvalue.You log before assigning; prefer logging
pageTokento reflect the current fetch.Apply:
- logger.info("Fetched threads", { - emailAccountId, - threadCount: threads.length, - nextPageToken, - }); + logger.info("Fetched threads", { + emailAccountId, + threadCount: threads.length, + nextPageToken: pageToken, + });
50-53: Consider returning 402 for premium gating for clearer client handling.Optional, but
SafeError("…", 402)can improve UI flows.Apply:
- if (!premium) throw new SafeError("User not premium"); - if (!isActivePremium(premium)) throw new SafeError("Premium not active"); + if (!premium) throw new SafeError("User not premium", 402); + if (!isActivePremium(premium)) throw new SafeError("Premium not active", 402);apps/web/app/api/clean/route.ts (2)
74-77: Optionally include HTTP 402 for premium gating.Improves downstream handling without exposing internals.
Apply:
- if (!premium) throw new SafeError("User not premium"); - if (!isActivePremium(premium)) throw new SafeError("Premium not active"); + if (!premium) throw new SafeError("User not premium", 402); + if (!isActivePremium(premium)) throw new SafeError("Premium not active", 402);
74-77: Deduplicate premium gating via a small helper to reduce drift.Extract
assertActivePremium(userId)in utils and reuse here and in the server action.Proposed helper:
// apps/web/utils/premium/assert.ts import { getUserPremium } from "@/utils/user/get"; import { isActivePremium } from "@/utils/premium"; import { SafeError } from "@/utils/error"; export async function assertActivePremium(userId: string) { const premium = await getUserPremium({ userId }); if (!premium) throw new SafeError("User not premium", 402); if (!isActivePremium(premium)) throw new SafeError("Premium not active", 402); return premium; }Then replace local checks with:
await assertActivePremium(emailAccount.userId);Also applies to: 50-67, 31-47
apps/web/components/PremiumAlert.tsx (2)
48-56: Narrow the type of stripeSubscriptionStatus.Avoid plain string; use a string union to encode known statuses for safer checks.
Example:
export type StripeSubscriptionStatus = "active" | "trialing" | "past_due" | "canceled" | "incomplete" | "incomplete_expired" | null; export function PremiumAiAssistantAlert({ showSetApiKey, className, tier, stripeSubscriptionStatus, activeOnly, }: { showSetApiKey: boolean; className?: string; tier?: PremiumTier | null; stripeSubscriptionStatus?: StripeSubscriptionStatus; activeOnly?: boolean; }) { /* ... */ }
62-75: Make the status check boolean and fix misleading copy.The variable is not boolean and the description implies “trial” only, but the condition matches any non-active status.
- const isStripeTrialing = - stripeSubscriptionStatus && stripeSubscriptionStatus !== "active"; - - if (activeOnly && isStripeTrialing) { + const isActiveSubscription = stripeSubscriptionStatus === "active"; + if (activeOnly && !isActiveSubscription) { return ( <div className={className}> <ActionCard icon={<CrownIcon className="h-5 w-5" />} title="Active Subscription Required" - description="This feature is not available on trial plans." + description="This feature requires an active subscription." /> </div> ); }
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (8)
apps/web/app/(app)/[emailAccountId]/automation/page.tsx(1 hunks)apps/web/app/(app)/[emailAccountId]/clean/IntroStep.tsx(2 hunks)apps/web/app/api/clean/route.ts(3 hunks)apps/web/components/PremiumAlert.tsx(3 hunks)apps/web/utils/actions/clean.ts(3 hunks)apps/web/utils/premium/index.ts(1 hunks)apps/web/utils/user/get.ts(1 hunks)version.txt(1 hunks)
🧰 Additional context used
📓 Path-based instructions (23)
!{.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:
version.txtapps/web/components/PremiumAlert.tsxapps/web/utils/actions/clean.tsapps/web/utils/user/get.tsapps/web/app/(app)/[emailAccountId]/automation/page.tsxapps/web/utils/premium/index.tsapps/web/app/(app)/[emailAccountId]/clean/IntroStep.tsxapps/web/app/api/clean/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:
version.txtapps/web/components/PremiumAlert.tsxapps/web/utils/actions/clean.tsapps/web/utils/user/get.tsapps/web/app/(app)/[emailAccountId]/automation/page.tsxapps/web/utils/premium/index.tsapps/web/app/(app)/[emailAccountId]/clean/IntroStep.tsxapps/web/app/api/clean/route.ts
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/components/PremiumAlert.tsxapps/web/utils/actions/clean.tsapps/web/utils/user/get.tsapps/web/app/(app)/[emailAccountId]/automation/page.tsxapps/web/utils/premium/index.tsapps/web/app/(app)/[emailAccountId]/clean/IntroStep.tsxapps/web/app/api/clean/route.ts
apps/web/**/*.tsx
📄 CodeRabbit inference engine (apps/web/CLAUDE.md)
apps/web/**/*.tsx: Follow tailwindcss patterns with prettier-plugin-tailwindcss
Prefer functional components with hooks
Use shadcn/ui components when available
Ensure responsive design with mobile-first approach
Follow consistent naming conventions (PascalCase for components)
Use LoadingContent component for async data
Useresult?.serverErrorwithtoastErrorandtoastSuccess
UseLoadingContentcomponent to handle loading and error states consistently
Passloading,error, and children props toLoadingContent
Files:
apps/web/components/PremiumAlert.tsxapps/web/app/(app)/[emailAccountId]/automation/page.tsxapps/web/app/(app)/[emailAccountId]/clean/IntroStep.tsx
apps/web/components/**/*.tsx
📄 CodeRabbit inference engine (apps/web/CLAUDE.md)
Use React Hook Form with Zod validation for form handling
Use the
LoadingContentcomponent to handle loading and error states consistently in data-fetching components.Use PascalCase for components (e.g.
components/Button.tsx)
Files:
apps/web/components/PremiumAlert.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/components/PremiumAlert.tsxapps/web/app/(app)/[emailAccountId]/automation/page.tsxapps/web/app/(app)/[emailAccountId]/clean/IntroStep.tsx
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/logging.mdc)
**/*.{ts,tsx}: UsecreateScopedLoggerfor logging in backend TypeScript files
Typically add the logger initialization at the top of the file when usingcreateScopedLogger
Only use.with()on a logger instance within a specific function, not for a global loggerImport 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/components/PremiumAlert.tsxapps/web/utils/actions/clean.tsapps/web/utils/user/get.tsapps/web/app/(app)/[emailAccountId]/automation/page.tsxapps/web/utils/premium/index.tsapps/web/app/(app)/[emailAccountId]/clean/IntroStep.tsxapps/web/app/api/clean/route.ts
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)
**/*.{js,jsx,ts,tsx}: Don't useelements 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/components/PremiumAlert.tsxapps/web/utils/actions/clean.tsapps/web/utils/user/get.tsapps/web/app/(app)/[emailAccountId]/automation/page.tsxapps/web/utils/premium/index.tsapps/web/app/(app)/[emailAccountId]/clean/IntroStep.tsxapps/web/app/api/clean/route.ts
**/*.{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/components/PremiumAlert.tsxapps/web/app/(app)/[emailAccountId]/automation/page.tsxapps/web/app/(app)/[emailAccountId]/clean/IntroStep.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/components/PremiumAlert.tsxapps/web/app/(app)/[emailAccountId]/automation/page.tsxapps/web/app/(app)/[emailAccountId]/clean/IntroStep.tsxapps/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-actionprovides centralized error handling
Use Zod schemas for validation on both client and server
UserevalidatePathin server actions for cache invalidation
apps/web/utils/actions/**/*.ts: Use server actions (withnext-safe-action) for all mutations (create/update/delete operations); do NOT use POST API routes for mutations.
UserevalidatePathin server actions to invalidate cache after mutations.Files:
apps/web/utils/actions/clean.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 ZodFiles:
apps/web/utils/actions/clean.tsapps/web/utils/user/get.tsapps/web/utils/premium/index.tsapps/web/app/api/clean/route.tsapps/web/utils/actions/*.ts
📄 CodeRabbit inference engine (.cursor/rules/server-actions.mdc)
apps/web/utils/actions/*.ts: Implement all server actions using thenext-safe-actionlibrary for type safety, input validation, context management, and error handling. Refer toapps/web/utils/actions/safe-action.tsfor client definitions (actionClient,actionClientUser,adminActionClient).
UseactionClientUserwhen only authenticated user context (userId) is needed.
UseactionClientwhen both authenticated user context and a specificemailAccountIdare needed. TheemailAccountIdmust be bound when calling the action from the client.
UseadminActionClientfor actions restricted to admin users.
Access necessary context (likeuserId,emailAccountId, etc.) provided by the safe action client via thectxobject 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.
UseSafeErrorfor expected/handled errors within actions if needed.next-safe-actionprovides centralized error handling.
Use the.metadata({ name: "actionName" })method to provide a meaningful name for monitoring. Sentry instrumentation is automatically applied viawithServerActionInstrumentationwithin the safe action clients.
If an action modifies data displayed elsewhere, userevalidatePathorrevalidateTagfromnext/cachewithin the action handler as needed.Server action files must start with
use serverFiles:
apps/web/utils/actions/clean.tsapps/web/utils/**
📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)
Create utility functions in
utils/folder for reusable logicFiles:
apps/web/utils/actions/clean.tsapps/web/utils/user/get.tsapps/web/utils/premium/index.tsapps/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 sizeFiles:
apps/web/utils/actions/clean.tsapps/web/utils/user/get.tsapps/web/utils/premium/index.tsapps/web/app/**
📄 CodeRabbit inference engine (apps/web/CLAUDE.md)
NextJS app router structure with (app) directory
Files:
apps/web/app/(app)/[emailAccountId]/automation/page.tsxapps/web/app/(app)/[emailAccountId]/clean/IntroStep.tsxapps/web/app/api/clean/route.tsapps/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)/[emailAccountId]/automation/page.tsxapps/web/app/(app)/[emailAccountId]/clean/IntroStep.tsxapps/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)/[emailAccountId]/automation/page.tsxapps/web/app/(app)/[emailAccountId]/clean/IntroStep.tsxapps/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)/[emailAccountId]/automation/page.tsxapps/web/app/(app)/[emailAccountId]/clean/IntroStep.tsxapps/web/app/**/*.tsx
📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)
Components with
onClickmust be client components withuse clientdirectiveFiles:
apps/web/app/(app)/[emailAccountId]/automation/page.tsxapps/web/app/(app)/[emailAccountId]/clean/IntroStep.tsxapps/web/app/api/**/route.ts
📄 CodeRabbit inference engine (apps/web/CLAUDE.md)
apps/web/app/api/**/route.ts: UsewithAuthfor user-level operations
UsewithEmailAccountfor 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 withwithAuthorwithEmailAccountmiddleware 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/clean/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).
UsewithEmailAccountmiddleware for API routes that operate on a specific email account (i.e., use or requireemailAccountId).
UsewithAuthmiddleware for API routes that operate at the user level (i.e., use or require onlyuserId).
UsewithErrormiddleware (with proper validation) for public endpoints, custom authentication, or cron endpoints.
Cron endpoints MUST usewithErrormiddleware and validate the cron secret usinghasCronSecret(request)orhasPostCronSecret(request).
Cron endpoints MUST capture unauthorized attempts withcaptureExceptionand 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.
AllfindUniqueandfindFirstPrisma calls in API routes MUST include ownership filters (e.g., userId or emailAccountId).
AllfindManyPrisma 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/clean/route.tsapps/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/clean/route.ts🧠 Learnings (3)
📚 Learning: 2025-07-18T17:27:58.249Z
Learnt from: CR PR: elie222/inbox-zero#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/clean.ts📚 Learning: 2025-07-08T13:14:07.449Z
Learnt from: elie222 PR: elie222/inbox-zero#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/utils/actions/clean.ts📚 Learning: 2025-07-19T17:50:28.270Z
Learnt from: CR PR: elie222/inbox-zero#0 File: .cursor/rules/utilities.mdc:0-0 Timestamp: 2025-07-19T17:50:28.270Z Learning: The `utils` folder also contains core app logic such as Next.js Server Actions and Gmail API requests.Applied to files:
apps/web/app/api/clean/route.ts🧬 Code graph analysis (5)
apps/web/components/PremiumAlert.tsx (1)
apps/web/app/(app)/premium/PremiumModal.tsx (1)
usePremiumModal(5-25)apps/web/utils/actions/clean.ts (3)
apps/web/utils/user/get.ts (1)
getUserPremium(105-112)apps/web/utils/error.ts (1)
SafeError(86-96)apps/web/utils/premium/index.ts (1)
isActivePremium(24-36)apps/web/app/(app)/[emailAccountId]/automation/page.tsx (1)
apps/web/components/PremiumAlert.tsx (1)
PremiumAlertWithData(110-140)apps/web/app/(app)/[emailAccountId]/clean/IntroStep.tsx (1)
apps/web/components/PremiumAlert.tsx (1)
PremiumAlertWithData(110-140)apps/web/app/api/clean/route.ts (3)
apps/web/utils/user/get.ts (1)
getUserPremium(105-112)apps/web/utils/error.ts (1)
SafeError(86-96)apps/web/utils/premium/index.ts (1)
isActivePremium(24-36)🔇 Additional comments (9)
version.txt (1)
1-1: Version bump looks good.No issues.
apps/web/utils/premium/index.ts (1)
24-36: Active premium gating logic is correct and aligned with objective.Excludes Stripe “trialing” while honoring Lemon Squeezy renewals. Good separation from broader
isPremium.apps/web/utils/actions/clean.ts (3)
50-53: Premium checks in server action are in the right place (pre-Gmail).Logic and ordering look good.
198-224: Confirm intent: undo/change actions not gated by active premium.If the product should block all Gmail mutations when inactive, add the same checks here; if not, ignore.
Also applies to: 263-324
41-41: No change required — actionClient populates userId on ctx.
actionClient's middleware injects userId (along with userEmail, emailAccountId, provider, logger, session) into ctx before calling next, so ctx.userId will be defined at runtime.apps/web/app/api/clean/route.ts (1)
74-77: Premium checks before Gmail client creation are correct.Prevents unnecessary token refresh and Gmail calls.
apps/web/app/(app)/[emailAccountId]/automation/page.tsx (1)
89-89: Spacing tweak LGTM.mb-8 reads better in this layout; no functional impact.
apps/web/app/(app)/[emailAccountId]/clean/IntroStep.tsx (1)
22-23: Good placement, but depends on PremiumAlert fix to actually gate trials.With activeOnly, the alert must not be short-circuited by AI access; see suggested fix in PremiumAlert.tsx.
apps/web/components/PremiumAlert.tsx (1)
117-135: I’ve requested the relevant snippet for verification. [pending_results]
| {unhandledCount === null ? ( | ||
| <SectionDescription className="mx-auto mt-2 max-w-prose"> | ||
| You have {unhandledCount.toLocaleString()}{" "} | ||
| {cleanAction === CleanAction.ARCHIVE ? "unarchived" : "unread"}{" "} | ||
| emails in your inbox. | ||
| Checking your inbox... | ||
| </SectionDescription> | ||
| <SectionDescription className="mx-auto mt-2 max-w-prose"> | ||
| Let's clean up your inbox while keeping important emails safe. | ||
| </SectionDescription> | ||
| </> | ||
| )} | ||
| ) : ( | ||
| <> | ||
| <SectionDescription className="mx-auto mt-2 max-w-prose"> | ||
| You have {unhandledCount.toLocaleString()}{" "} | ||
| {cleanAction === CleanAction.ARCHIVE ? "unarchived" : "unread"}{" "} | ||
| emails in your inbox. | ||
| </SectionDescription> | ||
| <SectionDescription className="mx-auto mt-2 max-w-prose"> | ||
| Let's clean up your inbox while keeping important emails safe. | ||
| </SectionDescription> | ||
| </> | ||
| )} | ||
|
|
||
| <div className="mt-6"> | ||
| <Button onClick={onNext} disabled={unhandledCount === null}> | ||
| Next | ||
| </Button> | ||
| <div className="mt-6"> | ||
| <Button onClick={onNext} disabled={unhandledCount === null}> | ||
| Next | ||
| </Button> |
There was a problem hiding this comment.
🧩 Analysis chain
Type mismatch: unhandledCount compared to null but typed as number.
Either change the prop type to number | null or remove the null checks. Prefer widening the type.
Proposed signature (outside this hunk):
export function IntroStep({
unhandledCount,
cleanAction,
}: {
unhandledCount: number | null;
cleanAction: CleanAction;
}) { /* ... */ }🏁 Script executed:
#!/bin/bash
# Verify the IntroStep prop type and all call sites expect number|null
rg -nC2 'IntroStep\(' apps/web | sed -n '1,200p'
rg -nP 'unhandledCount:\s*(number( \| null)?)' --type=ts --type=tsxLength of output: 920
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "---- locate export function IntroStep occurrences ----"
rg -n --hidden -S 'export function IntroStep' apps/web || true
echo
target='apps/web/app/(app)/[emailAccountId]/clean/IntroStep.tsx'
echo "---- show: $target ----"
if [ -f "$target" ]; then
sed -n '1,300p' "$target"
else
echo "File not found: $target"
fi
echo
echo "---- search for other files mentioning IntroStep (usages/definitions) ----"
rg -n --hidden -S '\bIntroStep\b' apps/web || true
echo
echo "---- search for 'unhandledCount' usages across repo ----"
rg -n --hidden -S '\bunhandledCount\b' apps/web || true
echo
echo "---- search for Props/type declarations referencing unhandledCount or IntroStep props ----"
rg -n --hidden -S 'unhandledCount|IntroStepProps|Intro.*Props|interface .*Props|type .*Props' apps/web || trueLength of output: 17404
🏁 Script executed:
#!/bin/bash
set -euo pipefail
file='apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx'
echo "---- show: $file ----"
if [ -f "$file" ]; then
sed -n '1,240p' "$file"
else
echo "File not found: $file"
fiLength of output: 3258
🏁 Script executed:
#!/bin/bash
set -euo pipefail
file='apps/web/utils/assess.ts'
echo "---- show: $file (lines 1-240) ----"
if [ -f "$file" ]; then
sed -n '1,240p' "$file"
else
echo "File not found: $file"
fiLength of output: 5372
Make IntroStep.unhandledCount nullable (number | null)
IntroStep compares unhandledCount to null (e.g. unhandledCount === null and disabled={unhandledCount === null}) but the prop is declared as number — this produces a TypeScript "condition always false" error. Widen the prop to number | null.
File: apps/web/app/(app)/[emailAccountId]/clean/IntroStep.tsx — change the prop signature:
export function IntroStep({
unhandledCount,
cleanAction,
}: {
unhandledCount: number | null;
cleanAction: CleanAction;
}) { /* ... */ }🤖 Prompt for AI Agents
In apps/web/app/(app)/[emailAccountId]/clean/IntroStep.tsx around lines 37 to
57, the component treats unhandledCount as possibly null but its prop type is
declared as number, causing a TS "condition always false" error; change the prop
signature to widen unhandledCount to number | null (update the function props
type to accept unhandledCount: number | null) so the null checks and disabled
prop are valid, and run TypeScript to ensure no other call sites need updates.
Summary by CodeRabbit
New Features
Style
Chores