Repository navigation
Record why an email send was rejected or failed - #1235
Conversation
POST /api/emails rejected 59% of logged sends with nothing to say why: the rejected path stored only the raw body. validateSendEmailBody now returns a reason (short code then detail) and the account once auth has resolved it; sendEmailHandler passes both to logEmailAttempt, and the send_failed path records the Resend error. Needs the email_send_log.reason column (recoupable/database#132). Refs recoupable/app#1949 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Important
This repository does not receive automatic reviews because it has fewer than 10 stars.
|
There was a problem hiding this comment.
3 issues found across 8 files
Confidence score: 4/5
validateSendEmailBody.test.tsdoesn’t verify the returned error response, so these tests could miss a broken caller-facing rejection contract. Assert the error branch, status, and parsed error payload.sendEmailHandler.tslogs a generic Resend reason, making rate limits and other provider failures indistinguishable inemail_send_log. Pass through a bounded provider code or detail.validateSendEmailBody.tstreats account-email lookup failures asno_account_email, hiding infrastructure errors as missing data. Preserve the query error and record a distinct reason.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="lib/emails/__tests__/validateSendEmailBody.test.ts">
<violation number="1" location="lib/emails/__tests__/validateSendEmailBody.test.ts:256">
P2: These new error-path tests never assert the returned `NextResponse` envelope, so they do not protect the caller-facing rejection contract. Assert the `error` branch, expected status, and parsed `{ status: "error", error: expect.any(String) }` body in each rejection test (including `disallowed_recipients` for the 403 case).
(Based on your team's feedback about asserting validator error envelopes.) [3bbabfba-f1c6-4e42-9d18-d0036968bf66]</violation>
</file>
<file name="lib/emails/sendEmailHandler.ts">
<violation number="1" location="lib/emails/sendEmailHandler.ts:53">
P2: The logged Resend reason is always generic with the real adapter, so rate limits, validation failures, and other provider causes cannot be distinguished in `email_send_log`. Pass a bounded provider code/detail through `processAndSendEmail` while keeping the caller response redacted.</violation>
</file>
<file name="lib/emails/validateSendEmailBody.ts">
<violation number="1" location="lib/emails/validateSendEmailBody.ts:104">
P2: `no_account_email` also hides account-email lookup failures because `selectAccountEmails` converts database errors to an empty array. Preserve the query error and record a distinct infrastructure reason instead of mislabeling the rejection.</violation>
</file>
Architecture diagram
sequenceDiagram
participant Client as API Caller
participant Handler as sendEmailHandler
participant Validator as validateSendEmailBody
participant Auth as validateAuthContext
participant DB as Database
participant Resend as Resend Adapter
Client->>Handler: POST /api/emails
Handler->>Validator: validateSendEmailBody(request)
Validator->>Validator: parse body against schema
alt Invalid body
Validator-->>Handler: rejected + reason: invalid_body
Handler->>DB: logEmailAttempt(rejected, reason, no accountId)
else Valid body
Validator->>Auth: validateAuthContext(request)
alt Auth fails
Auth-->>Validator: 401 response
Validator-->>Handler: rejected + reason: auth_failed: 401
Handler->>DB: logEmailAttempt(rejected, reason)
else Auth succeeds
Auth-->>Validator: authContext (accountId)
Validator->>Validator: check recipient gate
alt Recipient not allowed
Validator-->>Handler: rejected + reason: recipient_not_allowed + accountId
Handler->>DB: logEmailAttempt(rejected, reason, accountId)
else Recipient allowed
alt No account email
Validator-->>Handler: rejected + reason: no_account_email + accountId
Handler->>DB: logEmailAttempt(rejected, reason, accountId)
else Account email exists
Validator-->>Handler: { rawBody, data }
Handler->>Resend: processAndSendEmail(data)
alt Resend fails
Resend-->>Handler: send_failed + error
Handler->>DB: logEmailAttempt(send_failed, reason: resend_error, accountId)
Handler-->>Client: 502 response
else Resend succeeds
Resend-->>Handler: success
Handler->>DB: logEmailAttempt(sent, reason: null)
Handler-->>Client: 200 success response
end
end
end
end
end
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
| { "x-api-key": "k" }, | ||
| ); | ||
| const result = await validateSendEmailBody(request); | ||
| expect(result).toMatchObject({ |
There was a problem hiding this comment.
P2: These new error-path tests never assert the returned NextResponse envelope, so they do not protect the caller-facing rejection contract. Assert the error branch, expected status, and parsed { status: "error", error: expect.any(String) } body in each rejection test (including disallowed_recipients for the 403 case).
(Based on your team's feedback about asserting validator error envelopes.) [3bbabfba-f1c6-4e42-9d18-d0036968bf66]
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At lib/emails/__tests__/validateSendEmailBody.test.ts, line 256:
<comment>These new error-path tests never assert the returned `NextResponse` envelope, so they do not protect the caller-facing rejection contract. Assert the `error` branch, expected status, and parsed `{ status: "error", error: expect.any(String) }` body in each rejection test (including `disallowed_recipients` for the 403 case).
(Based on your team's feedback about asserting validator error envelopes.) [3bbabfba-f1c6-4e42-9d18-d0036968bf66]</comment>
<file context>
@@ -240,4 +240,48 @@ describe("validateSendEmailBody", () => {
+ { "x-api-key": "k" },
+ );
+ const result = await validateSendEmailBody(request);
+ expect(result).toMatchObject({
+ reason: "recipient_not_allowed: stranger@example.com, other@example.com",
+ accountId: "account-123",
</file context>
| status: "send_failed", | ||
| accountId, | ||
| chatId: chat_id, | ||
| reason: `resend_error: ${result.error}`, |
There was a problem hiding this comment.
P2: The logged Resend reason is always generic with the real adapter, so rate limits, validation failures, and other provider causes cannot be distinguished in email_send_log. Pass a bounded provider code/detail through processAndSendEmail while keeping the caller response redacted.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At lib/emails/sendEmailHandler.ts, line 53:
<comment>The logged Resend reason is always generic with the real adapter, so rate limits, validation failures, and other provider causes cannot be distinguished in `email_send_log`. Pass a bounded provider code/detail through `processAndSendEmail` while keeping the caller response redacted.</comment>
<file context>
@@ -46,7 +46,12 @@ export async function sendEmailHandler(request: NextRequest): Promise<NextRespon
+ status: "send_failed",
+ accountId,
+ chatId: chat_id,
+ reason: `resend_error: ${result.error}`,
+ };
} else {
</file context>
| { status: "error", error: "No email address found for the authenticated account." }, | ||
| { status: 400, headers: getCorsHeaders() }, | ||
| ), | ||
| reason: "no_account_email", |
There was a problem hiding this comment.
P2: no_account_email also hides account-email lookup failures because selectAccountEmails converts database errors to an empty array. Preserve the query error and record a distinct infrastructure reason instead of mislabeling the rejection.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At lib/emails/validateSendEmailBody.ts, line 104:
<comment>`no_account_email` also hides account-email lookup failures because `selectAccountEmails` converts database errors to an empty array. Preserve the query error and record a distinct infrastructure reason instead of mislabeling the rejection.</comment>
<file context>
@@ -97,6 +101,8 @@ export async function validateSendEmailBody(
{ status: "error", error: "No email address found for the authenticated account." },
{ status: 400, headers: getCorsHeaders() },
),
+ reason: "no_account_email",
+ accountId: authContext.accountId,
};
</file context>
Successful sends now leave the reason key out of the insert, so they keep logging even if this deploys before email_send_log.reason exists. The sent rows matter: welcome, valuation and abandoned-checkout emails dedupe on them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
0 issues found across 2 files (changes from recent commits).
Confidence score: 5/5
- Automated review surfaced no issues in the provided summaries.
- No files require special attention.
Requires human review: Auto-approval blocked by 3 unresolved issues from previous reviews.
View guided diff | Turn on auto-fix | Re-trigger cubic
Records the merged monthly-onboarding and missed-report work: recoupable/database#132, recoupable/api#1235 and #1236, and recoupable/app#2392, #2393 and #2394, plus whatever else landed on those mains since the last recorded commits. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Summary
Every rejected or failed
POST /api/emailsattempt now records why inemail_send_log.reason, plus the sending account when auth has resolved it.reasoninvalid_body: html: a non-empty html or text body is requiredauth_failed: 401no_account_emailrecipient_not_allowed: a@example.com, …resend_error: …Why
recoupable/app#1949 F2: 59% of logged sends were
rejectedand the log could not say why, so scheduled reports that never arrived could not be diagnosed. The response bodies callers receive are unchanged.Changes
validateSendEmailBody: the rejection branch now carriesreasonand, after auth,accountId.sendEmailHandler: passesreason/accountIdonrejected; recordsresend_error: …onsend_failed.logEmailAttempt: writesreasononly when set.types/database.types.ts: adds the column.Merge order
Merge and apply recoupable/database#132 first; this PR writes the new column. As a guard, inserts include
reasononly when there is one, so successful sends keep logging even if this deploys early. That matters because welcome, valuation and abandoned-checkout emails dedupe onsentrows.Tests
Tests first: 8 new assertions failed before the change.
pnpm vitest run lib/emails→ 218 passed. Lint and Prettier clean on changed files.🤖 Generated with Claude Code