Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
WalkthroughIntroduces early-exit guards in the AI digest POST route to skip processing for assistant or RESEND_FROM_EMAIL messages, adjusts eligibility window in the resend digest-all route from 4 days to 1 day, applies a minor formatting change in a feature flag hook, and bumps version to v2.9.27. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant C as Client
participant R as AI Digest Route
participant G as Guards
participant S as Summarizer/DB
C->>R: POST /api/ai/digest
R->>G: Check sender (assistant or RESEND_FROM_EMAIL)
alt Guard matched (skip)
G-->>R: Skip processing
R-->>C: 200 OK (no-op)
else Proceed
R->>S: Summarize + Upsert Digest
S-->>R: Result
R-->>C: 200 OK (processed)
end
rect rgba(230, 246, 255, 0.6)
note right of G: New early-exit guards
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 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
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/ai/digest/route.ts (1)
24-25: Logger context dropped:.with()result unused
.with()likely returns a child logger; current call doesn’t persist context.Create a child and use it for subsequent logs:
- const logger = createScopedLogger("digest"); + const baseLogger = createScopedLogger("digest"); ... - logger.with({ emailAccountId, messageId: message.id }); + const logger = baseLogger.with({ emailAccountId, messageId: message.id });Then replace later
logger.calls within this handler with the newlogger(or rename tologif preferred).
🧹 Nitpick comments (3)
apps/web/hooks/useFeatureFlags.ts (1)
63-66: Formatting-only change—OKVariant typing and control fallback remain correct.
Consider extracting "welcome-testimonial" into a const (like HERO_FLAG_NAME) to avoid stringly-typed keys.
apps/web/app/api/resend/digest/all/route.ts (1)
37-38: Confirm 4→1 day eligibility changeThis will include newer accounts (age > 1 day vs > 4 days) and increase send volume. Intentional?
If this is tunable, consider env-driven config:
-import subDays from "date-fns/subDays"; +import subDays from "date-fns/subDays"; +import { env } from "@/env"; - createdAt: { - lt: subDays(now, 1), - }, + createdAt: { + lt: subDays(now, Number(env.DIGEST_MIN_ACCOUNT_AGE_DAYS ?? 1)), + },apps/web/app/api/ai/digest/route.ts (1)
39-47: Assistant-originated skip—good guardPrevents self/assistant echoes from polluting digests.
Consider extracting both skip checks into a
shouldSkipDigest(message, emailAccount)helper for easier unit testing.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
apps/web/app/api/ai/digest/route.ts(2 hunks)apps/web/app/api/resend/digest/all/route.ts(2 hunks)apps/web/hooks/useFeatureFlags.ts(1 hunks)version.txt(1 hunks)
🧰 Additional context used
📓 Path-based instructions (15)
!{.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/app/api/ai/digest/route.tsapps/web/app/api/resend/digest/all/route.tsapps/web/hooks/useFeatureFlags.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/app/api/ai/digest/route.tsapps/web/app/api/resend/digest/all/route.tsapps/web/hooks/useFeatureFlags.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/app/api/ai/digest/route.tsapps/web/app/api/resend/digest/all/route.tsapps/web/hooks/useFeatureFlags.ts
apps/web/app/**
📄 CodeRabbit inference engine (apps/web/CLAUDE.md)
NextJS app router structure with (app) directory
Files:
apps/web/app/api/ai/digest/route.tsapps/web/app/api/resend/digest/all/route.ts
apps/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/ai/digest/route.tsapps/web/app/api/resend/digest/all/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/ai/digest/route.tsapps/web/app/api/resend/digest/all/route.tsapps/web/hooks/useFeatureFlags.ts
**/*.{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/app/api/ai/digest/route.tsapps/web/app/api/resend/digest/all/route.tsapps/web/hooks/useFeatureFlags.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/ai/digest/route.tsapps/web/app/api/resend/digest/all/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/ai/digest/route.tsapps/web/app/api/resend/digest/all/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/app/api/ai/digest/route.tsapps/web/app/api/resend/digest/all/route.tsapps/web/hooks/useFeatureFlags.ts
apps/web/hooks/**/*.ts
📄 CodeRabbit inference engine (apps/web/CLAUDE.md)
Use SWR for efficient data fetching and caching
apps/web/hooks/**/*.ts: Use SWR for client-side data fetching and caching.
Callmutate()after successful mutations to refresh SWR data on the client.
Files:
apps/web/hooks/useFeatureFlags.ts
apps/web/hooks/**/*.{ts,tsx}
📄 CodeRabbit inference engine (apps/web/CLAUDE.md)
Call
mutate()after successful mutations to refresh data
Files:
apps/web/hooks/useFeatureFlags.ts
apps/web/hooks/**/*.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/hooks.mdc)
Place custom hooks in the
apps/web/hooks/directory.
Files:
apps/web/hooks/useFeatureFlags.ts
apps/web/hooks/use*.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/hooks.mdc)
apps/web/hooks/use*.{js,jsx,ts,tsx}: Name custom hooks with theuseprefix (e.g.,useAccounts.ts).
For fetching data from API endpoints in custom hooks, prefer usinguseSWR.
Create dedicated hooks for specific data types (e.g.,useAccounts,useLabels).
Custom hooks should encapsulate reusable stateful logic, especially for data fetching or complex UI interactions.
Keep custom hooks focused on a single responsibility.
Files:
apps/web/hooks/useFeatureFlags.ts
apps/web/hooks/useFeatureFlags.ts
📄 CodeRabbit inference engine (.cursor/rules/posthog-feature-flags.mdc)
apps/web/hooks/useFeatureFlags.ts: All feature flag hooks should be defined in apps/web/hooks/useFeatureFlags.ts
Use kebab-case for feature flag keys (e.g., 'inbox-cleaner', 'pricing-options-2')
Use 'use[FeatureName]Enabled' for boolean flag hook names and 'use[FeatureName]Variant' for variant flag hook names
Always define types for variant flags
Always provide a default/control fallback for variant flags
Keep all feature flag hooks centralized in useFeatureFlags.ts
Files:
apps/web/hooks/useFeatureFlags.ts
🧠 Learnings (9)
📚 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/ai/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/ai/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/all/route.ts
📚 Learning: 2025-07-18T15:07:12.415Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/posthog-feature-flags.mdc:0-0
Timestamp: 2025-07-18T15:07:12.415Z
Learning: Applies to apps/web/hooks/useFeatureFlags.ts : Use 'use[FeatureName]Enabled' for boolean flag hook names and 'use[FeatureName]Variant' for variant flag hook names
Applied to files:
apps/web/hooks/useFeatureFlags.ts
📚 Learning: 2025-07-18T15:07:12.415Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/posthog-feature-flags.mdc:0-0
Timestamp: 2025-07-18T15:07:12.415Z
Learning: Applies to apps/web/hooks/useFeatureFlags.ts : Always define types for variant flags
Applied to files:
apps/web/hooks/useFeatureFlags.ts
📚 Learning: 2025-07-18T15:07:12.415Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/posthog-feature-flags.mdc:0-0
Timestamp: 2025-07-18T15:07:12.415Z
Learning: Applies to apps/web/hooks/useFeatureFlags.ts : Keep all feature flag hooks centralized in useFeatureFlags.ts
Applied to files:
apps/web/hooks/useFeatureFlags.ts
📚 Learning: 2025-07-18T15:07:12.415Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/posthog-feature-flags.mdc:0-0
Timestamp: 2025-07-18T15:07:12.415Z
Learning: Applies to apps/web/hooks/useFeatureFlags.ts : All feature flag hooks should be defined in apps/web/hooks/useFeatureFlags.ts
Applied to files:
apps/web/hooks/useFeatureFlags.ts
📚 Learning: 2025-07-18T15:07:12.415Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/posthog-feature-flags.mdc:0-0
Timestamp: 2025-07-18T15:07:12.415Z
Learning: Applies to apps/web/hooks/useFeatureFlags.ts : Always provide a default/control fallback for variant flags
Applied to files:
apps/web/hooks/useFeatureFlags.ts
📚 Learning: 2025-07-18T15:07:12.415Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/posthog-feature-flags.mdc:0-0
Timestamp: 2025-07-18T15:07:12.415Z
Learning: Applies to apps/web/hooks/useFeatureFlags.ts : Use kebab-case for feature flag keys (e.g., 'inbox-cleaner', 'pricing-options-2')
Applied to files:
apps/web/hooks/useFeatureFlags.ts
🧬 Code graph analysis (1)
apps/web/app/api/ai/digest/route.ts (1)
apps/web/env.ts (1)
env(16-235)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: cubic · AI code reviewer
🔇 Additional comments (3)
version.txt (1)
1-1: Version bump looks goodv2.9.27 recorded.
apps/web/app/api/resend/digest/all/route.ts (1)
25-26: No-op query shape change—OK
nextOccurrenceAt: { lte: now }is equivalent to prior formatting.apps/web/app/api/ai/digest/route.ts (1)
13-14: Imports for assistant/ENV—OKNeeded for the new skip guards.
| // Don't summarize Digest emails (this will actually block all emails that we send, but that's okay) | ||
| if (message.from === env.RESEND_FROM_EMAIL) { | ||
| logger.info("Skipping digest item because it is from us"); | ||
| return new NextResponse("OK", { status: 200 }); | ||
| } |
There was a problem hiding this comment.
💡 Verification agent
🧩 Analysis chain
Make “from us” check robust to display names/casing
Direct string equality may miss cases like different display names or casing. Normalize to the bare address before compare.
Apply:
- // Don't summarize Digest emails (this will actually block all emails that we send, but that's okay)
- if (message.from === env.RESEND_FROM_EMAIL) {
+ // Don't summarize any emails we send ourselves
+ const fromAddr =
+ (message.from?.match(/<([^>]+)>/)?.[1] ?? message.from)?.toLowerCase();
+ const resendAddr =
+ (env.RESEND_FROM_EMAIL?.match(/<([^>]+)>/)?.[1] ??
+ env.RESEND_FROM_EMAIL)?.toLowerCase();
+ if (fromAddr && resendAddr && fromAddr === resendAddr) {
logger.info("Skipping digest item because it is from us");
return new NextResponse("OK", { status: 200 });
}You may want to also check Reply-To/Sender if those can differ from From in your pipeline.
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "=== Print file (if exists) ==="
if [ -f "apps/web/app/api/ai/digest/route.ts" ]; then
sed -n '1,240p' apps/web/app/api/ai/digest/route.ts
else
echo "FILE_NOT_FOUND: apps/web/app/api/ai/digest/route.ts"
fi
echo
echo "=== Search for RESEND_FROM_EMAIL across repo ==="
rg -n --hidden --no-ignore-vcs 'RESEND_FROM_EMAIL' || true
echo
echo "=== Search for 'message.from' usage across repo ==="
rg -n --hidden --no-ignore-vcs '\bmessage\.from\b' || true
echo
echo "=== Show surrounding lines for 'message.from' matches (in file if present) ==="
rg -n -C3 '\bmessage\.from\b' apps -S || true
echo
echo "=== Show env exports / definitions that reference RESEND_FROM_EMAIL (common places) ==="
rg -n --hidden --no-ignore-vcs 'RESEND_FROM_EMAIL' -S || trueLength of output: 9624
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "=== rg digestBody ==="
rg -n 'digestBody' -S || true
echo
echo "=== validation file (if exists) ==="
if [ -f "apps/web/app/api/ai/digest/validation.ts" ]; then
sed -n '1,240p' apps/web/app/api/ai/digest/validation.ts
else
echo "NOT_FOUND: apps/web/app/api/ai/digest/validation.ts"
fi
echo
echo "=== env.ts ==="
sed -n '1,240p' apps/web/env.ts || true
echo
echo "=== resend summary route (around 220-260) ==="
sed -n '200,300p' apps/web/app/api/resend/summary/route.ts || true
echo
echo "=== resend digest route (around 270-300) ==="
sed -n '260,320p' apps/web/app/api/resend/digest/route.ts || true
echo
echo "=== outlook message mapping (around 320-360) ==="
sed -n '320,380p' apps/web/utils/outlook/message.ts || true
echo
echo "=== microsoft email parsing (around 740-780) ==="
sed -n '720,800p' apps/web/utils/email/microsoft.ts || true
echo
echo "=== assistant is-assistant-email utility ==="
sed -n '1,240p' apps/web/utils/assistant/is-assistant-email.ts || true
echo
echo "=== ai group find-receipts snippet (around 120-140) ==="
sed -n '110,140p' apps/web/utils/ai/group/find-receipts.ts || trueLength of output: 21445
Make “from us” check robust to display names/casing
Strict equality fails because env.RESEND_FROM_EMAIL defaults to a display-name form (e.g. "Inbox Zero updates@transactional.getinboxzero.com") while incoming messages may have only the bare address. Normalize to the bare address before comparing.
File: apps/web/app/api/ai/digest/route.ts (around lines 33–37) — add import:
import { extractEmailAddress } from "@/utils/email";
Replace the equality check with:
// Don't summarize any emails we send ourselves
const fromAddr =
extractEmailAddress(message.from)?.toLowerCase() ??
message.from?.toLowerCase();
const resendAddr =
extractEmailAddress(env.RESEND_FROM_EMAIL)?.toLowerCase() ??
env.RESEND_FROM_EMAIL?.toLowerCase();
if (fromAddr && resendAddr && fromAddr === resendAddr) {
logger.info("Skipping digest item because it is from us");
return new NextResponse("OK", { status: 200 });
}Also consider checking Reply-To / Sender if those can differ in your pipeline.
🤖 Prompt for AI Agents
In apps/web/app/api/ai/digest/route.ts around lines 33 to 37, the strict
equality check against env.RESEND_FROM_EMAIL fails for display-name forms and
different casing; import extractEmailAddress from "@/utils/email" and replace
the check by extracting the bare email address from both message.from and
env.RESEND_FROM_EMAIL, lowercasing both (falling back to the original string if
extraction returns undefined), then compare the normalized addresses and return
the 200 response if they match; optionally extend the same normalization/check
to Reply-To or Sender headers if those may differ in your pipeline.
There was a problem hiding this comment.
1 issue found across 4 files
Prompt for AI agents (all 1 issues)
Understand the root cause of the following 1 issues and fix them.
<file name="apps/web/app/api/ai/digest/route.ts">
<violation number="1" location="apps/web/app/api/ai/digest/route.ts:34">
Normalize From and RESEND_FROM_EMAIL to bare, lowercase addresses before comparing; strict equality will miss cases with display names or different casing and fail to skip our own emails.</violation>
</file>
React with 👍 or 👎 to teach cubic. Mention @cubic-dev-ai to give feedback, ask questions, or re-run the review.
| } | ||
|
|
||
| // Don't summarize Digest emails (this will actually block all emails that we send, but that's okay) | ||
| if (message.from === env.RESEND_FROM_EMAIL) { |
There was a problem hiding this comment.
Normalize From and RESEND_FROM_EMAIL to bare, lowercase addresses before comparing; strict equality will miss cases with display names or different casing and fail to skip our own emails.
Prompt for AI agents
Address the following comment on apps/web/app/api/ai/digest/route.ts at line 34:
<comment>Normalize From and RESEND_FROM_EMAIL to bare, lowercase addresses before comparing; strict equality will miss cases with display names or different casing and fail to skip our own emails.</comment>
<file context>
@@ -28,6 +30,22 @@ export const POST = withError(
}
+ // Don't summarize Digest emails (this will actually block all emails that we send, but that's okay)
+ if (message.from === env.RESEND_FROM_EMAIL) {
+ logger.info("Skipping digest item because it is from us");
+ return new NextResponse("OK", { status: 200 });
</file context>
Summary by CodeRabbit
Bug Fixes
Chores
Style