From 430d498f47eb01fb3c9a709d8fadb3839abdb920 Mon Sep 17 00:00:00 2001 From: KM Koushik Date: Tue, 10 Nov 2026 15:10:11 +1100 Subject: [PATCH 1/4] feat(feedback): save feedback in the database, with an admin API to list, reply and import --- .env.example | 3 + .../20261110130000_add_feedback/migration.sql | 66 ++++ apps/web/prisma/schema.prisma | 59 ++++ .../api/admin/feedback/[id]/reply/route.ts | 55 ++++ .../src/app/api/admin/feedback/[id]/route.ts | 21 ++ .../app/api/admin/feedback/import/route.ts | 15 + .../app/api/admin/feedback/route.api.test.ts | 67 ++++ apps/web/src/app/api/admin/feedback/route.ts | 17 + apps/web/src/components/FeedbackDialog.tsx | 19 +- apps/web/src/env.js | 3 + apps/web/src/server/admin-api.ts | 107 +++++++ apps/web/src/server/admin-auth.ts | 23 ++ apps/web/src/server/admin-auth.unit.test.ts | 26 ++ apps/web/src/server/api/routers/feedback.ts | 43 +-- apps/web/src/server/mailer.ts | 72 +++++ apps/web/src/server/service/feedback-admin.ts | 297 ++++++++++++++++++ .../service/feedback-admin.unit.test.ts | 201 ++++++++++++ .../src/server/service/feedback-service.ts | 183 +++++++++++ .../service/feedback-service.unit.test.ts | 152 +++++++++ 19 files changed, 1396 insertions(+), 33 deletions(-) create mode 100644 apps/web/prisma/migrations/20261110130000_add_feedback/migration.sql create mode 100644 apps/web/src/app/api/admin/feedback/[id]/reply/route.ts create mode 100644 apps/web/src/app/api/admin/feedback/[id]/route.ts create mode 100644 apps/web/src/app/api/admin/feedback/import/route.ts create mode 100644 apps/web/src/app/api/admin/feedback/route.api.test.ts create mode 100644 apps/web/src/app/api/admin/feedback/route.ts create mode 100644 apps/web/src/server/admin-api.ts create mode 100644 apps/web/src/server/admin-auth.ts create mode 100644 apps/web/src/server/admin-auth.unit.test.ts create mode 100644 apps/web/src/server/service/feedback-admin.ts create mode 100644 apps/web/src/server/service/feedback-admin.unit.test.ts create mode 100644 apps/web/src/server/service/feedback-service.ts create mode 100644 apps/web/src/server/service/feedback-service.unit.test.ts diff --git a/.env.example b/.env.example index 7d9fe8874..4b41693d4 100644 --- a/.env.example +++ b/.env.example @@ -28,3 +28,6 @@ AUTH_EMAIL_RATE_LIMIT=5 # REDIS_KEY_PREFIX="" NEXT_PUBLIC_IS_CLOUD=true + +# Optional: bearer token (at least 32 characters) for the internal admin API at /api/admin. Off when empty. +# ADMIN_API_TOKEN="" diff --git a/apps/web/prisma/migrations/20261110130000_add_feedback/migration.sql b/apps/web/prisma/migrations/20261110130000_add_feedback/migration.sql new file mode 100644 index 000000000..967b9ba21 --- /dev/null +++ b/apps/web/prisma/migrations/20261110130000_add_feedback/migration.sql @@ -0,0 +1,66 @@ +-- CreateEnum +CREATE TYPE "FeedbackStatus" AS ENUM ('OPEN', 'REPLIED', 'CLOSED'); + +-- CreateEnum +CREATE TYPE "FeedbackReplyStatus" AS ENUM ('SENDING', 'SENT', 'FAILED'); + +-- CreateTable +CREATE TABLE "Feedback" ( + "id" TEXT NOT NULL, + "userId" INTEGER, + "teamId" INTEGER, + "email" TEXT NOT NULL, + "name" TEXT, + "teamName" TEXT, + "message" TEXT NOT NULL, + "source" TEXT NOT NULL, + "clientKey" TEXT, + "externalId" TEXT, + "status" "FeedbackStatus" NOT NULL DEFAULT 'OPEN', + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "Feedback_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "FeedbackReply" ( + "id" TEXT NOT NULL, + "feedbackId" TEXT NOT NULL, + "message" TEXT NOT NULL, + "idempotencyKey" TEXT NOT NULL, + "deliveryStatus" "FeedbackReplyStatus" NOT NULL DEFAULT 'SENDING', + "sentAt" TIMESTAMP(3), + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "FeedbackReply_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "Feedback_clientKey_key" ON "Feedback"("clientKey"); + +-- CreateIndex +CREATE UNIQUE INDEX "Feedback_externalId_key" ON "Feedback"("externalId"); + +-- CreateIndex +CREATE INDEX "Feedback_status_createdAt_idx" ON "Feedback"("status", "createdAt"); + +-- CreateIndex +CREATE INDEX "Feedback_userId_createdAt_idx" ON "Feedback"("userId", "createdAt"); + +-- CreateIndex +CREATE UNIQUE INDEX "FeedbackReply_idempotencyKey_key" ON "FeedbackReply"("idempotencyKey"); + +-- CreateIndex +CREATE INDEX "FeedbackReply_feedbackId_idx" ON "FeedbackReply"("feedbackId"); + +-- AddForeignKey +ALTER TABLE "Feedback" ADD CONSTRAINT "Feedback_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "Feedback" ADD CONSTRAINT "Feedback_teamId_fkey" FOREIGN KEY ("teamId") REFERENCES "Team"("id") ON DELETE SET NULL ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "FeedbackReply" ADD CONSTRAINT "FeedbackReply_feedbackId_fkey" FOREIGN KEY ("feedbackId") REFERENCES "Feedback"("id") ON DELETE CASCADE ON UPDATE CASCADE; + diff --git a/apps/web/prisma/schema.prisma b/apps/web/prisma/schema.prisma index f590ee6d8..501cdeca0 100644 --- a/apps/web/prisma/schema.prisma +++ b/apps/web/prisma/schema.prisma @@ -92,6 +92,7 @@ model User { teamUsers TeamUser[] webhookEndpoints Webhook[] waitlistApplication WaitlistApplication? + feedback Feedback[] } enum WaitlistStatus { @@ -155,6 +156,7 @@ model Team { suppressionList SuppressionList[] webhookEndpoints Webhook[] webhookCalls WebhookCall[] + feedback Feedback[] } model TeamInvite { @@ -540,3 +542,60 @@ model WebhookCall { @@index([teamId, webhookId, status]) @@index([createdAt(sort: Desc)]) } + +enum FeedbackStatus { + OPEN + REPLIED + CLOSED +} + +/// Feedback sent from the dashboard's Feedback button. Deleted with the user. +model Feedback { + id String @id @default(cuid()) + userId Int? + /// The team they were using when they sent it + teamId Int? + /// The sender's email, name and team name when they sent it + email String + name String? + teamName String? + message String + /// `web`, or `import` for feedback copied from the old feedback emails + source String + /// Sent by the dashboard once per draft, so a retried submit doesn't save it twice + clientKey String? @unique + /// Only set on imported feedback + externalId String? @unique + status FeedbackStatus @default(OPEN) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + user User? @relation(fields: [userId], references: [id], onDelete: Cascade) + team Team? @relation(fields: [teamId], references: [id], onDelete: SetNull) + replies FeedbackReply[] + + @@index([status, createdAt]) + @@index([userId, createdAt]) +} + +enum FeedbackReplyStatus { + /// Being sent, or it's unknown whether it went + SENDING + SENT + FAILED +} + +/// A reply emailed to whoever sent the feedback. +model FeedbackReply { + id String @id @default(cuid()) + feedbackId String + message String + /// One per reply: sending again with the same key never sends a second email + idempotencyKey String @unique + deliveryStatus FeedbackReplyStatus @default(SENDING) + sentAt DateTime? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + feedback Feedback @relation(fields: [feedbackId], references: [id], onDelete: Cascade) + + @@index([feedbackId]) +} diff --git a/apps/web/src/app/api/admin/feedback/[id]/reply/route.ts b/apps/web/src/app/api/admin/feedback/[id]/reply/route.ts new file mode 100644 index 000000000..539c9895a --- /dev/null +++ b/apps/web/src/app/api/admin/feedback/[id]/reply/route.ts @@ -0,0 +1,55 @@ +import { AdminApiError, adminApiRoute, json, param } from "~/server/admin-api"; +import { + FeedbackNotFoundError, + IdempotencyConflictError, + MailNotSentError, + ReplyNeedsCheckError, + replyBody, + replyToFeedback, +} from "~/server/service/feedback-admin"; + +export const dynamic = "force-dynamic"; + +/** + * POST /api/admin/feedback/{id}/reply with `{ "message": "...", "idempotencyKey": "..." }`. + * Emails the reply to whoever sent the feedback. The same key and message again + * never sends a second email: 200 with the reply once it's sent, or a retry if + * it failed. 201 when this request sent it. + */ +export const POST = adminApiRoute(async ({ body, params }) => { + const input = replyBody.parse(body); + try { + const { reply, sent } = await replyToFeedback( + param(params.id) ?? "", + input, + ); + return json(sent ? 201 : 200, { + id: reply.id, + deliveryStatus: reply.deliveryStatus, + sentAt: reply.sentAt?.toISOString() ?? null, + }); + } catch (error) { + if (error instanceof FeedbackNotFoundError) { + throw new AdminApiError(404, "Feedback not found"); + } + if (error instanceof IdempotencyConflictError) { + throw new AdminApiError( + 409, + "This key was used for a different reply; use a new key", + ); + } + if (error instanceof ReplyNeedsCheckError) { + throw new AdminApiError( + 409, + "This reply may have been sent over a day ago; check before sending it again with a new key", + ); + } + if (error instanceof MailNotSentError) { + throw new AdminApiError( + 502, + "The reply email was not sent; try again with the same key", + ); + } + throw error; + } +}); diff --git a/apps/web/src/app/api/admin/feedback/[id]/route.ts b/apps/web/src/app/api/admin/feedback/[id]/route.ts new file mode 100644 index 000000000..fccf036b8 --- /dev/null +++ b/apps/web/src/app/api/admin/feedback/[id]/route.ts @@ -0,0 +1,21 @@ +import { AdminApiError, adminApiRoute, param } from "~/server/admin-api"; +import { + FeedbackNotFoundError, + setFeedbackStatus, + statusBody, +} from "~/server/service/feedback-admin"; + +export const dynamic = "force-dynamic"; + +/** PATCH /api/admin/feedback/{id} with `{ "status": "OPEN" | "REPLIED" | "CLOSED" }`. */ +export const PATCH = adminApiRoute(async ({ body, params }) => { + const { status } = statusBody.parse(body); + try { + return await setFeedbackStatus(param(params.id) ?? "", status); + } catch (error) { + if (error instanceof FeedbackNotFoundError) { + throw new AdminApiError(404, "Feedback not found"); + } + throw error; + } +}); diff --git a/apps/web/src/app/api/admin/feedback/import/route.ts b/apps/web/src/app/api/admin/feedback/import/route.ts new file mode 100644 index 000000000..a35dc4a16 --- /dev/null +++ b/apps/web/src/app/api/admin/feedback/import/route.ts @@ -0,0 +1,15 @@ +import { adminApiRoute } from "~/server/admin-api"; +import { importBody, importFeedback } from "~/server/service/feedback-admin"; + +export const dynamic = "force-dynamic"; + +/** + * POST /api/admin/feedback/import with `{ "items": [...] }`, at most 500 items. + * Copies feedback from the old feedback emails. Only feedback from existing + * accounts is stored; the rest is counted as `unmatched`. Safe to run again. + */ +export const POST = adminApiRoute( + async ({ body }) => importFeedback(importBody.parse(body)), + // A full batch of long messages is past the default 1mb + { maxBodyBytes: 10 * 1024 * 1024 }, +); diff --git a/apps/web/src/app/api/admin/feedback/route.api.test.ts b/apps/web/src/app/api/admin/feedback/route.api.test.ts new file mode 100644 index 000000000..ea4033092 --- /dev/null +++ b/apps/web/src/app/api/admin/feedback/route.api.test.ts @@ -0,0 +1,67 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const { mockEnv, mockListFeedback } = vi.hoisted(() => ({ + mockEnv: { ADMIN_API_TOKEN: undefined as string | undefined }, + mockListFeedback: vi.fn(), +})); + +vi.mock("~/env", () => ({ env: mockEnv })); +vi.mock("~/server/logger/log", () => ({ + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() }, +})); +vi.mock("~/server/service/feedback-admin", async (importOriginal) => { + const actual = + await importOriginal(); + return { ...actual, listFeedback: mockListFeedback }; +}); +vi.mock("~/server/db", () => ({ db: {} })); +vi.mock("~/server/mailer", () => ({ + MailNotSentError: class extends Error {}, + sendFeedbackReply: vi.fn(), + sendFeedbackNotification: vi.fn(), +})); + +import { GET } from "~/app/api/admin/feedback/route"; + +const TOKEN = "t".repeat(40); +const request = (auth?: string, query = "") => + new Request(`http://localhost/api/admin/feedback${query}`, { + headers: auth ? { authorization: auth } : {}, + }); + +describe("GET /api/admin/feedback", () => { + beforeEach(() => { + mockEnv.ADMIN_API_TOKEN = TOKEN; + mockListFeedback.mockReset(); + mockListFeedback.mockResolvedValue({ items: [], nextCursor: null }); + }); + + it("doesn't exist when no admin token is configured", async () => { + mockEnv.ADMIN_API_TOKEN = undefined; + const response = await GET(request(`Bearer ${TOKEN}`)); + expect(response.status).toBe(404); + expect(mockListFeedback).not.toHaveBeenCalled(); + }); + + it("refuses a wrong token", async () => { + const response = await GET(request("Bearer wrong-token")); + expect(response.status).toBe(401); + expect(mockListFeedback).not.toHaveBeenCalled(); + }); + + it("lists feedback with the right token", async () => { + const response = await GET( + request(`Bearer ${TOKEN}`, "?status=OPEN&limit=5"), + ); + expect(response.status).toBe(200); + expect(response.headers.get("cache-control")).toBe("no-store"); + expect(mockListFeedback).toHaveBeenCalledWith( + expect.objectContaining({ status: "OPEN", limit: 5 }), + ); + }); + + it("answers 400 for a bad query", async () => { + const response = await GET(request(`Bearer ${TOKEN}`, "?limit=900")); + expect(response.status).toBe(400); + }); +}); diff --git a/apps/web/src/app/api/admin/feedback/route.ts b/apps/web/src/app/api/admin/feedback/route.ts new file mode 100644 index 000000000..ba164e3d2 --- /dev/null +++ b/apps/web/src/app/api/admin/feedback/route.ts @@ -0,0 +1,17 @@ +import { adminApiRoute } from "~/server/admin-api"; +import { + listFeedback, + listFeedbackQuery, +} from "~/server/service/feedback-admin"; + +export const dynamic = "force-dynamic"; + +/** + * GET /api/admin/feedback?status=&since=&limit=<1-200>&cursor= + * Feedback newest first, with `nextCursor` for the next page. + */ +export const GET = adminApiRoute(async ({ req }) => { + const url = new URL(req.url); + const query = listFeedbackQuery.parse(Object.fromEntries(url.searchParams)); + return listFeedback(query); +}); diff --git a/apps/web/src/components/FeedbackDialog.tsx b/apps/web/src/components/FeedbackDialog.tsx index 65da5c213..a2b31c9a8 100644 --- a/apps/web/src/components/FeedbackDialog.tsx +++ b/apps/web/src/components/FeedbackDialog.tsx @@ -1,6 +1,12 @@ "use client"; -import { type KeyboardEvent, type ReactNode, useEffect, useState } from "react"; +import { + type KeyboardEvent, + type ReactNode, + useEffect, + useRef, + useState, +} from "react"; import { Button } from "@usesend/ui/src/button"; import { Dialog, @@ -34,6 +40,9 @@ const FeedbackSchema = z.object({ export function FeedbackDialog({ trigger }: { trigger?: ReactNode }) { const [open, setOpen] = useState(false); const [isMac, setIsMac] = useState(false); + // Resending the same text (a double click, a retry after an error) reuses + // its key, so it's saved once; edited text gets a new key. + const draftKey = useRef<{ text: string; key: string } | null>(null); const form = useForm>({ resolver: zodResolver(FeedbackSchema), @@ -45,6 +54,7 @@ export function FeedbackDialog({ trigger }: { trigger?: ReactNode }) { const feedbackMutation = api.feedback.send.useMutation({ onSuccess: () => { toast.success("Thanks for sharing your feedback!"); + draftKey.current = null; form.reset(); setOpen(false); }, @@ -69,7 +79,12 @@ export function FeedbackDialog({ trigger }: { trigger?: ReactNode }) { } function onSubmit(values: z.infer) { - feedbackMutation.mutate({ message: values.message.trim() }); + if (feedbackMutation.isPending) return; + const message = values.message.trim(); + if (draftKey.current?.text !== message) { + draftKey.current = { text: message, key: crypto.randomUUID() }; + } + feedbackMutation.mutate({ message, clientKey: draftKey.current.key }); } function handleKeyDown(event: KeyboardEvent) { diff --git a/apps/web/src/env.js b/apps/web/src/env.js index 01403ee53..ae57114bf 100644 --- a/apps/web/src/env.js +++ b/apps/web/src/env.js @@ -59,6 +59,8 @@ export const env = createEnv({ ADMIN_EMAIL: z.string().optional(), FOUNDER_EMAIL: z.string().optional(), DISCORD_WEBHOOK_URL: z.string().optional(), + /** Bearer token for the internal admin API (/api/admin). The API is off when unset. */ + ADMIN_API_TOKEN: z.string().min(32).optional(), REDIS_URL: z.string(), REDIS_KEY_PREFIX: z.string().default(""), S3_COMPATIBLE_ACCESS_KEY: z.string().optional(), @@ -131,6 +133,7 @@ export const env = createEnv({ ADMIN_EMAIL: process.env.ADMIN_EMAIL, FOUNDER_EMAIL: process.env.FOUNDER_EMAIL, DISCORD_WEBHOOK_URL: process.env.DISCORD_WEBHOOK_URL, + ADMIN_API_TOKEN: process.env.ADMIN_API_TOKEN || undefined, REDIS_URL: process.env.REDIS_URL, REDIS_KEY_PREFIX: process.env.REDIS_KEY_PREFIX, FROM_EMAIL: process.env.FROM_EMAIL, diff --git a/apps/web/src/server/admin-api.ts b/apps/web/src/server/admin-api.ts new file mode 100644 index 000000000..2f483a331 --- /dev/null +++ b/apps/web/src/server/admin-api.ts @@ -0,0 +1,107 @@ +import { ZodError } from "zod"; + +import { env } from "~/env"; +import { logger } from "~/server/logger/log"; +import { isAdminAuthorized } from "~/server/admin-auth"; + +/** + * The internal admin API: routes under /api/admin, used by our own tools (HQ, + * the Guard). Off unless ADMIN_API_TOKEN is set; then every request needs + * `Authorization: Bearer `. + */ + +export class AdminApiError extends Error { + constructor( + public status: number, + message: string, + ) { + super(message); + } +} + +const DEFAULT_MAX_BODY_BYTES = 1024 * 1024; +const HEADERS = { "Cache-Control": "no-store" }; + +type Params = Record; +type Handler = (input: { + req: Request; + body: unknown; + params: Params; +}) => Promise; + +export function json(status: number, body: unknown) { + return Response.json(body, { status, headers: HEADERS }); +} + +async function readJsonBody(req: Request, maxBytes: number) { + const declared = Number(req.headers.get("content-length") ?? 0); + if (declared > maxBytes) throw new AdminApiError(413, "Body too large"); + const text = await req.text(); + if (Buffer.byteLength(text) > maxBytes) { + throw new AdminApiError(413, "Body too large"); + } + if (text.trim() === "") return undefined; + try { + return JSON.parse(text) as unknown; + } catch { + throw new AdminApiError(400, "Invalid JSON"); + } +} + +/** Only an error's name and code: messages can contain request data. */ +function safeErrorDetails(error: unknown) { + if (!(error instanceof Error)) return { name: typeof error }; + const { code } = error as { code?: unknown }; + return { + name: error.name, + code: typeof code === "string" ? code : undefined, + }; +} + +/** + * Wraps a route handler: answers 404 unless ADMIN_API_TOKEN is set, 401 + * without the token, and reads a JSON body only once the request is + * authorised. A handler returns the JSON to send with status 200, or a + * Response. `AdminApiError` and zod errors become their status codes. + */ +export function adminApiRoute( + handler: Handler, + { maxBodyBytes = DEFAULT_MAX_BODY_BYTES } = {}, +) { + return async (req: Request, context?: { params?: Promise }) => { + if (!env.ADMIN_API_TOKEN) return json(404, { error: "Not found" }); + if ( + !isAdminAuthorized(req.headers.get("authorization"), env.ADMIN_API_TOKEN) + ) { + return json(401, { error: "Unauthorized" }); + } + + try { + let body: unknown; + if (req.method !== "GET") { + const type = req.headers.get("content-type") ?? ""; + if (!/^application\/json\b/i.test(type)) { + return json(415, { error: "Send a JSON body" }); + } + body = await readJsonBody(req, maxBodyBytes); + } + const params = (await context?.params) ?? {}; + const result = await handler({ req, body, params }); + return result instanceof Response ? result : json(200, result); + } catch (error) { + if (error instanceof AdminApiError) { + return json(error.status, { error: error.message }); + } + if (error instanceof ZodError) { + return json(400, { error: "Invalid request", issues: error.issues }); + } + logger.error(safeErrorDetails(error), "[AdminApi]: Request failed"); + return json(500, { error: "Internal server error" }); + } + }; +} + +/** A single string route or query param. */ +export function param(value: string | string[] | undefined) { + return Array.isArray(value) ? value[0] : value; +} diff --git a/apps/web/src/server/admin-auth.ts b/apps/web/src/server/admin-auth.ts new file mode 100644 index 000000000..d1dff3195 --- /dev/null +++ b/apps/web/src/server/admin-auth.ts @@ -0,0 +1,23 @@ +import { createHash, timingSafeEqual } from "crypto"; + +/** + * Pure helpers for the internal admin API, kept free of db and env imports so + * they can be unit tested. + */ + +const digest = (value: string) => createHash("sha256").update(value).digest(); + +/** + * Whether `authorization` is `Bearer `. Compares digests in constant + * time, so neither the token nor its length leaks through timing. Never true + * without an expected token. + */ +export function isAdminAuthorized( + authorization: string | null | undefined, + expected: string | undefined, +) { + if (!expected || !authorization) return false; + const match = authorization.match(/^Bearer\s+(\S+)\s*$/i); + if (!match?.[1]) return false; + return timingSafeEqual(digest(match[1]), digest(expected)); +} diff --git a/apps/web/src/server/admin-auth.unit.test.ts b/apps/web/src/server/admin-auth.unit.test.ts new file mode 100644 index 000000000..168ce3323 --- /dev/null +++ b/apps/web/src/server/admin-auth.unit.test.ts @@ -0,0 +1,26 @@ +import { describe, expect, it } from "vitest"; + +import { isAdminAuthorized } from "~/server/admin-auth"; + +const TOKEN = "a".repeat(40); + +describe("isAdminAuthorized", () => { + it("accepts the right bearer token", () => { + expect(isAdminAuthorized(`Bearer ${TOKEN}`, TOKEN)).toBe(true); + expect(isAdminAuthorized(`bearer ${TOKEN}`, TOKEN)).toBe(true); + }); + + it("refuses a wrong, missing or malformed token", () => { + expect(isAdminAuthorized(`Bearer ${"b".repeat(40)}`, TOKEN)).toBe(false); + expect(isAdminAuthorized(`Bearer ${TOKEN.slice(1)}`, TOKEN)).toBe(false); + expect(isAdminAuthorized(TOKEN, TOKEN)).toBe(false); + expect(isAdminAuthorized(null, TOKEN)).toBe(false); + expect(isAdminAuthorized("Bearer ", TOKEN)).toBe(false); + }); + + it("refuses everything when no token is configured", () => { + expect(isAdminAuthorized("Bearer ", undefined)).toBe(false); + expect(isAdminAuthorized(`Bearer ${TOKEN}`, undefined)).toBe(false); + expect(isAdminAuthorized(`Bearer ${TOKEN}`, "")).toBe(false); + }); +}); diff --git a/apps/web/src/server/api/routers/feedback.ts b/apps/web/src/server/api/routers/feedback.ts index 2b8b9244a..7b91586fd 100644 --- a/apps/web/src/server/api/routers/feedback.ts +++ b/apps/web/src/server/api/routers/feedback.ts @@ -1,19 +1,15 @@ -import { z } from "zod"; import { TRPCError } from "@trpc/server"; import { createTRPCRouter, teamProcedure } from "~/server/api/trpc"; -import { env } from "~/env"; +import { + submitFeedback, + submitFeedbackInput, +} from "~/server/service/feedback-service"; import { isCloud } from "~/utils/common"; -import { sendMail } from "~/server/mailer"; -import { toPlainHtml } from "~/server/utils/email-content"; export const feedbackRouter = createTRPCRouter({ send: teamProcedure - .input( - z.object({ - message: z.string().trim().min(1, "Feedback cannot be empty").max(2000), - }), - ) + .input(submitFeedbackInput) .mutation(async ({ ctx, input }) => { if (!isCloud()) { throw new TRPCError({ @@ -22,28 +18,13 @@ export const feedbackRouter = createTRPCRouter({ }); } - if (!env.FOUNDER_EMAIL) { - throw new TRPCError({ - code: "INTERNAL_SERVER_ERROR", - message: "Feedback email is not configured.", - }); - } - - const senderEmail = ctx.session.user.email ?? "Unknown"; - const senderName = ctx.session.user.name ?? "Unknown"; - - const text = `New feedback received\n\nFrom: ${senderName} (${senderEmail})\nUser ID: ${ctx.session.user.id}\nTeam: ${ctx.team.name} (ID: ${ctx.team.id})\n\nMessage:\n${ - input.message - }`; - - await sendMail( - env.FOUNDER_EMAIL, - `Product feedback from ${ctx.team.name}`, - text, - toPlainHtml(text), - ctx.session.user.email ?? undefined, + const { id } = await submitFeedback( + { + userId: ctx.session.user.id, + team: { id: ctx.team.id, name: ctx.team.name }, + }, + input, ); - - return { success: true }; + return { success: true, id }; }), }); diff --git a/apps/web/src/server/mailer.ts b/apps/web/src/server/mailer.ts index bc360e62f..ea0e7b487 100644 --- a/apps/web/src/server/mailer.ts +++ b/apps/web/src/server/mailer.ts @@ -6,6 +6,7 @@ import { getDomains } from "./service/domain-service"; import { sendEmail } from "./service/email-service"; import { logger } from "./logger/log"; import { renderOtpEmail, renderTeamInviteEmail } from "./email-templates"; +import { toPlainHtml } from "./utils/email-content"; let usesend: UseSend | undefined; @@ -156,3 +157,74 @@ export async function sendMail( throw new Error("USESEND_API_KEY/UNSEND_API_KEY not found"); } } + +/** Emails the founder about new feedback. Errors are the caller's to log. */ +export async function sendFeedbackNotification(feedback: { + id: string; + email: string; + name: string | null; + userId: number | null; + teamId: number | null; + teamName: string | null; + message: string; +}) { + if (!env.FOUNDER_EMAIL) { + logger.warn("[Feedback]: FOUNDER_EMAIL not configured, not emailing feedback"); + return; + } + + const team = feedback.teamName ?? "Unknown team"; + const text = `New feedback received\n\nFrom: ${feedback.name ?? "Unknown"} (${feedback.email})\nUser ID: ${feedback.userId ?? "Unknown"}\nTeam: ${team} (ID: ${feedback.teamId ?? "Unknown"})\nFeedback ID: ${feedback.id}\n\nMessage:\n${feedback.message}`; + + await sendMail( + env.FOUNDER_EMAIL, + `Product feedback from ${team}`, + text, + toPlainHtml(text), + feedback.email, + ); +} + +/** The reply email was not accepted. Safe to try again with the same key. */ +export class MailNotSentError extends Error {} + +/** + * Emails a reply to someone's feedback through useSend's own API. The + * idempotency key makes a retry within 24 hours return the first send instead + * of sending a second email. Throws `MailNotSentError` when it isn't accepted. + */ +export async function sendFeedbackReply(params: { + to: string; + subject: string; + text: string; + idempotencyKey: string; +}) { + const from = env.FOUNDER_EMAIL ?? env.FROM_EMAIL; + if (!(env.USESEND_API_KEY ?? env.UNSEND_API_KEY) || !from) { + throw new MailNotSentError("Replies need UNSEND_API_KEY and FOUNDER_EMAIL"); + } + + let response: Awaited>; + try { + response = await getClient().emails.send( + { + to: params.to, + from, + replyTo: from, + subject: params.subject, + text: params.text, + html: toPlainHtml(params.text), + }, + { idempotencyKey: params.idempotencyKey }, + ); + } catch (error) { + throw new MailNotSentError( + error instanceof Error ? error.name : "Sending the reply failed", + ); + } + + if (!response.data) { + throw new MailNotSentError(response.error?.code ?? "Sending the reply failed"); + } + return { emailId: response.data.emailId }; +} diff --git a/apps/web/src/server/service/feedback-admin.ts b/apps/web/src/server/service/feedback-admin.ts new file mode 100644 index 000000000..a6aba501c --- /dev/null +++ b/apps/web/src/server/service/feedback-admin.ts @@ -0,0 +1,297 @@ +import { FeedbackStatus, type Prisma, type PrismaClient } from "@prisma/client"; +import { z } from "zod"; + +import { db as defaultDb } from "~/server/db"; +import { MailNotSentError, sendFeedbackReply } from "~/server/mailer"; +import { isUniqueViolation } from "~/server/service/feedback-service"; + +/** + * Reviewing and replying to feedback, for the internal admin API. + */ + +export const FEEDBACK_LIST_MAX = 200; +export const FEEDBACK_IMPORT_MAX = 500; +const IMPORTED_MESSAGE_MAX = 50_000; +const REPLY_MAX = 20_000; +const IMPORT_OPEN_WINDOW_MS = 30 * 24 * 60 * 60 * 1000; + +/** + * useSend's API remembers an idempotency key for 24 hours. A reply still + * unconfirmed after this long can't be retried safely by key alone: it may + * have gone out, so it needs a person to check. + */ +export const REPLY_RETRY_WINDOW_MS = 23 * 60 * 60 * 1000; + +export class FeedbackNotFoundError extends Error {} +export class IdempotencyConflictError extends Error {} +/** An unconfirmed reply too old to retry by key: check whether it arrived. */ +export class ReplyNeedsCheckError extends Error {} +export { MailNotSentError }; + +export const listFeedbackQuery = z.object({ + status: z.nativeEnum(FeedbackStatus).optional(), + since: z.coerce.date().optional(), + limit: z.coerce.number().int().min(1).max(FEEDBACK_LIST_MAX).default(50), + cursor: z.string().min(1).optional(), +}); + +export const statusBody = z.object({ status: z.nativeEnum(FeedbackStatus) }); + +export const replyBody = z.object({ + message: z.string().trim().min(1).max(REPLY_MAX), + /** One per reply. Sending again with the same key and message never sends twice. */ + idempotencyKey: z.string().trim().min(8).max(200), +}); + +export const importBody = z.object({ + items: z + .array( + z.object({ + /** Unique per original feedback email, e.g. the email's id. */ + externalId: z.string().trim().min(1).max(200), + email: z.string().trim().email(), + name: z.string().trim().max(200).optional(), + teamName: z.string().trim().max(200).optional(), + message: z.string().trim().min(1).max(IMPORTED_MESSAGE_MAX), + createdAt: z.coerce.date(), + }), + ) + .max(FEEDBACK_IMPORT_MAX), +}); + +const feedbackInclude = { + replies: { + orderBy: { createdAt: "asc" }, + select: { + id: true, + message: true, + deliveryStatus: true, + sentAt: true, + createdAt: true, + }, + }, +} satisfies Prisma.FeedbackInclude; + +type FeedbackWithReplies = Prisma.FeedbackGetPayload<{ + include: typeof feedbackInclude; +}>; + +function toFeedbackJson(feedback: FeedbackWithReplies) { + return { + id: feedback.id, + createdAt: feedback.createdAt.toISOString(), + status: feedback.status, + source: feedback.source, + userId: feedback.userId, + email: feedback.email, + name: feedback.name, + teamId: feedback.teamId, + teamName: feedback.teamName, + message: feedback.message, + replies: feedback.replies.map((reply) => ({ + id: reply.id, + message: reply.message, + deliveryStatus: reply.deliveryStatus, + sentAt: reply.sentAt?.toISOString() ?? null, + createdAt: reply.createdAt.toISOString(), + })), + }; +} + +/** Newest first. Pass the previous page's `nextCursor` as `cursor` for the next page. */ +export async function listFeedback( + query: z.infer, + db: PrismaClient = defaultDb, +) { + const rows = await db.feedback.findMany({ + where: { + status: query.status, + createdAt: query.since ? { gte: query.since } : undefined, + }, + orderBy: [{ createdAt: "desc" }, { id: "desc" }], + take: query.limit + 1, + ...(query.cursor ? { cursor: { id: query.cursor }, skip: 1 } : {}), + include: feedbackInclude, + }); + const page = rows.slice(0, query.limit); + return { + items: page.map(toFeedbackJson), + nextCursor: rows.length > query.limit ? (page.at(-1)?.id ?? null) : null, + }; +} + +export async function setFeedbackStatus( + id: string, + status: FeedbackStatus, + db: PrismaClient = defaultDb, +) { + const { count } = await db.feedback.updateMany({ + where: { id }, + data: { status }, + }); + if (count === 0) throw new FeedbackNotFoundError(); + const feedback = await db.feedback.findUniqueOrThrow({ + where: { id }, + include: feedbackInclude, + }); + return toFeedbackJson(feedback); +} + +type ReplyDeps = { db: PrismaClient; send: typeof sendFeedbackReply }; + +function replyEmail(feedbackMessage: string, reply: string) { + const quoted = feedbackMessage + .split("\n") + .map((line) => `> ${line}`) + .join("\n"); + return { + subject: "Re: your feedback to useSend", + text: `${reply}\n\nYou wrote:\n${quoted}`, + }; +} + +/** + * Emails a reply to whoever sent the feedback and records it, at most once per + * `idempotencyKey`. + * + * The reply is saved as SENDING, then sent through useSend's API with the + * reply's id as the idempotency key, so retrying a reply that may or may not + * have gone out returns the first send instead of sending again. On success + * the reply is SENT and the feedback REPLIED; on failure it's FAILED and the + * same key can be retried. + */ +export async function replyToFeedback( + feedbackId: string, + input: z.infer, + { db, send }: ReplyDeps = { db: defaultDb, send: sendFeedbackReply }, +) { + const feedback = await db.feedback.findUnique({ where: { id: feedbackId } }); + if (!feedback) throw new FeedbackNotFoundError(); + + let reply = await db.feedbackReply.findUnique({ + where: { idempotencyKey: input.idempotencyKey }, + }); + if (!reply) { + try { + reply = await db.feedbackReply.create({ + data: { + feedbackId, + message: input.message, + idempotencyKey: input.idempotencyKey, + }, + }); + } catch (error) { + // Another request with the same key saved it first. + if (!isUniqueViolation(error, "idempotencyKey")) throw error; + reply = await db.feedbackReply.findUniqueOrThrow({ + where: { idempotencyKey: input.idempotencyKey }, + }); + } + } + + // A key stands for one message: an edited reply needs a new key. + if (reply.feedbackId !== feedbackId || reply.message !== input.message) { + throw new IdempotencyConflictError(); + } + if (reply.deliveryStatus === "SENT") { + return { reply, sent: false }; + } + if ( + reply.deliveryStatus === "SENDING" && + Date.now() - reply.createdAt.getTime() > REPLY_RETRY_WINDOW_MS + ) { + throw new ReplyNeedsCheckError(); + } + + const email = replyEmail(feedback.message, reply.message); + try { + await send({ + to: feedback.email, + subject: email.subject, + text: email.text, + idempotencyKey: `feedback-reply:${reply.id}`, + }); + } catch (error) { + // Only from SENDING: a concurrent attempt that already succeeded wins. + await db.feedbackReply.updateMany({ + where: { id: reply.id, deliveryStatus: "SENDING" }, + data: { deliveryStatus: "FAILED" }, + }); + throw error instanceof MailNotSentError + ? error + : new MailNotSentError("Sending the reply failed"); + } + + const [sent] = await db.$transaction([ + db.feedbackReply.update({ + where: { id: reply.id }, + data: { deliveryStatus: "SENT", sentAt: new Date() }, + }), + db.feedback.update({ + where: { id: feedbackId }, + data: { status: "REPLIED" }, + }), + ]); + return { reply: sent, sent: true }; +} + +/** + * Copies feedback from the old feedback emails. Only feedback from an existing + * account is stored; the rest is counted as `unmatched`. Safe to run again: + * items already imported (by `externalId`) are skipped. + */ +export async function importFeedback( + input: z.infer, + db: PrismaClient = defaultDb, +) { + const emails = [ + ...new Set(input.items.map((item) => item.email.toLowerCase())), + ]; + const users = await db.user.findMany({ + where: { email: { in: emails, mode: "insensitive" } }, + select: { + id: true, + email: true, + teamUsers: { select: { team: { select: { id: true, name: true } } } }, + }, + }); + const byEmail = new Map( + users.map((user) => [user.email?.toLowerCase(), user]), + ); + + let unmatched = 0; + const rows: Prisma.FeedbackCreateManyInput[] = []; + for (const item of input.items) { + const user = byEmail.get(item.email.toLowerCase()); + if (!user) { + unmatched += 1; + continue; + } + const team = user.teamUsers.find( + (teamUser) => teamUser.team.name === item.teamName, + )?.team; + rows.push({ + externalId: item.externalId, + userId: user.id, + teamId: team?.id ?? null, + teamName: item.teamName ?? team?.name ?? null, + email: item.email, + name: item.name ?? null, + message: item.message, + source: "import", + // Old feedback was answered by email, if at all; only the last month's + // stays open so it can still get a reply. + status: + Date.now() - item.createdAt.getTime() > IMPORT_OPEN_WINDOW_MS + ? "CLOSED" + : "OPEN", + createdAt: item.createdAt, + }); + } + + const { count } = await db.feedback.createMany({ + data: rows, + skipDuplicates: true, + }); + return { created: count, skipped: rows.length - count, unmatched }; +} diff --git a/apps/web/src/server/service/feedback-admin.unit.test.ts b/apps/web/src/server/service/feedback-admin.unit.test.ts new file mode 100644 index 000000000..fce35df51 --- /dev/null +++ b/apps/web/src/server/service/feedback-admin.unit.test.ts @@ -0,0 +1,201 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +vi.mock("~/server/db", () => ({ db: {} })); +vi.mock("~/server/logger/log", () => ({ + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() }, +})); +vi.mock("~/server/mailer", () => { + class MailNotSentError extends Error {} + return { + MailNotSentError, + sendFeedbackReply: vi.fn(), + sendFeedbackNotification: vi.fn(), + }; +}); + +import { + IdempotencyConflictError, + MailNotSentError, + REPLY_RETRY_WINDOW_MS, + ReplyNeedsCheckError, + importFeedback, + replyToFeedback, +} from "~/server/service/feedback-admin"; + +const feedback = { + id: "fb_1", + email: "a@acme.com", + message: "Love it\nThanks", +}; + +function reply(overrides: Record = {}) { + return { + id: "rep_1", + feedbackId: "fb_1", + message: "Thanks!", + idempotencyKey: "key-123456", + deliveryStatus: "SENDING", + sentAt: null, + createdAt: new Date(), + ...overrides, + }; +} + +function setup() { + const db = { + feedback: { + findUnique: vi.fn(async () => feedback), + update: vi.fn(async () => feedback), + }, + feedbackReply: { + findUnique: vi.fn(async () => null as unknown), + findUniqueOrThrow: vi.fn(), + create: vi.fn(async () => reply()), + update: vi.fn(async () => + reply({ deliveryStatus: "SENT", sentAt: new Date() }), + ), + updateMany: vi.fn(async () => ({ count: 1 })), + }, + $transaction: vi.fn(async (ops: Promise[]) => Promise.all(ops)), + }; + const send = vi.fn(async () => ({ emailId: "em_1" })); + return { db, send, deps: { db: db as any, send } }; +} + +const input = { message: "Thanks!", idempotencyKey: "key-123456" }; + +describe("replyToFeedback", () => { + let ctx: ReturnType; + beforeEach(() => { + ctx = setup(); + }); + + it("emails the reply with the reply's id as the idempotency key, then marks it sent", async () => { + const result = await replyToFeedback("fb_1", input, ctx.deps); + + expect(ctx.send).toHaveBeenCalledWith({ + to: "a@acme.com", + subject: "Re: your feedback to useSend", + text: "Thanks!\n\nYou wrote:\n> Love it\n> Thanks", + idempotencyKey: "feedback-reply:rep_1", + }); + expect(result.sent).toBe(true); + expect(ctx.db.feedback.update).toHaveBeenCalledWith({ + where: { id: "fb_1" }, + data: { status: "REPLIED" }, + }); + }); + + it("doesn't send a reply that was already sent", async () => { + ctx.db.feedbackReply.findUnique.mockResolvedValueOnce( + reply({ deliveryStatus: "SENT" }), + ); + + const result = await replyToFeedback("fb_1", input, ctx.deps); + + expect(result.sent).toBe(false); + expect(ctx.send).not.toHaveBeenCalled(); + }); + + it("retries a failed or unconfirmed reply with the same idempotency key", async () => { + ctx.db.feedbackReply.findUnique.mockResolvedValueOnce( + reply({ deliveryStatus: "FAILED" }), + ); + + await replyToFeedback("fb_1", input, ctx.deps); + + expect(ctx.db.feedbackReply.create).not.toHaveBeenCalled(); + expect(ctx.send).toHaveBeenCalledWith( + expect.objectContaining({ idempotencyKey: "feedback-reply:rep_1" }), + ); + }); + + it("won't retry an unconfirmed reply older than the API remembers keys", async () => { + ctx.db.feedbackReply.findUnique.mockResolvedValueOnce( + reply({ createdAt: new Date(Date.now() - REPLY_RETRY_WINDOW_MS - 1000) }), + ); + + await expect( + replyToFeedback("fb_1", input, ctx.deps), + ).rejects.toBeInstanceOf(ReplyNeedsCheckError); + expect(ctx.send).not.toHaveBeenCalled(); + }); + + it("refuses a key reused for a different message", async () => { + ctx.db.feedbackReply.findUnique.mockResolvedValueOnce( + reply({ message: "Something else" }), + ); + + await expect( + replyToFeedback("fb_1", input, ctx.deps), + ).rejects.toBeInstanceOf(IdempotencyConflictError); + }); + + it("marks the reply failed, only if still sending, when the email isn't accepted", async () => { + ctx.send.mockRejectedValueOnce(new MailNotSentError("rate limited")); + + await expect( + replyToFeedback("fb_1", input, ctx.deps), + ).rejects.toBeInstanceOf(MailNotSentError); + expect(ctx.db.feedbackReply.updateMany).toHaveBeenCalledWith({ + where: { id: "rep_1", deliveryStatus: "SENDING" }, + data: { deliveryStatus: "FAILED" }, + }); + expect(ctx.db.feedback.update).not.toHaveBeenCalled(); + }); +}); + +describe("importFeedback", () => { + it("stores feedback from known accounts and counts the rest", async () => { + const createMany = vi.fn(async ({ data }: { data: unknown[] }) => ({ + count: data.length, + })); + const db = { + user: { + findMany: vi.fn(async () => [ + { + id: 7, + email: "a@acme.com", + teamUsers: [{ team: { id: 3, name: "Acme" } }], + }, + ]), + }, + feedback: { createMany }, + }; + + const result = await importFeedback( + { + items: [ + { + externalId: "em_1", + email: "A@acme.com", + teamName: "Acme", + message: "Old feedback", + createdAt: new Date("2026-01-01T00:00:00Z"), + }, + { + externalId: "em_2", + email: "nobody@else.com", + message: "Who?", + createdAt: new Date("2026-01-02T00:00:00Z"), + }, + ], + }, + db as any, + ); + + expect(result).toEqual({ created: 1, skipped: 0, unmatched: 1 }); + expect(createMany).toHaveBeenCalledWith({ + data: [ + expect.objectContaining({ + externalId: "em_1", + userId: 7, + teamId: 3, + source: "import", + status: "CLOSED", + }), + ], + skipDuplicates: true, + }); + }); +}); diff --git a/apps/web/src/server/service/feedback-service.ts b/apps/web/src/server/service/feedback-service.ts new file mode 100644 index 000000000..82784ad01 --- /dev/null +++ b/apps/web/src/server/service/feedback-service.ts @@ -0,0 +1,183 @@ +import { Prisma, type Feedback, type PrismaClient } from "@prisma/client"; +import { TRPCError } from "@trpc/server"; +import { z } from "zod"; + +import { db as defaultDb } from "~/server/db"; +import { logger } from "~/server/logger/log"; +import { sendFeedbackNotification } from "~/server/mailer"; + +const HOUR_MS = 60 * 60 * 1000; + +export const FEEDBACK_MAX_LENGTH = 2000; + +/** The same message from the same person within this window is a resend, not new feedback. */ +export const DUPLICATE_WINDOW_MS = 24 * HOUR_MS; +export const FEEDBACK_RATE_LIMIT = { limit: 10, windowMs: HOUR_MS }; + +export const submitFeedbackInput = z.object({ + message: z + .string() + .trim() + .min(1, "Feedback cannot be empty") + .max(FEEDBACK_MAX_LENGTH), + /** One per draft, so retrying the same draft never saves it twice. */ + clientKey: z.string().uuid().optional(), +}); + +export type SubmitFeedbackInput = z.infer; + +type Deps = { + db: PrismaClient; + notify: (feedback: Feedback) => Promise; +}; + +const defaultDeps: Deps = { db: defaultDb, notify: sendFeedbackNotification }; + +export function isUniqueViolation(error: unknown, field: string) { + return ( + error instanceof Prisma.PrismaClientKnownRequestError && + error.code === "P2002" && + JSON.stringify(error.meta?.target ?? "").includes(field) + ); +} + +const keyConflict = () => + new TRPCError({ code: "CONFLICT", message: "Feedback key already used" }); + +/** + * The feedback this submission repeats, if any: the same draft (`clientKey`) + * with the same text, or the same message from the same person within a day. + */ +async function findExisting( + tx: Prisma.TransactionClient, + userId: number, + message: string, + clientKey: string | undefined, + now: Date, +) { + if (clientKey) { + const byKey = await tx.feedback.findUnique({ where: { clientKey } }); + if (byKey) { + // Someone else's key, or the same draft edited after a failed send: + // never report text as saved when it wasn't. + if (byKey.userId !== userId || byKey.message !== message) { + throw keyConflict(); + } + return byKey; + } + } + + return tx.feedback.findFirst({ + where: { + userId, + message, + createdAt: { gte: new Date(now.getTime() - DUPLICATE_WINDOW_MS) }, + }, + orderBy: { createdAt: "desc" }, + }); +} + +/** + * Saves feedback, then emails the founder about it without waiting, so a mail + * failure never loses it. Resubmitting returns the saved feedback instead of + * saving or emailing it again. + */ +export async function submitFeedback( + sender: { userId: number; team: { id: number; name: string } }, + input: SubmitFeedbackInput, + { db, notify }: Deps = defaultDeps, +): Promise<{ id: string; created: boolean }> { + const message = input.message.trim(); + const now = new Date(); + + let result: { feedback: Feedback; created: boolean }; + try { + // Locking the sender's row makes their submissions one at a time, so two + // quick resends can't both miss each other in the checks below. The email + // and name come from the locked row, not the possibly stale session. + result = await db.$transaction(async (tx) => { + const [user] = await tx.$queryRaw< + { email: string | null; name: string | null }[] + >`SELECT email, name FROM "User" WHERE id = ${sender.userId} FOR UPDATE`; + if (!user) { + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "Account not found", + }); + } + if (!user.email) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: "Add an email address to send feedback", + }); + } + + const existing = await findExisting( + tx, + sender.userId, + message, + input.clientKey, + now, + ); + if (existing) { + return { feedback: existing, created: false }; + } + + const recent = await tx.feedback.count({ + where: { + userId: sender.userId, + createdAt: { + gte: new Date(now.getTime() - FEEDBACK_RATE_LIMIT.windowMs), + }, + }, + }); + if (recent >= FEEDBACK_RATE_LIMIT.limit) { + throw new TRPCError({ + code: "TOO_MANY_REQUESTS", + message: "Too much feedback at once. Try again in an hour.", + }); + } + + const feedback = await tx.feedback.create({ + data: { + userId: sender.userId, + teamId: sender.team.id, + teamName: sender.team.name, + email: user.email, + name: user.name, + message, + source: "web", + clientKey: input.clientKey ?? null, + }, + }); + return { feedback, created: true }; + }); + } catch (error) { + // Two requests with the same key raced past each other: the other one saved it. + if (!input.clientKey || !isUniqueViolation(error, "clientKey")) { + throw error; + } + const existing = await db.feedback.findUnique({ + where: { clientKey: input.clientKey }, + }); + if (existing?.userId !== sender.userId || existing.message !== message) { + throw keyConflict(); + } + result = { feedback: existing, created: false }; + } + + const { feedback, created } = result; + if (created) { + notify(feedback).catch((error: unknown) => + logger.error( + { + feedbackId: feedback.id, + err: error instanceof Error ? error.name : typeof error, + }, + "[Feedback]: Failed to email feedback", + ), + ); + } + + return { id: feedback.id, created }; +} diff --git a/apps/web/src/server/service/feedback-service.unit.test.ts b/apps/web/src/server/service/feedback-service.unit.test.ts new file mode 100644 index 000000000..e5b3b55d8 --- /dev/null +++ b/apps/web/src/server/service/feedback-service.unit.test.ts @@ -0,0 +1,152 @@ +import { Prisma } from "@prisma/client"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +vi.mock("~/server/db", () => ({ db: {} })); +vi.mock("~/server/mailer", () => ({ sendFeedbackNotification: vi.fn() })); +vi.mock("~/server/logger/log", () => ({ + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() }, +})); + +import { + FEEDBACK_RATE_LIMIT, + submitFeedback, +} from "~/server/service/feedback-service"; + +const sender = { userId: 7, team: { id: 3, name: "Acme" } }; +const KEY = "1b4e28ba-2fa1-41d2-883f-0016d3cca427"; + +function saved(overrides: Record = {}) { + return { + id: "fb_1", + userId: 7, + message: "Love it", + clientKey: KEY, + ...overrides, + }; +} + +function setup() { + const tx = { + $queryRaw: vi.fn(async () => [{ email: "a@acme.com", name: "Ana" }]), + feedback: { + findUnique: vi.fn(async () => null), + findFirst: vi.fn(async () => null), + count: vi.fn(async () => 0), + create: vi.fn(async ({ data }: { data: object }) => ({ + id: "fb_new", + ...data, + })), + }, + }; + const db = { + $transaction: vi.fn(async (fn: (client: typeof tx) => unknown) => fn(tx)), + feedback: { findUnique: vi.fn() }, + }; + const notify = vi.fn(async () => undefined); + return { tx, db, notify, deps: { db: db as any, notify } }; +} + +describe("submitFeedback", () => { + let ctx: ReturnType; + beforeEach(() => { + ctx = setup(); + }); + + it("saves the feedback with the sender's details, then emails about it", async () => { + const result = await submitFeedback( + sender, + { message: " Love it ", clientKey: KEY }, + ctx.deps, + ); + + expect(result).toEqual({ id: "fb_new", created: true }); + expect(ctx.tx.feedback.create).toHaveBeenCalledWith({ + data: expect.objectContaining({ + userId: 7, + teamId: 3, + teamName: "Acme", + email: "a@acme.com", + name: "Ana", + message: "Love it", + source: "web", + clientKey: KEY, + }), + }); + expect(ctx.notify).toHaveBeenCalledTimes(1); + }); + + it("still saves it when the email fails", async () => { + ctx.notify.mockRejectedValueOnce(new Error("smtp down")); + + await expect( + submitFeedback(sender, { message: "Love it" }, ctx.deps), + ).resolves.toEqual({ id: "fb_new", created: true }); + }); + + it("returns the saved feedback for a retry of the same draft, without emailing again", async () => { + ctx.tx.feedback.findUnique.mockResolvedValueOnce(saved() as any); + + const result = await submitFeedback( + sender, + { message: "Love it", clientKey: KEY }, + ctx.deps, + ); + + expect(result).toEqual({ id: "fb_1", created: false }); + expect(ctx.tx.feedback.create).not.toHaveBeenCalled(); + expect(ctx.notify).not.toHaveBeenCalled(); + }); + + it("refuses a draft key reused for different text", async () => { + ctx.tx.feedback.findUnique.mockResolvedValueOnce( + saved({ message: "Something else" }) as any, + ); + + await expect( + submitFeedback(sender, { message: "Love it", clientKey: KEY }, ctx.deps), + ).rejects.toMatchObject({ code: "CONFLICT" }); + }); + + it("treats the same message from the same person within a day as a resend", async () => { + ctx.tx.feedback.findFirst.mockResolvedValueOnce( + saved({ clientKey: null }) as any, + ); + + const result = await submitFeedback( + sender, + { message: "Love it" }, + ctx.deps, + ); + + expect(result.created).toBe(false); + expect(ctx.notify).not.toHaveBeenCalled(); + }); + + it("refuses more than the hourly limit", async () => { + ctx.tx.feedback.count.mockResolvedValueOnce(FEEDBACK_RATE_LIMIT.limit); + + await expect( + submitFeedback(sender, { message: "Love it" }, ctx.deps), + ).rejects.toMatchObject({ code: "TOO_MANY_REQUESTS" }); + }); + + it("returns the other request's save when two submits with the same key race", async () => { + ctx.db.$transaction.mockRejectedValueOnce( + new Prisma.PrismaClientKnownRequestError("dup", { + code: "P2002", + clientVersion: "6", + meta: { target: ["clientKey"] }, + }), + ); + ctx.db.feedback.findUnique.mockResolvedValueOnce(saved()); + + const result = await submitFeedback( + sender, + { message: "Love it", clientKey: KEY }, + ctx.deps, + ); + + expect(result).toEqual({ id: "fb_1", created: false }); + expect(ctx.notify).not.toHaveBeenCalled(); + }); +}); From 8d3a0607acd1e1900d1c60b38eb3631f7ddb7012 Mon Sep 17 00:00:00 2001 From: KM Koushik Date: Tue, 10 Nov 2026 15:16:22 +1100 Subject: [PATCH 2/4] fix(feedback): claim replies per attempt and never resend one that may have gone out; cap admin bodies while reading --- .../20261110130000_add_feedback/migration.sql | 2 + apps/web/prisma/schema.prisma | 6 +- .../feedback/[id]/reply/[replyId]/route.ts | 46 ++++ .../api/admin/feedback/[id]/reply/route.ts | 23 +- .../app/api/admin/feedback/route.api.test.ts | 37 +++ apps/web/src/server/admin-api.ts | 21 +- apps/web/src/server/mailer.ts | 56 ++-- apps/web/src/server/service/feedback-admin.ts | 244 +++++++++++++----- .../service/feedback-admin.unit.test.ts | 151 +++++++++-- 9 files changed, 477 insertions(+), 109 deletions(-) create mode 100644 apps/web/src/app/api/admin/feedback/[id]/reply/[replyId]/route.ts diff --git a/apps/web/prisma/migrations/20261110130000_add_feedback/migration.sql b/apps/web/prisma/migrations/20261110130000_add_feedback/migration.sql index 967b9ba21..7da495cc0 100644 --- a/apps/web/prisma/migrations/20261110130000_add_feedback/migration.sql +++ b/apps/web/prisma/migrations/20261110130000_add_feedback/migration.sql @@ -30,6 +30,8 @@ CREATE TABLE "FeedbackReply" ( "message" TEXT NOT NULL, "idempotencyKey" TEXT NOT NULL, "deliveryStatus" "FeedbackReplyStatus" NOT NULL DEFAULT 'SENDING', + "attemptId" TEXT, + "attemptStartedAt" TIMESTAMP(3), "sentAt" TIMESTAMP(3), "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, "updatedAt" TIMESTAMP(3) NOT NULL, diff --git a/apps/web/prisma/schema.prisma b/apps/web/prisma/schema.prisma index 501cdeca0..67e44c428 100644 --- a/apps/web/prisma/schema.prisma +++ b/apps/web/prisma/schema.prisma @@ -578,9 +578,10 @@ model Feedback { } enum FeedbackReplyStatus { - /// Being sent, or it's unknown whether it went + /// Being sent, or it's unknown whether it went: never resent automatically SENDING SENT + /// Certainly not sent, so it's safe to send again FAILED } @@ -592,6 +593,9 @@ model FeedbackReply { /// One per reply: sending again with the same key never sends a second email idempotencyKey String @unique deliveryStatus FeedbackReplyStatus @default(SENDING) + /// The send attempt holding it while SENDING: only that attempt may complete it + attemptId String? + attemptStartedAt DateTime? sentAt DateTime? createdAt DateTime @default(now()) updatedAt DateTime @updatedAt diff --git a/apps/web/src/app/api/admin/feedback/[id]/reply/[replyId]/route.ts b/apps/web/src/app/api/admin/feedback/[id]/reply/[replyId]/route.ts new file mode 100644 index 000000000..5be840673 --- /dev/null +++ b/apps/web/src/app/api/admin/feedback/[id]/reply/[replyId]/route.ts @@ -0,0 +1,46 @@ +import { AdminApiError, adminApiRoute, param } from "~/server/admin-api"; +import { + ReplyNotFoundError, + ReplyNotSendingError, + ReplyStillSendingError, + settleReply, + settleReplyBody, +} from "~/server/service/feedback-admin"; + +export const dynamic = "force-dynamic"; + +/** + * PATCH /api/admin/feedback/{id}/reply/{replyId} with `{ "deliveryStatus": "SENT" | "FAILED" }`. + * Settles a reply whose send is unknown. Only after checking whether the email + * arrived: FAILED lets the same key be sent again. Allowed only for a SENDING + * reply whose attempt started at least 10 minutes ago. + */ +export const PATCH = adminApiRoute(async ({ body, params }) => { + const { deliveryStatus } = settleReplyBody.parse(body); + try { + const reply = await settleReply( + param(params.id) ?? "", + param(params.replyId) ?? "", + deliveryStatus, + ); + return { + id: reply.id, + deliveryStatus: reply.deliveryStatus, + sentAt: reply.sentAt?.toISOString() ?? null, + }; + } catch (error) { + if (error instanceof ReplyNotFoundError) { + throw new AdminApiError(404, "Reply not found"); + } + if (error instanceof ReplyNotSendingError) { + throw new AdminApiError( + 409, + "Only a reply that's still sending can be settled", + ); + } + if (error instanceof ReplyStillSendingError) { + throw new AdminApiError(409, "Reply is still sending; try again later"); + } + throw error; + } +}); diff --git a/apps/web/src/app/api/admin/feedback/[id]/reply/route.ts b/apps/web/src/app/api/admin/feedback/[id]/reply/route.ts index 539c9895a..ffc4aaa5b 100644 --- a/apps/web/src/app/api/admin/feedback/[id]/reply/route.ts +++ b/apps/web/src/app/api/admin/feedback/[id]/reply/route.ts @@ -3,7 +3,8 @@ import { FeedbackNotFoundError, IdempotencyConflictError, MailNotSentError, - ReplyNeedsCheckError, + MailUncertainError, + ReplyInProgressError, replyBody, replyToFeedback, } from "~/server/service/feedback-admin"; @@ -12,9 +13,11 @@ export const dynamic = "force-dynamic"; /** * POST /api/admin/feedback/{id}/reply with `{ "message": "...", "idempotencyKey": "..." }`. - * Emails the reply to whoever sent the feedback. The same key and message again - * never sends a second email: 200 with the reply once it's sent, or a retry if - * it failed. 201 when this request sent it. + * Emails the reply to whoever sent the feedback, at most once per key: + * - 201 sent now; 200 already sent with this key. + * - 502 certainly not sent: retry with the same key. + * - 409 being sent, or it may have been sent: check whether it arrived, then + * settle it with PATCH /api/admin/feedback/{id}/reply/{replyId}. */ export const POST = adminApiRoute(async ({ body, params }) => { const input = replyBody.parse(body); @@ -38,16 +41,22 @@ export const POST = adminApiRoute(async ({ body, params }) => { "This key was used for a different reply; use a new key", ); } - if (error instanceof ReplyNeedsCheckError) { + if (error instanceof ReplyInProgressError) { throw new AdminApiError( 409, - "This reply may have been sent over a day ago; check before sending it again with a new key", + "This reply is being sent, or it may have been sent; check whether it arrived before settling it", + ); + } + if (error instanceof MailUncertainError) { + throw new AdminApiError( + 409, + "It's unknown whether the reply was sent; check whether it arrived before settling it", ); } if (error instanceof MailNotSentError) { throw new AdminApiError( 502, - "The reply email was not sent; try again with the same key", + "The reply was not sent; try again with the same key", ); } throw error; diff --git a/apps/web/src/app/api/admin/feedback/route.api.test.ts b/apps/web/src/app/api/admin/feedback/route.api.test.ts index ea4033092..310e2f576 100644 --- a/apps/web/src/app/api/admin/feedback/route.api.test.ts +++ b/apps/web/src/app/api/admin/feedback/route.api.test.ts @@ -65,3 +65,40 @@ describe("GET /api/admin/feedback", () => { expect(response.status).toBe(400); }); }); + +describe("admin API bodies", () => { + beforeEach(() => { + mockEnv.ADMIN_API_TOKEN = TOKEN; + }); + + it("stops reading a body past the limit, even without a length header", async () => { + const { adminApiRoute } = await import("~/server/admin-api"); + const handler = vi.fn(async () => ({ ok: true })); + const route = adminApiRoute(handler, { maxBodyBytes: 10 }); + let pulled = 0; + const body = new ReadableStream({ + pull(controller) { + pulled += 1; + if (pulled > 100) return controller.close(); + controller.enqueue(new TextEncoder().encode("xxxxxxxx")); + }, + }); + + const response = await route( + new Request("http://localhost/api/admin/x", { + method: "POST", + headers: { + authorization: `Bearer ${TOKEN}`, + "content-type": "application/json", + }, + body, + // @ts-expect-error Node needs this for a streamed body + duplex: "half", + }), + ); + + expect(response.status).toBe(413); + expect(handler).not.toHaveBeenCalled(); + expect(pulled).toBeLessThan(10); + }); +}); diff --git a/apps/web/src/server/admin-api.ts b/apps/web/src/server/admin-api.ts index 2f483a331..3b6a27382 100644 --- a/apps/web/src/server/admin-api.ts +++ b/apps/web/src/server/admin-api.ts @@ -33,13 +33,28 @@ export function json(status: number, body: unknown) { return Response.json(body, { status, headers: HEADERS }); } +/** Reads a JSON body, stopping as soon as it's past `maxBytes`. */ async function readJsonBody(req: Request, maxBytes: number) { const declared = Number(req.headers.get("content-length") ?? 0); if (declared > maxBytes) throw new AdminApiError(413, "Body too large"); - const text = await req.text(); - if (Buffer.byteLength(text) > maxBytes) { - throw new AdminApiError(413, "Body too large"); + + const chunks: Uint8Array[] = []; + let size = 0; + if (req.body) { + const reader = req.body.getReader(); + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + size += value.byteLength; + if (size > maxBytes) { + await reader.cancel(); + throw new AdminApiError(413, "Body too large"); + } + chunks.push(value); + } } + + const text = Buffer.concat(chunks).toString("utf8"); if (text.trim() === "") return undefined; try { return JSON.parse(text) as unknown; diff --git a/apps/web/src/server/mailer.ts b/apps/web/src/server/mailer.ts index ea0e7b487..01500918a 100644 --- a/apps/web/src/server/mailer.ts +++ b/apps/web/src/server/mailer.ts @@ -20,7 +20,7 @@ const getClient = () => { export async function sendSignUpEmail( email: string, token: string, - url: string + url: string, ) { const { host } = new URL(url); @@ -47,7 +47,7 @@ export async function sendSignUpEmail( export async function sendTeamInviteEmail( email: string, url: string, - teamName: string + teamName: string, ) { const { host } = new URL(url); @@ -89,7 +89,7 @@ export async function sendMail( text: string, html: string, replyTo?: string, - fromOverride?: string + fromOverride?: string, ) { if (isSelfHosted()) { logger.info("Sending email using self hosted"); @@ -114,9 +114,11 @@ export async function sendMail( const availableDomains = domains.map((d) => d.name); const domain = domains[0]; - const candidateFroms = [fromOverride, env.FROM_EMAIL, `hello@${domain.name}`].filter( - (value): value is string => Boolean(value) - ); + const candidateFroms = [ + fromOverride, + env.FROM_EMAIL, + `hello@${domain.name}`, + ].filter((value): value is string => Boolean(value)); const selectedFrom = candidateFroms.find((address) => { @@ -150,7 +152,7 @@ export async function sendMail( } else { logger.error( { code: resp.error?.code, message: resp.error?.message }, - "Error sending email using usesend" + "Error sending email using usesend", ); } } else { @@ -169,7 +171,9 @@ export async function sendFeedbackNotification(feedback: { message: string; }) { if (!env.FOUNDER_EMAIL) { - logger.warn("[Feedback]: FOUNDER_EMAIL not configured, not emailing feedback"); + logger.warn( + "[Feedback]: FOUNDER_EMAIL not configured, not emailing feedback", + ); return; } @@ -185,13 +189,27 @@ export async function sendFeedbackNotification(feedback: { ); } -/** The reply email was not accepted. Safe to try again with the same key. */ +/** The reply email was certainly not sent. Safe to send again. */ export class MailNotSentError extends Error {} +/** It's unknown whether the reply email went out, e.g. the connection dropped. */ +export class MailUncertainError extends Error {} + +/** API errors returned before anything is sent. */ +const NOT_SENT_CODES = new Set([ + "BAD_REQUEST", + "UNAUTHORIZED", + "FORBIDDEN", + "NOT_FOUND", + "METHOD_NOT_ALLOWED", + "RATE_LIMITED", +]); + /** - * Emails a reply to someone's feedback through useSend's own API. The - * idempotency key makes a retry within 24 hours return the first send instead - * of sending a second email. Throws `MailNotSentError` when it isn't accepted. + * Emails a reply to someone's feedback through useSend's own API, with an + * idempotency key as extra protection against a second send. Throws + * `MailNotSentError` when it certainly wasn't sent and `MailUncertainError` + * when it may have been. */ export async function sendFeedbackReply(params: { to: string; @@ -218,13 +236,15 @@ export async function sendFeedbackReply(params: { { idempotencyKey: params.idempotencyKey }, ); } catch (error) { - throw new MailNotSentError( - error instanceof Error ? error.name : "Sending the reply failed", + // The request may have reached the API before the connection failed. + throw new MailUncertainError( + error instanceof Error ? error.name : "Unknown", ); } - if (!response.data) { - throw new MailNotSentError(response.error?.code ?? "Sending the reply failed"); - } - return { emailId: response.data.emailId }; + if (response.data) return { emailId: response.data.emailId }; + const code = response.error?.code ?? "UNKNOWN"; + throw NOT_SENT_CODES.has(code) + ? new MailNotSentError(code) + : new MailUncertainError(code); } diff --git a/apps/web/src/server/service/feedback-admin.ts b/apps/web/src/server/service/feedback-admin.ts index a6aba501c..c81ac43cc 100644 --- a/apps/web/src/server/service/feedback-admin.ts +++ b/apps/web/src/server/service/feedback-admin.ts @@ -1,8 +1,18 @@ -import { FeedbackStatus, type Prisma, type PrismaClient } from "@prisma/client"; +import { + FeedbackStatus, + type FeedbackReply, + type Prisma, + type PrismaClient, +} from "@prisma/client"; +import { randomUUID } from "crypto"; import { z } from "zod"; import { db as defaultDb } from "~/server/db"; -import { MailNotSentError, sendFeedbackReply } from "~/server/mailer"; +import { + MailNotSentError, + MailUncertainError, + sendFeedbackReply, +} from "~/server/mailer"; import { isUniqueViolation } from "~/server/service/feedback-service"; /** @@ -15,18 +25,25 @@ const IMPORTED_MESSAGE_MAX = 50_000; const REPLY_MAX = 20_000; const IMPORT_OPEN_WINDOW_MS = 30 * 24 * 60 * 60 * 1000; +/** Reserving a reply retries this often when another request changes it meanwhile. */ +const RESERVE_ATTEMPTS = 3; + /** - * useSend's API remembers an idempotency key for 24 hours. A reply still - * unconfirmed after this long can't be retried safely by key alone: it may - * have gone out, so it needs a person to check. + * A reply stuck in SENDING this long after its attempt started is treated as + * abandoned, and an operator may settle it after checking whether it arrived. */ -export const REPLY_RETRY_WINDOW_MS = 23 * 60 * 60 * 1000; +export const SETTLE_AFTER_MS = 10 * 60 * 1000; export class FeedbackNotFoundError extends Error {} export class IdempotencyConflictError extends Error {} -/** An unconfirmed reply too old to retry by key: check whether it arrived. */ -export class ReplyNeedsCheckError extends Error {} -export { MailNotSentError }; +/** A reply with this key is being sent, or it's unknown whether it went. */ +export class ReplyInProgressError extends Error {} +export class ReplyNotFoundError extends Error {} +/** Only a SENDING reply can be settled by hand. */ +export class ReplyNotSendingError extends Error {} +/** Its send attempt started less than `SETTLE_AFTER_MS` ago. */ +export class ReplyStillSendingError extends Error {} +export { MailNotSentError, MailUncertainError }; export const listFeedbackQuery = z.object({ status: z.nativeEnum(FeedbackStatus).optional(), @@ -37,6 +54,10 @@ export const listFeedbackQuery = z.object({ export const statusBody = z.object({ status: z.nativeEnum(FeedbackStatus) }); +export const settleReplyBody = z.object({ + deliveryStatus: z.enum(["SENT", "FAILED"]), +}); + export const replyBody = z.object({ message: z.string().trim().min(1).max(REPLY_MAX), /** One per reply. Sending again with the same key and message never sends twice. */ @@ -139,6 +160,12 @@ export async function setFeedbackStatus( type ReplyDeps = { db: PrismaClient; send: typeof sendFeedbackReply }; +/** A new attempt to send a reply: only the attempt holding a SENDING reply may complete it. */ +const newAttempt = () => ({ + attemptId: randomUUID(), + attemptStartedAt: new Date(), +}); + function replyEmail(feedbackMessage: string, reply: string) { const quoted = feedbackMessage .split("\n") @@ -150,15 +177,82 @@ function replyEmail(feedbackMessage: string, reply: string) { }; } +type Reservation = + | { kind: "claimed"; reply: FeedbackReply } + | { kind: "sent"; reply: FeedbackReply }; + +/** + * Claims the reply with this key for sending, or finds that it was sent. Each + * step is one atomic write (the unique key on insert, a conditional update + * from FAILED), so only one attempt ever holds a reply in SENDING. + */ +async function reserveReply( + db: PrismaClient, + feedbackId: string, + input: z.infer, +): Promise { + for (let i = 0; i < RESERVE_ATTEMPTS; i++) { + const existing = await db.feedbackReply.findUnique({ + where: { idempotencyKey: input.idempotencyKey }, + }); + + if (!existing) { + try { + const reply = await db.feedbackReply.create({ + data: { + feedbackId, + message: input.message, + idempotencyKey: input.idempotencyKey, + ...newAttempt(), + }, + }); + return { kind: "claimed", reply }; + } catch (error) { + // Another request with the same key saved it first: look again. + if (isUniqueViolation(error, "idempotencyKey")) continue; + throw error; + } + } + + // A key stands for one message: an edited reply needs a new key. + if ( + existing.feedbackId !== feedbackId || + existing.message !== input.message + ) { + throw new IdempotencyConflictError(); + } + if (existing.deliveryStatus === "SENT") { + return { kind: "sent", reply: existing }; + } + if (existing.deliveryStatus === "SENDING") { + throw new ReplyInProgressError(); + } + + // FAILED: it certainly wasn't sent, so claim it to send again. + const attempt = newAttempt(); + const { count } = await db.feedbackReply.updateMany({ + where: { id: existing.id, deliveryStatus: "FAILED" }, + data: { deliveryStatus: "SENDING", ...attempt }, + }); + if (count === 1) { + return { + kind: "claimed", + reply: { ...existing, deliveryStatus: "SENDING", ...attempt }, + }; + } + } + throw new ReplyInProgressError(); +} + /** * Emails a reply to whoever sent the feedback and records it, at most once per * `idempotencyKey`. * - * The reply is saved as SENDING, then sent through useSend's API with the - * reply's id as the idempotency key, so retrying a reply that may or may not - * have gone out returns the first send instead of sending again. On success - * the reply is SENT and the feedback REPLIED; on failure it's FAILED and the - * same key can be retried. + * The reply is claimed as SENDING first, then sent outside any transaction. + * Sent: the reply is SENT and the feedback REPLIED. Certainly not sent: it's + * FAILED and the same key can be retried. Unknown (e.g. the connection + * dropped): it stays SENDING and is never resent automatically; someone checks + * whether it arrived and settles it with `settleReply`. */ export async function replyToFeedback( feedbackId: string, @@ -168,40 +262,17 @@ export async function replyToFeedback( const feedback = await db.feedback.findUnique({ where: { id: feedbackId } }); if (!feedback) throw new FeedbackNotFoundError(); - let reply = await db.feedbackReply.findUnique({ - where: { idempotencyKey: input.idempotencyKey }, - }); - if (!reply) { - try { - reply = await db.feedbackReply.create({ - data: { - feedbackId, - message: input.message, - idempotencyKey: input.idempotencyKey, - }, - }); - } catch (error) { - // Another request with the same key saved it first. - if (!isUniqueViolation(error, "idempotencyKey")) throw error; - reply = await db.feedbackReply.findUniqueOrThrow({ - where: { idempotencyKey: input.idempotencyKey }, - }); - } - } - - // A key stands for one message: an edited reply needs a new key. - if (reply.feedbackId !== feedbackId || reply.message !== input.message) { - throw new IdempotencyConflictError(); - } - if (reply.deliveryStatus === "SENT") { - return { reply, sent: false }; - } - if ( - reply.deliveryStatus === "SENDING" && - Date.now() - reply.createdAt.getTime() > REPLY_RETRY_WINDOW_MS - ) { - throw new ReplyNeedsCheckError(); + const reservation = await reserveReply(db, feedbackId, input); + if (reservation.kind === "sent") { + return { reply: reservation.reply, sent: false }; } + const { reply } = reservation; + // Only this attempt may record the outcome. + const mine = { + id: reply.id, + attemptId: reply.attemptId, + deliveryStatus: "SENDING" as const, + }; const email = replyEmail(feedback.message, reply.message); try { @@ -212,27 +283,82 @@ export async function replyToFeedback( idempotencyKey: `feedback-reply:${reply.id}`, }); } catch (error) { - // Only from SENDING: a concurrent attempt that already succeeded wins. - await db.feedbackReply.updateMany({ - where: { id: reply.id, deliveryStatus: "SENDING" }, - data: { deliveryStatus: "FAILED" }, - }); - throw error instanceof MailNotSentError + if (error instanceof MailNotSentError) { + await db.feedbackReply.updateMany({ + where: mine, + data: { deliveryStatus: "FAILED" }, + }); + throw error; + } + // It may have gone out: leave it SENDING for a person to check. + throw error instanceof MailUncertainError ? error - : new MailNotSentError("Sending the reply failed"); + : new MailUncertainError("Unknown"); } - const [sent] = await db.$transaction([ - db.feedbackReply.update({ - where: { id: reply.id }, - data: { deliveryStatus: "SENT", sentAt: new Date() }, + const sentAt = new Date(); + await db.$transaction([ + db.feedbackReply.updateMany({ + where: mine, + data: { deliveryStatus: "SENT", sentAt }, }), db.feedback.update({ where: { id: feedbackId }, data: { status: "REPLIED" }, }), ]); - return { reply: sent, sent: true }; + return { + reply: { ...reply, deliveryStatus: "SENT" as const, sentAt }, + sent: true, + }; +} + +/** + * Settles a reply stuck in SENDING, after checking whether the email arrived: + * SENT records it as sent, FAILED lets the same key be sent again. Never done + * automatically, and only once its attempt is at least `SETTLE_AFTER_MS` old. + */ +export async function settleReply( + feedbackId: string, + replyId: string, + deliveryStatus: "SENT" | "FAILED", + db: PrismaClient = defaultDb, +) { + const reply = await db.feedbackReply.findFirst({ + where: { id: replyId, feedbackId }, + }); + if (!reply) throw new ReplyNotFoundError(); + if (reply.deliveryStatus !== "SENDING") throw new ReplyNotSendingError(); + const startedAt = reply.attemptStartedAt ?? reply.createdAt; + if (Date.now() - startedAt.getTime() < SETTLE_AFTER_MS) { + throw new ReplyStillSendingError(); + } + + const where = { + id: reply.id, + deliveryStatus: "SENDING" as const, + attemptId: reply.attemptId, + }; + if (deliveryStatus === "SENT") { + await db.$transaction(async (tx) => { + const { count } = await tx.feedbackReply.updateMany({ + where, + data: { deliveryStatus: "SENT", sentAt: new Date() }, + }); + if (count === 0) throw new ReplyNotSendingError(); + await tx.feedback.update({ + where: { id: feedbackId }, + data: { status: "REPLIED" }, + }); + }); + } else { + const { count } = await db.feedbackReply.updateMany({ + where, + data: { deliveryStatus: "FAILED" }, + }); + if (count === 0) throw new ReplyNotSendingError(); + } + return db.feedbackReply.findUniqueOrThrow({ where: { id: reply.id } }); } /** diff --git a/apps/web/src/server/service/feedback-admin.unit.test.ts b/apps/web/src/server/service/feedback-admin.unit.test.ts index fce35df51..5f2623a66 100644 --- a/apps/web/src/server/service/feedback-admin.unit.test.ts +++ b/apps/web/src/server/service/feedback-admin.unit.test.ts @@ -6,8 +6,10 @@ vi.mock("~/server/logger/log", () => ({ })); vi.mock("~/server/mailer", () => { class MailNotSentError extends Error {} + class MailUncertainError extends Error {} return { MailNotSentError, + MailUncertainError, sendFeedbackReply: vi.fn(), sendFeedbackNotification: vi.fn(), }; @@ -16,10 +18,14 @@ vi.mock("~/server/mailer", () => { import { IdempotencyConflictError, MailNotSentError, - REPLY_RETRY_WINDOW_MS, - ReplyNeedsCheckError, + MailUncertainError, + ReplyInProgressError, + ReplyNotSendingError, + ReplyStillSendingError, + SETTLE_AFTER_MS, importFeedback, replyToFeedback, + settleReply, } from "~/server/service/feedback-admin"; const feedback = { @@ -35,6 +41,8 @@ function reply(overrides: Record = {}) { message: "Thanks!", idempotencyKey: "key-123456", deliveryStatus: "SENDING", + attemptId: "att_1", + attemptStartedAt: new Date(), sentAt: null, createdAt: new Date(), ...overrides, @@ -42,24 +50,26 @@ function reply(overrides: Record = {}) { } function setup() { - const db = { + const db: any = { feedback: { findUnique: vi.fn(async () => feedback), update: vi.fn(async () => feedback), }, feedbackReply: { findUnique: vi.fn(async () => null as unknown), - findUniqueOrThrow: vi.fn(), + findFirst: vi.fn(async () => null as unknown), + findUniqueOrThrow: vi.fn(async () => reply({ deliveryStatus: "SENT" })), create: vi.fn(async () => reply()), - update: vi.fn(async () => - reply({ deliveryStatus: "SENT", sentAt: new Date() }), - ), updateMany: vi.fn(async () => ({ count: 1 })), }, - $transaction: vi.fn(async (ops: Promise[]) => Promise.all(ops)), }; + db.$transaction = vi.fn(async (arg: unknown) => + typeof arg === "function" + ? arg(db) + : Promise.all(arg as Promise[]), + ); const send = vi.fn(async () => ({ emailId: "em_1" })); - return { db, send, deps: { db: db as any, send } }; + return { db, send, deps: { db, send } }; } const input = { message: "Thanks!", idempotencyKey: "key-123456" }; @@ -70,7 +80,7 @@ describe("replyToFeedback", () => { ctx = setup(); }); - it("emails the reply with the reply's id as the idempotency key, then marks it sent", async () => { + it("claims the reply, emails it, then marks it sent by this attempt only", async () => { const result = await replyToFeedback("fb_1", input, ctx.deps); expect(ctx.send).toHaveBeenCalledWith({ @@ -80,6 +90,10 @@ describe("replyToFeedback", () => { idempotencyKey: "feedback-reply:rep_1", }); expect(result.sent).toBe(true); + expect(ctx.db.feedbackReply.updateMany).toHaveBeenCalledWith({ + where: { id: "rep_1", attemptId: "att_1", deliveryStatus: "SENDING" }, + data: expect.objectContaining({ deliveryStatus: "SENT" }), + }); expect(ctx.db.feedback.update).toHaveBeenCalledWith({ where: { id: "fb_1" }, data: { status: "REPLIED" }, @@ -97,27 +111,39 @@ describe("replyToFeedback", () => { expect(ctx.send).not.toHaveBeenCalled(); }); - it("retries a failed or unconfirmed reply with the same idempotency key", async () => { + it("never resends a reply that's sending or may have been sent", async () => { + ctx.db.feedbackReply.findUnique.mockResolvedValueOnce(reply()); + + await expect( + replyToFeedback("fb_1", input, ctx.deps), + ).rejects.toBeInstanceOf(ReplyInProgressError); + expect(ctx.send).not.toHaveBeenCalled(); + }); + + it("claims a failed reply again before retrying it", async () => { ctx.db.feedbackReply.findUnique.mockResolvedValueOnce( reply({ deliveryStatus: "FAILED" }), ); await replyToFeedback("fb_1", input, ctx.deps); + expect(ctx.db.feedbackReply.updateMany).toHaveBeenNthCalledWith(1, { + where: { id: "rep_1", deliveryStatus: "FAILED" }, + data: expect.objectContaining({ deliveryStatus: "SENDING" }), + }); expect(ctx.db.feedbackReply.create).not.toHaveBeenCalled(); - expect(ctx.send).toHaveBeenCalledWith( - expect.objectContaining({ idempotencyKey: "feedback-reply:rep_1" }), - ); + expect(ctx.send).toHaveBeenCalledTimes(1); }); - it("won't retry an unconfirmed reply older than the API remembers keys", async () => { - ctx.db.feedbackReply.findUnique.mockResolvedValueOnce( - reply({ createdAt: new Date(Date.now() - REPLY_RETRY_WINDOW_MS - 1000) }), + it("doesn't send when another request claimed the failed reply first", async () => { + ctx.db.feedbackReply.findUnique.mockResolvedValue( + reply({ deliveryStatus: "FAILED" }), ); + ctx.db.feedbackReply.updateMany.mockResolvedValue({ count: 0 }); await expect( replyToFeedback("fb_1", input, ctx.deps), - ).rejects.toBeInstanceOf(ReplyNeedsCheckError); + ).rejects.toBeInstanceOf(ReplyInProgressError); expect(ctx.send).not.toHaveBeenCalled(); }); @@ -131,16 +157,99 @@ describe("replyToFeedback", () => { ).rejects.toBeInstanceOf(IdempotencyConflictError); }); - it("marks the reply failed, only if still sending, when the email isn't accepted", async () => { - ctx.send.mockRejectedValueOnce(new MailNotSentError("rate limited")); + it("marks the reply failed when it certainly wasn't sent", async () => { + ctx.send.mockRejectedValueOnce(new MailNotSentError("RATE_LIMITED")); await expect( replyToFeedback("fb_1", input, ctx.deps), ).rejects.toBeInstanceOf(MailNotSentError); expect(ctx.db.feedbackReply.updateMany).toHaveBeenCalledWith({ - where: { id: "rep_1", deliveryStatus: "SENDING" }, + where: { id: "rep_1", attemptId: "att_1", deliveryStatus: "SENDING" }, + data: { deliveryStatus: "FAILED" }, + }); + expect(ctx.db.feedback.update).not.toHaveBeenCalled(); + }); + + it("leaves the reply sending when it may have gone out", async () => { + ctx.send.mockRejectedValueOnce(new MailUncertainError("TypeError")); + + await expect( + replyToFeedback("fb_1", input, ctx.deps), + ).rejects.toBeInstanceOf(MailUncertainError); + expect(ctx.db.feedbackReply.updateMany).not.toHaveBeenCalled(); + }); + + it("treats an unexpected error as possibly sent", async () => { + ctx.send.mockRejectedValueOnce(new Error("boom")); + + await expect( + replyToFeedback("fb_1", input, ctx.deps), + ).rejects.toBeInstanceOf(MailUncertainError); + expect(ctx.db.feedbackReply.updateMany).not.toHaveBeenCalled(); + }); +}); + +describe("settleReply", () => { + let ctx: ReturnType; + const old = () => new Date(Date.now() - SETTLE_AFTER_MS - 1000); + beforeEach(() => { + ctx = setup(); + }); + + it("records a checked reply as sent", async () => { + ctx.db.feedbackReply.findFirst.mockResolvedValueOnce( + reply({ attemptStartedAt: old() }), + ); + + await settleReply("fb_1", "rep_1", "SENT", ctx.db); + + expect(ctx.db.feedbackReply.updateMany).toHaveBeenCalledWith({ + where: { id: "rep_1", deliveryStatus: "SENDING", attemptId: "att_1" }, + data: expect.objectContaining({ deliveryStatus: "SENT" }), + }); + expect(ctx.db.feedback.update).toHaveBeenCalled(); + }); + + it("lets a checked, unsent reply be sent again", async () => { + ctx.db.feedbackReply.findFirst.mockResolvedValueOnce( + reply({ attemptStartedAt: old() }), + ); + + await settleReply("fb_1", "rep_1", "FAILED", ctx.db); + + expect(ctx.db.feedbackReply.updateMany).toHaveBeenCalledWith({ + where: { id: "rep_1", deliveryStatus: "SENDING", attemptId: "att_1" }, data: { deliveryStatus: "FAILED" }, }); + }); + + it("waits until the attempt is old enough", async () => { + ctx.db.feedbackReply.findFirst.mockResolvedValueOnce(reply()); + + await expect( + settleReply("fb_1", "rep_1", "FAILED", ctx.db), + ).rejects.toBeInstanceOf(ReplyStillSendingError); + }); + + it("only settles a reply that's still sending", async () => { + ctx.db.feedbackReply.findFirst.mockResolvedValueOnce( + reply({ deliveryStatus: "SENT", attemptStartedAt: old() }), + ); + + await expect( + settleReply("fb_1", "rep_1", "FAILED", ctx.db), + ).rejects.toBeInstanceOf(ReplyNotSendingError); + }); + + it("refuses when a newer attempt took the reply meanwhile", async () => { + ctx.db.feedbackReply.findFirst.mockResolvedValueOnce( + reply({ attemptStartedAt: old() }), + ); + ctx.db.feedbackReply.updateMany.mockResolvedValueOnce({ count: 0 }); + + await expect( + settleReply("fb_1", "rep_1", "SENT", ctx.db), + ).rejects.toBeInstanceOf(ReplyNotSendingError); expect(ctx.db.feedback.update).not.toHaveBeenCalled(); }); }); From 74dda850d739ec17dc84b1f66440d6ea4c96a1b9 Mon Sep 17 00:00:00 2001 From: KM Koushik Date: Tue, 10 Nov 2026 15:18:48 +1100 Subject: [PATCH 3/4] fix(feedback): read the SDK's wrapped error codes; keep a manual settle over a late send --- .../api/admin/feedback/[id]/reply/route.ts | 7 ++ .../server/mailer-feedback-reply.unit.test.ts | 107 ++++++++++++++++++ apps/web/src/server/mailer.ts | 12 +- apps/web/src/server/service/feedback-admin.ts | 14 ++- .../service/feedback-admin.unit.test.ts | 9 ++ apps/web/vitest.config.ts | 9 ++ 6 files changed, 151 insertions(+), 7 deletions(-) create mode 100644 apps/web/src/server/mailer-feedback-reply.unit.test.ts diff --git a/apps/web/src/app/api/admin/feedback/[id]/reply/route.ts b/apps/web/src/app/api/admin/feedback/[id]/reply/route.ts index ffc4aaa5b..539531f20 100644 --- a/apps/web/src/app/api/admin/feedback/[id]/reply/route.ts +++ b/apps/web/src/app/api/admin/feedback/[id]/reply/route.ts @@ -5,6 +5,7 @@ import { MailNotSentError, MailUncertainError, ReplyInProgressError, + ReplyNotSendingError, replyBody, replyToFeedback, } from "~/server/service/feedback-admin"; @@ -47,6 +48,12 @@ export const POST = adminApiRoute(async ({ body, params }) => { "This reply is being sent, or it may have been sent; check whether it arrived before settling it", ); } + if (error instanceof ReplyNotSendingError) { + throw new AdminApiError( + 409, + "This reply was settled by hand while it was sending; that decision stands", + ); + } if (error instanceof MailUncertainError) { throw new AdminApiError( 409, diff --git a/apps/web/src/server/mailer-feedback-reply.unit.test.ts b/apps/web/src/server/mailer-feedback-reply.unit.test.ts new file mode 100644 index 000000000..6ee5ce789 --- /dev/null +++ b/apps/web/src/server/mailer-feedback-reply.unit.test.ts @@ -0,0 +1,107 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +// Goes through the real usesend-js SDK with HTTP mocked, so the SDK's error +// shape is what's tested. +vi.mock("~/env", () => ({ + env: { + UNSEND_API_KEY: "us_test", + FOUNDER_EMAIL: "founder@usesend.com", + NODE_ENV: "test", + }, +})); +vi.mock("~/server/db", () => ({ db: {} })); +vi.mock("~/server/service/domain-service", () => ({ getDomains: vi.fn() })); +vi.mock("~/server/service/email-service", () => ({ sendEmail: vi.fn() })); +vi.mock("~/server/logger/log", () => ({ + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() }, +})); +vi.mock("~/server/email-templates", () => ({ + renderOtpEmail: vi.fn(), + renderTeamInviteEmail: vi.fn(), +})); + +import { + MailNotSentError, + MailUncertainError, + sendFeedbackReply, +} from "~/server/mailer"; + +const params = { + to: "a@acme.com", + subject: "Re: your feedback to useSend", + text: "Thanks!", + idempotencyKey: "feedback-reply:rep_1", +}; + +function respond(status: number, body: unknown) { + return vi.fn( + async () => + new Response(JSON.stringify(body), { + status, + headers: { "content-type": "application/json" }, + }), + ); +} + +describe("sendFeedbackReply through the SDK", () => { + const realFetch = globalThis.fetch; + beforeEach(() => { + vi.restoreAllMocks(); + }); + afterEach(() => { + globalThis.fetch = realFetch; + }); + + it("sends with the idempotency key", async () => { + const fetch = respond(200, { emailId: "em_1" }); + globalThis.fetch = fetch as any; + + await expect(sendFeedbackReply(params)).resolves.toEqual({ + emailId: "em_1", + }); + const [, init] = fetch.mock.calls[0] as unknown as [string, RequestInit]; + expect(new Headers(init.headers).get("Idempotency-Key")).toBe( + "feedback-reply:rep_1", + ); + }); + + it("knows a rate-limited send wasn't sent", async () => { + globalThis.fetch = respond(429, { + error: { code: "RATE_LIMITED", message: "Too many requests" }, + }) as any; + + await expect(sendFeedbackReply(params)).rejects.toBeInstanceOf( + MailNotSentError, + ); + }); + + it("treats a server error as maybe sent", async () => { + globalThis.fetch = respond(500, { + error: { code: "INTERNAL_SERVER_ERROR", message: "boom" }, + }) as any; + + await expect(sendFeedbackReply(params)).rejects.toBeInstanceOf( + MailUncertainError, + ); + }); + + it("treats an in-progress duplicate as maybe sent", async () => { + globalThis.fetch = respond(409, { + error: { code: "NOT_UNIQUE", message: "in progress" }, + }) as any; + + await expect(sendFeedbackReply(params)).rejects.toBeInstanceOf( + MailUncertainError, + ); + }); + + it("treats a dropped connection as maybe sent", async () => { + globalThis.fetch = vi.fn(async () => { + throw new TypeError("fetch failed"); + }) as any; + + await expect(sendFeedbackReply(params)).rejects.toBeInstanceOf( + MailUncertainError, + ); + }); +}); diff --git a/apps/web/src/server/mailer.ts b/apps/web/src/server/mailer.ts index 01500918a..9fd75e552 100644 --- a/apps/web/src/server/mailer.ts +++ b/apps/web/src/server/mailer.ts @@ -205,6 +205,16 @@ const NOT_SENT_CODES = new Set([ "RATE_LIMITED", ]); +/** + * The API's error code. The SDK returns API errors either as `{ code }` or + * still wrapped as `{ error: { code } }`, so read both. + */ +function errorCode(error: unknown): string | undefined { + const outer = error as { code?: unknown; error?: { code?: unknown } } | null; + const code = outer?.code ?? outer?.error?.code; + return typeof code === "string" ? code : undefined; +} + /** * Emails a reply to someone's feedback through useSend's own API, with an * idempotency key as extra protection against a second send. Throws @@ -243,7 +253,7 @@ export async function sendFeedbackReply(params: { } if (response.data) return { emailId: response.data.emailId }; - const code = response.error?.code ?? "UNKNOWN"; + const code = errorCode(response.error) ?? "UNKNOWN"; throw NOT_SENT_CODES.has(code) ? new MailNotSentError(code) : new MailUncertainError(code); diff --git a/apps/web/src/server/service/feedback-admin.ts b/apps/web/src/server/service/feedback-admin.ts index c81ac43cc..9cb4f1661 100644 --- a/apps/web/src/server/service/feedback-admin.ts +++ b/apps/web/src/server/service/feedback-admin.ts @@ -297,16 +297,18 @@ export async function replyToFeedback( } const sentAt = new Date(); - await db.$transaction([ - db.feedbackReply.updateMany({ + await db.$transaction(async (tx) => { + const { count } = await tx.feedbackReply.updateMany({ where: mine, data: { deliveryStatus: "SENT", sentAt }, - }), - db.feedback.update({ + }); + // Someone settled this attempt by hand meanwhile: their decision stands. + if (count === 0) throw new ReplyNotSendingError(); + await tx.feedback.update({ where: { id: feedbackId }, data: { status: "REPLIED" }, - }), - ]); + }); + }); return { reply: { ...reply, deliveryStatus: "SENT" as const, sentAt }, sent: true, diff --git a/apps/web/src/server/service/feedback-admin.unit.test.ts b/apps/web/src/server/service/feedback-admin.unit.test.ts index 5f2623a66..492761099 100644 --- a/apps/web/src/server/service/feedback-admin.unit.test.ts +++ b/apps/web/src/server/service/feedback-admin.unit.test.ts @@ -100,6 +100,15 @@ describe("replyToFeedback", () => { }); }); + it("keeps a decision made by hand while the send was finishing", async () => { + ctx.db.feedbackReply.updateMany.mockResolvedValueOnce({ count: 0 }); + + await expect( + replyToFeedback("fb_1", input, ctx.deps), + ).rejects.toBeInstanceOf(ReplyNotSendingError); + expect(ctx.db.feedback.update).not.toHaveBeenCalled(); + }); + it("doesn't send a reply that was already sent", async () => { ctx.db.feedbackReply.findUnique.mockResolvedValueOnce( reply({ deliveryStatus: "SENT" }), diff --git a/apps/web/vitest.config.ts b/apps/web/vitest.config.ts index c15cb0976..529bebaa4 100644 --- a/apps/web/vitest.config.ts +++ b/apps/web/vitest.config.ts @@ -1,8 +1,17 @@ +import { fileURLToPath } from "node:url"; import { defineConfig } from "vitest/config"; import tsconfigPaths from "vite-tsconfig-paths"; export default defineConfig({ plugins: [tsconfigPaths()], + resolve: { + // Tests use the SDK's source, so they don't need a built package. + alias: { + "usesend-js": fileURLToPath( + new URL("../../packages/sdk/index.ts", import.meta.url), + ), + }, + }, test: { environment: "node", globals: true, From 172a795395d1a2d020db7080f2b843bcde66f7a8 Mon Sep 17 00:00:00 2001 From: KM Koushik Date: Tue, 10 Nov 2026 15:20:48 +1100 Subject: [PATCH 4/4] chore(mailer): use the ~/ alias for the email-content import --- apps/web/src/server/mailer.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/web/src/server/mailer.ts b/apps/web/src/server/mailer.ts index 9fd75e552..165bba576 100644 --- a/apps/web/src/server/mailer.ts +++ b/apps/web/src/server/mailer.ts @@ -6,7 +6,7 @@ import { getDomains } from "./service/domain-service"; import { sendEmail } from "./service/email-service"; import { logger } from "./logger/log"; import { renderOtpEmail, renderTeamInviteEmail } from "./email-templates"; -import { toPlainHtml } from "./utils/email-content"; +import { toPlainHtml } from "~/server/utils/email-content"; let usesend: UseSend | undefined;