Skip to content

Comments

Fix empty digest email#744

Merged
elie222 merged 3 commits intomainfrom
fix/empty-digest
Sep 3, 2025
Merged

Fix empty digest email#744
elie222 merged 3 commits intomainfrom
fix/empty-digest

Conversation

@elie222
Copy link
Owner

@elie222 elie222 commented Sep 3, 2025

Summary by CodeRabbit

  • New Features

    • Digest emails now show a clear “No emails to summarize” message when there are no items.
  • Bug Fixes

    • More reliable digest processing and resend behavior, with consistent success responses even when no content is available.
    • Clearer errors and targeted warnings for invalid or unparsable resend requests.
  • Chores

    • Added signature verification to digest processing and resend endpoints for enhanced security.
    • Consolidated and simplified digest endpoints for more consistent behavior.
    • Version bumped to v2.8.3.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 3, 2025

Walkthrough

Adds Upstash/QStash signature verification to digest routes, consolidates and centralizes the AI digest POST handler, switches digest content typing to StoredDigestContent, refactors validation schemas and summarizer exports, updates tests to structural checks, and adds a no-items UI fallback in the digest email component.

Changes

Cohort / File(s) Summary of Changes
AI Digest Route Consolidation & Signature Verification
apps/web/app/api/ai/digest/route.ts
Wrapped POST with verifySignatureAppRouter and withError; consolidated duplicate POST into a single top-level handler; added helpers (resolveRuleName, findOrCreateDigest, updateDigestItem, createDigestItem, upsertDigest); swapped digest upsert type to StoredDigestContent; removed legacy duplicate block.
Resend Digest Routes & Validation
apps/web/app/api/resend/digest/route.ts
Added top-level GET (wrapped with withEmailAccount) and POST (wrapped with withError + verifySignatureAppRouter); added POST body validation (sendDigestEmailBody.safeParse), returns 400 on invalid body; switched content parsing to storedDigestContentSchema and use contentResult.data.content; improved logging; removed old bottom-level exports.
Digest Validation Schema Refactor
apps/web/app/api/resend/digest/validation.ts
Removed digestEmailSummarySchema and related exports; made digestItemSchema and digestSchema private and changed content to string; added storedDigestContentSchema and StoredDigestContent; added public Digest type alias.
AI Summarizer Exports & Tests
apps/web/utils/ai/digest/summarize-email-for-digest.ts, apps/web/utils/ai/digest/summarize-email-for-digest.test.ts
Made summarizer schema and AISummarizeResult internal (no exports); tests removed schema-based validation and now assert result exists and content is a string.
Digest Email No-Items Fallback
packages/resend/emails/digest.tsx
Removed early return for empty digest; render hasItems conditional — existing category sections when items exist, new centered fallback Section with “No emails to summarize in this digest.” when empty.
Verify Import Path Updates
apps/web/app/api/clean/gmail/route.ts, apps/web/app/api/clean/route.ts
Changed verifySignatureAppRouter import from @upstash/qstash/dist/nextjs to @upstash/qstash/nextjs.
Version Bump
version.txt
Updated version string from v2.8.2 to v2.8.3.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant QStash as Upstash/QStash
  participant Client as Client/Worker
  participant Route as /api/ai/digest (POST)
  participant Verify as verifySignatureAppRouter
  participant Handler as POST Handler
  participant DB as Database

  Client->>Route: POST digest payload
  Note over Route,Verify: Signature verification (QStash)
  Route->>Verify: verifySignatureAppRouter wraps handler
  Verify->>Handler: invoke on valid signature
  Handler->>Handler: parse body, load email account, resolve rule name
  Handler->>DB: findOrCreateDigest()
  alt digest item exists
    Handler->>DB: updateDigestItem(content: StoredDigestContent)
  else new item
    Handler->>DB: createDigestItem(content: StoredDigestContent)
  end
  Handler-->>Client: 200 OK (or 200 when skipped)
  Verify-->>Client: 401/403 on invalid signature
  Handler-->>Client: 500 on internal error
Loading
sequenceDiagram
  autonumber
  participant User as Authenticated User
  participant GET as /api/resend/digest (GET)
  participant withAcct as withEmailAccount
  participant Sender as sendEmail

  User->>GET: GET
  GET->>withAcct: withEmailAccount wrapper
  withAcct->>Sender: sendEmail(emailAccountId, force: true)
  Sender-->>User: JSON result (200)
Loading
sequenceDiagram
  autonumber
  participant QStash as Upstash/QStash
  participant POST as /api/resend/digest (POST)
  participant Verify as verifySignatureAppRouter
  participant Body as sendDigestEmailBody.safeParse
  participant Sender as sendEmail

  QStash->>POST: POST { emailAccountId }
  POST->>Verify: verifySignatureAppRouter wraps handler
  Verify->>Body: validate body
  alt valid body
    Body->>Sender: sendEmail(emailAccountId)
    Sender-->>QStash: 200 JSON result
  else invalid body
    Body-->>QStash: 400 Bad Request
  end
  Verify-->>QStash: 401/403 on invalid signature
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

A rabbit taps the digest lane,
QStash signs each hopping train.
When inboxes rest, we softly wait,
Till mails arrive to summarize and state.
Hops, logs, and carrots — code complete. 🥕

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/empty-digest

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

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

Other keywords and placeholders

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

Status, Documentation and Community

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

@vercel
Copy link

vercel bot commented Sep 3, 2025

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

Project Deployment Preview Updated (UTC)
inbox-zero Ready Ready Preview Sep 3, 2025 1:13pm

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: 3

Caution

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

⚠️ Outside diff range comments (1)
apps/web/app/api/resend/digest/route.ts (1)

165-174: Empty digest never sends despite force: true + digests get stuck in PROCESSING.

  • Bug 1: When pendingDigests.length === 0, you log “Force sending empty digest” but later still early-return because executedRulesByRule is empty, so no email is sent on GET. This defeats the PR goal to send an empty digest.
  • Bug 2: If there are pending digests but all items are skipped (e.g., parse/validation fails), you early-return and leave those digests in PROCESSING forever.

Fix: allow send to proceed when force is true, and if you do early-return, revert statuses moved to PROCESSING back to PENDING to avoid marooning.

-    if (Object.keys(executedRulesByRule).length === 0) {
+    if (Object.keys(executedRulesByRule).length === 0 && !force) {
       logger.info(
         "No executed rules found, skipping digest email",
         loggerOptions,
       );
-      return {
-        success: true,
-        message: "No executed rules found, skipping digest email",
-      };
+      // We moved digests to PROCESSING earlier; reset to PENDING to avoid getting stuck.
+      if (processedDigestIds.length) {
+        await prisma.digest.updateMany({
+          where: { id: { in: processedDigestIds } },
+          data: { status: DigestStatus.PENDING },
+        });
+      }
+      return { success: true, message: "No executed rules found, skipping digest email" };
     }

Optional alternative: instead of resetting to PENDING, mark as SENT and redact items if you consider “processed but produced no items” as terminal for those digests; if you do that, do not advance the schedule in this branch.

Also applies to: 265-274

🧹 Nitpick comments (11)
packages/resend/emails/digest.tsx (2)

182-186: Optionally exclude known non-category props from iteration.

Minor: date (and any future non-category props) still flow into digestData and get iterated. Not harmful (normalizeCategoryData returns null), but you can destructure date to keep iteration purely on categories.

Example outside this hunk:

const {
  baseUrl = "https://www.getinboxzero.com",
  unsubscribeToken,
  ruleNames,
  emailAccountId,
  date, // exclude from digestData
  ...digestData
} = props;

342-357: Prefer stable, intention-revealing ordering for categories.

Rendering order currently depends on Object.keys, which can feel arbitrary. Optionally sort by count (desc) for a consistent, content-driven layout and avoid doing work twice (you already scan once for hasItems).

- {hasItems ? (
-   Object.keys(digestData).map((categoryKey) => {
-     const categoryData = normalizeCategoryData(
-       categoryKey,
-       digestData[categoryKey],
-     );
-     if (!categoryData) return null;
-
-     return (
-       <CategorySection
-         key={categoryKey}
-         categoryKey={categoryKey}
-         categoryData={categoryData}
-       />
-     );
-   })
- ) : (
+ {hasItems ? (
+   Object.keys(digestData)
+     .map((categoryKey) => {
+       const categoryData = normalizeCategoryData(categoryKey, digestData[categoryKey]);
+       return categoryData ? { categoryKey, categoryData } : null;
+     })
+     .filter(Boolean) as Array<{ categoryKey: string; categoryData: NormalizedCategoryData }>
+     .sort((a, b) => b.categoryData.count - a.categoryData.count)
+     .map(({ categoryKey, categoryData }) => (
+       <CategorySection
+         key={categoryKey}
+         categoryKey={categoryKey}
+         categoryData={categoryData}
+       />
+     ))
+ ) : (
apps/web/utils/ai/digest/summarize-email-for-digest.ts (2)

39-45: Align prompt with schema to avoid avoidable validation failures.

The instruction “return 'null'” conflicts with the schema requiring { content: string }. Recommend instructing the model to emit an empty string for non-summarizable emails.

- - If the email is spam, promotional, or irrelevant, return "null".
+ - If the email is spam, promotional, or irrelevant, return an empty string for content (i.e., content: "").

58-60: Add minimal context to logs for traceability.

Include ruleName and messageId without leaking content.

-  logger.info("Summarizing email for digest");
+  logger.info("Summarizing email for digest", {
+    ruleName,
+    messageId: userMessageForPrompt.id,
+  });
apps/web/utils/ai/digest/summarize-email-for-digest.test.ts (2)

78-82: Remove redundant assertions.

You already assert with toMatchObject({ content: expect.any(String) }). The additional structure checks duplicate that signal.

-      // Verify the result has the expected structure
-      expect(result).toBeDefined();
-      expect(result).toHaveProperty("content");
-      expect(typeof result?.content).toBe("string");

109-113: Remove redundant assertions.

Same duplication here; keep one style of assertion.

-      // Verify the result has the expected structure
-      expect(result).toBeDefined();
-      expect(result).toHaveProperty("content");
-      expect(typeof result?.content).toBe("string");
apps/web/app/api/resend/digest/validation.ts (1)

3-4: Harden stored content validation (trim + non-empty).

Prevent empty or whitespace-only content from passing validation.

-export const storedDigestContentSchema = z.object({ content: z.string() });
+export const storedDigestContentSchema = z.object({
+  content: z.string().trim().min(1, "content cannot be empty"),
+});
apps/web/app/api/resend/digest/route.ts (4)

151-163: PROCESSING state applied before we know there’s anything to send.

Current flow can set digests to PROCESSING and then exit early (no items), leaving them stuck. The minimal fix is in the earlier comment (reset to PENDING on early return). Longer-term, consider determining whether there’s at least one valid digest item before flipping to PROCESSING.


245-247: Trim error verbosity for Zod issues and avoid logging large objects.

Log a compact, serializable version to keep logs readable and avoid accidental PII sprawl.

-  logger.warn("Failed to validate digest content structure", {
-    messageId: item.messageId,
-    digestId: digest.id,
-    error: contentResult.error,
-  });
+  logger.warn("Failed to validate digest content structure", {
+    messageId: item.messageId,
+    digestId: digest.id,
+    error: contentResult.error.flatten?.() ?? String(contentResult.error),
+  });

Also applies to: 249-255


188-200: Move provider-specific batching/sleep into the provider.

This loop is a good candidate for encapsulation (single source of truth for rate limits, retries, and backoff).

-      for (let i = 0; i < messageIds.length; i += batchSize) {
-        const batch = messageIds.slice(i, i + batchSize);
-        const batchResults = await emailProvider.getMessagesBatch(batch);
-        messages.push(...batchResults);
-        if (i + batchSize < messageIds.length) {
-          await sleep(2000);
-        }
-      }
+      const batchResults = await emailProvider.getMessagesBatchWithRateLimit(messageIds);
+      messages.push(...batchResults);

28-31: Export the GET response type for client-side type safety.

Guideline asks GET routes to export response types. You can alias the existing SendEmailResult.

 type SendEmailResult = {
   success: boolean;
   message: string;
 };
+
+export type ResendDigestGetResponse = SendEmailResult;
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

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

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between a2f869e and 20847d1.

📒 Files selected for processing (6)
  • apps/web/app/api/ai/digest/route.ts (3 hunks)
  • apps/web/app/api/resend/digest/route.ts (3 hunks)
  • apps/web/app/api/resend/digest/validation.ts (1 hunks)
  • apps/web/utils/ai/digest/summarize-email-for-digest.test.ts (2 hunks)
  • apps/web/utils/ai/digest/summarize-email-for-digest.ts (1 hunks)
  • packages/resend/emails/digest.tsx (2 hunks)
🧰 Additional context used
📓 Path-based instructions (19)
!{.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:

  • packages/resend/emails/digest.tsx
  • apps/web/utils/ai/digest/summarize-email-for-digest.ts
  • apps/web/utils/ai/digest/summarize-email-for-digest.test.ts
  • apps/web/app/api/resend/digest/route.ts
  • apps/web/app/api/ai/digest/route.ts
  • apps/web/app/api/resend/digest/validation.ts
**/*.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:

  • packages/resend/emails/digest.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:

  • packages/resend/emails/digest.tsx
  • apps/web/utils/ai/digest/summarize-email-for-digest.ts
  • apps/web/utils/ai/digest/summarize-email-for-digest.test.ts
  • apps/web/app/api/resend/digest/route.ts
  • apps/web/app/api/ai/digest/route.ts
  • apps/web/app/api/resend/digest/validation.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:

  • packages/resend/emails/digest.tsx
  • apps/web/utils/ai/digest/summarize-email-for-digest.ts
  • apps/web/utils/ai/digest/summarize-email-for-digest.test.ts
  • apps/web/app/api/resend/digest/route.ts
  • apps/web/app/api/ai/digest/route.ts
  • apps/web/app/api/resend/digest/validation.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:

  • packages/resend/emails/digest.tsx
  • apps/web/utils/ai/digest/summarize-email-for-digest.ts
  • apps/web/utils/ai/digest/summarize-email-for-digest.test.ts
  • apps/web/app/api/resend/digest/route.ts
  • apps/web/app/api/ai/digest/route.ts
  • apps/web/app/api/resend/digest/validation.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:

  • packages/resend/emails/digest.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:

  • packages/resend/emails/digest.tsx
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/utils/ai/digest/summarize-email-for-digest.ts
  • apps/web/utils/ai/digest/summarize-email-for-digest.test.ts
  • apps/web/app/api/resend/digest/route.ts
  • apps/web/app/api/ai/digest/route.ts
  • apps/web/app/api/resend/digest/validation.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/utils/ai/digest/summarize-email-for-digest.ts
  • apps/web/utils/ai/digest/summarize-email-for-digest.test.ts
  • apps/web/app/api/resend/digest/route.ts
  • apps/web/app/api/ai/digest/route.ts
  • apps/web/app/api/resend/digest/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/ai/digest/summarize-email-for-digest.ts
  • apps/web/utils/ai/digest/summarize-email-for-digest.test.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/ai/digest/summarize-email-for-digest.ts
  • apps/web/utils/ai/digest/summarize-email-for-digest.test.ts
apps/web/utils/{ai,llms}/**/*.ts

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

apps/web/utils/{ai,llms}/**/*.ts: Place LLM-related implementation code under apps/web/utils/ai or apps/web/utils/llms
Keep system and user prompts separate; system defines role/task, user contains data/context
Always validate LLM responses with a specific Zod schema
Use descriptive scoped loggers per feature and log inputs/outputs with appropriate levels and context
Implement early returns for invalid inputs and use proper error types with logging
Add fallbacks for AI failures and include retry logic for transient errors using withRetry
Format prompts with XML-like tags; remove excessive whitespace; truncate overly long inputs; keep formatting consistent
Use TypeScript types for all parameters/returns and define interfaces for complex IO structures
Keep related AI functions co-located; extract shared logic into utilities; document complex AI logic with clear comments
Call LLMs via createGenerateObject; pass system, prompt, and a Zod schema; return the validated result.object
Derive model options using getModel(...) and pass them to createGenerateObject and the generate call

Files:

  • apps/web/utils/ai/digest/summarize-email-for-digest.ts
  • apps/web/utils/ai/digest/summarize-email-for-digest.test.ts
**/*.test.{ts,js}

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

Include security tests in your test suites to verify authentication, authorization, and error handling.

Files:

  • apps/web/utils/ai/digest/summarize-email-for-digest.test.ts
**/*.test.{ts,js,tsx,jsx}

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

**/*.test.{ts,js,tsx,jsx}: Tests are colocated next to the tested file (e.g., dir/format.ts and dir/format.test.ts)
Use vi.mock("server-only", () => ({})); to mock the server-only module in tests
Mock @/utils/prisma in tests using vi.mock("@/utils/prisma") and use the provided prisma mock
Mock external dependencies in tests
Clean up mocks between tests
Do not mock the Logger

Files:

  • apps/web/utils/ai/digest/summarize-email-for-digest.test.ts
**/*.{test,spec}.{js,jsx,ts,tsx}

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

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

Files:

  • apps/web/utils/ai/digest/summarize-email-for-digest.test.ts
apps/web/app/**

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

NextJS app router structure with (app) directory

Files:

  • apps/web/app/api/resend/digest/route.ts
  • apps/web/app/api/ai/digest/route.ts
  • apps/web/app/api/resend/digest/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/resend/digest/route.ts
  • apps/web/app/api/ai/digest/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/resend/digest/route.ts
  • apps/web/app/api/ai/digest/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/resend/digest/route.ts
  • apps/web/app/api/ai/digest/route.ts
  • apps/web/app/api/resend/digest/validation.ts
🧠 Learnings (10)
📚 Learning: 2025-07-17T04:19:57.099Z
Learnt from: edulelis
PR: elie222/inbox-zero#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:

  • packages/resend/emails/digest.tsx
  • apps/web/utils/ai/digest/summarize-email-for-digest.test.ts
  • apps/web/app/api/resend/digest/route.ts
  • apps/web/app/api/ai/digest/route.ts
  • apps/web/app/api/resend/digest/validation.ts
📚 Learning: 2025-08-17T16:57:25.834Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-08-17T16:57:25.834Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.ts : Call LLMs via createGenerateObject; pass system, prompt, and a Zod schema; return the validated result.object

Applied to files:

  • apps/web/utils/ai/digest/summarize-email-for-digest.ts
📚 Learning: 2025-08-31T12:17:19.408Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm-test.mdc:0-0
Timestamp: 2025-08-31T12:17:19.408Z
Learning: Applies to apps/web/__tests__/**/*.test.ts : Test both AI and non-AI code paths (e.g., return unchanged when no AI processing is needed)

Applied to files:

  • apps/web/utils/ai/digest/summarize-email-for-digest.test.ts
📚 Learning: 2025-06-23T12:27:30.570Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-06-23T12:27:30.570Z
Learning: When mocking Prisma in Vitest, import the Prisma mock from '@/utils/__mocks__/prisma', mock '@/utils/prisma', and clear all mocks in a beforeEach hook to ensure test isolation.

Applied to files:

  • apps/web/utils/ai/digest/summarize-email-for-digest.test.ts
📚 Learning: 2025-07-18T15:05:16.146Z
Learnt from: CR
PR: elie222/inbox-zero#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/resend/digest/route.ts
📚 Learning: 2025-07-18T15:05:26.713Z
Learnt from: CR
PR: elie222/inbox-zero#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/resend/digest/route.ts
📚 Learning: 2025-07-18T15:04:30.467Z
Learnt from: CR
PR: elie222/inbox-zero#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/resend/digest/route.ts
📚 Learning: 2025-07-20T09:00:41.968Z
Learnt from: CR
PR: elie222/inbox-zero#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 QStash endpoints (API routes called via publishToQstash or publishToQstashQueue) must use verifySignatureAppRouter to verify request authenticity.

Applied to files:

  • apps/web/app/api/resend/digest/route.ts
  • apps/web/app/api/ai/digest/route.ts
📚 Learning: 2025-07-18T17:27:46.389Z
Learnt from: CR
PR: elie222/inbox-zero#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/resend/digest/route.ts
📚 Learning: 2025-07-18T15:04:30.467Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-18T15:04:30.467Z
Learning: Applies to apps/web/app/** : NextJS app router structure with (app) directory

Applied to files:

  • apps/web/app/api/ai/digest/route.ts
🧬 Code graph analysis (2)
apps/web/app/api/resend/digest/route.ts (7)
apps/web/app/api/resend/digest/all/route.ts (2)
  • GET (75-84)
  • POST (86-97)
apps/web/app/api/resend/summary/route.ts (2)
  • GET (272-281)
  • POST (283-315)
apps/web/utils/middleware.ts (2)
  • withEmailAccount (251-255)
  • withError (243-245)
apps/web/app/api/ai/digest/route.ts (1)
  • POST (14-61)
apps/web/app/api/resend/digest/validation.ts (2)
  • sendDigestEmailBody (14-14)
  • storedDigestContentSchema (3-3)
apps/web/utils/error.ts (1)
  • captureException (63-75)
apps/web/utils/email.ts (1)
  • extractNameFromEmail (9-16)
apps/web/app/api/ai/digest/route.ts (6)
apps/web/app/api/resend/digest/route.ts (1)
  • POST (44-72)
apps/web/utils/middleware.ts (1)
  • withError (243-245)
apps/web/app/api/ai/digest/validation.ts (1)
  • digestBody (3-15)
apps/web/utils/user/get.ts (1)
  • getEmailAccountWithAi (35-62)
apps/web/utils/ai/digest/summarize-email-for-digest.ts (1)
  • aiSummarizeEmailForDigest (16-82)
apps/web/app/api/resend/digest/validation.ts (1)
  • StoredDigestContent (4-4)
🔇 Additional comments (8)
packages/resend/emails/digest.tsx (2)

182-186: Good fallback guard — prevents empty emails.

The hasItems check is clear and avoids the previous early-return pitfall.


359-367: Nice empty state wording.

Clear, reassuring copy for the no-items case.

apps/web/utils/ai/digest/summarize-email-for-digest.ts (1)

11-14: Schema kept internal — aligns with our LLM integration rules.

Validates output via Zod and returns aiResponse.object. Good.

apps/web/app/api/ai/digest/route.ts (2)

14-16: Correct use of verifySignatureAppRouter with withError.

Good protection for a QStash-called endpoint.


165-166: No action needed: schemas match exactly
storedDigestContentSchema is z.object({ content: z.string() }), identical to aiSummarizeEmailForDigest’s output schema—no runtime/type drift.

apps/web/app/api/resend/digest/validation.ts (2)

6-10: Schema alignment with new storage shape looks good.

content: z.string() matches the persisted JSON contract used in routes.


12-16: Keep schema private, export type: good boundary.

Leaner public API while retaining type safety via Digest. No issues.

apps/web/app/api/resend/digest/route.ts (1)

33-43: GET handler is correctly wrapped with withEmailAccount.

Auth/ownership enforced; good use of force: true path (once the early-return bug is fixed).

Comment on lines +19 to +23
const body = digestBody.parse(await request.json());
const { emailAccountId, coldEmailId, actionId, message } = body;

logger.with({ emailAccountId, messageId: message.id });

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Return 400 on invalid body; avoid throwing on parse.

Use safeParse and a consistent error payload per API guidelines.

-      const body = digestBody.parse(await request.json());
-      const { emailAccountId, coldEmailId, actionId, message } = body;
+      const json = await request.json();
+      const parsed = digestBody.safeParse(json);
+      if (!parsed.success) {
+        logger.error("Invalid request body", { error: parsed.error });
+        return NextResponse.json({ error: "Invalid request body" }, { status: 400 });
+      }
+      const { emailAccountId, coldEmailId, actionId, message } = parsed.data;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const body = digestBody.parse(await request.json());
const { emailAccountId, coldEmailId, actionId, message } = body;
logger.with({ emailAccountId, messageId: message.id });
const json = await request.json();
const parsed = digestBody.safeParse(json);
if (!parsed.success) {
logger.error("Invalid request body", { error: parsed.error });
return NextResponse.json({ error: "Invalid request body" }, { status: 400 });
}
const { emailAccountId, coldEmailId, actionId, message } = parsed.data;
logger.with({ emailAccountId, messageId: message.id });
🤖 Prompt for AI Agents
In apps/web/app/api/ai/digest/route.ts around lines 19–23, replace
digestBody.parse(...) with digestBody.safeParse(await request.json()) and branch
on the result; if safeParse returns success: true, proceed and extract {
emailAccountId, coldEmailId, actionId, message } and call logger.with(...). If
success is false, return a 400 response using the API’s standard error payload
(e.g., { error: { type: "validation", message: "<validation summary or first
error>" } }) and avoid throwing so the endpoint consistently returns a JSON 400
for invalid bodies.

@elie222
Copy link
Owner Author

elie222 commented Sep 3, 2025

@claude review

@claude
Copy link

claude bot commented Sep 3, 2025

Claude encountered an error —— View job


I'll analyze this and get back to you.

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/app/api/resend/digest/route.ts (4)

33-42: GET auth flow looks right; export the response type

withEmailAccount for GET is appropriate. To meet our guideline “Export response types from GET routes,” export the SendEmailResult type.

Apply:

- type SendEmailResult = {
+ export type SendEmailResult = {
   success: boolean;
   message: string;
 };

245-259: Skip items with empty content to avoid “empty-looking” sections

You validate structure but still accept empty strings. Trimming and skipping empty content prevents headers with blank bullets and further reduces empty digests.

Apply:

-        const contentResult =
-          storedDigestContentSchema.safeParse(parsedContent);
+        const contentResult =
+          storedDigestContentSchema.safeParse(parsedContent);

         if (contentResult.success) {
-          acc[ruleNameKey].push({
-            content: contentResult.data.content,
+          const trimmed = (contentResult.data.content || "").trim();
+          if (!trimmed) {
+            logger.warn("Empty digest content after validation, skipping item", {
+              messageId: item.messageId,
+              digestId: digest.id,
+            });
+            return;
+          }
+          acc[ruleNameKey].push({
+            content: trimmed,
             from: extractNameFromEmail(message?.headers?.from || ""),
             subject: message?.headers?.subject || "",
           });
         } else {

167-173: Update comment/log to reflect new behavior (no empty digest on force)

The comment/log says “Force sending empty digest,” but later you skip sending when there are no items. Adjust wording to avoid confusion.

Apply:

-      // When force is true, send an empty digest to indicate the system is working
-      logger.info("Force sending empty digest", { emailAccountId });
+      // When force is true, attempt a digest send; if no items, it will be skipped
+      logger.info("Force trigger digest send (may skip due to no items)", { emailAccountId });

17-17: Use path alias for project-root import

Prefer "@/utils/email" over a long relative path for consistency with apps/web path alias usage.

Apply:

-import { extractNameFromEmail } from "../../../../utils/email";
+import { extractNameFromEmail } from "@/utils/email";
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

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

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 20847d1 and 8c802dc.

📒 Files selected for processing (5)
  • apps/web/app/api/ai/digest/route.ts (3 hunks)
  • apps/web/app/api/clean/gmail/route.ts (1 hunks)
  • apps/web/app/api/clean/route.ts (1 hunks)
  • apps/web/app/api/resend/digest/route.ts (3 hunks)
  • version.txt (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • version.txt
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/web/app/api/ai/digest/route.ts
🧰 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/clean/gmail/route.ts
  • apps/web/app/api/clean/route.ts
  • apps/web/app/api/resend/digest/route.ts
apps/web/app/**

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

NextJS app router structure with (app) directory

Files:

  • apps/web/app/api/clean/gmail/route.ts
  • apps/web/app/api/clean/route.ts
  • apps/web/app/api/resend/digest/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/clean/gmail/route.ts
  • apps/web/app/api/clean/route.ts
  • apps/web/app/api/resend/digest/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/clean/gmail/route.ts
  • apps/web/app/api/clean/route.ts
  • apps/web/app/api/resend/digest/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/clean/gmail/route.ts
  • apps/web/app/api/clean/route.ts
  • apps/web/app/api/resend/digest/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/clean/gmail/route.ts
  • apps/web/app/api/clean/route.ts
  • apps/web/app/api/resend/digest/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/clean/gmail/route.ts
  • apps/web/app/api/clean/route.ts
  • apps/web/app/api/resend/digest/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/clean/gmail/route.ts
  • apps/web/app/api/clean/route.ts
  • apps/web/app/api/resend/digest/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/clean/gmail/route.ts
  • apps/web/app/api/clean/route.ts
  • apps/web/app/api/resend/digest/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/clean/gmail/route.ts
  • apps/web/app/api/clean/route.ts
  • apps/web/app/api/resend/digest/route.ts
🧠 Learnings (12)
📓 Common learnings
Learnt from: CR
PR: elie222/inbox-zero#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 QStash endpoints (API routes called via publishToQstash or publishToQstashQueue) must use verifySignatureAppRouter to verify request authenticity.
📚 Learning: 2025-07-20T09:00:41.968Z
Learnt from: CR
PR: elie222/inbox-zero#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 QStash endpoints (API routes called via publishToQstash or publishToQstashQueue) must use verifySignatureAppRouter to verify request authenticity.

Applied to files:

  • apps/web/app/api/clean/gmail/route.ts
  • apps/web/app/api/clean/route.ts
  • apps/web/app/api/resend/digest/route.ts
📚 Learning: 2025-07-18T15:05:34.899Z
Learnt from: CR
PR: elie222/inbox-zero#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/clean/gmail/route.ts
📚 Learning: 2025-07-18T15:04:30.467Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-18T15:04:30.467Z
Learning: Applies to apps/web/app/** : NextJS app router structure with (app) directory

Applied to files:

  • apps/web/app/api/clean/gmail/route.ts
  • apps/web/app/api/clean/route.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/gmail/route.ts
📚 Learning: 2025-07-19T17:50:22.078Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/ui-components.mdc:0-0
Timestamp: 2025-07-19T17:50:22.078Z
Learning: Applies to {components,app}/**/*.tsx : For API get requests to server use the `swr` package

Applied to files:

  • apps/web/app/api/clean/gmail/route.ts
📚 Learning: 2025-07-18T15:04:30.467Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-18T15:04:30.467Z
Learning: Applies to apps/web/**/*.{ts,tsx} : Path aliases: Use `@/` for imports from project root

Applied to files:

  • apps/web/app/api/clean/route.ts
📚 Learning: 2025-07-20T09:00:41.968Z
Learnt from: CR
PR: elie222/inbox-zero#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/resend/digest/route.ts
📚 Learning: 2025-07-17T04:19:57.099Z
Learnt from: edulelis
PR: elie222/inbox-zero#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/app/api/resend/digest/route.ts
📚 Learning: 2025-07-18T15:04:30.467Z
Learnt from: CR
PR: elie222/inbox-zero#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/resend/digest/route.ts
📚 Learning: 2025-07-18T15:05:26.713Z
Learnt from: CR
PR: elie222/inbox-zero#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/resend/digest/route.ts
📚 Learning: 2025-07-18T17:27:46.389Z
Learnt from: CR
PR: elie222/inbox-zero#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/resend/digest/route.ts
🧬 Code graph analysis (1)
apps/web/app/api/resend/digest/route.ts (5)
apps/web/utils/middleware.ts (2)
  • withEmailAccount (251-255)
  • withError (243-245)
apps/web/app/api/ai/digest/route.ts (1)
  • POST (14-61)
apps/web/app/api/resend/digest/validation.ts (2)
  • sendDigestEmailBody (14-14)
  • storedDigestContentSchema (3-3)
apps/web/utils/error.ts (1)
  • captureException (63-75)
apps/web/utils/email.ts (1)
  • extractNameFromEmail (9-16)
🔇 Additional comments (4)
apps/web/app/api/clean/gmail/route.ts (1)

2-2: Correct QStash import path

Importing verifySignatureAppRouter from "@upstash/qstash/nextjs" is the documented, stable path. Good fix.

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

1-1: Correct QStash import path

Alignment with the official "@upstash/qstash/nextjs" entry point looks good and keeps this route consistent with others.

apps/web/app/api/resend/digest/route.ts (2)

19-19: QStash signature verification is correctly wired

POST is wrapped with withError + verifySignatureAppRouter, matching the security rule for QStash endpoints.


11-15: Digest type export & shape verified
The Digest type is exported from validation.ts as z.infer<typeof digestSchema>, which resolves to Record<string, ({ from: string; subject: string; content: string }[] | undefined)>, matching the expected structure.

@elie222 elie222 merged commit 6c97e33 into main Sep 3, 2025
13 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Dec 18, 2025
@elie222 elie222 deleted the fix/empty-digest branch December 18, 2025 23:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant