Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions lib/emails/__tests__/emailFailureFallback.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ describe("email failure fallback through the real Resend adapter", () => {
status: "send_failed",
accountId: "synthetic-account",
chatId: undefined,
reason: "resend_error: Failed to send email.",
});
});

Expand Down
19 changes: 19 additions & 0 deletions lib/emails/__tests__/logEmailAttempt.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,25 @@ describe("logEmailAttempt", () => {
expect(row.raw_body).toBe(raw);
});

it("records why a send was rejected", async () => {
await logEmailAttempt({
rawBody: "{}",
status: "rejected",
accountId: "acc-1",
reason: "no_account_email",
});
const row = mockInsert.mock.calls[0][0];
expect(row.reason).toBe("no_account_email");
expect(row.account_id).toBe("acc-1");
});

// Sends without a reason never touch the column, so they keep logging even if
// this code ships before the email_send_log.reason migration is applied.
it("leaves reason out of the insert when none is given", async () => {
await logEmailAttempt({ rawBody: "{}", status: "sent" });
expect(mockInsert.mock.calls[0][0]).not.toHaveProperty("reason");
});

it("stores the full raw body (no truncation)", async () => {
await logEmailAttempt({ rawBody: "x".repeat(20000), status: "rejected" });
expect(mockInsert.mock.calls[0][0].raw_body.length).toBe(20000);
Expand Down
10 changes: 8 additions & 2 deletions lib/emails/__tests__/sendEmailHandler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,12 +85,18 @@ describe("sendEmailHandler", () => {
mockValidateSendEmailBody.mockResolvedValue({
rawBody: "{}",
error: NextResponse.json({ status: "error", error: "Forbidden" }, { status: 403 }),
reason: "recipient_not_allowed: stranger@example.com",
accountId: "account-123",
});
const response = await sendEmailHandler(createRequest());
expect(response.status).toBe(403);
expect(mockProcessAndSendEmail).not.toHaveBeenCalled();
expect(mockLogEmailAttempt).toHaveBeenCalledWith(
expect.objectContaining({ status: "rejected" }),
expect.objectContaining({
status: "rejected",
reason: "recipient_not_allowed: stranger@example.com",
accountId: "account-123",
}),
);
});

Expand All @@ -101,7 +107,7 @@ describe("sendEmailHandler", () => {
const json = await response.json();
expect(json.error).toBe("resend boom");
expect(mockLogEmailAttempt).toHaveBeenCalledWith(
expect.objectContaining({ status: "send_failed" }),
expect.objectContaining({ status: "send_failed", reason: "resend_error: resend boom" }),
);
});
});
44 changes: 44 additions & 0 deletions lib/emails/__tests__/validateSendEmailBody.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -240,4 +240,48 @@ describe("validateSendEmailBody", () => {
if ("error" in result) expect(result.error.status).toBe(401);
});
});

// recoupable/app#1949 F2: a rejected send records why, so the rejection rate is diagnosable.
describe("rejection reason", () => {
it("names the disallowed recipients and the sending account", async () => {
mockAssertRecipientsAllowed.mockResolvedValue({
allowed: false,
disallowed: ["stranger@example.com", "other@example.com"],
});
const request = createRequest(
{ to: ["stranger@example.com", "other@example.com"], text: "body" },
{ "x-api-key": "k" },
);
const result = await validateSendEmailBody(request);
expect(result).toMatchObject({

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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>

reason: "recipient_not_allowed: stranger@example.com, other@example.com",
accountId: "account-123",
});
});

it("names the failing field when the body is invalid", async () => {
const request = createRequest({ to: ["d@example.com"], html: " " }, { "x-api-key": "k" });
const result = await validateSendEmailBody(request);
expect(result).toMatchObject({
reason: "invalid_body: html: a non-empty html or text body is required",
});
expect("accountId" in result && result.accountId).toBeFalsy();
});

it("records the account when it has no email on file", async () => {
mockSelectAccountEmails.mockResolvedValue([]);
const request = createRequest({ text: "body" }, { "x-api-key": "k" });
const result = await validateSendEmailBody(request);
expect(result).toMatchObject({ reason: "no_account_email", accountId: "account-123" });
});

it("records the auth status when authentication fails", async () => {
mockValidateAuthContext.mockResolvedValue(
NextResponse.json({ status: "error", error: "Unauthorized" }, { status: 401 }),
);
const request = createRequest({ to: ["d@example.com"], text: "body" });
const result = await validateSendEmailBody(request);
expect(result).toMatchObject({ reason: "auth_failed: 401" });
});
});
});
5 changes: 5 additions & 0 deletions lib/emails/logEmailAttempt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ export type EmailAttemptLog = {
accountId?: string | null;
chatId?: string | null;
resendId?: string;
/** Why the send was rejected or failed: a short code, then detail. */
reason?: string | null;
};

/**
Expand All @@ -28,6 +30,9 @@ export async function logEmailAttempt(attempt: EmailAttemptLog): Promise<void> {
status: attempt.status,
resend_id: attempt.resendId ?? null,
raw_body: attempt.rawBody,
// Only rejected/failed sends carry a reason; omitting the key otherwise keeps
// ordinary sends logging if this ships before the column exists.
...(attempt.reason ? { reason: attempt.reason } : {}),
});
if (error) {
console.error("email_send_log insert failed:", error);
Expand Down
9 changes: 7 additions & 2 deletions lib/emails/sendEmailHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,12 @@ export async function sendEmailHandler(request: NextRequest): Promise<NextRespon
{ status: "error", error: result.error },
{ status: 502, headers: getCorsHeaders() },
);
attempt = { status: "send_failed", accountId, chatId: chat_id };
attempt = {
status: "send_failed",
accountId,
chatId: chat_id,
reason: `resend_error: ${result.error}`,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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>

};
} else {
response = NextResponse.json(
{ success: true, message: result.message, id: result.id },
Expand All @@ -56,7 +61,7 @@ export async function sendEmailHandler(request: NextRequest): Promise<NextRespon
}
} else {
response = validated.error;
attempt = { status: "rejected" };
attempt = { status: "rejected", accountId: validated.accountId, reason: validated.reason };
}

await logEmailAttempt({ rawBody: validated.rawBody, ...attempt });
Expand Down
16 changes: 12 additions & 4 deletions lib/emails/validateSendEmailBody.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,12 @@ export type ValidatedSendEmailRequest = Omit<SendEmailBody, "to" | "subject"> &
/**
* Validation outcome. Always carries `rawBody` — the request body as received —
* so the handler can record it in `email_send_log` on both the rejected and the
* accepted paths without re-reading the request.
* accepted paths without re-reading the request. A rejection also carries
* `reason` (a short code, then detail) and the account once auth has resolved
* it, so the rejection rate can be grouped by cause (recoupable/app#1949 F2).
*/
export type ValidateSendEmailResult =
| { rawBody: string; error: NextResponse }
| { rawBody: string; error: NextResponse; reason: string; accountId?: string }
| { rawBody: string; data: ValidatedSendEmailRequest };

/**
Expand All @@ -54,7 +56,7 @@ export type ValidateSendEmailResult =
* `subject` is derived from the body when omitted. Always returns `rawBody`.
*
* @param request - The NextRequest object
* @returns `{ rawBody, error }` if validation/auth/recipients fail, else `{ rawBody, data }`.
* @returns `{ rawBody, error, reason }` if validation/auth/recipients fail, else `{ rawBody, data }`.
*/
export async function validateSendEmailBody(
request: NextRequest,
Expand All @@ -72,18 +74,20 @@ export async function validateSendEmailBody(
const result = sendEmailBodySchema.safeParse(parsed);
if (!result.success) {
const firstError = result.error.issues[0];
const field = firstError.path.join(".");
return {
rawBody,
error: NextResponse.json(
{ status: "error", missing_fields: firstError.path, error: firstError.message },
{ status: 400, headers: getCorsHeaders() },
),
reason: `invalid_body: ${field ? `${field}: ` : ""}${firstError.message}`,
};
}

const authContext = await validateAuthContext(request, { accountId: result.data.account_id });
if (authContext instanceof NextResponse) {
return { rawBody, error: authContext };
return { rawBody, error: authContext, reason: `auth_failed: ${authContext.status}` };
}

let to = result.data.to ?? [];
Expand All @@ -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",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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>

accountId: authContext.accountId,
};
}
}
Expand All @@ -116,6 +122,8 @@ export async function validateSendEmailBody(
},
{ status: 403, headers: getCorsHeaders() },
),
reason: `recipient_not_allowed: ${recipientCheck.disallowed.join(", ")}`,
accountId: authContext.accountId,
};
}

Expand Down
3 changes: 3 additions & 0 deletions types/database.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2480,6 +2480,7 @@ export type Database = {
created_at: string;
id: string;
raw_body: string | null;
reason: string | null;
resend_id: string | null;
status: string;
};
Expand All @@ -2489,6 +2490,7 @@ export type Database = {
created_at?: string;
id?: string;
raw_body?: string | null;
reason?: string | null;
resend_id?: string | null;
status: string;
};
Expand All @@ -2498,6 +2500,7 @@ export type Database = {
created_at?: string;
id?: string;
raw_body?: string | null;
reason?: string | null;
resend_id?: string | null;
status?: string;
};
Expand Down
Loading