From ae99931826c844bd7c6927d0ff9db83b2b1973d7 Mon Sep 17 00:00:00 2001 From: JOY <5027251+JOY@users.noreply.github.com> Date: Thu, 19 Nov 2026 04:26:16 +0700 Subject: [PATCH 01/23] fix(campaigns): revalidate moderation routes and harden report queue (#259) (#265) - Revalidate /admin/reports on reportCampaign, organizer/notice/public routes on approveCampaign, requestChanges, and setVerification, and organizer/pledge/statement/contribution routes on moderateCampaignReports suspend and stop_payment_requests. - Filter concurrently-resolved campaign IDs and clamp/reload the new last page in listCampaignReportQueue so moderators are never stranded on a phantom empty page. - Chunk loadUnresolvedForCampaigns by CAMPAIGNS_PER_REQUEST (100), add id DESC tie-breaking on resolved reports, and harden parseReportsPage with /^[1-9][0-9]*$/ capped at 10,000. --- apps/web/src/app/admin/actions.test.ts | 66 ++++- apps/web/src/app/admin/actions.ts | 29 ++- .../web/src/app/admin/reports/actions.test.ts | 39 ++- apps/web/src/app/admin/reports/actions.ts | 9 + .../src/app/campaigns/[slug]/actions.test.ts | 7 +- apps/web/src/app/campaigns/[slug]/actions.ts | 3 + apps/web/src/lib/campaign-reports.test.ts | 229 +++++++++++++++++- apps/web/src/lib/campaign-reports.ts | 99 +++++--- 8 files changed, 426 insertions(+), 55 deletions(-) diff --git a/apps/web/src/app/admin/actions.test.ts b/apps/web/src/app/admin/actions.test.ts index 0079b4e3..67a1a773 100644 --- a/apps/web/src/app/admin/actions.test.ts +++ b/apps/web/src/app/admin/actions.test.ts @@ -7,8 +7,9 @@ const CAMPAIGN = "22222222-2222-4222-8222-222222222222" const ORGANIZER = "55555555-5555-4555-8555-555555555555" const state = vi.hoisted(() => ({ handler: (() => undefined) as Handler, calls: [] as Call[] })) +const revalidatePathMock = vi.hoisted(() => vi.fn()) -vi.mock("next/cache", () => ({ revalidatePath: vi.fn() })) +vi.mock("next/cache", () => ({ revalidatePath: revalidatePathMock })) vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn(async () => ({ user: { id: "staff", email: null, name: null }, accessToken: "token" })), })) @@ -23,10 +24,21 @@ const transitions = () => .map((c) => (op(c, "args")?.[0] as { p_to_status: string }).p_to_status) beforeEach(() => { + revalidatePathMock.mockClear() state.calls.length = 0 }) describe("approveCampaign", () => { + const expectedApprovalRevalidations = [ + ["/admin"], + [`/me/campaigns/${CAMPAIGN}`], + ["/me/campaigns"], + ["/me/notices"], + ["/campaigns/a-b"], + ["/campaigns"], + ["/"], + ] + it("approves and opens a campaign whose start time has come", async () => { state.handler = (call) => op(call, "maybeSingle") @@ -35,9 +47,10 @@ describe("approveCampaign", () => { const result = await approveCampaign(CAMPAIGN, null, new FormData()) expect(result).toEqual({ ok: true, message: "Đã duyệt và mở chiến dịch công khai." }) expect(transitions()).toEqual(["approved", "live"]) + expect(revalidatePathMock.mock.calls).toEqual(expectedApprovalRevalidations) }) - it("only approves a campaign scheduled for later", async () => { + it("only approves a campaign scheduled for later and still revalidates organizer and campaign routes", async () => { state.handler = (call) => op(call, "maybeSingle") ? { @@ -50,6 +63,7 @@ describe("approveCampaign", () => { : undefined expect((await approveCampaign(CAMPAIGN, null, new FormData()))?.ok).toBe(true) expect(transitions()).toEqual(["approved"]) + expect(revalidatePathMock.mock.calls).toEqual(expectedApprovalRevalidations) }) it("refuses a campaign whose end date passed during review", async () => { @@ -59,6 +73,7 @@ describe("approveCampaign", () => { : undefined expect((await approveCampaign(CAMPAIGN, null, new FormData()))?.ok).toBe(false) expect(transitions()).toEqual([]) + expect(revalidatePathMock).not.toHaveBeenCalled() }) it("surfaces the database's self-review refusal", async () => { @@ -72,6 +87,7 @@ describe("approveCampaign", () => { ok: false, message: "Không thể chuyển chiến dịch sang trạng thái này lúc này.", }) + expect(revalidatePathMock).not.toHaveBeenCalled() }) it("surfaces a failed campaign read instead of claiming the campaign was not found (DOS/Give#77)", async () => { @@ -133,20 +149,42 @@ describe("requestChanges", () => { return f } const statusIs = - (status: string, rpc?: Handler): Handler => + (status: string, rpc?: Handler, slug?: string | null): Handler => (call) => - op(call, "maybeSingle") ? { data: { status } } : rpc?.(call) + op(call, "maybeSingle") ? { data: slug === undefined ? { status } : { status, slug } } : rpc?.(call) - it("sends a campaign back with the trimmed reason", async () => { - state.handler = statusIs("approved") + it("sends a campaign back with the trimmed reason and revalidates organizer and slug routes", async () => { + state.handler = statusIs("approved", undefined, "a-b") const result = await requestChanges(CAMPAIGN, null, form(" Bind another account. ")) expect(result).toEqual({ ok: true, message: "Đã gửi yêu cầu chỉnh sửa cho người tổ chức." }) + const readCall = state.calls.find((c) => c.target === "campaigns") + expect(op(readCall, "select")).toEqual(["status, slug"]) const call = state.calls.find((c) => c.target === "rpc:transition_campaign") expect(op(call, "args")?.[0]).toEqual({ p_campaign_id: CAMPAIGN, p_to_status: "changes_requested", p_reason: "Bind another account.", }) + expect(revalidatePathMock.mock.calls).toEqual([ + ["/admin"], + [`/me/campaigns/${CAMPAIGN}`], + ["/me/campaigns"], + ["/me/notices"], + ["/campaigns/a-b"], + ]) + }) + + it("falls back to page-level /campaigns/[slug] revalidation when slug is absent", async () => { + state.handler = statusIs("approved", undefined, null) + const result = await requestChanges(CAMPAIGN, null, form("Bind another account.")) + expect(result?.ok).toBe(true) + expect(revalidatePathMock.mock.calls).toEqual([ + ["/admin"], + [`/me/campaigns/${CAMPAIGN}`], + ["/me/campaigns"], + ["/me/notices"], + ["/campaigns/[slug]", "page"], + ]) }) it("does not send back a campaign approved since the review form was shown (DOS/Give#64)", async () => { @@ -220,7 +258,7 @@ describe("requestChanges", () => { }) describe("setVerification", () => { - it("passes the names and kind the moderator saw", async () => { + it("passes the names and kind the moderator saw and revalidates all organizer, admin, and public routes", async () => { state.handler = () => undefined const form = new FormData() form.set("status", "verified") @@ -236,12 +274,24 @@ describe("setVerification", () => { p_expected_kind: "individual", p_reason: null, }) + expect(revalidatePathMock.mock.calls).toEqual([ + ["/admin"], + ["/admin/reports"], + ["/start"], + ["/me/campaigns/[id]", "page"], + ["/me/accounts"], + ["/me/notices"], + ["/campaigns/[slug]", "page"], + ["/campaigns"], + ["/"], + ]) }) - it("rejects statuses other than verified or rejected", async () => { + it("rejects statuses other than verified or rejected without revalidating", async () => { const form = new FormData() form.set("status", "unverified") expect((await setVerification(ORGANIZER, null, form))?.ok).toBe(false) expect(state.calls).toHaveLength(0) + expect(revalidatePathMock).not.toHaveBeenCalled() }) }) diff --git a/apps/web/src/app/admin/actions.ts b/apps/web/src/app/admin/actions.ts index ea7047d7..e3cfd6a9 100644 --- a/apps/web/src/app/admin/actions.ts +++ b/apps/web/src/app/admin/actions.ts @@ -58,9 +58,12 @@ export async function approveCampaign( message = live.error ? `Đã duyệt, nhưng chưa mở được: ${dbErrorMessage(live.error, OPEN_MESSAGES)}` : "Đã duyệt và mở chiến dịch công khai." - if (!live.error) revalidatePath(`/campaigns/${campaign.slug}`) } revalidatePath("/admin") + revalidatePath(`/me/campaigns/${campaignId}`) + revalidatePath("/me/campaigns") + revalidatePath("/me/notices") + revalidatePath(`/campaigns/${campaign.slug}`) revalidatePath("/campaigns") revalidatePath("/") return done(message) @@ -84,9 +87,13 @@ export async function requestChanges(campaignId: string, _state: ActionResult, f if (fromStatus !== "in_review" && fromStatus !== "approved") return fail(STATUS_CHANGED) const db = dbAs(session.accessToken) - const { data, error: readError } = await db.from("campaigns").select("status").eq("id", campaignId).maybeSingle() + const { data, error: readError } = await db + .from("campaigns") + .select("status, slug") + .eq("id", campaignId) + .maybeSingle() if (readError) return fail(dbErrorMessage(readError)) - const current = data as { status: string } | null + const current = data as { status: string; slug?: string | null } | null if (!current) return fail(dbErrorMessage({ message: "GIVE_CAMPAIGN_NOT_FOUND" })) if (current.status !== fromStatus) return fail(STATUS_CHANGED) @@ -97,6 +104,14 @@ export async function requestChanges(campaignId: string, _state: ActionResult, f }) if (error) return fail(dbErrorMessage(error, fromStatus === "approved" ? SEND_BACK_MESSAGES : undefined)) revalidatePath("/admin") + revalidatePath(`/me/campaigns/${campaignId}`) + revalidatePath("/me/campaigns") + revalidatePath("/me/notices") + if (current.slug) { + revalidatePath(`/campaigns/${current.slug}`) + } else { + revalidatePath("/campaigns/[slug]", "page") + } return done("Đã gửi yêu cầu chỉnh sửa cho người tổ chức.") } @@ -125,5 +140,13 @@ export async function setVerification(userId: string, _state: ActionResult, form }) if (error) return fail(dbErrorMessage(error)) revalidatePath("/admin") + revalidatePath("/admin/reports") + revalidatePath("/start") + revalidatePath("/me/campaigns/[id]", "page") + revalidatePath("/me/accounts") + revalidatePath("/me/notices") + revalidatePath("/campaigns/[slug]", "page") + revalidatePath("/campaigns") + revalidatePath("/") return done(status === "verified" ? "Đã xác minh người tổ chức." : "Đã từ chối xác minh.") } diff --git a/apps/web/src/app/admin/reports/actions.test.ts b/apps/web/src/app/admin/reports/actions.test.ts index abc1ddbc..75a465c0 100644 --- a/apps/web/src/app/admin/reports/actions.test.ts +++ b/apps/web/src/app/admin/reports/actions.test.ts @@ -67,7 +67,7 @@ describe("moderateCampaignReports (DOS/Give#98)", () => { p_reason: "Đã xác minh", p_public_note: null, }) - expect(revalidatePathMock).toHaveBeenCalledWith("/admin/reports") + expect(revalidatePathMock.mock.calls).toEqual([["/admin/reports"]]) }) it("supports ask_organizer, distinguishing sent inquiries from zero-open-report replays", async () => { @@ -78,7 +78,7 @@ describe("moderateCampaignReports (DOS/Give#98)", () => { ) expect(sent?.ok).toBe(true) expect(sent?.message).toContain("Đã gửi câu hỏi cho người tổ chức") - expect(revalidatePathMock).toHaveBeenCalledWith("/me/notices") + expect(revalidatePathMock.mock.calls).toEqual([["/admin/reports"], ["/me/notices"]]) state.serviceHandler = () => ({ data: 0 }) const replay = await moderateCampaignReports( @@ -90,7 +90,7 @@ describe("moderateCampaignReports (DOS/Give#98)", () => { expect(replay?.message).toContain("Không còn báo cáo mới nào") }) - it("supports suspend and revalidates public campaign and admin pages", async () => { + it("supports suspend and revalidates organizer, public campaign, pledge, statement, and admin pages", async () => { const res = await moderateCampaignReports( CAMPAIGN, null, @@ -102,14 +102,22 @@ describe("moderateCampaignReports (DOS/Give#98)", () => { p_reason: "Chưa xác minh được người thụ hưởng.", p_public_note: null, }) - expect(revalidatePathMock).toHaveBeenCalledWith("/admin/reports") - expect(revalidatePathMock).toHaveBeenCalledWith("/admin") - expect(revalidatePathMock).toHaveBeenCalledWith("/campaigns/[slug]", "page") - expect(revalidatePathMock).toHaveBeenCalledWith("/campaigns") - expect(revalidatePathMock).toHaveBeenCalledWith("/") + expect(revalidatePathMock.mock.calls).toEqual([ + ["/admin/reports"], + ["/admin"], + [`/me/campaigns/${CAMPAIGN}`], + ["/me/campaigns"], + ["/me/notices"], + ["/campaigns/[slug]", "page"], + ["/campaigns/[slug]/pledge", "page"], + ["/campaigns/[slug]/statement", "page"], + ["/me/pledges/[code]", "page"], + ["/campaigns"], + ["/"], + ]) }) - it("supports stop_payment_requests with a required public_note and revalidates pledge payment pages", async () => { + it("supports stop_payment_requests with a required public_note and revalidates organizer, contribution, notice, and pledge pages", async () => { const res = await moderateCampaignReports( CAMPAIGN, null, @@ -127,9 +135,15 @@ describe("moderateCampaignReports (DOS/Give#98)", () => { p_reason: "Nghi vấn gian lận hậu gây quỹ.", p_public_note: "Give đang xác minh dự án này.", }) - expect(revalidatePathMock).toHaveBeenCalledWith("/admin/payment-requests") - expect(revalidatePathMock).toHaveBeenCalledWith("/campaigns/[slug]", "page") - expect(revalidatePathMock).toHaveBeenCalledWith("/me/pledges/[code]", "page") + expect(revalidatePathMock.mock.calls).toEqual([ + ["/admin/reports"], + ["/admin/payment-requests"], + [`/me/campaigns/${CAMPAIGN}`], + ["/me/contributions"], + ["/me/notices"], + ["/campaigns/[slug]", "page"], + ["/me/pledges/[code]", "page"], + ]) }) it("validates inputs and refuses public_note on actions that publish none before touching the DB", async () => { @@ -207,5 +221,6 @@ describe("moderateCampaignReports (DOS/Give#98)", () => { ) )?.message ).toContain("dự án có quà tặng đã đạt mục tiêu") + expect(revalidatePathMock).not.toHaveBeenCalled() }) }) diff --git a/apps/web/src/app/admin/reports/actions.ts b/apps/web/src/app/admin/reports/actions.ts index 014c1a84..0ff11d92 100644 --- a/apps/web/src/app/admin/reports/actions.ts +++ b/apps/web/src/app/admin/reports/actions.ts @@ -72,11 +72,20 @@ export async function moderateCampaignReports( revalidatePath("/me/notices") } else if (parsed.data.action === "suspend") { revalidatePath("/admin") + revalidatePath(`/me/campaigns/${campaignId}`) + revalidatePath("/me/campaigns") + revalidatePath("/me/notices") revalidatePath("/campaigns/[slug]", "page") + revalidatePath("/campaigns/[slug]/pledge", "page") + revalidatePath("/campaigns/[slug]/statement", "page") + revalidatePath("/me/pledges/[code]", "page") revalidatePath("/campaigns") revalidatePath("/") } else if (parsed.data.action === "stop_payment_requests") { revalidatePath("/admin/payment-requests") + revalidatePath(`/me/campaigns/${campaignId}`) + revalidatePath("/me/contributions") + revalidatePath("/me/notices") revalidatePath("/campaigns/[slug]", "page") revalidatePath("/me/pledges/[code]", "page") } diff --git a/apps/web/src/app/campaigns/[slug]/actions.test.ts b/apps/web/src/app/campaigns/[slug]/actions.test.ts index 81d25357..6b9eb916 100644 --- a/apps/web/src/app/campaigns/[slug]/actions.test.ts +++ b/apps/web/src/app/campaigns/[slug]/actions.test.ts @@ -19,9 +19,11 @@ vi.mock("@/lib/auth/session", () => ({ ), })) +const revalidatePathMock = vi.hoisted(() => vi.fn()) const dbAsMock = vi.hoisted(() => vi.fn((_token?: string) => fakeDb((call) => state.userHandler(call), state.userCalls)) ) +vi.mock("next/cache", () => ({ revalidatePath: revalidatePathMock })) vi.mock("@/lib/supabase", () => ({ dbAs: dbAsMock, dbService: () => fakeDb((call) => state.serviceHandler(call), state.serviceCalls), @@ -39,6 +41,7 @@ function form(reasonCode?: string, details?: string) { const rpc = () => state.serviceCalls.find((c) => c.target === "rpc:report_campaign") beforeEach(() => { + revalidatePathMock.mockClear() dbAsMock.mockClear() state.userCalls.length = 0 state.serviceCalls.length = 0 @@ -48,7 +51,7 @@ beforeEach(() => { }) describe("reportCampaign (DOS/Give#98)", () => { - it("verifies the reporter's token and public campaign status first, then calls give.report_campaign as service_role", async () => { + it("verifies the reporter's token and public campaign status first, calls give.report_campaign, and revalidates /admin/reports", async () => { const result = await reportCampaign(CAMPAIGN, null, form("fraud_or_impersonation", " Mạo danh bệnh viện ")) expect(result).toEqual({ ok: true, @@ -64,6 +67,7 @@ describe("reportCampaign (DOS/Give#98)", () => { p_reason_code: "fraud_or_impersonation", p_details: "Mạo danh bệnh viện", }) + expect(revalidatePathMock.mock.calls).toEqual([["/admin/reports"]]) }) it("accepts non-'other' reasons without details and requires details for 'other'", async () => { @@ -133,5 +137,6 @@ describe("reportCampaign (DOS/Give#98)", () => { state.serviceHandler = () => ({ error: { code: "23514", message: "GIVE_REPORT_LIMIT" } }) expect((await reportCampaign(CAMPAIGN, null, form("fraud_or_impersonation")))?.message).toContain("24 giờ") + expect(revalidatePathMock).not.toHaveBeenCalled() }) }) diff --git a/apps/web/src/app/campaigns/[slug]/actions.ts b/apps/web/src/app/campaigns/[slug]/actions.ts index 37fd6eff..77667974 100644 --- a/apps/web/src/app/campaigns/[slug]/actions.ts +++ b/apps/web/src/app/campaigns/[slug]/actions.ts @@ -1,5 +1,7 @@ "use server" +import { revalidatePath } from "next/cache" + import { getSession } from "@/lib/auth/session" import { reportCampaignSchema } from "@/lib/campaign-reports" import { isPublicStatus, type CampaignStatus } from "@/lib/campaigns" @@ -52,5 +54,6 @@ export async function reportCampaign(campaignId: string, _state: ActionResult, f }) if (error) return fail(dbErrorMessage(error, REPORT_CAMPAIGN_MESSAGES)) + revalidatePath("/admin/reports") return done("Cảm ơn bạn. Đội kiểm duyệt Give đã nhận báo cáo và sẽ xem xét chiến dịch này.") } diff --git a/apps/web/src/lib/campaign-reports.test.ts b/apps/web/src/lib/campaign-reports.test.ts index eff439ea..862c70f2 100644 --- a/apps/web/src/lib/campaign-reports.test.ts +++ b/apps/web/src/lib/campaign-reports.test.ts @@ -7,6 +7,7 @@ import { canStopReportedPaymentRequests, canSuspendReportedCampaign, listCampaignReportQueue, + MAX_REPORTS_PAGE, moderateCampaignReportsSchema, parseReportsPage, reportCampaignSchema, @@ -190,6 +191,15 @@ describe("listCampaignReportQueue", () => { expect(cols).not.toMatch(/reporter_id|handled_by/) } + const resolvedRead = reportReads.find((read) => { + const statusIn = read.ops.find(([n, col]) => n === "in" && col === "status")?.[2] as string[] | undefined + return statusIn?.includes("dismissed") + }) + expect(resolvedRead?.ops.filter(([n]) => n === "order")).toEqual([ + ["order", "handled_at", { ascending: false }], + ["order", "id", { ascending: false }], + ]) + expect(queue.totalUnresolvedCampaigns).toBe(3) expect(queue.page).toBe(1) expect(queue.totalPages).toBe(1) @@ -252,10 +262,19 @@ describe("listCampaignReportQueue", () => { return undefined }, calls) - // Page 1 with pageSize 110 forces two chunks of managed_campaigns (100 + 6). + // Page 1 with pageSize 110 forces two chunks (100 + 6) for BOTH loadUnresolvedForCampaigns and managed_campaigns. const p1 = await listCampaignReportQueue(db as never, 1, 110) expect(p1.unresolved[0].campaign_id).toBe(freshOpenId) expect(p1.unresolved[0].open_count).toBe(1) + expect(p1.unresolved).toHaveLength(106) + + const unresolvedBatchCalls = calls.filter( + (c) => c.target === "campaign_reports" && c.ops.some(([n, col]) => n === "in" && col === "campaign_id") + ) + expect(unresolvedBatchCalls).toHaveLength(2) + expect((op(unresolvedBatchCalls[0], "in")?.[1] as string[]).length).toBe(CAMPAIGNS_PER_REQUEST) + expect((op(unresolvedBatchCalls[1], "in")?.[1] as string[]).length).toBe(6) + const managedCalls = calls.filter((c) => c.target === "rpc:managed_campaigns") expect(managedCalls).toHaveLength(2) expect((op(managedCalls[0], "in")?.[1] as string[]).length).toBe(CAMPAIGNS_PER_REQUEST) @@ -327,15 +346,221 @@ describe("listCampaignReportQueue", () => { }) expect(calls.map((c) => c.target)).toEqual(["campaign_reports", "campaign_reports", "campaign_reports"]) }) + + it("clamps and reloads the new last page when the sole campaign on page N > 1 is resolved concurrently", async () => { + // Scan sees C1, C2 on page 1 and C3 on page 2 (pageSize = 2), but C3 is resolved before loadUnresolvedForCampaigns runs. + const initialOpenRows = [ + { id: "r-c1", campaign_id: C1, created_at: "2026-11-15T08:00:00Z" }, + { id: "r-c2", campaign_id: C2, created_at: "2026-11-15T09:00:00Z" }, + { id: "r-c3", campaign_id: C3, created_at: "2026-11-15T10:00:00Z" }, + ] + const liveUnresolvedRows = [ + { + id: "r-c1", + campaign_id: C1, + reason_code: "fraud_or_impersonation" as const, + details: "C1", + status: "open" as const, + action_taken: null, + resolution_note: null, + handled_at: null, + created_at: "2026-11-15T08:00:00Z", + updated_at: "2026-11-15T08:00:00Z", + }, + { + id: "r-c2", + campaign_id: C2, + reason_code: "misuse_of_funds" as const, + details: "C2", + status: "open" as const, + action_taken: null, + resolution_note: null, + handled_at: null, + created_at: "2026-11-15T09:00:00Z", + updated_at: "2026-11-15T09:00:00Z", + }, + ] + + const calls: Call[] = [] + const db = fakeDb((call) => { + if (call.target === "campaign_reports") { + const eqStatus = call.ops.find(([n, col]) => n === "eq" && col === "status")?.[2] as string | undefined + if (eqStatus === "open") return { data: initialOpenRows } + if (eqStatus === "awaiting_organizer") return { data: [] } + const statusFilter = call.ops.find(([n, col]) => n === "in" && col === "status")?.[2] as string[] | undefined + const campaignFilter = call.ops.find(([n, col]) => n === "in" && col === "campaign_id")?.[2] as + string[] | undefined + if (statusFilter?.includes("open")) { + return { + data: liveUnresolvedRows.filter((r) => !campaignFilter || campaignFilter.includes(r.campaign_id)), + } + } + return { data: [] } + } + if (call.target === "rpc:managed_campaigns") { + const ids = (op(call, "in")?.[1] as string[] | undefined) ?? [] + return { + data: ids.map((id) => ({ + id, + slug: `slug-${id.slice(0, 4)}`, + type: "give", + status: "live", + title: `Campaign ${id.slice(0, 4)}`, + organizer_id: ORG, + review_note: null, + payments_stopped_at: null, + payments_stopped_note: null, + organizer: null, + })), + } + } + return undefined + }, calls) + + const queue = await listCampaignReportQueue(db as never, 2, 2) + expect(queue.totalUnresolvedCampaigns).toBe(2) + expect(queue.totalPages).toBe(1) + expect(queue.page).toBe(1) + expect(queue.unresolved.map((u) => [u.campaign_id, u.campaign?.slug])).toEqual([ + [C1, "slug-1111"], + [C2, "slug-2222"], + ]) + }) + + it("shifts and loads replacement campaigns on partial concurrent resolution, and settles cleanly if all resolve", async () => { + // Page 1 (pageSize = 2) starts with [C1, C2] and C3 on page 2; C1 resolves concurrently -> C3 shifts onto page 1. + const initialOpenRows = [ + { id: "r-c1", campaign_id: C1, created_at: "2026-11-15T08:00:00Z" }, + { id: "r-c2", campaign_id: C2, created_at: "2026-11-15T09:00:00Z" }, + { id: "r-c3", campaign_id: C3, created_at: "2026-11-15T10:00:00Z" }, + ] + let remainingIds = new Set([C2, C3]) + const db = fakeDb((call) => { + if (call.target === "campaign_reports") { + const eqStatus = call.ops.find(([n, col]) => n === "eq" && col === "status")?.[2] as string | undefined + if (eqStatus === "open") return { data: initialOpenRows } + if (eqStatus === "awaiting_organizer") return { data: [] } + const statusFilter = call.ops.find(([n, col]) => n === "in" && col === "status")?.[2] as string[] | undefined + const campaignFilter = call.ops.find(([n, col]) => n === "in" && col === "campaign_id")?.[2] as + string[] | undefined + if (statusFilter?.includes("open")) { + return { + data: initialOpenRows + .filter( + (r) => remainingIds.has(r.campaign_id) && (!campaignFilter || campaignFilter.includes(r.campaign_id)) + ) + .map((r) => ({ + ...r, + reason_code: "other", + details: "d", + status: "open", + action_taken: null, + resolution_note: null, + handled_at: null, + updated_at: r.created_at, + })), + } + } + return { data: [] } + } + if (call.target === "rpc:managed_campaigns") return { data: [] } + return undefined + }) + + const partial = await listCampaignReportQueue(db as never, 1, 2) + expect(partial.totalUnresolvedCampaigns).toBe(2) + expect(partial.totalPages).toBe(1) + expect(partial.page).toBe(1) + expect(partial.unresolved.map((u) => u.campaign_id)).toEqual([C2, C3]) + + // If every campaign resolves concurrently between scan and load, queue settles to 0 unresolved on page 1. + remainingIds = new Set() + const allGone = await listCampaignReportQueue(db as never, 2, 2) + expect(allGone).toEqual({ + unresolved: [], + totalUnresolvedCampaigns: 0, + page: 1, + totalPages: 1, + resolved: [], + }) + }) + + it("breaks handled_at ties deterministically by id descending on resolved reports", async () => { + const tied = [ + { + id: "00000000-0000-4000-8000-000000000001", + campaign_id: C3, + reason_code: "other" as const, + details: "older id", + status: "dismissed" as const, + action_taken: "dismissed" as const, + resolution_note: "Cùng giao dịch", + handled_at: "2026-11-16T05:00:00Z", + created_at: "2026-11-14T07:00:00Z", + updated_at: "2026-11-16T05:00:00Z", + }, + { + id: "00000000-0000-4000-8000-000000000009", + campaign_id: C3, + reason_code: "false_or_misleading" as const, + details: "newer id", + status: "dismissed" as const, + action_taken: "dismissed" as const, + resolution_note: "Cùng giao dịch", + handled_at: "2026-11-16T05:00:00Z", + created_at: "2026-11-14T08:00:00Z", + updated_at: "2026-11-16T05:00:00Z", + }, + ] + + const db = fakeDb((call) => { + if (call.target === "campaign_reports") { + const statusFilter = call.ops.find(([n, col]) => n === "in" && col === "status")?.[2] as string[] | undefined + if (statusFilter?.includes("dismissed")) { + const orders = call.ops.filter(([n]) => n === "order") as [ + "order", + keyof (typeof tied)[number], + { ascending: boolean }, + ][] + const sorted = [...tied].sort((a, b) => { + for (const [, col, opts] of orders) { + const av = String(a[col] ?? "") + const bv = String(b[col] ?? "") + if (av !== bv) return opts.ascending ? av.localeCompare(bv) : bv.localeCompare(av) + } + return 0 + }) + return { data: sorted } + } + return { data: [] } + } + return { data: [] } + }) + + const queue = await listCampaignReportQueue(db as never) + expect(queue.resolved[0].reports.map((r) => r.id)).toEqual([ + "00000000-0000-4000-8000-000000000009", + "00000000-0000-4000-8000-000000000001", + ]) + expect(queue.resolved[0].latest.id).toBe("00000000-0000-4000-8000-000000000009") + }) }) describe("parseReportsPage and reportsPageHref", () => { - it("normalizes page query parameters and omits ?page=1", () => { + it("accepts only canonical positive integers bounded by MAX_REPORTS_PAGE and omits ?page=1", () => { expect(parseReportsPage({})).toBe(1) + expect(parseReportsPage({ page: "" })).toBe(1) expect(parseReportsPage({ page: "0" })).toBe(1) + expect(parseReportsPage({ page: "01" })).toBe(1) expect(parseReportsPage({ page: "-3" })).toBe(1) + expect(parseReportsPage({ page: "1.5" })).toBe(1) + expect(parseReportsPage({ page: "1e2" })).toBe(1) + expect(parseReportsPage({ page: "0x10" })).toBe(1) + expect(parseReportsPage({ page: " 2 " })).toBe(1) expect(parseReportsPage({ page: "abc" })).toBe(1) expect(parseReportsPage({ page: ["3", "4"] })).toBe(3) + expect(parseReportsPage({ page: "10000" })).toBe(MAX_REPORTS_PAGE) + expect(parseReportsPage({ page: "999999" })).toBe(MAX_REPORTS_PAGE) expect(reportsPageHref(1)).toBe("/admin/reports") expect(reportsPageHref(2)).toBe("/admin/reports?page=2") }) diff --git a/apps/web/src/lib/campaign-reports.ts b/apps/web/src/lib/campaign-reports.ts index 58e4c2a6..e63a9300 100644 --- a/apps/web/src/lib/campaign-reports.ts +++ b/apps/web/src/lib/campaign-reports.ts @@ -70,6 +70,8 @@ const MANAGED_REPORT_CAMPAIGN_COLUMNS = /** Unresolved campaigns shown per page on `/admin/reports`. */ export const UNRESOLVED_CAMPAIGNS_PER_PAGE = 20 +/** Maximum 1-based `?page=` value accepted on `/admin/reports`. */ +export const MAX_REPORTS_PAGE = 10_000 /** Rows read per PostgREST range request while scanning unresolved reports. */ export const REPORT_SCAN_BATCH = 1000 /** Maximum UUIDs in one `.in(...)` filter so query URLs stay well under proxy caps. */ @@ -131,11 +133,11 @@ export interface CampaignReportQueue { resolved: ResolvedCampaignItem[] } -/** Parses `?page=` on `/admin/reports` into a 1-based page integer. */ +/** Parses `?page=` on `/admin/reports` into a bounded 1-based page integer. */ export function parseReportsPage(params: Record): number { - const raw = Array.isArray(params.page) ? params.page[0] : params.page - const parsed = Number(raw) - return Number.isInteger(parsed) && parsed >= 1 ? parsed : 1 + const raw = (Array.isArray(params.page) ? params.page[0] : params.page) ?? "" + if (!/^[1-9][0-9]*$/.test(raw)) return 1 + return Math.min(Number(raw), MAX_REPORTS_PAGE) } export function reportsPageHref(page: number): string { @@ -185,16 +187,23 @@ async function scanCampaignIdsByStatus(db: Db, status: "open" | "awaiting_organi return campaignIds } -async function loadUnresolvedForCampaigns(db: Db, campaignIds: readonly string[]): Promise { - if (campaignIds.length === 0) return [] - const all: CampaignReport[] = [] +function chunkIds(ids: readonly string[], size = CAMPAIGNS_PER_REQUEST): string[][] { + const result: string[][] = [] + for (let i = 0; i < ids.length; i += size) { + result.push(ids.slice(i, i + size)) + } + return result +} + +async function loadUnresolvedChunk(db: Db, campaignChunk: readonly string[]): Promise { + const chunkRows: CampaignReport[] = [] const seenRowIds = new Set() for (let from = 0; ; from += REPORT_SCAN_BATCH) { const to = from + REPORT_SCAN_BATCH - 1 const { data, error } = await db .from("campaign_reports") .select(CAMPAIGN_REPORT_COLUMNS) - .in("campaign_id", [...campaignIds]) + .in("campaign_id", [...campaignChunk]) .in("status", ["open", "awaiting_organizer"]) .order("created_at", { ascending: true }) .order("id", { ascending: true }) @@ -205,24 +214,29 @@ async function loadUnresolvedForCampaigns(db: Db, campaignIds: readonly string[] for (const row of rows) { if (!seenRowIds.has(row.id)) { seenRowIds.add(row.id) - all.push(row) + chunkRows.push(row) added++ } } if (rows.length < REPORT_SCAN_BATCH || added === 0) break } - return all + return chunkRows +} + +async function loadUnresolvedForCampaigns(db: Db, campaignIds: readonly string[]): Promise { + const unique = [...new Set(campaignIds)] + if (unique.length === 0) return [] + const chunkResults = await Promise.all(chunkIds(unique).map((chunk) => loadUnresolvedChunk(db, chunk))) + return chunkResults.flat() } async function loadReportedCampaigns(db: Db, ids: readonly string[]): Promise> { const unique = [...new Set(ids)] if (unique.length === 0) return new Map() - const chunks: string[][] = [] - for (let i = 0; i < unique.length; i += CAMPAIGNS_PER_REQUEST) { - chunks.push(unique.slice(i, i + CAMPAIGNS_PER_REQUEST)) - } const results = await Promise.all( - chunks.map((chunk) => db.rpc("managed_campaigns", {}).select(MANAGED_REPORT_CAMPAIGN_COLUMNS).in("id", chunk)) + chunkIds(unique).map((chunk) => + db.rpc("managed_campaigns", {}).select(MANAGED_REPORT_CAMPAIGN_COLUMNS).in("id", chunk) + ) ) const byId = new Map() for (const { data, error } of results) { @@ -251,6 +265,9 @@ export async function listCampaignReportQueue( requestedPage = 1, pageSize = UNRESOLVED_CAMPAIGNS_PER_PAGE ): Promise { + const safePageSize = Math.max(1, Math.trunc(pageSize)) + const safeRequestedPage = Number.isFinite(requestedPage) ? Math.max(1, Math.trunc(requestedPage)) : 1 + const [openFirstIds, awaitingIds, resolvedRes] = await Promise.all([ scanCampaignIdsByStatus(db, "open"), scanCampaignIdsByStatus(db, "awaiting_organizer"), @@ -259,6 +276,7 @@ export async function listCampaignReportQueue( .select(CAMPAIGN_REPORT_COLUMNS) .in("status", ["actioned", "dismissed"]) .order("handled_at", { ascending: false }) + .order("id", { ascending: false }) .limit(RESOLVED_REPORTS_LIMIT), ]) if (resolvedRes.error) throw resolvedRes.error @@ -267,13 +285,7 @@ export async function listCampaignReportQueue( for (const id of awaitingIds) { if (!openFirstIds.has(id)) awaitingOnlyIds.push(id) } - const orderedCampaignIds = [...openFirstIds, ...awaitingOnlyIds] - - const totalUnresolvedCampaigns = orderedCampaignIds.length - const totalPages = Math.max(1, Math.ceil(totalUnresolvedCampaigns / pageSize)) - const page = Math.min(Math.max(1, requestedPage), totalPages) - const start = (page - 1) * pageSize - const pageCampaignIds = orderedCampaignIds.slice(start, start + pageSize) + let activeCampaignIds = [...openFirstIds, ...awaitingOnlyIds] const resolvedRows = (resolvedRes.data ?? []) as CampaignReport[] const resolvedByCampaign = new Map() @@ -281,14 +293,43 @@ export async function listCampaignReportQueue( resolvedByCampaign.set(row.campaign_id, [...(resolvedByCampaign.get(row.campaign_id) ?? []), row]) } - const [pageReports, campaigns] = await Promise.all([ - loadUnresolvedForCampaigns(db, pageCampaignIds), - loadReportedCampaigns(db, [...pageCampaignIds, ...resolvedByCampaign.keys()]), - ]) - const unresolvedByCampaign = new Map() - for (const row of pageReports) { - unresolvedByCampaign.set(row.campaign_id, [...(unresolvedByCampaign.get(row.campaign_id) ?? []), row]) + const queriedReportCampaignIds = new Set() + const queriedManagedCampaignIds = new Set() + const campaigns = new Map() + + let totalUnresolvedCampaigns = activeCampaignIds.length + let totalPages = Math.max(1, Math.ceil(totalUnresolvedCampaigns / safePageSize)) + let page = Math.min(safeRequestedPage, totalPages) + let pageCampaignIds = activeCampaignIds.slice((page - 1) * safePageSize, page * safePageSize) + + while (true) { + const unqueriedReportIds = pageCampaignIds.filter((id) => !queriedReportCampaignIds.has(id)) + const campaignIdsToLoad = [...pageCampaignIds, ...resolvedByCampaign.keys()].filter( + (id) => !queriedManagedCampaignIds.has(id) + ) + if (unqueriedReportIds.length === 0 && campaignIdsToLoad.length === 0) break + + for (const id of unqueriedReportIds) queriedReportCampaignIds.add(id) + for (const id of campaignIdsToLoad) queriedManagedCampaignIds.add(id) + + const [fetchedReports, fetchedCampaigns] = await Promise.all([ + loadUnresolvedForCampaigns(db, unqueriedReportIds), + loadReportedCampaigns(db, campaignIdsToLoad), + ]) + for (const [id, campaign] of fetchedCampaigns) campaigns.set(id, campaign) + for (const row of fetchedReports) { + unresolvedByCampaign.set(row.campaign_id, [...(unresolvedByCampaign.get(row.campaign_id) ?? []), row]) + } + + const resolvedConcurrently = new Set(unqueriedReportIds.filter((id) => !unresolvedByCampaign.has(id))) + if (resolvedConcurrently.size === 0) break + + activeCampaignIds = activeCampaignIds.filter((id) => !resolvedConcurrently.has(id)) + totalUnresolvedCampaigns = activeCampaignIds.length + totalPages = Math.max(1, Math.ceil(totalUnresolvedCampaigns / safePageSize)) + page = Math.min(safeRequestedPage, totalPages) + pageCampaignIds = activeCampaignIds.slice((page - 1) * safePageSize, page * safePageSize) } const unresolved: UnresolvedCampaignItem[] = pageCampaignIds.flatMap((campaign_id) => { From 1da02c1e9c5acaf185d260d911fb97a41c1141bc Mon Sep 17 00:00:00 2001 From: JOY <5027251+JOY@users.noreply.github.com> Date: Thu, 19 Nov 2026 05:39:47 +0700 Subject: [PATCH 02/23] fix(campaigns): harden organizer list UX, statement preview, and home ranking (#260) (#266) Co-authored-by: Qwen-Coder --- apps/web/src/app/me/campaigns/page.test.ts | 120 ++++++++++++++---- apps/web/src/app/me/campaigns/page.tsx | 111 +++++++++------- apps/web/src/components/CampaignCard.test.ts | 98 +++++++++++++- apps/web/src/components/CampaignCard.tsx | 11 +- .../campaign/RecentSupporters.test.ts | 43 +++++++ .../components/campaign/RecentSupporters.tsx | 10 +- .../campaign/StatementPreview.test.ts | 100 ++++++++++++++- .../components/campaign/StatementPreview.tsx | 8 +- apps/web/src/lib/home.test.ts | 60 +++++++++ apps/web/src/lib/home.ts | 7 +- apps/web/src/lib/reward-tiers.test.ts | 42 +++++- apps/web/src/lib/reward-tiers.ts | 4 +- 12 files changed, 518 insertions(+), 96 deletions(-) diff --git a/apps/web/src/app/me/campaigns/page.test.ts b/apps/web/src/app/me/campaigns/page.test.ts index 6d8d5b77..5750652c 100644 --- a/apps/web/src/app/me/campaigns/page.test.ts +++ b/apps/web/src/app/me/campaigns/page.test.ts @@ -11,6 +11,7 @@ const USER = "11111111-1111-4111-8111-111111111111" const CAMPAIGN_A = "22222222-2222-4222-8222-222222222222" const CAMPAIGN_B = "33333333-3333-4333-8333-333333333333" const CAMPAIGN_C = "44444444-4444-4444-8444-444444444444" +const CAMPAIGN_D = "55555555-5555-4555-8555-555555555555" const state = vi.hoisted(() => ({ handler: (() => undefined) as Handler, @@ -19,6 +20,12 @@ const state = vi.hoisted(() => ({ serviceUsed: false, })) +const redirectMock = vi.hoisted(() => + vi.fn((url: string): never => { + throw new Error(`NEXT_REDIRECT:${url}`) + }) +) + const requireSessionMock = vi.hoisted(() => vi.fn(async () => ({ user: { id: USER, email: "organizer@example.vn", name: "Lan" }, @@ -26,6 +33,9 @@ const requireSessionMock = vi.hoisted(() => })) ) +vi.mock("next/navigation", () => ({ + redirect: redirectMock, +})) vi.mock("@/lib/auth/session", () => ({ requireSession: requireSessionMock, })) @@ -49,21 +59,26 @@ const { default: MyCampaignsPage } = await import("./page") function renderAsync(node: ReactNode): Promise { return new Promise((resolve, reject) => { let html = "" + let failed = false const sink = new Writable({ write(chunk, _encoding, callback) { html += chunk.toString() callback() }, }) - const { pipe } = renderToPipeableStream(node, { + const { pipe, abort } = renderToPipeableStream(node, { onAllReady() { - pipe(sink) + if (!failed) pipe(sink) }, onError(error) { + failed = true + abort() reject(error) }, }) - sink.on("finish", () => resolve(html.replace(/\u00a0/g, " "))) + sink.on("finish", () => { + if (!failed) resolve(html.replace(/\u00a0/g, " ")) + }) sink.on("error", reject) }) } @@ -102,13 +117,14 @@ function makeCampaign( } beforeEach(() => { + redirectMock.mockClear() requireSessionMock.mockClear() state.calls.length = 0 state.tokens.length = 0 state.serviceUsed = false }) -describe("MyCampaignsPage (DOS/Give#217)", () => { +describe("MyCampaignsPage (DOS/Give#217, DOS/Give#260)", () => { it("requires /me/campaigns session, queries managed_campaigns via dbAs(accessToken), and renders level-2 EmptyState with PageHeader as sole CTA", async () => { state.handler = (call) => { if (call.target === "rpc:managed_campaigns") return { data: [] } @@ -134,7 +150,34 @@ describe("MyCampaignsPage (DOS/Give#217)", () => { expect(html).not.toContain(" { + it.each(["PGRST301", "PGRST303"])( + "redirects to /auth/login?return_path=%2Fme%2Fcampaigns when listMyCampaigns rejects an expired JWT (%s)", + async (code) => { + state.handler = (call) => { + if (call.target === "rpc:managed_campaigns") { + return { error: { code, message: "JWT expired" } } + } + return undefined + } + + const expectedLogin = "/auth/login?return_path=%2Fme%2Fcampaigns" + await expect(renderAsync(await MyCampaignsPage())).rejects.toThrow(`NEXT_REDIRECT:${expectedLogin}`) + expect(redirectMock).toHaveBeenCalledWith(expectedLogin) + } + ) + + it("rethrows non-JWT database errors instead of redirecting to login", async () => { + const dbError = { code: "XX000", message: "database unavailable" } + state.handler = (call) => { + if (call.target === "rpc:managed_campaigns") return { error: dbError } + return undefined + } + + await expect(renderAsync(await MyCampaignsPage())).rejects.toBe(dbError) + expect(redirectMock).not.toHaveBeenCalled() + }) + + it("renders h2 titles, sr-only row link disambiguators, private cover vs placeholder, and changes_requested & suspended review notes", async () => { const coverPath = "campaigns/22222222-2222-4222-8222-222222222222/cover.webp" state.handler = (call) => { if (call.target === "rpc:managed_campaigns") { @@ -156,7 +199,7 @@ describe("MyCampaignsPage (DOS/Give#217)", () => { title: "Sách ảnh thiếu nhi", type: "back", status: "changes_requested", - review_note: "Bổ sung dự toán in ấn, cần hỏi viết cho hi@give.vn", + review_note: "Bổ sung dự toán in ấn,\ncần hỏi viết cho hi@give.vn", cover: null, }), makeCampaign({ @@ -165,9 +208,18 @@ describe("MyCampaignsPage (DOS/Give#217)", () => { title: "Album nhạc indie", type: "back", status: "changes_requested", - review_note: null, + review_note: " ", cover: { storage_path: null, alt: null }, }), + makeCampaign({ + id: CAMPAIGN_D, + slug: "lop-hoc-vung-bien", + title: "Lớp học vùng biên", + type: "give", + status: "suspended", + review_note: "Đang xác minh chứng từ chi đợt 1.\nLiên hệ hi@give.vn để bổ sung.", + cover: null, + }), ], } } @@ -178,39 +230,61 @@ describe("MyCampaignsPage (DOS/Give#217)", () => { expect(state.serviceUsed).toBe(false) const items = [...html.matchAll(//g)].map((m) => m[0]) - expect(items).toHaveLength(3) + expect(items).toHaveLength(4) - // Row 0: public give campaign with private cover thumbnail; stale review_note stays hidden. + // Row 0: public give campaign with h2 title, private cover thumbnail, and sr-only link names; stale review_note stays hidden. expect(items[0]).toContain(">Từ thiện<") expect(items[0]).toContain(">Đang gây quỹ<") + expect(items[0]).toMatch( + new RegExp(`]*>]*href="/me/campaigns/${CAMPAIGN_A}"[^>]*>Bếp ấm vùng cao`) + ) expect(items[0]).toContain("Xem trang<") + expect(items[0]).toContain('Xem trang: Bếp ấm vùng cao') expect(items[0]).toContain(`href="/me/campaigns/${CAMPAIGN_A}"`) - expect(items[0]).toContain(">Quản lý<") + expect(items[0]).toContain('Quản lý: Bếp ấm vùng cao') expect(items[0]).not.toContain("Cần sửa:") + expect(items[0]).not.toContain("Lý do tạm dừng:") - // Row 1: non-public back campaign with CoverPlaceholder fallback and changes_requested review_note. + // Row 1: non-public back campaign with CoverPlaceholder fallback and multiline changes_requested review_note. expect(items[1]).toContain(">Dự án sáng tạo<") expect(items[1]).toContain(">Cần chỉnh sửa<") + expect(items[1]).toMatch( + new RegExp(`]*>]*href="/me/campaigns/${CAMPAIGN_B}"[^>]*>Sách ảnh thiếu nhi`) + ) expect(items[1]).not.toContain("Xem trang<") - expect(items[1]).toContain(`href="/me/campaigns/${CAMPAIGN_B}"`) - expect(items[1]).toContain(">Quản lý<") + expect(items[1]).not.toContain(">Xem trang") + expect(items[1]).toContain('Quản lý: Sách ảnh thiếu nhi') - // Row 2: changes_requested without review_note omits "Cần sửa:" and falls back when storage_path is null. + // Row 2: changes_requested with blank review_note omits "Cần sửa:" and falls back when storage_path is null. expect(items[2]).not.toContain("Xem trang<") - expect(items[2]).toContain(`href="/me/campaigns/${CAMPAIGN_C}"`) - expect(items[2]).toContain(">Quản lý<") + expect(items[2]).not.toContain(">Xem trang") + expect(items[2]).toContain('Quản lý: Album nhạc indie') + + // Row 3: suspended campaign shows moderator review_note with danger tone, max-w-[68ch], and whitespace-pre-line. + expect(items[3]).toContain(">Tạm dừng<") + expect(items[3]).toMatch( + new RegExp(`]*>]*href="/me/campaigns/${CAMPAIGN_D}"[^>]*>Lớp học vùng biên`) + ) + expect(items[3]).toContain("max-w-[68ch]") + expect(items[3]).toContain("whitespace-pre-line") + expect(items[3]).toContain("text-danger") + expect(items[3]).toContain("Lý do tạm dừng:") + expect(items[3]).toContain("Đang xác minh chứng từ chi đợt 1.\nLiên hệ ") + expect(items[3]).toContain('href="mailto:hi@give.vn"') + expect(items[3]).not.toContain(">Xem trang") + expect(items[3]).toContain('Quản lý: Lớp học vùng biên') }) it("shows 'Xem trang' strictly for public statuses and hides it for every non-public status", async () => { @@ -249,11 +323,13 @@ describe("MyCampaignsPage (DOS/Give#217)", () => { const publicSet = new Set(["live", "settling", "succeeded", "failed", "closed"]) statuses.forEach((status, index) => { + const title = `Chiến dịch camp-${status}` + expect(items[index]).toContain(`Quản lý: ${title}`) if (publicSet.has(status)) { expect(items[index]).toContain(`href="/campaigns/camp-${status}"`) - expect(items[index]).toContain(">Xem trang<") + expect(items[index]).toContain(`Xem trang: ${title}`) } else { - expect(items[index]).not.toContain(">Xem trang<") + expect(items[index]).not.toContain(">Xem trang") } }) }) diff --git a/apps/web/src/app/me/campaigns/page.tsx b/apps/web/src/app/me/campaigns/page.tsx index 8cf6a594..0a8cad1a 100644 --- a/apps/web/src/app/me/campaigns/page.tsx +++ b/apps/web/src/app/me/campaigns/page.tsx @@ -1,6 +1,7 @@ import type { Metadata } from "next" import Image from "next/image" import Link from "next/link" +import { redirect } from "next/navigation" import { Suspense } from "react" import { StatusBadge, TypeBadge } from "@/components/badges" @@ -15,6 +16,7 @@ import { isPublicStatus, listMyCampaigns } from "@/lib/campaigns" import { privateCoverUrl } from "@/lib/cover-urls" import { formatDate, formatVnd } from "@/lib/format" import { dbAs } from "@/lib/supabase" +import { isSessionRejected } from "@/server/contributions" import { MePage } from "../_components/MePage" @@ -36,7 +38,13 @@ export default async function MyCampaignsPage() { } async function CampaignList({ session }: { session: Session }) { - const campaigns = await listMyCampaigns(dbAs(session.accessToken), session.user.id) + let campaigns + try { + campaigns = await listMyCampaigns(dbAs(session.accessToken), session.user.id) + } catch (error) { + if (isSessionRejected(error)) redirect(`/auth/login?return_path=${encodeURIComponent("/me/campaigns")}`) + throw error + } if (campaigns.length === 0) { return ( @@ -48,57 +56,64 @@ async function CampaignList({ session }: { session: Session }) { return (
    - {campaigns.map((campaign) => ( -
  • -
    -
    - {campaign.cover?.storage_path ? ( - - ) : ( - - )} -
    -
    -
    - - + {campaigns.map((campaign) => { + const reviewNote = campaign.review_note?.trim() + return ( +
  • +
    +
    + {campaign.cover?.storage_path ? ( + + ) : ( + + )}
    - - {campaign.title} - -

    - Mục tiêu {formatVnd(campaign.goal_amount)} · - Tạo ngày {formatDate(campaign.created_at)} -

    - {campaign.status === "changes_requested" && campaign.review_note && ( -

    - Cần sửa: +

    +
    + + +
    +

    + + {campaign.title} + +

    +

    + Mục tiêu {formatVnd(campaign.goal_amount)}{" "} + · Tạo ngày {formatDate(campaign.created_at)}

    - )} + {(campaign.status === "changes_requested" || campaign.status === "suspended") && reviewNote && ( +

    + {campaign.status === "suspended" ? "Lý do tạm dừng: " : "Cần sửa: "} + +

    + )} +
    - -
    - {isPublicStatus(campaign.status) && ( - - Xem trang +
    + {isPublicStatus(campaign.status) && ( + + Xem trang{`: ${campaign.title}`} + + )} + + Quản lý{`: ${campaign.title}`} - )} - - Quản lý - -
    -
  • - ))} + + + ) + })}
) } diff --git a/apps/web/src/components/CampaignCard.test.ts b/apps/web/src/components/CampaignCard.test.ts index 244ccf9e..95bfb700 100644 --- a/apps/web/src/components/CampaignCard.test.ts +++ b/apps/web/src/components/CampaignCard.test.ts @@ -3,12 +3,16 @@ import { renderToStaticMarkup } from "react-dom/server" import { describe, expect, it, vi } from "vitest" import type { ListedCampaign } from "@/lib/campaigns" +import { publicCoverUrl } from "@/lib/cover-urls" vi.mock("next/link", () => ({ default: ({ href, children, ...rest }: { href: string; children: unknown }) => createElement("a", { href, ...rest }, children as never), })) -vi.mock("next/image", () => ({ default: () => null })) +vi.mock("next/image", () => ({ + default: ({ priority, fill: _fill, ...rest }: { src: string; alt: string; priority?: boolean; fill?: boolean }) => + createElement("img", { ...rest, ...(priority ? { "data-priority": "true" } : {}) }), +})) const { CampaignCard } = await import("./CampaignCard") @@ -76,4 +80,96 @@ describe("CampaignCard", () => { expect(ended("live", past)).toContain("Đã hết hạn") expect(ended("live", "2999-01-01T00:00:00Z")).toMatch(/Còn \d+ ngày/) }) + + it("renders back campaign copy ('Dự án sáng tạo', 'đã cam kết', 'người đồng hành') and headingLevel={2}", () => { + const html = renderToStaticMarkup( + createElement(CampaignCard, { + campaign: campaign(null, { + type: "back", + slug: "sach-anh", + title: "Sách ảnh thiếu nhi", + ends_at: "2999-01-01T00:00:00Z", + }), + raised: 35_000_000, + people: 14, + headingLevel: 2, + }) + ) + expect(html).toContain(">Dự án sáng tạo<") + expect(html).toMatch(/]*>]*>Sách ảnh thiếu nhi<\/a><\/h2>/) + expect(html).not.toContain(" { + const path = "campaigns/1060c000-0000-4000-8000-000000000001/cover.webp" + const withCover = renderToStaticMarkup( + createElement(CampaignCard, { + campaign: campaign(null, { cover: { storage_path: path, alt: "Ảnh bìa" } }), + priority: true, + }) + ) + expect(withCover).toContain(`src="${publicCoverUrl(path)}"`) + expect(withCover).toContain('alt=""') + expect(withCover).toContain('data-priority="true"') + + const withNullPath = renderToStaticMarkup( + createElement(CampaignCard, { + campaign: campaign(null, { cover: { storage_path: null, alt: null } }), + }) + ) + expect(withNullPath).not.toContain(" { + const nullOptions = renderToStaticMarkup( + createElement(CampaignCard, { + campaign: campaign(null, { + display_options: null as never, + ends_at: "2999-01-01T00:00:00Z", + }), + raised: 50_000_000, + people: 6, + }) + ) + expect(nullOptions).toContain("h-1.5") + expect(nullOptions).toContain('

') + expect(nullOptions).toContain("đã nhận · 50%") + expect(nullOptions).toMatch(/6 người ủng hộ · Còn \d+ ngày/) + + const hiddenProgress = renderToStaticMarkup( + createElement(CampaignCard, { + campaign: campaign(null, { + display_options: { progress_bar: false, backers_count: false, time_remaining: false }, + ends_at: "2999-01-01T00:00:00Z", + }), + raised: 50_000_000, + people: 6, + }) + ) + expect(hiddenProgress).not.toContain("h-1.5") + expect(hiddenProgress).not.toContain("mt-3") + expect(hiddenProgress).toContain('

') + expect(hiddenProgress).toContain("đã nhận") + expect(hiddenProgress).not.toContain("50%") + expect(hiddenProgress).not.toContain("6 người ủng hộ") + expect(hiddenProgress).not.toContain("Còn ") + + // Ended status still renders in meta even when time_remaining is false. + const endedHiddenTime = renderToStaticMarkup( + createElement(CampaignCard, { + campaign: campaign(null, { + status: "succeeded", + ends_at: "2026-01-01T00:00:00Z", + display_options: { progress_bar: false, backers_count: false, time_remaining: false }, + }), + raised: 100_000_000, + people: 6, + }) + ) + expect(endedHiddenTime).toContain("Thành công") + expect(endedHiddenTime).not.toContain("6 người ủng hộ") + }) }) diff --git a/apps/web/src/components/CampaignCard.tsx b/apps/web/src/components/CampaignCard.tsx index d38a9931..fb3027f8 100644 --- a/apps/web/src/components/CampaignCard.tsx +++ b/apps/web/src/components/CampaignCard.tsx @@ -5,7 +5,7 @@ import { TypeBadge } from "@/components/badges" import { ProgressBar } from "@/components/ProgressBar" import { CoverPlaceholder } from "@/components/ui/CoverPlaceholder" import { CheckIcon } from "@/components/ui/icons" -import { STATUS_LABELS, type ListedCampaign } from "@/lib/campaigns" +import { STATUS_LABELS, type DisplayOptions, type ListedCampaign } from "@/lib/campaigns" import { publicCoverUrl } from "@/lib/cover-urls" import { daysLeft, formatVnd, progressPercent } from "@/lib/format" @@ -38,7 +38,8 @@ export function CampaignCard({ }) { const percent = progressPercent(raised, campaign.goal_amount) const days = daysLeft(campaign.ends_at) - const options = campaign.display_options + const options: Partial = campaign.display_options ?? {} + const showProgress = options.progress_bar !== false const organizer = campaign.organizer const isGive = campaign.type === "give" const Heading = headingLevel === 2 ? "h2" : "h3" @@ -100,12 +101,12 @@ export function CampaignCard({

)}
- {options.progress_bar !== false && } -

+ {showProgress && } +

{formatVnd(raised)}{" "} {isGive ? "đã nhận" : "đã cam kết"} - {options.progress_bar !== false && ` · ${percent}%`} + {showProgress && ` · ${percent}%`}

{meta.length > 0 &&

{meta.join(" · ")}

} diff --git a/apps/web/src/components/campaign/RecentSupporters.test.ts b/apps/web/src/components/campaign/RecentSupporters.test.ts index 08e9081e..195c40e5 100644 --- a/apps/web/src/components/campaign/RecentSupporters.test.ts +++ b/apps/web/src/components/campaign/RecentSupporters.test.ts @@ -106,4 +106,47 @@ describe("RecentSupporters", () => { expect(html).not.toContain("LE THI TAI KHOAN NGAN HANG") expect(html).toContain("Xem tất cả lượt ủng hộ") }) + + it("defensively excludes own-transfer and bank-returned rows even if matched is true", () => { + const onlyNonDonations: StatementRow[] = [ + row({ + id: "own-in", + matched: true, + own_transfer_id: "pair-1", + own_transfer_label: "Chuyển sang tài khoản mới", + }), + row({ + id: "return-in", + matched: true, + return_of: "out-1", + }), + ] + expect(RecentSupporters({ slug: "be-an", rows: onlyNonDonations, count: 4 })).toBeNull() + + const mixed = renderToStaticMarkup( + createElement(RecentSupporters, { + slug: "be-an", + rows: [...onlyNonDonations, row({ id: "real-in", donor_name: "Anh Khoa" })], + count: 4, + }) + ) + expect(mixed.match(/ { + const donorRow = [row({ id: "in-1", donor_name: "Chị Mai" })] + + const withNullCount = renderToStaticMarkup( + createElement(RecentSupporters, { slug: "be-an", rows: donorRow, count: null }) + ) + expect(withNullCount).toContain(">Xem tất cả lượt ủng hộ<") + expect(withNullCount).not.toContain("người ủng hộ<") + + const withOmittedCount = renderToStaticMarkup(createElement(RecentSupporters, { slug: "be-an", rows: donorRow })) + expect(withOmittedCount).toContain(">Xem tất cả lượt ủng hộ<") + expect(withOmittedCount).not.toContain("người ủng hộ<") + }) }) diff --git a/apps/web/src/components/campaign/RecentSupporters.tsx b/apps/web/src/components/campaign/RecentSupporters.tsx index 21ebe37a..dbae0f37 100644 --- a/apps/web/src/components/campaign/RecentSupporters.tsx +++ b/apps/web/src/components/campaign/RecentSupporters.tsx @@ -18,10 +18,12 @@ export function RecentSupporters({ }: { slug: string rows: readonly StatementRow[] - /** All supporters of the campaign, for the "see all" link. */ - count: number + /** All supporters of the campaign, for the "see all" link; omitted or null when the count is hidden. */ + count?: number | null }) { - const donations = rows.filter((row) => row.direction === "in" && row.matched).slice(0, RECENT_SUPPORTERS) + const donations = rows + .filter((row) => row.direction === "in" && row.matched && !row.own_transfer_label && !row.return_of) + .slice(0, RECENT_SUPPORTERS) if (donations.length === 0) return null return (
@@ -40,7 +42,7 @@ export function RecentSupporters({ ))} - {count > 0 ? `Xem tất cả ${count} người ủng hộ` : "Xem tất cả lượt ủng hộ"} + {count != null && count > 0 ? `Xem tất cả ${count} người ủng hộ` : "Xem tất cả lượt ủng hộ"}
) diff --git a/apps/web/src/components/campaign/StatementPreview.test.ts b/apps/web/src/components/campaign/StatementPreview.test.ts index 84c09840..16794db1 100644 --- a/apps/web/src/components/campaign/StatementPreview.test.ts +++ b/apps/web/src/components/campaign/StatementPreview.test.ts @@ -10,7 +10,7 @@ vi.mock("next/link", () => ({ createElement("a", { href, ...rest }, children as never), })) -const { StatementPreview } = await import("./StatementPreview") +const { PREVIEW_ROWS, StatementPreview } = await import("./StatementPreview") const totals: MoneyTotals = { campaign_id: "22222222-2222-4222-8222-222222222222", @@ -75,10 +75,14 @@ describe("StatementPreview: a transfer between the campaign's own accounts (DOS/ createElement(StatementPreview, { slug: "a", totals: { ...totals, own_transfer_amount: 3_000_000 }, - rows: [row({ id: "out", explained: true, ...pair }), row({ id: "in", direction: "in", ...pair })], + rows: [ + row({ id: "out", explained: true, purpose: "Chuyển nội bộ cũ", ...pair }), + row({ id: "in", direction: "in", ...pair }), + ], }) ) - expect(html.match(/Chuyển sang tài khoản mới/g)?.length).toBeGreaterThanOrEqual(2) + expect(html.match(/Chuyển sang tài khoản mới/g)?.length).toBeGreaterThanOrEqual(4) + expect(html).not.toContain("Chuyển nội bộ cũ") expect(html).toContain("Chuyển tài khoản") expect(html).not.toContain("Đã giải trình") expect(html).not.toContain("Không công khai") @@ -115,6 +119,9 @@ describe("StatementPreview: a transfer out that a bank returned (DOS/Give#72)", expect(html).toContain("Ngân hàng trả lại tiền chuyển đi") expect(html).toContain("Không phải tiền ủng hộ") expect(html).toContain("Bị ngân hàng trả lại") + // Neither leg is colored in donation green. + expect(html).not.toContain('text-primary">+') + expect(html).toContain(`text-fg">+${formatVnd(290_000)}`) // The returned transfer out keeps its purpose but not the "explained" badge. expect(html).toContain("Mua rau") expect(html).not.toContain("Đã giải trình") @@ -186,15 +193,98 @@ describe("StatementPreview: a corrected explanation (DOS/Give#71)", () => { expect(stale).toBe(html) }) - it("still labels an uncorrected explanation as not a donation", () => { + it("still labels an uncorrected explanation as not a donation, without donation green", () => { const html = renderToStaticMarkup( createElement(StatementPreview, { slug: "a", totals, - rows: [row({ id: "in", direction: "in", in_explanation: "organizer_top_up" })], + rows: [row({ id: "in", direction: "in", amount: 450_000, in_explanation: "organizer_top_up" })], }) ) expect(html).toContain("Không phải tiền ủng hộ") expect(html).toContain("Người tổ chức nạp thêm tiền") + expect(html).not.toContain('text-primary">+') + expect(html).toContain(`text-fg">+${formatVnd(450_000)}`) + }) +}) + +describe("StatementPreview: summary blocks, row states, and refund badge tone (DOS/Give#260)", () => { + it("renders PledgeTotals for back campaigns and omits the give-only other_in_amount note", () => { + const backTotals: MoneyTotals = { + ...totals, + type: "back", + goal_amount: 40_000_000, + pledged_amount: 30_000_000, + paid_amount: 12_000_000, + other_in_amount: 2_000_000, + refund_owed_amount: 500_000, + } + const html = renderToStaticMarkup( + createElement(StatementPreview, { slug: "du-an-a", totals: backTotals, rows: [] }) + ) + + expect(html).toContain('aria-label="Số liệu cam kết"') + expect(html).toContain("Đã cam kết") + expect(html).toContain("Đã thanh toán") + expect(html).toContain(formatVnd(10_000_000)) + expect(html).toContain("Còn thiếu") + expect(html).toContain(`Hoàn tiền còn nợ người ủng hộ:`) + expect(html).toContain(formatVnd(500_000)) + expect(html).not.toContain("người tổ chức nạp thêm, ngân hàng hoàn phí hoặc trả lãi") + expect(html).toContain("Chưa có giao dịch nào trong sao kê.") + }) + + it("renders other_in_amount and unexplained_out_count notices on give campaigns, and omits row lists when rows === null", () => { + const giveTotals: MoneyTotals = { + ...totals, + other_in_amount: 250_000, + unexplained_out_count: 2, + unexplained_out_amount: 1_200_000, + } + const html = renderToStaticMarkup( + createElement(StatementPreview, { slug: "be-an", totals: giveTotals, rows: null }) + ) + + expect(html).toContain('aria-label="Số liệu sao kê"') + expect(html).toContain(`Trong đó ${formatVnd(250_000)} không phải tiền ủng hộ`) + expect(html).toContain(`2 khoản chi, tổng ${formatVnd(1_200_000)}, chưa được người tổ chức giải trình.`) + expect(html).not.toContain("Chưa có giao dịch nào trong sao kê.") + expect(html).not.toContain(" { + expect(PREVIEW_ROWS).toBe(5) + + const rows: StatementRow[] = [ + row({ + id: "refund-1", + direction: "out", + amount: 200_000, + explained: true, + is_refund: true, + purpose: "Hoàn tiền chuyển thừa", + }), + ...Array.from({ length: 5 }, (_, i) => + row({ + id: `in-${i + 1}`, + direction: "in", + amount: (i + 1) * 100_000, + matched: true, + donor_name: `Người ${i + 1}`, + }) + ), + ] + + const html = renderToStaticMarkup(createElement(StatementPreview, { slug: "be-an", totals, rows })) + + // Badge tone="info" uses bg-surface text-fg, never neutral text-muted or "Đã giải trình". + expect(html).toMatch(/Hoàn tiền<\/span>/) + expect(html).not.toContain("Đã giải trình") + expect(html).toContain("Hoàn tiền chuyển thừa") + // Matched donations keep donation green, and row 6 ("Người 5") is truncated by PREVIEW_ROWS = 5. + expect(html).toContain(`text-primary">+${formatVnd(100_000)}`) + expect(html).toContain("Người 4") + expect(html).not.toContain("Người 5") }) }) diff --git a/apps/web/src/components/campaign/StatementPreview.tsx b/apps/web/src/components/campaign/StatementPreview.tsx index d2481cbf..215c0847 100644 --- a/apps/web/src/components/campaign/StatementPreview.tsx +++ b/apps/web/src/components/campaign/StatementPreview.tsx @@ -20,6 +20,7 @@ import { export const PREVIEW_ROWS = 5 function rowText(row: StatementRow): string { + if (row.own_transfer_label) return row.own_transfer_label if (row.direction === "out" && row.explained && row.purpose) return row.purpose return counterpartyLabel(row) } @@ -42,16 +43,15 @@ function RowNote({ row }: { row: StatementRow }) { } // A transfer out that a bank returned (DOS/Give#72). if (row.returned_by) return Bị ngân hàng trả lại - if (row.is_refund) return Hoàn tiền + if (row.is_refund) return Hoàn tiền return row.explained ? Đã giải trình : Chưa giải trình } function Amount({ row }: { row: StatementRow }) { const incoming = row.direction === "in" + const donationTone = incoming && !row.own_transfer_label && !row.return_of && !explainedNotDonation(row) return ( - + {incoming ? "+" : "−"} {formatVnd(row.amount)} diff --git a/apps/web/src/lib/home.test.ts b/apps/web/src/lib/home.test.ts index 46e1a939..d8766587 100644 --- a/apps/web/src/lib/home.test.ts +++ b/apps/web/src/lib/home.test.ts @@ -37,4 +37,64 @@ describe("homeSections", () => { it("handles no campaigns", () => { expect(homeSections([], new Map())).toEqual({ featured: null, trending: [], newest: [] }) }) + + it("ranks trending by exact progress ratio (including sub-percent and >100%) and breaks ties by raised amount", () => { + // Featured takes g-hero (highest give raised = 1_000_000). + // Remaining candidates: + // - b-over-250: 250 / 100 = 2.50 (progressPercent would cap at 100) + // - b-over-120: 120 / 100 = 1.20 (progressPercent would also cap at 100) + // - g-999: 999 / 1_000 = 0.999 (progressPercent would floor to 99) + // - g-990: 990 / 1_000 = 0.990 (progressPercent would also floor to 99) + // - b-half-big: 500_000 / 1_000_000 = 0.50 (tie on ratio, higher raised wins) + // - b-half-sm: 500 / 1_000 = 0.50 + const list = [ + campaign("g-hero", "give", 10_000_000), + campaign("b-half-sm", "back", 1_000), + campaign("g-990", "give", 1_000), + campaign("b-over-120", "back", 100), + campaign("b-half-big", "back", 1_000_000), + campaign("g-999", "give", 1_000), + campaign("b-over-250", "back", 100), + ] + const map = new Map([ + totals("g-hero", "give", 1_000_000), + totals("b-half-sm", "back", 500), + totals("g-990", "give", 990), + totals("b-over-120", "back", 120), + totals("b-half-big", "back", 500_000), + totals("g-999", "give", 999), + totals("b-over-250", "back", 250), + ]) + + const { featured, trending, newest } = homeSections(list, map, 6) + expect(featured?.id).toBe("g-hero") + expect(trending.map((c) => c.id)).toEqual(["b-over-250", "b-over-120", "g-999", "g-990", "b-half-big", "b-half-sm"]) + expect(newest).toEqual([]) + }) + + it("treats non-positive goal_amount as 0 progress and clamps non-positive trendingCount to 0", () => { + const list = [ + campaign("g-hero", "give", 1_000), + campaign("b-zero-goal", "back", 0), + campaign("b-normal", "back", 100), + campaign("b-second", "back", 100), + ] + const map = new Map([ + totals("g-hero", "give", 500), + totals("b-zero-goal", "back", 900), + totals("b-normal", "back", 10), + totals("b-second", "back", 80), + ]) + + // Positive progress (0.8, 0.1) ranks ahead of goal_amount === 0 (ratio 0). + expect(homeSections(list, map, 3).trending.map((c) => c.id)).toEqual(["b-second", "b-normal", "b-zero-goal"]) + + // Negative or zero trendingCount never slices from the end (.slice(0, -1) bug). + for (const badCount of [0, -1, -5]) { + const sections = homeSections(list, map, badCount) + expect(sections.featured?.id).toBe("g-hero") + expect(sections.trending).toEqual([]) + expect(sections.newest.map((c) => c.id)).toEqual(["b-zero-goal", "b-normal", "b-second"]) + } + }) }) diff --git a/apps/web/src/lib/home.ts b/apps/web/src/lib/home.ts index 7cf8866a..4f921e88 100644 --- a/apps/web/src/lib/home.ts +++ b/apps/web/src/lib/home.ts @@ -1,5 +1,4 @@ import type { CardCampaign } from "@/lib/campaigns" -import { progressPercent } from "@/lib/format" import { raisedAmount, type MoneyTotals } from "@/lib/statement" export interface HomeSections { @@ -21,14 +20,16 @@ export function homeSections( trendingCount = 3 ): HomeSections { const raised = (c: CardCampaign) => raisedAmount(totals.get(c.id), c.type) + const progress = (c: CardCampaign) => (c.goal_amount > 0 ? raised(c) / c.goal_amount : 0) + const limit = trendingCount > 0 ? trendingCount : 0 const give = campaigns.filter((c) => c.type === "give") const featured = give.length > 0 ? give.reduce((best, c) => (raised(c) > raised(best) ? c : best)) : (campaigns[0] ?? null) const rest = campaigns.filter((c) => c !== featured) const trending = [...rest] .filter((c) => raised(c) > 0) - .sort((a, b) => progressPercent(raised(b), b.goal_amount) - progressPercent(raised(a), a.goal_amount)) - .slice(0, trendingCount) + .sort((a, b) => progress(b) - progress(a) || raised(b) - raised(a)) + .slice(0, limit) const newest = rest.filter((c) => !trending.includes(c)) return { featured, trending, newest } } diff --git a/apps/web/src/lib/reward-tiers.test.ts b/apps/web/src/lib/reward-tiers.test.ts index f7abcfe6..c47c88e3 100644 --- a/apps/web/src/lib/reward-tiers.test.ts +++ b/apps/web/src/lib/reward-tiers.test.ts @@ -7,6 +7,7 @@ import { canEditTiers, canRetireTier, deliveryMonthInput, + listCampaignTiers, minAmountLabel, moveTier, pledgeHref, @@ -86,9 +87,11 @@ describe("editor rules", () => { }) describe("tier display", () => { - it("labels slots left, sold out and unlimited", () => { + it("labels slots left, sold out (clamping negative remainingSlots to 0) and unlimited", () => { expect(quantityLabel(tier({ quantity_limit: 10, quantity_claimed: 7 }))).toBe("Còn 3/10 suất") expect(quantityLabel(tier({ quantity_limit: 10, quantity_claimed: 10 }))).toBe("Hết suất") + expect(remainingSlots(tier({ quantity_limit: 10, quantity_claimed: 12 }))).toBe(0) + expect(quantityLabel(tier({ quantity_limit: 10, quantity_claimed: 12 }))).toBe("Hết suất") expect(quantityLabel(tier())).toBe("Không giới hạn số suất") expect(remainingSlots(tier())).toBeNull() }) @@ -98,11 +101,46 @@ describe("tier display", () => { expect(deliveryMonthInput(null)).toBe("") }) - it("formats the minimum and links the pledge flow with the tier", () => { + it("formats the minimum and URL-encodes both slug and tierId in pledgeHref", () => { expect(minAmountLabel(200_000)).toMatch(/^Từ 200\.000/) expect(pledgeHref("ao-thun-abcde", "a0000000-0000-4000-8000-000000000001")).toBe( "/campaigns/ao-thun-abcde/pledge?tier=a0000000-0000-4000-8000-000000000001" ) + expect(pledgeHref("du-an/co dau?x=1", "tier id+1")).toBe( + `/campaigns/${encodeURIComponent("du-an/co dau?x=1")}/pledge?tier=${encodeURIComponent("tier id+1")}` + ) + }) +}) + +describe("listCampaignTiers", () => { + it("reads every tier (including retired) of one campaign from reward_tiers in sort_order, id order", async () => { + const calls: Call[] = [] + const rows = [ + tier({ id: "t1", sort_order: 1, status: "active" }), + tier({ id: "t2", sort_order: 2, status: "retired", retired_at: "2026-11-05T00:00:00Z" }), + ] + const db = fakeDb(() => ({ data: rows }), calls) + + expect(await listCampaignTiers(db as never, CAMPAIGN)).toEqual(rows) + expect(calls).toHaveLength(1) + expect(calls[0].target).toBe("reward_tiers") + expect(op(calls[0], "eq")).toEqual(["campaign_id", CAMPAIGN]) + const selected = String(op(calls[0], "select")?.[0] ?? "") + expect(selected).not.toContain("*") + expect(selected).toContain("status") + expect(selected).toContain("retired_at") + expect(calls[0].ops.filter(([n]) => n === "order").map(([, c]) => c)).toEqual(["sort_order", "id"]) + }) + + it("returns an empty array when data is null and rethrows database errors", async () => { + const emptyDb = fakeDb(() => ({ data: null })) + expect(await listCampaignTiers(emptyDb as never, CAMPAIGN)).toEqual([]) + + const failingDb = fakeDb(() => ({ error: { code: "42501", message: "permission denied" } })) + await expect(listCampaignTiers(failingDb as never, CAMPAIGN)).rejects.toEqual({ + code: "42501", + message: "permission denied", + }) }) }) diff --git a/apps/web/src/lib/reward-tiers.ts b/apps/web/src/lib/reward-tiers.ts index 27df42e2..d50402ed 100644 --- a/apps/web/src/lib/reward-tiers.ts +++ b/apps/web/src/lib/reward-tiers.ts @@ -96,7 +96,7 @@ export function moveTier(ids: readonly string[], id: string, direction: "up" | " /** Slots left, or null for an unlimited tier. */ export function remainingSlots(tier: Pick): number | null { - return tier.quantity_limit === null ? null : Math.max(tier.quantity_limit - tier.quantity_claimed, 0) + return tier.quantity_limit === null ? null : Math.max(0, tier.quantity_limit - tier.quantity_claimed) } /** "Còn 3/10 suất", "Hết suất" or "Không giới hạn số suất". */ @@ -118,7 +118,7 @@ export function minAmountLabel(amount: number): string { /** The pledge flow (DOS/Give#31) with this tier chosen. */ export function pledgeHref(slug: string, tierId: string): string { - return `/campaigns/${slug}/pledge?tier=${encodeURIComponent(tierId)}` + return `/campaigns/${encodeURIComponent(slug)}/pledge?tier=${encodeURIComponent(tierId)}` } // --------------------------------------------------------------------------- From 402e8b3e822d414de3792d14f20f4326c7108b19 Mon Sep 17 00:00:00 2001 From: JOY <5027251+JOY@users.noreply.github.com> Date: Thu, 19 Nov 2026 07:27:03 +0700 Subject: [PATCH 03/23] fix(campaigns): prevent replaced-cover exposure, guard cleanup, and fix organizer/activate revalidations (#258) (#267) * fix(campaigns): prevent replaced-cover exposure, guard cleanup, and fix organizer/activate revalidations (#258) - Require coverResponse to match the active campaigns.cover_media_fk cover_media_id, add X-Content-Type-Options: nosniff on cover responses and X-Robots-Tag: noindex, noimageindex on private covers, and lazily open dbService only after viewer access succeeds. - Re-read active cover_media_id after uploadCover commits and best-effort delete all superseded image rows/objects inside try/catch; guard deleteDraft post-commit Storage cleanup in try/catch; normalize blank cancelCampaign reasons to null, use cancellation-specific error messages, and revalidate /admin on submitForReview and cancelCampaign. - Recover from concurrent initial saveOrganizer 23505 races via update by user_id and revalidate /, /campaigns, /campaigns/[slug], /me/campaigns/[id], /admin, and /admin/reports; revalidate /campaigns/[slug]/pledge in reward-actions and /me/pledges/[code] in fulfillment actions. - Validate non-negative integer output and catch thrown RPC errors in GET /api/cron/activate, revalidate downstream routes when activated > 0, and add route/unit tests for activate cron, public/private cover routes, coverResponse, and reencodeCover. * fix(campaigns): use optimistic CAS for cover swaps and revalidate account routes (#258) - Replace the post-update cover_media_id re-read and neq("id", activeCoverId) sweep in uploadCover with optimistic compare-and-swap against prevCoverId (retrying up to 3 attempts on concurrent cover updates) and delete only the atomically replaced prevCoverId row + Storage object so ON DELETE SET NULL and in-flight sibling uploads are never clobbered. - Revalidate /me/accounts, /admin/accounts, and /admin/account-swaps in saveOrganizer when organizer identity/verification state changes. --- .../src/app/api/cron/activate/route.test.ts | 134 ++++++++++++ apps/web/src/app/api/cron/activate/route.ts | 25 ++- .../[id]/fulfillment/actions.test.ts | 12 +- .../me/campaigns/[id]/fulfillment/actions.ts | 1 + apps/web/src/app/me/campaigns/actions.test.ts | 203 ++++++++++++++++-- apps/web/src/app/me/campaigns/actions.ts | 135 +++++++++--- .../app/me/campaigns/reward-actions.test.ts | 32 ++- .../src/app/me/campaigns/reward-actions.ts | 1 + .../app/media/private/[...path]/route.test.ts | 103 +++++++++ .../src/app/media/private/[...path]/route.ts | 2 +- .../app/media/public/[...path]/route.test.ts | 94 ++++++++ .../src/app/media/public/[...path]/route.ts | 2 +- apps/web/src/app/start/actions.test.ts | 69 +++++- apps/web/src/app/start/actions.ts | 14 +- apps/web/src/lib/cover-route.test.ts | 80 ++++++- apps/web/src/lib/cover-route.ts | 46 ++-- apps/web/src/lib/media.test.ts | 59 ++++- apps/web/src/lib/media.ts | 1 + 18 files changed, 912 insertions(+), 101 deletions(-) create mode 100644 apps/web/src/app/api/cron/activate/route.test.ts create mode 100644 apps/web/src/app/media/private/[...path]/route.test.ts create mode 100644 apps/web/src/app/media/public/[...path]/route.test.ts diff --git a/apps/web/src/app/api/cron/activate/route.test.ts b/apps/web/src/app/api/cron/activate/route.test.ts new file mode 100644 index 00000000..4dc0e31d --- /dev/null +++ b/apps/web/src/app/api/cron/activate/route.test.ts @@ -0,0 +1,134 @@ +import { revalidatePath } from "next/cache" +import { NextRequest } from "next/server" +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" + +import { fakeDb, op, type Call, type Handler } from "@/test/fake-db" + +const SECRET = "0123456789abcdef0123" + +const state = vi.hoisted(() => ({ + handler: (() => undefined) as Handler, + calls: [] as Call[], +})) + +vi.mock("next/cache", () => ({ revalidatePath: vi.fn() })) +vi.mock("@/lib/supabase", () => ({ + dbService: () => fakeDb((call) => state.handler(call), state.calls), +})) + +const { GET } = await import("./route") + +function request(authorization?: string) { + const headers: Record = {} + if (authorization !== undefined) headers.authorization = authorization + return new NextRequest("http://localhost/api/cron/activate", { headers }) +} + +beforeEach(() => { + vi.stubEnv("CRON_SECRET", SECRET) + state.handler = () => undefined + state.calls.length = 0 + vi.mocked(revalidatePath).mockClear() +}) + +afterEach(() => { + vi.unstubAllEnvs() +}) + +describe("GET /api/cron/activate", () => { + it.each([ + ["no header", undefined], + ["a wrong secret", `Bearer ${SECRET}x`], + ["the secret without Bearer", SECRET], + ])("refuses %s without touching the database or revalidating", async (_name, authorization) => { + const response = await GET(request(authorization)) + expect(response.status).toBe(401) + expect(await response.json()).toEqual({ error: "unauthorized" }) + expect(state.calls).toHaveLength(0) + expect(revalidatePath).not.toHaveBeenCalled() + }) + + it("refuses every request when CRON_SECRET is missing or too short", async () => { + vi.stubEnv("CRON_SECRET", "") + expect((await GET(request("Bearer "))).status).toBe(401) + + vi.stubEnv("CRON_SECRET", "short") + expect((await GET(request("Bearer short"))).status).toBe(401) + expect(state.calls).toHaveLength(0) + expect(revalidatePath).not.toHaveBeenCalled() + }) + + it("activates due campaigns, revalidates downstream routes when activated > 0, and skips revalidation on 0", async () => { + const campaigns = [ + { id: "a", status: "approved", due: true }, + { id: "b", status: "approved", due: true }, + { id: "c", status: "approved", due: false }, + ] + state.handler = (call) => { + if (call.target !== "rpc:activate_scheduled_campaigns") return undefined + const due = campaigns.filter((c) => c.status === "approved" && c.due) + for (const c of due) c.status = "live" + return { data: due.length } + } + + const first = await GET(request(`Bearer ${SECRET}`)) + expect(first.status).toBe(200) + expect(await first.json()).toEqual({ activated: 2 }) + expect(vi.mocked(revalidatePath).mock.calls).toEqual([ + ["/"], + ["/campaigns"], + ["/campaigns/[slug]", "page"], + ["/me/campaigns"], + ["/me/campaigns/[id]", "page"], + ["/admin"], + ]) + + vi.mocked(revalidatePath).mockClear() + const second = await GET(request(`Bearer ${SECRET}`)) + expect(second.status).toBe(200) + expect(await second.json()).toEqual({ activated: 0 }) + expect(revalidatePath).not.toHaveBeenCalled() + expect(state.calls.map((c) => c.target)).toEqual([ + "rpc:activate_scheduled_campaigns", + "rpc:activate_scheduled_campaigns", + ]) + expect(op(state.calls[0], "args")).toEqual([undefined]) + }) + + it.each([[null], [undefined], ["2"], [-1], [1.5], [Number.NaN], [{}], [[]]])( + "answers 500 without revalidating on an unexpected RPC result %j", + async (data) => { + const spy = vi.spyOn(console, "error").mockImplementation(() => {}) + state.handler = () => ({ data }) + try { + const response = await GET(request(`Bearer ${SECRET}`)) + expect(response.status).toBe(500) + expect(await response.json()).toEqual({ error: "activation_failed" }) + expect(revalidatePath).not.toHaveBeenCalled() + } finally { + spy.mockRestore() + } + } + ) + + it("answers 500 without details when the RPC returns an error or throws", async () => { + const spy = vi.spyOn(console, "error").mockImplementation(() => {}) + try { + state.handler = () => ({ error: { code: "57014", message: "statement timeout" } }) + const erred = await GET(request(`Bearer ${SECRET}`)) + expect(erred.status).toBe(500) + expect(await erred.json()).toEqual({ error: "activation_failed" }) + expect(revalidatePath).not.toHaveBeenCalled() + + state.handler = () => { + throw new Error("connection reset") + } + const thrown = await GET(request(`Bearer ${SECRET}`)) + expect(thrown.status).toBe(500) + expect(await thrown.json()).toEqual({ error: "activation_failed" }) + expect(revalidatePath).not.toHaveBeenCalled() + } finally { + spy.mockRestore() + } + }) +}) diff --git a/apps/web/src/app/api/cron/activate/route.ts b/apps/web/src/app/api/cron/activate/route.ts index 2f6179e2..e0d00bc5 100644 --- a/apps/web/src/app/api/cron/activate/route.ts +++ b/apps/web/src/app/api/cron/activate/route.ts @@ -1,3 +1,4 @@ +import { revalidatePath } from "next/cache" import { NextResponse, type NextRequest } from "next/server" import { isAuthorizedCron } from "@/lib/cron" @@ -14,10 +15,30 @@ export async function GET(request: NextRequest) { if (!isAuthorizedCron(request.headers.get("authorization"), process.env.CRON_SECRET)) { return NextResponse.json({ error: "unauthorized" }, { status: 401 }) } - const { data, error } = await dbService().rpc("activate_scheduled_campaigns") + + let data: unknown + let error: { code?: string; message?: string } | null + try { + ;({ data, error } = await dbService().rpc("activate_scheduled_campaigns")) + } catch (thrown) { + console.error("activate_scheduled_campaigns threw", thrown) + return NextResponse.json({ error: "activation_failed" }, { status: 500 }) + } if (error) { console.error("activate_scheduled_campaigns failed", error.code, error.message) return NextResponse.json({ error: "activation_failed" }, { status: 500 }) } - return NextResponse.json({ activated: data as number }) + if (typeof data !== "number" || !Number.isInteger(data) || data < 0) { + console.error("activate_scheduled_campaigns answered unexpectedly") + return NextResponse.json({ error: "activation_failed" }, { status: 500 }) + } + if (data > 0) { + revalidatePath("/") + revalidatePath("/campaigns") + revalidatePath("/campaigns/[slug]", "page") + revalidatePath("/me/campaigns") + revalidatePath("/me/campaigns/[id]", "page") + revalidatePath("/admin") + } + return NextResponse.json({ activated: data }) } diff --git a/apps/web/src/app/me/campaigns/[id]/fulfillment/actions.test.ts b/apps/web/src/app/me/campaigns/[id]/fulfillment/actions.test.ts index d5c47c6f..525e0470 100644 --- a/apps/web/src/app/me/campaigns/[id]/fulfillment/actions.test.ts +++ b/apps/web/src/app/me/campaigns/[id]/fulfillment/actions.test.ts @@ -1,3 +1,4 @@ +import { revalidatePath } from "next/cache" import { beforeEach, describe, expect, it, vi } from "vitest" import { fakeDb, op, type Call, type Handler } from "@/test/fake-db" @@ -7,6 +8,11 @@ const OTHER = "99999999-9999-4999-8999-999999999999" const CAMPAIGN = "22222222-2222-4222-8222-222222222222" const P1 = "c0000000-0000-4000-8000-000000000001" const P2 = "c0000000-0000-4000-8000-000000000002" +const FULFILLMENT_REVALIDATIONS = [ + [`/me/campaigns/${CAMPAIGN}/fulfillment`], + ["/me/contributions"], + ["/me/pledges/[code]", "page"], +] const state = vi.hoisted(() => ({ userHandler: (() => undefined) as Handler, @@ -42,10 +48,11 @@ beforeEach(() => { state.serviceCalls.length = 0 state.userHandler = campaign() state.serviceHandler = () => ({ data: 2 }) + vi.mocked(revalidatePath).mockClear() }) describe("setFulfillment", () => { - it("updates the ticked pledges with the bulk status and note", async () => { + it("updates the ticked pledges with the bulk status and note and revalidates backer pledge pages", async () => { const result = await setFulfillment( CAMPAIGN, null, @@ -68,6 +75,7 @@ describe("setFulfillment", () => { p_note: "Đã gửi GHN ngày 10/03", }, ]) + expect(vi.mocked(revalidatePath).mock.calls).toEqual(FULFILLMENT_REVALIDATIONS) }) it("updates one pledge from its own row, ignoring the ticks and the bulk fields", async () => { @@ -89,6 +97,7 @@ describe("setFulfillment", () => { p_status: "delivered", p_note: null, }) + expect(vi.mocked(revalidatePath).mock.calls).toEqual(FULFILLMENT_REVALIDATIONS) }) it("refuses nothing ticked, a bad status, a long note and a forged id", async () => { @@ -190,5 +199,6 @@ describe("setFulfillment", () => { ) )?.message ).toContain("không còn ở trạng thái đã thanh toán") + expect(revalidatePath).not.toHaveBeenCalled() }) }) diff --git a/apps/web/src/app/me/campaigns/[id]/fulfillment/actions.ts b/apps/web/src/app/me/campaigns/[id]/fulfillment/actions.ts index 22d385de..fd5a2ea3 100644 --- a/apps/web/src/app/me/campaigns/[id]/fulfillment/actions.ts +++ b/apps/web/src/app/me/campaigns/[id]/fulfillment/actions.ts @@ -66,6 +66,7 @@ export async function setFulfillment(campaignId: string, _state: ActionResult, f revalidatePath(`/me/campaigns/${campaign.id}/fulfillment`) revalidatePath("/me/contributions") + revalidatePath("/me/pledges/[code]", "page") const n = typeof data === "number" ? data : ids.length return done(`Đã cập nhật ${n} lượt ủng hộ: ${FULFILLMENT_LABELS[status]}.`) } diff --git a/apps/web/src/app/me/campaigns/actions.test.ts b/apps/web/src/app/me/campaigns/actions.test.ts index 7bacc279..68afdb73 100644 --- a/apps/web/src/app/me/campaigns/actions.test.ts +++ b/apps/web/src/app/me/campaigns/actions.test.ts @@ -225,13 +225,19 @@ describe("submitForReview", () => { expect(transitioned()).toBe(false) }) - it("submits a give campaign with a usable bound account", async () => { + it("submits a give campaign with a usable bound account and revalidates /admin", async () => { state.userHandler = reads() expect(await submitForReview(CAMPAIGN, null, new FormData())).toEqual({ ok: true, message: "Đã gửi duyệt. Kiểm duyệt viên sẽ xem chiến dịch của bạn.", }) expect(transitioned()).toBe(true) + expect(vi.mocked(revalidatePath).mock.calls).toEqual([ + [`/me/campaigns/${CAMPAIGN}`], + ["/me/campaigns"], + ["/campaigns/quy-hoc-bong-abcde"], + ["/admin"], + ]) }) it("resubmits a give campaign sent back for changes under the same check", async () => { @@ -340,6 +346,22 @@ describe("deleteDraft", () => { ).toEqual([`campaigns/${CAMPAIGN}/a.webp`, `campaigns/${CAMPAIGN}/b.webp`]) }) + it("still revalidates and redirects when best-effort Storage cleanup throws after DB delete", async () => { + const spy = vi.spyOn(console, "error").mockImplementation(() => {}) + state.userHandler = (call) => + op(call, "maybeSingle") ? { data: owned() } : op(call, "delete") ? { data: [{ id: CAMPAIGN }] } : undefined + state.serviceHandler = () => { + throw new Error("storage unreachable") + } + try { + await expect(deleteDraft(CAMPAIGN, null, new FormData())).rejects.toThrow("NEXT_REDIRECT /me/campaigns") + expect(vi.mocked(revalidatePath)).toHaveBeenCalledExactlyOnceWith("/me/campaigns") + expect(spy).toHaveBeenCalled() + } finally { + spy.mockRestore() + } + }) + it("leaves storage alone when RLS deleted nothing", async () => { state.userHandler = (call) => (op(call, "maybeSingle") ? { data: owned() } : { data: [] }) expect((await deleteDraft(CAMPAIGN, null, new FormData()))?.ok).toBe(false) @@ -354,6 +376,8 @@ describe("deleteDraft", () => { }) describe("uploadCover", () => { + const NEWER_COVER = "77777777-7777-4777-8777-777777777777" + async function photoWithGps(): Promise { const jpeg = await sharp({ create: { width: 64, height: 32, channels: 3, background: "#e11d48" } }) .jpeg() @@ -369,17 +393,19 @@ describe("uploadCover", () => { return form } - it("re-encodes without metadata, stores it, sets the cover and drops the old one", async () => { + it("re-encodes without metadata, stores it, atomically swaps cover_media_id from prevCoverId, and deletes only prevCoverId", async () => { state.userHandler = (call) => op(call, "maybeSingle") ? { data: owned({ cover_media_id: OLD_COVER }) } : op(call, "update") ? { data: [{ id: CAMPAIGN }] } : undefined - state.serviceHandler = (call) => - call.target === "campaign_media" && op(call, "delete") - ? { data: [{ storage_path: `campaigns/${CAMPAIGN}/old.webp` }] } - : undefined + state.serviceHandler = (call) => { + if (call.target === "campaign_media" && op(call, "delete")) { + return { data: [{ storage_path: `campaigns/${CAMPAIGN}/old.webp` }] } + } + return undefined + } const result = await uploadCover(CAMPAIGN, null, coverForm(await photoWithGps())) expect(result).toEqual({ ok: true, message: "Đã cập nhật ảnh bìa." }) @@ -392,15 +418,147 @@ describe("uploadCover", () => { expect(meta.format).toBe("webp") expect(meta.exif).toBeUndefined() - const [cover] = op( - state.userCalls.find((c) => op(c, "update")), - "update" - ) as [{ cover_media_id: string }] + const updateCall = state.userCalls.find((c) => op(c, "update")) + const [cover] = op(updateCall, "update") as [{ cover_media_id: string }] expect(path).toContain(cover.cover_media_id) + expect(updateCall?.ops).toContainEqual(["eq", "id", CAMPAIGN]) + expect(updateCall?.ops).toContainEqual(["eq", "cover_media_id", OLD_COVER]) + expect(updateCall?.ops).toContainEqual(["select", "id"]) + + const deleteCalls = state.serviceCalls.filter((c) => c.target === "campaign_media" && op(c, "delete")) + expect(deleteCalls).toHaveLength(1) + expect(deleteCalls[0].ops).toContainEqual(["eq", "id", OLD_COVER]) + expect(deleteCalls[0].ops).toContainEqual(["eq", "campaign_id", CAMPAIGN]) + expect(deleteCalls[0].ops.some(([name]) => name === "neq")).toBe(false) + const removed = state.serviceCalls.filter((c) => op(c, "remove")).map((c) => op(c, "remove")?.[0]) expect(removed).toEqual([[`campaigns/${CAMPAIGN}/old.webp`]]) }) + it("uses is(cover_media_id, null) on initial cover upload and skips post-commit media deletion", async () => { + state.userHandler = (call) => + op(call, "maybeSingle") + ? { data: owned({ cover_media_id: null }) } + : op(call, "update") + ? { data: [{ id: CAMPAIGN }] } + : undefined + + expect(await uploadCover(CAMPAIGN, null, coverForm(await photoWithGps()))).toEqual({ + ok: true, + message: "Đã cập nhật ảnh bìa.", + }) + + const updateCall = state.userCalls.find((c) => op(c, "update")) + expect(updateCall?.ops).toContainEqual(["eq", "id", CAMPAIGN]) + expect(updateCall?.ops).toContainEqual(["is", "cover_media_id", null]) + expect(state.serviceCalls.some((c) => c.target === "campaign_media" && op(c, "delete"))).toBe(false) + expect(state.serviceCalls.some((c) => op(c, "remove"))).toBe(false) + }) + + it("retries optimistic CAS when cover_media_id changed concurrently during upload and deletes only the swapped-out cover", async () => { + let reads = 0 + let updates = 0 + state.userHandler = (call) => { + if (op(call, "maybeSingle")) { + reads += 1 + // Initial read sees null; reload after CAS miss sees NEWER_COVER committed concurrently. + return { data: owned({ cover_media_id: reads === 1 ? null : NEWER_COVER }) } + } + if (op(call, "update")) { + updates += 1 + return { data: updates === 1 ? [] : [{ id: CAMPAIGN }] } + } + return undefined + } + state.serviceHandler = (call) => { + if (call.target === "campaign_media" && op(call, "delete")) { + return { data: [{ storage_path: `campaigns/${CAMPAIGN}/${NEWER_COVER}.webp` }] } + } + return undefined + } + + expect(await uploadCover(CAMPAIGN, null, coverForm(await photoWithGps()))).toEqual({ + ok: true, + message: "Đã cập nhật ảnh bìa.", + }) + + const updateCalls = state.userCalls.filter((c) => op(c, "update")) + expect(updateCalls).toHaveLength(2) + expect(updateCalls[0].ops).toContainEqual(["is", "cover_media_id", null]) + expect(updateCalls[1].ops).toContainEqual(["eq", "cover_media_id", NEWER_COVER]) + + const deleteCalls = state.serviceCalls.filter((c) => c.target === "campaign_media" && op(c, "delete")) + expect(deleteCalls).toHaveLength(1) + expect(deleteCalls[0].ops).toContainEqual(["eq", "id", NEWER_COVER]) + expect(deleteCalls[0].ops).toContainEqual(["eq", "campaign_id", CAMPAIGN]) + const removed = state.serviceCalls.filter((c) => op(c, "remove")).map((c) => op(c, "remove")?.[0]) + expect(removed).toEqual([[`campaigns/${CAMPAIGN}/${NEWER_COVER}.webp`]]) + }) + + it("rolls back the newly uploaded cover without deleting existing covers if the campaign becomes non-editable during CAS retry", async () => { + let reads = 0 + state.userHandler = (call) => { + if (op(call, "maybeSingle")) { + reads += 1 + return { + data: + reads === 1 + ? owned({ cover_media_id: OLD_COVER }) + : owned({ status: "in_review", cover_media_id: NEWER_COVER }), + } + } + if (op(call, "update")) return { data: [] } + return undefined + } + + expect(await uploadCover(CAMPAIGN, null, coverForm(await photoWithGps()))).toEqual({ + ok: false, + message: "Chỉ sửa được chiến dịch đang là bản nháp hoặc cần chỉnh sửa.", + }) + + const [insertedRow] = op( + state.serviceCalls.find((c) => c.target === "campaign_media" && op(c, "insert")), + "insert" + ) as [{ id: string; storage_path: string }] + const deleteCalls = state.serviceCalls.filter((c) => c.target === "campaign_media" && op(c, "delete")) + expect(deleteCalls).toHaveLength(1) + expect(deleteCalls[0].ops).toEqual([["delete"], ["eq", "id", insertedRow.id]]) + const removed = state.serviceCalls.filter((c) => op(c, "remove")).map((c) => op(c, "remove")?.[0]) + expect(removed).toEqual([[insertedRow.storage_path]]) + }) + + it("succeeds and revalidates even when post-commit Storage cleanup throws", async () => { + const spy = vi.spyOn(console, "error").mockImplementation(() => {}) + state.userHandler = (call) => + op(call, "maybeSingle") + ? { data: owned({ cover_media_id: OLD_COVER }) } + : op(call, "update") + ? { data: [{ id: CAMPAIGN }] } + : undefined + state.serviceHandler = (call) => { + if (call.target === "campaign_media" && op(call, "delete")) { + return { data: [{ storage_path: `campaigns/${CAMPAIGN}/old.webp` }] } + } + if (op(call, "remove")) throw new Error("storage timeout") + return undefined + } + + try { + expect(await uploadCover(CAMPAIGN, null, coverForm(await photoWithGps()))).toEqual({ + ok: true, + message: "Đã cập nhật ảnh bìa.", + }) + expect(vi.mocked(revalidatePath).mock.calls).toEqual([ + [`/me/campaigns/${CAMPAIGN}`], + ["/me/campaigns"], + ["/campaigns/quy-hoc-bong-abcde"], + ]) + expect(spy).toHaveBeenCalled() + } finally { + spy.mockRestore() + } + }) + it("rolls back the object and media row when RLS refuses the cover update", async () => { state.userHandler = (call) => op(call, "maybeSingle") ? { data: owned() } : op(call, "update") ? { data: [] } : undefined @@ -534,7 +692,7 @@ describe("cancelCampaign", () => { return form } - it("trims and caps reason at 500 chars, forwards p_to_status 'cancelled', and revalidates", async () => { + it("trims and caps reason at 500 chars, forwards p_to_status 'cancelled', and revalidates including /admin", async () => { state.userHandler = (call) => (op(call, "maybeSingle") ? { data: owned({ status: "in_review" }) } : undefined) const longReason = ` ${"L".repeat(525)} ` const result = await cancelCampaign(CAMPAIGN, null, cancelForm(longReason)) @@ -552,27 +710,31 @@ describe("cancelCampaign", () => { [`/me/campaigns/${CAMPAIGN}`], ["/me/campaigns"], ["/campaigns/quy-hoc-bong-abcde"], + ["/admin"], ]) }) - it("forwards an empty trimmed reason when omitted", async () => { + it.each([undefined, "", " "])("converts blank or omitted reason (%j) to null", async (reason) => { + state.userCalls.length = 0 state.userHandler = (call) => (op(call, "maybeSingle") ? { data: owned() } : undefined) - expect(await cancelCampaign(CAMPAIGN, null, cancelForm())).toEqual({ ok: true, message: "Đã hủy chiến dịch." }) + expect(await cancelCampaign(CAMPAIGN, null, cancelForm(reason))).toEqual({ + ok: true, + message: "Đã hủy chiến dịch.", + }) const rpc = state.userCalls.find((c) => c.target === "rpc:transition_campaign") - expect(op(rpc, "args")).toEqual([{ p_campaign_id: CAMPAIGN, p_to_status: "cancelled", p_reason: "" }]) + expect(op(rpc, "args")).toEqual([{ p_campaign_id: CAMPAIGN, p_to_status: "cancelled", p_reason: null }]) }) - it("maps transition_campaign errors with SUBMIT_MESSAGES and standard GIVE_* messages without revalidating", async () => { + it("maps transition_campaign errors with cancellation-appropriate messages instead of SUBMIT_MESSAGES without revalidating", async () => { state.userHandler = (call) => op(call, "maybeSingle") ? { data: owned({ status: "live" }) } : call.target === "rpc:transition_campaign" ? { error: { code: "23514", message: "GIVE_CAMPAIGN_NO_RECEIVING_ACCOUNT" } } : undefined - expect(await cancelCampaign(CAMPAIGN, null, cancelForm("Đổi kế hoạch"))).toEqual({ - ok: false, - message: SUBMIT_MESSAGES.GIVE_CAMPAIGN_NO_RECEIVING_ACCOUNT, - }) + const noAccount = await cancelCampaign(CAMPAIGN, null, cancelForm("Đổi kế hoạch")) + expect(noAccount?.ok).toBe(false) + expect(noAccount?.message).not.toContain("Chưa gửi duyệt được") expect(vi.mocked(revalidatePath)).not.toHaveBeenCalled() state.userHandler = (call) => @@ -583,7 +745,8 @@ describe("cancelCampaign", () => { : undefined expect(await cancelCampaign(CAMPAIGN, null, cancelForm("Đổi kế hoạch"))).toEqual({ ok: false, - message: "Không thể chuyển chiến dịch sang trạng thái này lúc này.", + message: + "Không hủy được chiến dịch: chiến dịch không còn ở trạng thái cho phép hủy (có thể vừa được mở công khai). Hãy tải lại trang.", }) expect(vi.mocked(revalidatePath)).not.toHaveBeenCalled() }) diff --git a/apps/web/src/app/me/campaigns/actions.ts b/apps/web/src/app/me/campaigns/actions.ts index 99db742e..bf6c258c 100644 --- a/apps/web/src/app/me/campaigns/actions.ts +++ b/apps/web/src/app/me/campaigns/actions.ts @@ -17,6 +17,11 @@ const SIGNED_OUT = "Phiên đăng nhập đã hết. Hãy đăng nhập lại." const NOT_EDITABLE = "Chỉ sửa được chiến dịch đang là bản nháp hoặc cần chỉnh sửa." const NOT_FOUND = "Không tìm thấy chiến dịch của bạn." +const CANCEL_MESSAGES: Record = { + GIVE_TRANSITION_NOT_ALLOWED: + "Không hủy được chiến dịch: chiến dịch không còn ở trạng thái cho phép hủy (có thể vừa được mở công khai). Hãy tải lại trang.", +} + interface OwnedCampaign { id: string slug: string @@ -195,34 +200,90 @@ export async function uploadCover(campaignId: string, _state: ActionResult, form .from("campaign_media") .insert({ id: mediaId, campaign_id: campaign.id, kind: "image", storage_path: path, alt, sort_order: 0 }) if (inserted.error) { - await storage.remove([path]) + try { + await storage.remove([path]) + } catch { + // Best-effort rollback cleanup. + } return fail(dbErrorMessage(inserted.error)) } - const updated = await dbAs(session.accessToken) - .from("campaigns") - .update({ cover_media_id: mediaId }) - .eq("id", campaign.id) - .select("id") - if (updated.error || !updated.data?.length) { - await service.from("campaign_media").delete().eq("id", mediaId) - await storage.remove([path]) - return fail(updated.error ? dbErrorMessage(updated.error) : NOT_EDITABLE) + const rollbackNewCover = async () => { + try { + await service.from("campaign_media").delete().eq("id", mediaId) + } catch { + // Best-effort rollback cleanup. + } + try { + await storage.remove([path]) + } catch { + // Best-effort rollback cleanup. + } } - // Drop the previous cover; it is no longer referenced. - if (campaign.cover_media_id && campaign.cover_media_id !== mediaId) { - const old = await service - .from("campaign_media") - .delete() - .eq("id", campaign.cover_media_id) - .eq("campaign_id", campaign.id) - .select("storage_path") - const oldPath = (old.data?.[0] as { storage_path: string | null } | undefined)?.storage_path - if (oldPath) await storage.remove([oldPath]) + // Optimistic compare-and-swap on cover_media_id so overlapping uploads swap + // atomically and each winner deletes only the exact cover row it replaced + // (never an uncommitted sibling or a newer upload, which ON DELETE SET NULL + // would clobber). + let current = campaign + let prevCoverId = current.cover_media_id + let swapped = false + let contended = false + + for (let attempt = 0; attempt < 3; attempt++) { + const query = dbAs(session.accessToken).from("campaigns").update({ cover_media_id: mediaId }).eq("id", current.id) + const updated = await ( + prevCoverId === null ? query.is("cover_media_id", null) : query.eq("cover_media_id", prevCoverId) + ).select("id") + + if (updated.error) { + await rollbackNewCover() + return fail(dbErrorMessage(updated.error)) + } + if (updated.data?.length) { + swapped = true + break + } + if (attempt === 2) break + + const reloaded = await ownedCampaign(session, current.id) + if (!reloaded.campaign) { + await rollbackNewCover() + return fail(reloaded.error) + } + if (!isEditableStatus(reloaded.campaign.status)) { + await rollbackNewCover() + return fail(NOT_EDITABLE) + } + if (reloaded.campaign.cover_media_id === prevCoverId) break + contended = true + current = reloaded.campaign + prevCoverId = current.cover_media_id } - refresh(campaign) + if (!swapped) { + await rollbackNewCover() + return fail(contended ? "Không cập nhật được ảnh bìa do có thay đổi đồng thời. Hãy thử lại." : NOT_EDITABLE) + } + + if (prevCoverId !== null) { + try { + const stale = await service + .from("campaign_media") + .delete() + .eq("id", prevCoverId) + .eq("campaign_id", current.id) + .select("storage_path") + const stalePaths = ((stale.data ?? []) as { storage_path: string | null }[]) + .map((row) => row.storage_path) + .filter((p): p is string => Boolean(p)) + if (stalePaths.length > 0) await storage.remove(stalePaths) + } catch (error) { + console.error("uploadCover cleanup failed", error) + } + } + + refresh(current) return done("Đã cập nhật ảnh bìa.") } @@ -230,14 +291,15 @@ async function transition( session: Session, campaign: OwnedCampaign, toStatus: CampaignStatus, - reason?: string | null + reason?: string | null, + messages?: Record ): Promise { const { error } = await dbAs(session.accessToken).rpc("transition_campaign", { p_campaign_id: campaign.id, p_to_status: toStatus, p_reason: reason ?? null, }) - return error ? fail(dbErrorMessage(error, SUBMIT_MESSAGES)) : null + return error ? fail(dbErrorMessage(error, messages)) : null } export async function submitForReview( @@ -264,9 +326,10 @@ export async function submitForReview( return fail(dbErrorMessage(error as { message?: string; code?: string })) } if (problem) return fail(problem) - const failed = await transition(session, campaign, "in_review") + const failed = await transition(session, campaign, "in_review", null, SUBMIT_MESSAGES) if (failed) return failed refresh(campaign) + revalidatePath("/admin") return done("Đã gửi duyệt. Kiểm duyệt viên sẽ xem chiến dịch của bạn.") } @@ -275,12 +338,14 @@ export async function cancelCampaign(campaignId: string, _state: ActionResult, f if (!session) return fail(SIGNED_OUT) const { campaign, error: loadError } = await ownedCampaign(session, campaignId) if (!campaign) return fail(loadError) - const reason = String(form.get("reason") ?? "") - .trim() - .slice(0, 500) - const failed = await transition(session, campaign, "cancelled", reason) + const reason = + String(form.get("reason") ?? "") + .trim() + .slice(0, 500) || null + const failed = await transition(session, campaign, "cancelled", reason, CANCEL_MESSAGES) if (failed) return failed refresh(campaign) + revalidatePath("/admin") return done("Đã hủy chiến dịch.") } @@ -304,11 +369,15 @@ export async function deleteDraft(campaignId: string, _state: ActionResult, _for // RLS allowed the delete, so the caller owned everything under the // campaign's prefix; removing by prefix also catches covers uploaded // concurrently. Best effort: the draft is already gone. - const storage = dbService().storage.from(MEDIA_BUCKET) - const prefix = campaignMediaPrefix(campaign.id) - const listed = await storage.list(prefix, { limit: 1000 }) - const paths = (listed.data ?? []).map((object) => `${prefix}/${object.name}`) - if (paths.length) await storage.remove(paths) + try { + const storage = dbService().storage.from(MEDIA_BUCKET) + const prefix = campaignMediaPrefix(campaign.id) + const listed = await storage.list(prefix, { limit: 1000 }) + const paths = (listed.data ?? []).map((object) => `${prefix}/${object.name}`) + if (paths.length) await storage.remove(paths) + } catch (error) { + console.error("deleteDraft cleanup failed", error) + } revalidatePath("/me/campaigns") redirect("/me/campaigns") diff --git a/apps/web/src/app/me/campaigns/reward-actions.test.ts b/apps/web/src/app/me/campaigns/reward-actions.test.ts index d2f2dad4..40ae02da 100644 --- a/apps/web/src/app/me/campaigns/reward-actions.test.ts +++ b/apps/web/src/app/me/campaigns/reward-actions.test.ts @@ -1,3 +1,4 @@ +import { revalidatePath } from "next/cache" import { beforeEach, describe, expect, it, vi } from "vitest" import { fakeDb, op, type Call, type Handler } from "@/test/fake-db" @@ -78,16 +79,19 @@ const campaignIn = (status: string, fields: Record = {}) => ({ ...fields, }) +const TIER_REVALIDATIONS = [[`/me/campaigns/${CAMPAIGN}`], ["/campaigns/ao-abcde"], ["/campaigns/ao-abcde/pledge"]] + beforeEach(() => { state.userCalls.length = 0 state.serviceCalls.length = 0 state.signedIn = true state.userHandler = reads() state.serviceHandler = () => ({ data: T1 }) + vi.mocked(revalidatePath).mockClear() }) describe("saveRewardTier", () => { - it("creates a tier on a draft, last in order, with the actor id and parsed fields", async () => { + it("creates a tier on a draft, last in order, with the actor id, parsed fields and pledge revalidation", async () => { const result = await saveRewardTier(CAMPAIGN, null, null, tierForm()) expect(result).toEqual({ ok: true, message: "Đã thêm phần thưởng." }) expect(state.serviceCalls.map((c) => c.target)).toEqual(["rpc:save_reward_tier"]) @@ -108,6 +112,7 @@ describe("saveRewardTier", () => { ]) // Ownership was read with the user's token first. expect(state.userCalls.map((c) => c.target).sort()).toEqual(["reward_tiers", "rpc:managed_campaigns"]) + expect(vi.mocked(revalidatePath).mock.calls).toEqual(TIER_REVALIDATIONS) }) it("updates a tier of a campaign under changes, dropping the shipping note when nothing ships", async () => { @@ -169,9 +174,10 @@ describe("saveRewardTier", () => { }) describe("deleteRewardTier", () => { - it("deletes a tier of a draft", async () => { + it("deletes a tier of a draft and revalidates campaign and pledge routes", async () => { expect((await deleteRewardTier(CAMPAIGN, T1, null, new FormData()))?.ok).toBe(true) expect(op(state.serviceCalls[0], "args")).toEqual([{ p_actor_id: USER, p_tier_id: T1 }]) + expect(vi.mocked(revalidatePath).mock.calls).toEqual(TIER_REVALIDATIONS) }) it("refuses after submission and for a tier someone chose", async () => { @@ -181,15 +187,17 @@ describe("deleteRewardTier", () => { state.userHandler = reads() state.serviceHandler = () => ({ error: { message: "GIVE_REWARD_TIER_IN_USE" } }) expect((await deleteRewardTier(CAMPAIGN, T1, null, new FormData()))?.message).toContain("không xóa được") + expect(revalidatePath).not.toHaveBeenCalled() }) }) describe("moveRewardTier", () => { - it("sends the whole new order", async () => { + it("sends the whole new order and revalidates campaign and pledge routes", async () => { expect((await moveRewardTier(CAMPAIGN, T3, "up", null, new FormData()))?.ok).toBe(true) expect(op(state.serviceCalls[0], "args")).toEqual([ { p_actor_id: USER, p_campaign_id: CAMPAIGN, p_tier_ids: [T1, T3, T2] }, ]) + expect(vi.mocked(revalidatePath).mock.calls).toEqual(TIER_REVALIDATIONS) }) it("orders by sort_order even when rows come back shuffled", async () => { @@ -209,13 +217,17 @@ describe("moveRewardTier", () => { }) describe("retireRewardTier", () => { - it.each(["approved", "live", "suspended"])("retires an unclaimed tier of a %s campaign", async (status) => { - state.userHandler = reads({ campaign: campaignIn(status) }) - state.serviceHandler = () => ({ data: "retired" }) - const result = await retireRewardTier(CAMPAIGN, T1, null, new FormData()) - expect(result?.ok).toBe(true) - expect(op(state.serviceCalls[0], "args")).toEqual([{ p_actor_id: USER, p_tier_id: T1 }]) - }) + it.each(["approved", "live", "suspended"])( + "retires an unclaimed tier of a %s campaign and revalidates pledge route", + async (status) => { + state.userHandler = reads({ campaign: campaignIn(status) }) + state.serviceHandler = () => ({ data: "retired" }) + const result = await retireRewardTier(CAMPAIGN, T1, null, new FormData()) + expect(result?.ok).toBe(true) + expect(op(state.serviceCalls[0], "args")).toEqual([{ p_actor_id: USER, p_tier_id: T1 }]) + expect(vi.mocked(revalidatePath).mock.calls).toEqual(TIER_REVALIDATIONS) + } + ) it("refuses a tier a pledge holds", async () => { state.userHandler = reads({ campaign: campaignIn("live"), tiers: [tier(T1, { quantity_claimed: 2 })] }) diff --git a/apps/web/src/app/me/campaigns/reward-actions.ts b/apps/web/src/app/me/campaigns/reward-actions.ts index b026edae..87ae39a3 100644 --- a/apps/web/src/app/me/campaigns/reward-actions.ts +++ b/apps/web/src/app/me/campaigns/reward-actions.ts @@ -61,6 +61,7 @@ async function ownTiers(accessToken: string, userId: string, campaignId: string) function refresh(campaign: Pick) { revalidatePath(`/me/campaigns/${campaign.id}`) revalidatePath(`/campaigns/${campaign.slug}`) + revalidatePath(`/campaigns/${campaign.slug}/pledge`) } /** Creates a tier (tierId null, placed last) or updates one, while the campaign is editable. */ diff --git a/apps/web/src/app/media/private/[...path]/route.test.ts b/apps/web/src/app/media/private/[...path]/route.test.ts new file mode 100644 index 00000000..4295e7a9 --- /dev/null +++ b/apps/web/src/app/media/private/[...path]/route.test.ts @@ -0,0 +1,103 @@ +import { beforeEach, describe, expect, it, vi } from "vitest" + +import { getSession } from "@/lib/auth/session" +import { PRIVATE_COVER_CACHE } from "@/lib/cover-route" +import { dbAs, dbService } from "@/lib/supabase" +import { fakeDb, op, type Call, type Handler } from "@/test/fake-db" + +const USER = "11111111-1111-4111-8111-111111111111" +const CAMPAIGN = "22222222-2222-4222-8222-222222222222" +const MEDIA_ID = "33333333-3333-4333-8333-333333333333" +const SEGMENTS = ["campaigns", CAMPAIGN, `${MEDIA_ID}.webp`] +const PATH = SEGMENTS.join("/") + +const state = vi.hoisted(() => ({ + userHandler: (() => undefined) as Handler, + serviceHandler: (() => undefined) as Handler, + userCalls: [] as Call[], + serviceCalls: [] as Call[], +})) + +vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() })) +vi.mock("@/lib/supabase", () => ({ + MEDIA_BUCKET: "give-media", + dbAs: vi.fn(() => fakeDb((call) => state.userHandler(call), state.userCalls)), + dbService: vi.fn(() => fakeDb((call) => state.serviceHandler(call), state.serviceCalls)), +})) + +const { GET } = await import("./route") + +beforeEach(() => { + vi.clearAllMocks() + state.userCalls.length = 0 + state.serviceCalls.length = 0 + state.userHandler = () => undefined + state.serviceHandler = (call) => + op(call, "download") ? { data: new Blob([new Uint8Array([4, 5, 6])], { type: "image/webp" }) } : undefined + vi.mocked(getSession).mockResolvedValue({ user: { id: USER, email: null, name: null }, accessToken: "user-jwt" }) +}) + +describe("GET /media/private/[...path]", () => { + it("refuses signed-out requests without opening any database client", async () => { + vi.mocked(getSession).mockResolvedValueOnce(null) + + const response = await GET(new Request(`http://localhost/media/private/${PATH}`), { + params: Promise.resolve({ path: SEGMENTS }), + }) + + expect(response.status).toBe(404) + expect(response.headers.get("Cache-Control")).toBe("no-store") + expect(dbAs).not.toHaveBeenCalled() + expect(dbService).not.toHaveBeenCalled() + }) + + it("queries with the caller's token and serves an active cover with no-store, nosniff and noindex headers", async () => { + state.userHandler = (call) => + call.target === "campaign_media" + ? { data: [{ id: MEDIA_ID, campaign: [{ cover_media_id: MEDIA_ID }] }] } + : undefined + + const response = await GET(new Request(`http://localhost/media/private/${PATH}`), { + params: Promise.resolve({ path: SEGMENTS }), + }) + + expect(response.status).toBe(200) + expect(dbAs).toHaveBeenCalledExactlyOnceWith("user-jwt") + expect(dbService).toHaveBeenCalledTimes(1) + expect(response.headers.get("Content-Type")).toBe("image/webp") + expect(response.headers.get("Cache-Control")).toBe(PRIVATE_COVER_CACHE) + expect(response.headers.get("Content-Security-Policy")).toBe("default-src 'none'") + expect(response.headers.get("X-Content-Type-Options")).toBe("nosniff") + expect(response.headers.get("X-Robots-Tag")).toBe("noindex, noimageindex") + expect(new Uint8Array(await response.arrayBuffer())).toEqual(new Uint8Array([4, 5, 6])) + expect(state.serviceCalls).toEqual([{ target: "storage:give-media", ops: [["download", PATH]] }]) + }) + + it("refuses a replaced draft cover or RLS-hidden campaign without opening the service-role client", async () => { + state.userHandler = () => ({ data: [{ id: MEDIA_ID, campaign: [{ cover_media_id: "newer-cover" }] }] }) + + const response = await GET(new Request(`http://localhost/media/private/${PATH}`), { + params: Promise.resolve({ path: SEGMENTS }), + }) + + expect(response.status).toBe(404) + expect(response.headers.get("Cache-Control")).toBe("no-store") + expect(dbService).not.toHaveBeenCalled() + }) + + it("treats an expired JWT as 404 and malformed paths as 404 without touching Storage", async () => { + state.userHandler = () => ({ error: { code: "PGRST301", message: "JWT expired" } }) + const expired = await GET(new Request(`http://localhost/media/private/${PATH}`), { + params: Promise.resolve({ path: SEGMENTS }), + }) + expect(expired.status).toBe(404) + + state.userCalls.length = 0 + const badPath = await GET(new Request("http://localhost/media/private/bad"), { + params: Promise.resolve({ path: ["bad"] }), + }) + expect(badPath.status).toBe(404) + expect(state.userCalls).toEqual([]) + expect(dbService).not.toHaveBeenCalled() + }) +}) diff --git a/apps/web/src/app/media/private/[...path]/route.ts b/apps/web/src/app/media/private/[...path]/route.ts index e2df6c0f..5cfdf44a 100644 --- a/apps/web/src/app/media/private/[...path]/route.ts +++ b/apps/web/src/app/media/private/[...path]/route.ts @@ -6,5 +6,5 @@ import { dbAs, dbService, MEDIA_BUCKET } from "@/lib/supabase" export async function GET(_request: Request, { params }: { params: Promise<{ path: string[] }> }) { const { path } = await params const session = await getSession() - return coverResponse(path, session ? dbAs(session.accessToken) : null, dbService(), MEDIA_BUCKET, PRIVATE_COVER_CACHE) + return coverResponse(path, session ? dbAs(session.accessToken) : null, dbService, MEDIA_BUCKET, PRIVATE_COVER_CACHE) } diff --git a/apps/web/src/app/media/public/[...path]/route.test.ts b/apps/web/src/app/media/public/[...path]/route.test.ts new file mode 100644 index 00000000..56870bc7 --- /dev/null +++ b/apps/web/src/app/media/public/[...path]/route.test.ts @@ -0,0 +1,94 @@ +import { beforeEach, describe, expect, it, vi } from "vitest" + +import { PUBLIC_COVER_CACHE } from "@/lib/cover-route" +import { dbAs, dbService } from "@/lib/supabase" +import { fakeDb, op, type Call, type Handler } from "@/test/fake-db" + +const CAMPAIGN = "22222222-2222-4222-8222-222222222222" +const MEDIA_ID = "33333333-3333-4333-8333-333333333333" +const SEGMENTS = ["campaigns", CAMPAIGN, `${MEDIA_ID}.webp`] +const PATH = SEGMENTS.join("/") + +const state = vi.hoisted(() => ({ + anonHandler: (() => undefined) as Handler, + serviceHandler: (() => undefined) as Handler, + anonCalls: [] as Call[], + serviceCalls: [] as Call[], +})) + +vi.mock("@/lib/supabase", () => ({ + MEDIA_BUCKET: "give-media", + dbAs: vi.fn(() => fakeDb((call) => state.anonHandler(call), state.anonCalls)), + dbService: vi.fn(() => fakeDb((call) => state.serviceHandler(call), state.serviceCalls)), +})) + +const { GET } = await import("./route") + +beforeEach(() => { + vi.clearAllMocks() + state.anonCalls.length = 0 + state.serviceCalls.length = 0 + state.anonHandler = () => undefined + state.serviceHandler = (call) => + op(call, "download") ? { data: new Blob([new Uint8Array([9, 8, 7])], { type: "image/webp" }) } : undefined +}) + +describe("GET /media/public/[...path]", () => { + it("looks up the active cover as anon and serves it with public cache, CSP, nosniff and no X-Robots-Tag", async () => { + state.anonHandler = (call) => + call.target === "campaign_media" + ? { data: [{ id: MEDIA_ID, campaign: [{ cover_media_id: MEDIA_ID }] }] } + : undefined + + const response = await GET(new Request(`http://localhost/media/public/${PATH}`), { + params: Promise.resolve({ path: SEGMENTS }), + }) + + expect(response.status).toBe(200) + expect(dbAs).toHaveBeenCalledExactlyOnceWith() + expect(dbService).toHaveBeenCalledTimes(1) + expect(response.headers.get("Content-Type")).toBe("image/webp") + expect(response.headers.get("Cache-Control")).toBe(PUBLIC_COVER_CACHE) + expect(response.headers.get("Content-Security-Policy")).toBe("default-src 'none'") + expect(response.headers.get("X-Content-Type-Options")).toBe("nosniff") + expect(response.headers.get("X-Robots-Tag")).toBeNull() + expect(new Uint8Array(await response.arrayBuffer())).toEqual(new Uint8Array([9, 8, 7])) + expect(state.serviceCalls).toEqual([{ target: "storage:give-media", ops: [["download", PATH]] }]) + }) + + it("refuses a replaced draft cover or unpublished campaign without opening the service-role client", async () => { + state.anonHandler = () => ({ data: [{ id: MEDIA_ID, campaign: [{ cover_media_id: "newer-cover" }] }] }) + + const response = await GET(new Request(`http://localhost/media/public/${PATH}`), { + params: Promise.resolve({ path: SEGMENTS }), + }) + + expect(response.status).toBe(404) + expect(response.headers.get("Cache-Control")).toBe("no-store") + expect(dbService).not.toHaveBeenCalled() + expect(state.serviceCalls).toEqual([]) + }) + + it("refuses malformed paths without querying the database or Storage", async () => { + const response = await GET(new Request("http://localhost/media/public/../secret.webp"), { + params: Promise.resolve({ path: ["..", "secret.webp"] }), + }) + + expect(response.status).toBe(404) + expect(response.headers.get("Cache-Control")).toBe("no-store") + expect(state.anonCalls).toEqual([]) + expect(dbService).not.toHaveBeenCalled() + }) + + it("returns 502 when the anon visibility lookup fails", async () => { + state.anonHandler = () => ({ error: { code: "08006", message: "connection failure" } }) + + const response = await GET(new Request(`http://localhost/media/public/${PATH}`), { + params: Promise.resolve({ path: SEGMENTS }), + }) + + expect(response.status).toBe(502) + expect(response.headers.get("Cache-Control")).toBe("no-store") + expect(dbService).not.toHaveBeenCalled() + }) +}) diff --git a/apps/web/src/app/media/public/[...path]/route.ts b/apps/web/src/app/media/public/[...path]/route.ts index c15b13f5..f9b6c4a5 100644 --- a/apps/web/src/app/media/public/[...path]/route.ts +++ b/apps/web/src/app/media/public/[...path]/route.ts @@ -4,5 +4,5 @@ import { dbAs, dbService, MEDIA_BUCKET } from "@/lib/supabase" /** A cover anyone may see: looked up as an anonymous visitor, cacheable. */ export async function GET(_request: Request, { params }: { params: Promise<{ path: string[] }> }) { const { path } = await params - return coverResponse(path, dbAs(), dbService(), MEDIA_BUCKET, PUBLIC_COVER_CACHE) + return coverResponse(path, dbAs(), dbService, MEDIA_BUCKET, PUBLIC_COVER_CACHE) } diff --git a/apps/web/src/app/start/actions.test.ts b/apps/web/src/app/start/actions.test.ts index 50c8b935..c79b4bfb 100644 --- a/apps/web/src/app/start/actions.test.ts +++ b/apps/web/src/app/start/actions.test.ts @@ -68,11 +68,28 @@ function organizer(overrides: Partial = {}): Organizer { } } +const ORGANIZER_REVALIDATIONS = [ + ["/start"], + ["/"], + ["/campaigns"], + ["/campaigns/[slug]", "page"], + ["/me/campaigns/[id]", "page"], + ["/me/accounts"], + ["/admin"], + ["/admin/reports"], + ["/admin/accounts"], + ["/admin/account-swaps"], +] + function noNavigation() { expect(revalidatePath).not.toHaveBeenCalled() expect(redirect).not.toHaveBeenCalled() } +function expectOrganizerRevalidated() { + expect(vi.mocked(revalidatePath).mock.calls).toEqual(ORGANIZER_REVALIDATIONS) +} + beforeEach(() => { vi.clearAllMocks() state.calls.length = 0 @@ -132,7 +149,7 @@ describe("saveOrganizer (DOS/Give#208)", () => { ], ], }) - expect(revalidatePath).toHaveBeenCalledExactlyOnceWith("/start") + expectOrganizerRevalidated() expect(redirect).not.toHaveBeenCalled() }) @@ -141,6 +158,48 @@ describe("saveOrganizer (DOS/Give#208)", () => { expect(op(state.calls[1], "insert")?.[0]).toMatchObject({ phone: null }) }) + it("falls back to updating by user_id when a concurrent initial insert hits 23505", async () => { + state.handler = (call) => { + if (op(call, "maybeSingle")) return { data: null } + if (op(call, "insert")) return { error: { code: "23505", message: "duplicate key value" } } + return undefined + } + expect(await saveOrganizer(null, organizerForm())).toEqual({ ok: true, message: SAVED }) + expect(state.calls).toHaveLength(3) + expect(op(state.calls[1], "insert")).toEqual([ + { + user_id: USER, + kind: "individual", + legal_name: "Nguyễn Thị Lan", + display_name: "Quỹ học bổng", + phone: "0901234567", + }, + ]) + expect(state.calls[2]).toEqual({ + target: "organizers", + ops: [ + [ + "update", + { kind: "individual", legal_name: "Nguyễn Thị Lan", display_name: "Quỹ học bổng", phone: "0901234567" }, + ], + ["eq", "user_id", USER], + ], + }) + expectOrganizerRevalidated() + }) + + it("surfaces the fallback update error without revalidating when 23505 recovery fails", async () => { + const fallbackError = { code: "42501", message: "permission denied" } + state.handler = (call) => { + if (op(call, "maybeSingle")) return { data: null } + if (op(call, "insert")) return { error: { code: "23505", message: "duplicate key value" } } + return { error: fallbackError } + } + expect(await saveOrganizer(null, organizerForm())).toEqual({ ok: false, message: dbErrorMessage(fallbackError) }) + expect(state.calls).toHaveLength(3) + noNavigation() + }) + it("updates only editable columns, scoped to the session user, without inserting or upserting", async () => { state.handler = (call) => (op(call, "maybeSingle") ? { data: organizer() } : undefined) expect(await saveOrganizer(null, organizerForm({ user_id: "someone-else" }))).toEqual({ ok: true, message: SAVED }) @@ -156,7 +215,7 @@ describe("saveOrganizer (DOS/Give#208)", () => { ["eq", "user_id", USER], ], }) - expect(revalidatePath).toHaveBeenCalledExactlyOnceWith("/start") + expectOrganizerRevalidated() expect(redirect).not.toHaveBeenCalled() }) @@ -174,14 +233,14 @@ describe("saveOrganizer (DOS/Give#208)", () => { it.each(identityChanges)("reports re-verification when identity changes: %j", async (change) => { expect(await saveOrganizer(null, organizerForm(change))).toEqual({ ok: true, message: REVERIFY }) expect(op(state.calls[1], "update")?.[0]).toMatchObject(change) - expect(revalidatePath).toHaveBeenCalledExactlyOnceWith("/start") + expectOrganizerRevalidated() }) it.each([{ phone: "0987654321" }, { phone: "090 123.45-67" }])( "keeps the normal success message for phone-only edits or an unchanged normalized profile: %j", async (change) => { expect(await saveOrganizer(null, organizerForm(change))).toEqual({ ok: true, message: SAVED }) - expect(revalidatePath).toHaveBeenCalledExactlyOnceWith("/start") + expectOrganizerRevalidated() } ) }) @@ -190,7 +249,7 @@ describe("saveOrganizer (DOS/Give#208)", () => { it.each(identityChanges)("keeps the normal success message after an identity change: %j", async (change) => { state.handler = (call) => (op(call, "maybeSingle") ? { data: organizer({ verification_status }) } : undefined) expect(await saveOrganizer(null, organizerForm(change))).toEqual({ ok: true, message: SAVED }) - expect(revalidatePath).toHaveBeenCalledExactlyOnceWith("/start") + expectOrganizerRevalidated() }) }) diff --git a/apps/web/src/app/start/actions.ts b/apps/web/src/app/start/actions.ts index 229ba966..a9b8e45d 100644 --- a/apps/web/src/app/start/actions.ts +++ b/apps/web/src/app/start/actions.ts @@ -27,12 +27,24 @@ export async function saveOrganizer(_state: ActionResult, form: FormData): Promi return fail(dbErrorMessage(error as { message?: string })) } // Column grants allow user_id on insert only, so this is not an upsert. - const { error } = existing + let { error } = existing ? await db.from("organizers").update(parsed.data).eq("user_id", session.user.id) : await db.from("organizers").insert({ user_id: session.user.id, ...parsed.data }) + if (!existing && error?.code === "23505") { + ;({ error } = await db.from("organizers").update(parsed.data).eq("user_id", session.user.id)) + } if (error) return fail(dbErrorMessage(error)) revalidatePath("/start") + revalidatePath("/") + revalidatePath("/campaigns") + revalidatePath("/campaigns/[slug]", "page") + revalidatePath("/me/campaigns/[id]", "page") + revalidatePath("/me/accounts") + revalidatePath("/admin") + revalidatePath("/admin/reports") + revalidatePath("/admin/accounts") + revalidatePath("/admin/account-swaps") // Mirrors give.organizers_reset_verification. const reset = (existing?.verification_status === "verified" || existing?.verification_status === "pending") && diff --git a/apps/web/src/lib/cover-route.test.ts b/apps/web/src/lib/cover-route.test.ts index caafcef9..9e400220 100644 --- a/apps/web/src/lib/cover-route.test.ts +++ b/apps/web/src/lib/cover-route.test.ts @@ -4,19 +4,20 @@ import type { Db } from "@/lib/campaigns" import { coverResponse, PRIVATE_COVER_CACHE, PUBLIC_COVER_CACHE } from "@/lib/cover-route" import { fakeDb, op, type Call, type Handler } from "@/test/fake-db" -const SEGMENTS = ["campaigns", "22222222-2222-4222-8222-222222222222", "33333333-3333-4333-8333-333333333333.webp"] +const MEDIA_ID = "33333333-3333-4333-8333-333333333333" +const SEGMENTS = ["campaigns", "22222222-2222-4222-8222-222222222222", `${MEDIA_ID}.webp`] const PATH = SEGMENTS.join("/") let viewerCalls: Call[] let serviceCalls: Call[] -function dbs(viewerHandler: Handler) { +function dbs( + viewerHandler: Handler, + storageHandler: Handler = (call) => + op(call, "download") ? { data: new Blob([new Uint8Array([1, 2, 3])], { type: "image/webp" }) } : undefined +) { const viewer = fakeDb(viewerHandler, viewerCalls) as unknown as Db - const service = fakeDb( - (call) => - op(call, "download") ? { data: new Blob([new Uint8Array([1, 2, 3])], { type: "image/webp" }) } : undefined, - serviceCalls - ) as unknown as Db + const service = fakeDb(storageHandler, serviceCalls) as unknown as Db return { viewer, service } } @@ -26,17 +27,64 @@ beforeEach(() => { }) describe("coverResponse", () => { - it("serves a cover the viewer may see, with the given cache policy", async () => { - const { viewer, service } = dbs((call) => (call.target === "campaign_media" ? { data: [{ id: "m" }] } : undefined)) + it("serves an active public cover with nosniff, CSP and no X-Robots-Tag", async () => { + const { viewer, service } = dbs((call) => + call.target === "campaign_media" + ? { data: [{ id: MEDIA_ID, campaign: [{ cover_media_id: MEDIA_ID }] }] } + : undefined + ) const response = await coverResponse(SEGMENTS, viewer, service, "give-media", PUBLIC_COVER_CACHE) expect(response.status).toBe(200) expect(response.headers.get("Content-Type")).toBe("image/webp") expect(response.headers.get("Cache-Control")).toBe(PUBLIC_COVER_CACHE) + expect(response.headers.get("Content-Security-Policy")).toBe("default-src 'none'") + expect(response.headers.get("X-Content-Type-Options")).toBe("nosniff") + expect(response.headers.get("X-Robots-Tag")).toBeNull() expect(new Uint8Array(await response.arrayBuffer())).toEqual(new Uint8Array([1, 2, 3])) - expect(op(viewerCalls[0], "eq")).toEqual(["storage_path", PATH]) + expect(String(op(viewerCalls[0], "select")?.[0])).toContain( + "campaign:campaigns!campaigns_cover_media_fk!inner(cover_media_id)" + ) + expect(viewerCalls[0].ops).toContainEqual(["eq", "storage_path", PATH]) + expect(viewerCalls[0].ops).toContainEqual(["eq", "kind", "image"]) expect(serviceCalls).toEqual([{ target: "storage:give-media", ops: [["download", PATH]] }]) }) + it("adds X-Robots-Tag: noindex, noimageindex and accepts an object embed on private covers", async () => { + const { viewer, service } = dbs((call) => + call.target === "campaign_media" + ? { data: [{ id: MEDIA_ID, campaign: { cover_media_id: MEDIA_ID } }] } + : undefined + ) + const response = await coverResponse(SEGMENTS, viewer, () => service, "give-media", PRIVATE_COVER_CACHE) + expect(response.status).toBe(200) + expect(response.headers.get("Cache-Control")).toBe(PRIVATE_COVER_CACHE) + expect(response.headers.get("X-Content-Type-Options")).toBe("nosniff") + expect(response.headers.get("X-Robots-Tag")).toBe("noindex, noimageindex") + }) + + it.each([ + ["filtered out by the inner join", []], + ["campaign points to a newer cover", [{ id: MEDIA_ID, campaign: [{ cover_media_id: "other-cover" }] }]], + ["campaign has no active cover", [{ id: MEDIA_ID, campaign: null }]], + ])("refuses an orphaned/replaced draft cover (%s) without fetching Storage", async (_reason, rows) => { + let openedService = false + const { viewer, service } = dbs(() => ({ data: rows })) + const response = await coverResponse( + SEGMENTS, + viewer, + () => { + openedService = true + return service + }, + "give-media", + PUBLIC_COVER_CACHE + ) + expect(response.status).toBe(404) + expect(response.headers.get("Cache-Control")).toBe("no-store") + expect(openedService).toBe(false) + expect(serviceCalls).toEqual([]) + }) + it("refuses a cover RLS hides from the viewer (a draft for anon or another user) without fetching it", async () => { const { viewer, service } = dbs(() => ({ data: [] })) const response = await coverResponse(SEGMENTS, viewer, service, "give-media", PRIVATE_COVER_CACHE) @@ -53,7 +101,7 @@ describe("coverResponse", () => { }) it("refuses keys that are not media paths before any query", async () => { - const { viewer, service } = dbs(() => ({ data: [{ id: "m" }] })) + const { viewer, service } = dbs(() => ({ data: [{ id: MEDIA_ID, campaign: { cover_media_id: MEDIA_ID } }] })) const response = await coverResponse(["..", "secret.webp"], viewer, service, "give-media", PUBLIC_COVER_CACHE) expect(response.status).toBe(404) expect(viewerCalls).toEqual([]) @@ -71,4 +119,14 @@ describe("coverResponse", () => { ).toBe(502) expect(serviceCalls).toEqual([]) }) + + it("returns 404 when the object is missing in Storage", async () => { + const { viewer, service } = dbs( + () => ({ data: [{ id: MEDIA_ID, campaign: [{ cover_media_id: MEDIA_ID }] }] }), + () => ({ error: { message: "Object not found" } }) + ) + const response = await coverResponse(SEGMENTS, viewer, service, "give-media", PUBLIC_COVER_CACHE) + expect(response.status).toBe(404) + expect(response.headers.get("Cache-Control")).toBe("no-store") + }) }) diff --git a/apps/web/src/lib/cover-route.ts b/apps/web/src/lib/cover-route.ts index 3d8eedb3..3733110c 100644 --- a/apps/web/src/lib/cover-route.ts +++ b/apps/web/src/lib/cover-route.ts @@ -8,16 +8,29 @@ function status(code: number): Response { return new Response(null, { status: code, headers: { "Cache-Control": "no-store" } }) } +interface ActiveCoverRow { + id: string + campaign?: { cover_media_id: string | null } | { cover_media_id: string | null }[] | null +} + +function isActiveCover(row: ActiveCoverRow): boolean { + if (Array.isArray(row.campaign)) { + return row.campaign.some((c) => c?.cover_media_id === row.id) + } + return Boolean(row.campaign && row.campaign.cover_media_id === row.id) +} + /** * Serves a cover from the private give-media bucket. `viewer` runs under - * RLS, which shows a campaign_media row only for a public campaign, its - * organizer and staff; only when the viewer sees the row does the service - * role fetch the object. Anything else is a plain 404. + * RLS, which shows a campaign_media row and its referencing campaign only for + * a public campaign, its organizer and staff; only when the viewer sees that + * the row is currently the campaign's cover_media_id does the service role + * fetch the object. Superseded draft covers and anything else are a plain 404. */ export async function coverResponse( segments: readonly string[], viewer: Db | null, - service: Db, + service: Db | (() => Db), bucket: string, cacheControl: string ): Promise { @@ -26,21 +39,26 @@ export async function coverResponse( const { data, error } = await viewer .from("campaign_media") - .select("id") + .select("id, campaign:campaigns!campaigns_cover_media_fk!inner(cover_media_id)") .eq("storage_path", media.path) .eq("kind", "image") .limit(1) // A rejected or expired token (PGRST30x) is treated like no access. if (error) return status(error.code?.startsWith("PGRST30") ? 404 : 502) - if (!data?.length) return status(404) + const rows = (data ?? []) as unknown as ActiveCoverRow[] + if (!rows.some(isActiveCover)) return status(404) - const file = await service.storage.from(bucket).download(media.path) + const svc = typeof service === "function" ? service() : service + const file = await svc.storage.from(bucket).download(media.path) if (file.error || !file.data) return status(404) - return new Response(file.data, { - headers: { - "Content-Type": media.mime, - "Cache-Control": cacheControl, - "Content-Security-Policy": "default-src 'none'", - }, - }) + const headers: Record = { + "Content-Type": media.mime, + "Cache-Control": cacheControl, + "Content-Security-Policy": "default-src 'none'", + "X-Content-Type-Options": "nosniff", + } + if (cacheControl === PRIVATE_COVER_CACHE) { + headers["X-Robots-Tag"] = "noindex, noimageindex" + } + return new Response(file.data, { headers }) } diff --git a/apps/web/src/lib/media.test.ts b/apps/web/src/lib/media.test.ts index e874bb77..05f8c143 100644 --- a/apps/web/src/lib/media.test.ts +++ b/apps/web/src/lib/media.test.ts @@ -1,6 +1,7 @@ +import sharp from "sharp" import { describe, expect, it } from "vitest" -import { detectImageType, mediaPath, parseMediaPath } from "./media" +import { campaignMediaPrefix, detectImageType, mediaPath, parseMediaPath, reencodeCover } from "./media" const bytes = (...values: number[]) => new Uint8Array(values) @@ -26,6 +27,7 @@ describe("detectImageType", () => { describe("mediaPath", () => { it("keeps objects under the campaign's prefix", () => { expect(mediaPath("c1", "m1", "png")).toBe("campaigns/c1/m1.png") + expect(campaignMediaPrefix("c1")).toBe("campaigns/c1") }) }) @@ -39,10 +41,12 @@ describe("parseMediaPath", () => { mime: "image/webp", }) expect(parseMediaPath(["campaigns", campaign, `${object}.jpg`])?.mime).toBe("image/jpeg") + expect(parseMediaPath(["campaigns", campaign, `${object}.png`])?.mime).toBe("image/png") }) - it("rejects traversal, other prefixes, extra segments and other types", () => { + it("rejects traversal, embedded slashes, other prefixes, extra segments and other types", () => { expect(parseMediaPath(["campaigns", campaign, "..", `${object}.webp`])).toBeNull() + expect(parseMediaPath([`campaigns/${campaign}`, `${object}.webp`])).toBeNull() expect(parseMediaPath(["..", "other-bucket", `${object}.webp`])).toBeNull() expect(parseMediaPath(["campaigns", campaign, object, `${object}.webp`])).toBeNull() expect(parseMediaPath(["campaigns", campaign, `${object}.svg`])).toBeNull() @@ -50,3 +54,54 @@ describe("parseMediaPath", () => { expect(parseMediaPath([])).toBeNull() }) }) + +describe("reencodeCover", () => { + it("converts to WebP, applies EXIF orientation and strips EXIF metadata", async () => { + const jpegWithExif = await sharp({ + create: { width: 80, height: 40, channels: 3, background: "#e11d48" }, + }) + .jpeg() + .withMetadata({ + orientation: 6, + exif: { + IFD0: { Copyright: "private-owner" }, + IFD3: { GPSLatitudeRef: "N" }, + }, + }) + .toBuffer() + + const out = await reencodeCover(new Uint8Array(jpegWithExif)) + const meta = await sharp(out).metadata() + expect(meta.format).toBe("webp") + expect(meta.exif).toBeUndefined() + // Orientation 6 (90° CW) rotates 80x40 pixels into 40x80. + expect(meta.width).toBe(40) + expect(meta.height).toBe(80) + }) + + it("caps the longer edge at 2400px while preserving aspect ratio and never enlarging small images", async () => { + const largePng = await sharp({ + create: { width: 3000, height: 1500, channels: 3, background: "#0ea5e9" }, + }) + .png() + .toBuffer() + const downscaled = await sharp(await reencodeCover(new Uint8Array(largePng))).metadata() + expect(downscaled.format).toBe("webp") + expect(downscaled.width).toBe(2400) + expect(downscaled.height).toBe(1200) + + const smallPng = await sharp({ + create: { width: 320, height: 180, channels: 3, background: "#10b981" }, + }) + .png() + .toBuffer() + const untouched = await sharp(await reencodeCover(new Uint8Array(smallPng))).metadata() + expect(untouched.width).toBe(320) + expect(untouched.height).toBe(180) + }) + + it("throws when the bytes are not a decodable image", async () => { + await expect(reencodeCover(bytes(0xff, 0xd8, 0xff, 0x00, 0x01, 0x02))).rejects.toThrow() + await expect(reencodeCover(new TextEncoder().encode("not an image"))).rejects.toThrow() + }) +}) diff --git a/apps/web/src/lib/media.ts b/apps/web/src/lib/media.ts index 89d8d3b1..12b110db 100644 --- a/apps/web/src/lib/media.ts +++ b/apps/web/src/lib/media.ts @@ -46,6 +46,7 @@ const MEDIA_TYPES: Record = { * shape mediaPath() produces (so no traversal or other buckets' keys). */ export function parseMediaPath(segments: readonly string[]): { path: string; mime: ImageType["mime"] } | null { + if (segments.length !== 3) return null const path = segments.join("/") const match = MEDIA_PATH.exec(path) return match ? { path, mime: MEDIA_TYPES[match[1] as ImageType["ext"]] } : null From 3108be3576ed8e18963e86c6a64dcd8b27dbd95d Mon Sep 17 00:00:00 2001 From: JOY <5027251+JOY@users.noreply.github.com> Date: Thu, 19 Nov 2026 09:42:42 +0700 Subject: [PATCH 04/23] feat(email): email outbox and first transactional emails (#254) (#257) * Dependabot: open PRs against dev (#163) Dependabot reads its configuration from the default branch, main, whose copy lacked the target-branch lines #117 added on dev, so it opened #160, #161 and #162 against main. This makes main's file identical to dev's. Co-Authored-By: Claude Opus 5.5 * feat(email): outbox sender, first transactional emails, admin view (#254) The send-outbox cron leases due give.outbox rows, renders Vietnamese emails (donation receipt with a guest tracking link, pledge payment due, reminder and lapsed, campaign approved, changes requested, suspended, ended) and sends them through DOS.Me's AWS SES over SMTP; results go back through give.complete_outbox (retry with backoff, dead after 7 attempts). /admin/emails lists dead and retrying emails and retries a dead one. Notification emails carry an unsubscribe link and one-click header. Guest access accepts the receipt's tracking token. Co-Authored-By: Claude Opus 5.5 * feat(email): nodemailer 10.3.1 for SES, log transport outside Production (#254) Per the Give Product Owner: nodemailer pinned to 10.3.1, imported only by server-only code (tested); Give's own sender Give and no default Reply-To. Beta, previews and local runs use a log transport that mails nobody unless EMAIL_DELIVERY=smtp, and then only EMAIL_ALLOWLIST; @retry.invalid and @bounce.invalid fail on purpose to test retries and dead rows. Production without SES credentials claims nothing. Co-Authored-By: Claude Opus 5.5 * docs(changelog): link #257 Co-Authored-By: Claude Opus 5.5 * fix(email): send deadline, release unreached rows, pooled SMTP (#254 review) - No send starts unless it can time out by 45 s; rows the run cannot reach go back uncounted through give.release_outbox instead of waiting out the lease and spending an attempt. - After a send times out the run stops, gives back the rest of the batch and closes the transport, so the stuck connection is dropped. - One pooled SMTP connection per run, closed at the end. - Outside Production the job refuses to run against the Production database, so the log transport never marks real people's emails sent. Co-Authored-By: Claude Opus 5.5 * fix(email): link origin reads only the given env (#254) siteOrigin() defaults to process.env.NEXT_PUBLIC_SITE_URL when passed undefined, so emailLinkOrigin ignored the env it was given. Co-Authored-By: Claude Opus 5.5 * fix(email): second review of #257: cut timed-out sends, retry results, guards (#254) - A timed-out send has its SMTP connection destroyed (tracked sockets via nodemailer getSocket) before anything is recorded, and is recorded as outcome unknown (complete_outbox p_outcome_unknown: waits an hour). - complete_outbox is tried 3 times before the row is left to its lease. Delivery is documented as at least once. - Production refuses EMAIL_DELIVERY=log and non-https link origins; the Production DB guard also knows dos.supabase.co. - Only an EENVELOPE refusal at RCPT TO is permanent. - X-Give-Outbox-Id header (SES replaces Message-ID). - Receipt shows the amount only for VND; the changes-requested subject leaves out the not-yet-approved title. - The nodemailer import guard catches dynamic, require and subpath imports and a use client directive after comments, in js and mjs files too. Co-Authored-By: Claude Opus 5.5 * fix(email): bound result retries by the run deadline; purge cron; review fixes (#254) - complete_outbox and release_outbox calls time out after 5 s, retries run only for transient errors and only while they fit before 55 s; a stale answer after a lost one reads what the row recorded. - SMTP abort resets connections (TCP RST) and fails connects in progress; a connection lost before the provider answered is outcome unknown. - /api/cron/purge-outbox (daily) runs give.purge_outbox. - Admin: labels for the new skip reasons, message for an expired retry. - Import guard catches side-effect and template-literal imports; the Production DB guard ignores a trailing dot. Co-Authored-By: Claude Opus 5.5 * fix(email): outcome unknown only after MAIL FROM; bound claim and stale read (#254) - smtp: nodemailer's transaction log (commands only, nothing kept) tells whether a send reached MAIL FROM; a connection lost before that is a plain failure, not outcome unknown. - outbox: claim_outbox times out after 10 s; the stale-answer read runs only while it fits before 55 s. - purge-outbox route: maxDuration 60. Docs updated. Co-Authored-By: Claude Opus 5.5 * fix(email): purge in 4 s calls until done; timeout before MAIL FROM is a plain failure (#254) - /api/cron/purge-outbox calls give.purge_outbox again while it reports more, for up to 45 s (server/email/purge.ts). - The transport reports whether the last send reached MAIL FROM; a send that timed out before that is retried normally, not as outcome unknown. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 36 ++ apps/web/.env.example | 16 + apps/web/package.json | 2 + apps/web/src/app/admin/emails/actions.test.ts | 74 ++++ apps/web/src/app/admin/emails/actions.ts | 44 +++ apps/web/src/app/admin/emails/page.tsx | 150 +++++++ apps/web/src/app/admin/layout.tsx | 7 +- .../app/api/cron/purge-outbox/route.test.ts | 72 ++++ .../src/app/api/cron/purge-outbox/route.ts | 23 ++ .../app/api/cron/send-outbox/route.test.ts | 67 ++++ .../web/src/app/api/cron/send-outbox/route.ts | 39 ++ .../app/api/email/unsubscribe/route.test.ts | 80 ++++ .../src/app/api/email/unsubscribe/route.ts | 62 +++ apps/web/src/app/email/unsubscribe/page.tsx | 81 ++++ apps/web/src/lib/email-outbox.ts | 105 +++++ .../contributions/contributions.test.ts | 41 ++ apps/web/src/server/contributions/index.ts | 33 +- .../src/server/email/log-transport.test.ts | 36 ++ apps/web/src/server/email/log-transport.ts | 76 ++++ apps/web/src/server/email/outbox.test.ts | 337 ++++++++++++++++ apps/web/src/server/email/outbox.ts | 322 +++++++++++++++ apps/web/src/server/email/provider.test.ts | 165 ++++++++ apps/web/src/server/email/provider.ts | 123 ++++++ apps/web/src/server/email/purge.ts | 55 +++ apps/web/src/server/email/smtp.test.ts | 259 +++++++++++++ apps/web/src/server/email/smtp.ts | 212 ++++++++++ apps/web/src/server/email/templates.test.ts | 191 +++++++++ apps/web/src/server/email/templates.ts | 366 ++++++++++++++++++ apps/web/src/server/email/transport.ts | 45 +++ apps/web/vercel.json | 4 +- docs/Give-Technical-Design.md | 17 +- pnpm-lock.yaml | 19 + 32 files changed, 3151 insertions(+), 8 deletions(-) create mode 100644 apps/web/src/app/admin/emails/actions.test.ts create mode 100644 apps/web/src/app/admin/emails/actions.ts create mode 100644 apps/web/src/app/admin/emails/page.tsx create mode 100644 apps/web/src/app/api/cron/purge-outbox/route.test.ts create mode 100644 apps/web/src/app/api/cron/purge-outbox/route.ts create mode 100644 apps/web/src/app/api/cron/send-outbox/route.test.ts create mode 100644 apps/web/src/app/api/cron/send-outbox/route.ts create mode 100644 apps/web/src/app/api/email/unsubscribe/route.test.ts create mode 100644 apps/web/src/app/api/email/unsubscribe/route.ts create mode 100644 apps/web/src/app/email/unsubscribe/page.tsx create mode 100644 apps/web/src/lib/email-outbox.ts create mode 100644 apps/web/src/server/email/log-transport.test.ts create mode 100644 apps/web/src/server/email/log-transport.ts create mode 100644 apps/web/src/server/email/outbox.test.ts create mode 100644 apps/web/src/server/email/outbox.ts create mode 100644 apps/web/src/server/email/provider.test.ts create mode 100644 apps/web/src/server/email/provider.ts create mode 100644 apps/web/src/server/email/purge.ts create mode 100644 apps/web/src/server/email/smtp.test.ts create mode 100644 apps/web/src/server/email/smtp.ts create mode 100644 apps/web/src/server/email/templates.test.ts create mode 100644 apps/web/src/server/email/templates.ts create mode 100644 apps/web/src/server/email/transport.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 48d93949..558e73b7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -433,6 +433,27 @@ trang"` gating, `"Quản lý"`, and `changes_requested` review notes), ### Platform +- Email outbox (M4): Give sends email through `give.outbox`, filled in the + same transaction as the event: a donation turning `received` (a receipt to + the guest's donation email or the donor's account, with a fresh 7-day + tracking link for guests), pledge `payment_due`, `payment_reminder` and + `pledge_lapsed` notices, and campaign approved, changes requested, + suspended and ended (organizer). `/api/cron/send-outbox` (every minute) + leases due rows, sends them through AWS SES over SMTP (DOS.Me's provider, + `nodemailer` 10.3.1, server-only) from `Give `, retries + after 1, 5, 15, 60, 180 and 360 minutes and marks a row dead after 7 + attempts; `/admin/emails` (admins) lists dead and retrying emails and sends + a dead one again (audited). The campaign end summary is the only + notification email: it carries an unsubscribe link (`/email/unsubscribe`, + one-click `List-Unsubscribe`). No images or tracking pixels. Outside + Production a log transport mails nobody unless `EMAIL_DELIVERY=smtp`, and + then only `EMAIL_ALLOWLIST`; in Production sending waits for the SES + credentials, and `EMAIL_DELIVERY=log` is refused there. Delivery is at + least once: each event queues exactly one email, but a send whose result + was lost, or that timed out (its connection is cut off and it waits an + hour before the next attempt), can reach the recipient twice. A daily + `/api/cron/purge-outbox` clears old addresses and payloads and expired + tracking tokens (#254 / #257). - Contact: Give staff are reached at `hi@give.vn` (Give's own domain; it replaced the first choice, DOS.Me's `help@dos.me`), kept in one constant (`apps/web/src/lib/contact.ts`). The site footer shows @@ -454,6 +475,21 @@ trang"` gating, `"Quản lý"`, and `changes_requested` review notes), ### Database (DOS.Me) +- Email outbox: `give.outbox` (unique idempotency key, lease, attempts, + backoff, dead), `give.email_suppressions`, `give.contribution_access_tokens`; + enqueue triggers on `contributions`, `notices` and `campaign_status_events`; + `give.claim_outbox` (re-checks each row: a receipt whose donation is no + longer received, a payment request no longer due and rows past their + kind's maximum age are skipped; payment requests wait while a campaign's + requests are stopped; records the address it sends to), + `give.complete_outbox` (an outcome-unknown timeout waits at least an hour), + `give.release_outbox`, `give.retry_outbox` (admin, audited, not past the + maximum age), `give.unsubscribe_email` (suppresses the address the email + went to; suppressions are stored as SHA-256), `give.purge_outbox` + (retention). Only the triggers enqueue, validating rows instead of + catching errors; `recipient_user_id` has no foreign key to `auth.users`. + RLS on, service role only (#254 / DOS/DOS.Me#1782). Migration + `20261123090000_give_email_outbox`. - Finance can read why a bank transaction was refused: `give.bank_transaction_refusal_reasons(uuid[])`, finance and admin only, returns the `bank_transaction.account_owner_mismatch` and diff --git a/apps/web/.env.example b/apps/web/.env.example index 98bd3bc1..64e6791a 100644 --- a/apps/web/.env.example +++ b/apps/web/.env.example @@ -19,3 +19,19 @@ OIDC_CLIENT_ID= OIDC_CLIENT_SECRET= # Shared secret Vercel Cron sends as "Authorization: Bearer ". CRON_SECRET= +# Email (DOS/Give#254): AWS SES over SMTP, the provider DOS.Me uses. +# EMAIL_DELIVERY: smtp (real mail) or log (mails nobody). Defaults to smtp in +# Production and log everywhere else. Outside Production, smtp reaches only +# EMAIL_ALLOWLIST (comma-separated addresses or @domain); others are logged. +# In log mode, ...@retry.invalid fails every attempt and ...@bounce.invalid +# fails permanently, to test retries and dead emails without a provider. +EMAIL_DELIVERY=log +EMAIL_ALLOWLIST= +SMTP_HOST=email-smtp.ap-southeast-1.amazonaws.com +SMTP_PORT=587 +SMTP_USER= +SMTP_PASS= +EMAIL_FROM="Give " +# Origin of links in emails; defaults to NEXT_PUBLIC_SITE_URL, then +# https://give.vn in Production. Set https://beta.give.vn for beta. +EMAIL_LINK_ORIGIN= diff --git a/apps/web/package.json b/apps/web/package.json index 79e0d1dd..b14f30a5 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -15,6 +15,7 @@ "clsx": "^2.1.1", "jose": "^6.2.15", "next": "^16.4.6", + "nodemailer": "10.3.1", "react": "^19.3.1", "react-dom": "^19.3.1", "react-markdown": "^10.1.0", @@ -27,6 +28,7 @@ "devDependencies": { "@tailwindcss/postcss": "^4.3.5", "@types/node": "^24", + "@types/nodemailer": "8.0.2", "@types/react": "^19", "@types/react-dom": "^19", "eslint": "^10.14.0", diff --git a/apps/web/src/app/admin/emails/actions.test.ts b/apps/web/src/app/admin/emails/actions.test.ts new file mode 100644 index 00000000..1b4f9461 --- /dev/null +++ b/apps/web/src/app/admin/emails/actions.test.ts @@ -0,0 +1,74 @@ +import { revalidatePath } from "next/cache" +import { beforeEach, describe, expect, it, vi } from "vitest" + +import { fakeDb, op, type Call, type Handler, type Result } from "@/test/fake-db" + +const ADMIN = "66666666-6666-4666-8666-666666666666" +const ROW = "33333333-3333-4333-8333-333333333333" + +const state = vi.hoisted(() => ({ + session: true, + responses: {} as Record, + serviceHandler: (() => undefined) as Handler, + userCalls: [] as Call[], + serviceCalls: [] as Call[], +})) + +vi.mock("next/cache", () => ({ revalidatePath: vi.fn() })) +vi.mock("@/lib/auth/session", () => ({ + getSession: vi.fn(async () => + state.session ? { user: { id: ADMIN, email: null, name: null }, accessToken: "token" } : null + ), +})) +vi.mock("@/lib/supabase", () => ({ + dbAs: () => fakeDb((call) => state.responses[call.target], state.userCalls), + dbService: () => fakeDb((call) => state.serviceHandler(call), state.serviceCalls), +})) + +const { retryEmail } = await import("./actions") + +beforeEach(() => { + vi.mocked(revalidatePath).mockClear() + state.session = true + state.userCalls.length = 0 + state.serviceCalls.length = 0 + state.responses = { "rpc:is_admin": { data: true } } + state.serviceHandler = () => ({ data: "pending" }) +}) + +describe("retryEmail", () => { + it("sends a dead email again as the admin actor", async () => { + const result = await retryEmail(ROW, null, new FormData()) + expect(result?.ok).toBe(true) + expect(state.userCalls.map((c) => c.target)).toEqual(["rpc:is_admin"]) + expect(state.serviceCalls.map((c) => c.target)).toEqual(["rpc:retry_outbox"]) + expect(op(state.serviceCalls[0], "args")).toEqual([{ p_actor_id: ADMIN, p_id: ROW }]) + expect(revalidatePath).toHaveBeenCalledWith("/admin/emails") + }) + + it("refuses a signed-out visitor, a non-admin and a malformed id without calling the database", async () => { + state.session = false + expect((await retryEmail(ROW, null, new FormData()))?.ok).toBe(false) + state.session = true + expect((await retryEmail("nope", null, new FormData()))?.ok).toBe(false) + state.responses = { "rpc:is_admin": { data: false } } + expect(await retryEmail(ROW, null, new FormData())).toEqual({ + ok: false, + message: "Chỉ quản trị viên mới gửi lại được email.", + }) + expect(state.serviceCalls).toHaveLength(0) + }) + + it("explains a row someone already sent again", async () => { + state.serviceHandler = () => ({ error: { code: "23514", message: "GIVE_OUTBOX_NOT_DEAD" } }) + const result = await retryEmail(ROW, null, new FormData()) + expect(result?.ok).toBe(false) + expect(result?.message).toContain("có người đã gửi lại") + }) + + it("explains a row too old to send again", async () => { + state.serviceHandler = () => ({ error: { code: "23514", message: "GIVE_OUTBOX_EXPIRED" } }) + const result = await retryEmail(ROW, null, new FormData()) + expect(result?.message).toContain("đã quá lâu") + }) +}) diff --git a/apps/web/src/app/admin/emails/actions.ts b/apps/web/src/app/admin/emails/actions.ts new file mode 100644 index 00000000..3e7021b0 --- /dev/null +++ b/apps/web/src/app/admin/emails/actions.ts @@ -0,0 +1,44 @@ +"use server" + +import { revalidatePath } from "next/cache" + +import { getSession } from "@/lib/auth/session" +import { isStaff } from "@/lib/campaigns" +import { dbErrorMessage, done, fail, type ActionResult, type DbErrorLike } from "@/lib/errors" +import { isUuid } from "@/lib/ids" +import { dbAs, dbService } from "@/lib/supabase" + +/** + * An admin sends a dead email again (DOS/Give#254): give.retry_outbox runs + * as the service role with the actor's id, checks the admin role and that + * the row is dead under its locks, and audits the retry. The role is first + * read with the actor's own token, which PostgREST verifies, so a forged + * session cookie fails here. + */ + +const SIGNED_OUT = "Phiên đăng nhập đã hết. Hãy đăng nhập lại." +const NOT_ALLOWED = "Chỉ quản trị viên mới gửi lại được email." +const NOT_DEAD = "Email này không còn ở trạng thái không gửi được: có người đã gửi lại. Hãy tải lại trang." +const EXPIRED = "Email này đã quá lâu nên không gửi lại được: nội dung có thể không còn đúng." + +const MESSAGES: Record = { + GIVE_NOT_ALLOWED: NOT_ALLOWED, + GIVE_OUTBOX_NOT_DEAD: NOT_DEAD, + GIVE_OUTBOX_NOT_FOUND: NOT_DEAD, + GIVE_OUTBOX_EXPIRED: EXPIRED, +} + +export async function retryEmail(outboxId: string, _state: ActionResult, _form: FormData): Promise { + const session = await getSession() + if (!session) return fail(SIGNED_OUT) + if (!isUuid(outboxId)) return fail(NOT_DEAD) + try { + if (!(await isStaff(dbAs(session.accessToken), ["admin"]))) return fail(NOT_ALLOWED) + } catch (error) { + return fail(dbErrorMessage(error as DbErrorLike)) + } + const { error } = await dbService().rpc("retry_outbox", { p_actor_id: session.user.id, p_id: outboxId }) + if (error) return fail(dbErrorMessage(error, MESSAGES)) + revalidatePath("/admin/emails") + return done("Đã gửi lại email. Give gửi trong lần chạy tới (mỗi phút), với lượt thử mới từ đầu.") +} diff --git a/apps/web/src/app/admin/emails/page.tsx b/apps/web/src/app/admin/emails/page.tsx new file mode 100644 index 00000000..b41307c2 --- /dev/null +++ b/apps/web/src/app/admin/emails/page.tsx @@ -0,0 +1,150 @@ +import type { Metadata } from "next" +import { notFound } from "next/navigation" + +import { ActionForm, SubmitButton } from "@/components/forms" +import { Callout } from "@/components/ui/Callout" +import { EmptyState } from "@/components/ui/EmptyState" +import { MachineId } from "@/components/ui/RefCode" +import { requireSession } from "@/lib/auth/session" +import { isStaff } from "@/lib/campaigns" +import { + countEmailsByStatus, + listDeadEmails, + listRetryingEmails, + maskEmail, + OUTBOX_KIND_LABELS, + OUTBOX_STATUS_LABELS, + type OutboxRow, +} from "@/lib/email-outbox" +import { formatDateTime } from "@/lib/format" +import { dbAs, dbService } from "@/lib/supabase" + +import { AdminPage, AdminSection, DataTable, Fact, Facts, ItemActions, ItemCard, ItemList } from "../_components/ui" +import { retryEmail } from "./actions" + +export const metadata: Metadata = { title: "Email", robots: { index: false } } + +export default async function AdminEmailsPage() { + const session = await requireSession("/admin/emails") + // Admins only; others get a 404. The outbox is read with the service client + // after this check, since no client role may read it. + if (!(await isStaff(dbAs(session.accessToken), ["admin"]))) notFound() + + const service = dbService() + const [dead, retrying, counts] = await Promise.all([ + listDeadEmails(service), + listRetryingEmails(service), + countEmailsByStatus(service), + ]) + + return ( + + Give gửi email qua một hàng chờ: mỗi email được tạo cùng lúc với sự kiện gây ra nó (tiền ủng hộ được ghi nhận, + đến hạn thanh toán, quyết định kiểm duyệt, chiến dịch kết thúc) và được gửi trong vòng một phút. Gửi lỗi thì + Give tự thử lại sau 1, 5, 15, 60 phút, 3 giờ và 6 giờ; sau 7 lần vẫn lỗi, email dừng ở đây. Gửi lại khi nguyên + nhân đã được khắc phục; mỗi lần gửi lại được ghi vào nhật ký kiểm toán. +

+ } + > + + + {Object.entries(OUTBOX_STATUS_LABELS).map(([status, label]) => ( + + {label} + {counts[status] ?? 0} + + ))} + + + + dead.rows.length ? `${dead.rows.length} mới nhất / ${dead.total}` : dead.total} + > + {dead.rows.length === 0 ? ( + Mọi email đều đã gửi hoặc đang chờ gửi. + ) : ( + + {dead.rows.map((row) => ( + + ))} + + )} + + + retrying.rows.length ? `${retrying.rows.length} / ${retrying.total}` : retrying.total} + lead="Email gửi lỗi ít nhất một lần, Give sẽ tự thử lại." + > + {retrying.rows.length === 0 ? ( + + ) : ( + + {retrying.rows.map((row) => ( + + {OUTBOX_KIND_LABELS[row.kind] ?? row.kind} + {recipient(row)} + + {row.attempts}/{row.max_attempts} + + + {row.last_error ?? "—"} + + {formatDateTime(row.next_attempt_at)} + + ))} + + )} + +
+ ) +} + +function recipient(row: OutboxRow): string { + return row.recipient_email ? maskEmail(row.recipient_email) : row.recipient_user_id ? "Tài khoản DOS.Me" : "—" +} + +function DeadCard({ row }: { row: OutboxRow }) { + return ( + +
+

{OUTBOX_KIND_LABELS[row.kind] ?? row.kind}

+ +

+ Lỗi cuối: {row.last_error ?? "—"} +

+
+ + {recipient(row)} + + {row.attempts}/{row.max_attempts} lần + + {formatDateTime(row.created_at)} + {formatDateTime(row.dead_at)} + +

+ {row.id} +

+
+ + +

Gửi lại

+

+ Give gửi trong lần chạy tới, với 7 lượt thử mới. Chỉ nên gửi lại khi nguyên nhân đã được khắc phục. +

+ Gửi lại +
+
+
+ ) +} diff --git a/apps/web/src/app/admin/layout.tsx b/apps/web/src/app/admin/layout.tsx index e351b38a..59dc8efa 100644 --- a/apps/web/src/app/admin/layout.tsx +++ b/apps/web/src/app/admin/layout.tsx @@ -59,6 +59,11 @@ async function adminLinks(): Promise { { href: "/admin/inbound", label: "Tiền vào bị dừng" }, ] : []), - ...(admin ? [{ href: "/admin/roles", label: "Phân quyền" }] : []), + ...(admin + ? [ + { href: "/admin/emails", label: "Email" }, + { href: "/admin/roles", label: "Phân quyền" }, + ] + : []), ] } diff --git a/apps/web/src/app/api/cron/purge-outbox/route.test.ts b/apps/web/src/app/api/cron/purge-outbox/route.test.ts new file mode 100644 index 00000000..eff34458 --- /dev/null +++ b/apps/web/src/app/api/cron/purge-outbox/route.test.ts @@ -0,0 +1,72 @@ +import { NextRequest } from "next/server" +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" + +import { fakeDb, op, type Call, type Result } from "@/test/fake-db" + +const SECRET = "0123456789abcdef0123" + +const state = vi.hoisted(() => ({ calls: [] as unknown[], answer: {} as unknown })) + +vi.mock("@/lib/supabase", () => ({ + dbService: () => fakeDb(() => state.answer as Result, state.calls as Call[]), +})) + +const { GET } = await import("./route") +const { purgeUntilDone } = await import("@/server/email/purge") + +function request(authorization?: string) { + const headers: Record = {} + if (authorization !== undefined) headers.authorization = authorization + return new NextRequest("http://localhost/api/cron/purge-outbox", { headers }) +} + +beforeEach(() => { + vi.stubEnv("CRON_SECRET", SECRET) + state.calls = [] + vi.spyOn(console, "error").mockImplementation(() => {}) +}) + +afterEach(() => { + vi.unstubAllEnvs() +}) + +describe("GET /api/cron/purge-outbox", () => { + it("refuses a request without the cron secret", async () => { + expect((await GET(request())).status).toBe(401) + expect(state.calls).toHaveLength(0) + }) + + it("runs the purge and returns its counts", async () => { + state.answer = { data: { deleted_accounts: 1, cleared: 20, expired_tokens: 3, more: false } } + const response = await GET(request(`Bearer ${SECRET}`)) + expect(response.status).toBe(200) + expect(await response.json()).toEqual({ + deleted_accounts: 1, + cleared: 20, + expired_tokens: 3, + calls: 1, + more: false, + }) + expect((state.calls[0] as Call).target).toBe("rpc:purge_outbox") + expect(op(state.calls[0] as Call, "args")).toEqual([undefined]) + }) + + it("calls again while there is more, and stops at its time budget", async () => { + state.answer = { data: { deleted_accounts: 0, cleared: 1000, expired_tokens: 0, more: true } } + let t = 0 + const response = await purgeUntilDone(() => { + t += 10_000 + return t + }) + const body = await response.json() + expect(body).toMatchObject({ cleared: 4000, calls: 4, more: true }) + expect(state.calls).toHaveLength(4) + }) + + it("answers 500 when the purge fails or answers unexpectedly", async () => { + state.answer = { error: { code: "57014", message: "timeout" } } + expect((await GET(request(`Bearer ${SECRET}`))).status).toBe(500) + state.answer = { data: [] } + expect((await GET(request(`Bearer ${SECRET}`))).status).toBe(500) + }) +}) diff --git a/apps/web/src/app/api/cron/purge-outbox/route.ts b/apps/web/src/app/api/cron/purge-outbox/route.ts new file mode 100644 index 00000000..911af2ac --- /dev/null +++ b/apps/web/src/app/api/cron/purge-outbox/route.ts @@ -0,0 +1,23 @@ +import { NextResponse, type NextRequest } from "next/server" + +import { isAuthorizedCron } from "@/lib/cron" +import { purgeUntilDone } from "@/server/email/purge" + +export const dynamic = "force-dynamic" +export const maxDuration = 60 + +/** + * Vercel Cron (daily, see vercel.json): email outbox retention + * (DOS/Give#254). give.purge_outbox clears the address and payload of rows + * whose account was deleted and of rows settled more than 30 days ago (the + * row and its idempotency key stay), and deletes expired guest tracking + * tokens. One call works for about 4 s (under the API's 8 s statement + * timeout) and commits; the route calls again while it says there is more, + * for up to PURGE_BUDGET_MS. A larger backlog clears over the next days. + */ +export async function GET(request: NextRequest) { + if (!isAuthorizedCron(request.headers.get("authorization"), process.env.CRON_SECRET)) { + return NextResponse.json({ error: "unauthorized" }, { status: 401 }) + } + return purgeUntilDone(Date.now) +} diff --git a/apps/web/src/app/api/cron/send-outbox/route.test.ts b/apps/web/src/app/api/cron/send-outbox/route.test.ts new file mode 100644 index 00000000..8d1c11bc --- /dev/null +++ b/apps/web/src/app/api/cron/send-outbox/route.test.ts @@ -0,0 +1,67 @@ +import { NextRequest } from "next/server" +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" + +const SECRET = "0123456789abcdef0123" + +const state = vi.hoisted(() => ({ + settings: { ok: false, missing: ["SMTP_USER"] } as unknown, + run: vi.fn(), + db: { name: "service" }, +})) + +vi.mock("@/lib/supabase", () => ({ dbService: () => state.db })) +vi.mock("@/server/email/provider", () => ({ emailSettingsFromEnv: () => state.settings })) +vi.mock("@/server/email/outbox", () => ({ sendDueEmails: state.run })) + +const { GET } = await import("./route") + +function request(authorization?: string) { + const headers: Record = {} + if (authorization !== undefined) headers.authorization = authorization + return new NextRequest("http://localhost/api/cron/send-outbox", { headers }) +} + +beforeEach(() => { + vi.stubEnv("CRON_SECRET", SECRET) + state.run.mockReset() + state.settings = { ok: false, missing: ["SMTP_USER", "SMTP_PASS"] } + vi.spyOn(console, "warn").mockImplementation(() => {}) + vi.spyOn(console, "error").mockImplementation(() => {}) +}) + +afterEach(() => { + vi.unstubAllEnvs() +}) + +describe("GET /api/cron/send-outbox", () => { + it("refuses a request without the cron secret", async () => { + const response = await GET(request(`Bearer ${SECRET}x`)) + expect(response.status).toBe(401) + expect(state.run).not.toHaveBeenCalled() + }) + + it("claims nothing while email is not configured, so queued emails keep their attempts", async () => { + const response = await GET(request(`Bearer ${SECRET}`)) + expect(response.status).toBe(503) + expect(await response.json()).toEqual({ error: "email_not_configured", missing: ["SMTP_USER", "SMTP_PASS"] }) + expect(state.run).not.toHaveBeenCalled() + }) + + it("runs the sender with the configured transport and reports the counts", async () => { + const transport = { send: vi.fn() } + const options = { origin: "https://give.vn", from: "Give " } + state.settings = { ok: true, delivery: "smtp", transport, options } + state.run.mockResolvedValue({ claimed: 2, sent: 1, retrying: 1, dead: 0, stale: 0 }) + const response = await GET(request(`Bearer ${SECRET}`)) + expect(response.status).toBe(200) + expect(await response.json()).toEqual({ delivery: "smtp", claimed: 2, sent: 1, retrying: 1, dead: 0, stale: 0 }) + expect(state.run).toHaveBeenCalledWith(state.db, transport, options) + }) + + it("answers 500 when the run fails", async () => { + state.settings = { ok: true, transport: { send: vi.fn() }, options: { origin: "https://give.vn", from: "x@y.z" } } + state.run.mockRejectedValue({ code: "42501", message: "denied" }) + const response = await GET(request(`Bearer ${SECRET}`)) + expect(response.status).toBe(500) + }) +}) diff --git a/apps/web/src/app/api/cron/send-outbox/route.ts b/apps/web/src/app/api/cron/send-outbox/route.ts new file mode 100644 index 00000000..60780f70 --- /dev/null +++ b/apps/web/src/app/api/cron/send-outbox/route.ts @@ -0,0 +1,39 @@ +import { NextResponse, type NextRequest } from "next/server" + +import { isAuthorizedCron } from "@/lib/cron" +import { dbService } from "@/lib/supabase" +import { emailSettingsFromEnv } from "@/server/email/provider" +import { sendDueEmails } from "@/server/email/outbox" + +export const dynamic = "force-dynamic" +export const maxDuration = 60 + +/** + * Vercel Cron (every minute, see vercel.json): sends due rows of the email + * outbox (DOS/Give#254, design 5.3 "send-outbox"). give.claim_outbox leases + * each row to one run, so overlapping runs never send the same row; a failed + * send is retried with backoff and ends 'dead' (shown in /admin/emails) + * after its last attempt. Outside Production the log transport mails nobody + * unless real sending is switched on (server/email/provider). In Production + * without SES credentials, or with EMAIL_DELIVERY=log, the job claims + * nothing, so queued emails wait instead of being marked sent. Delivery is + * at least once (see server/email/outbox). + */ +export async function GET(request: NextRequest) { + if (!isAuthorizedCron(request.headers.get("authorization"), process.env.CRON_SECRET)) { + return NextResponse.json({ error: "unauthorized" }, { status: 401 }) + } + const settings = emailSettingsFromEnv() + if (!settings.ok) { + console.warn("send-outbox skipped: email is not configured", settings.missing.join(", ")) + return NextResponse.json({ error: "email_not_configured", missing: settings.missing }, { status: 503 }) + } + try { + const result = await sendDueEmails(dbService(), settings.transport, settings.options) + return NextResponse.json({ delivery: settings.delivery, ...result }) + } catch (error) { + const { code, message } = (error ?? {}) as { code?: string; message?: string } + console.error("send-outbox failed", code, message) + return NextResponse.json({ error: "send_failed" }, { status: 500 }) + } +} diff --git a/apps/web/src/app/api/email/unsubscribe/route.test.ts b/apps/web/src/app/api/email/unsubscribe/route.test.ts new file mode 100644 index 00000000..7351c338 --- /dev/null +++ b/apps/web/src/app/api/email/unsubscribe/route.test.ts @@ -0,0 +1,80 @@ +import { NextRequest } from "next/server" +import { beforeEach, describe, expect, it, vi } from "vitest" + +import { fakeDb, op, type Call, type Result } from "@/test/fake-db" + +const TOKEN = "77777777-7777-4777-8777-777777777777" + +const state = vi.hoisted(() => ({ result: {} as Result, calls: [] as Call[] })) + +vi.mock("@/lib/supabase", () => ({ + dbService: () => fakeDb(() => state.result, state.calls), +})) + +const { GET, POST } = await import("./route") + +function post(query: string, body: Record | null) { + const form = body ? new URLSearchParams(body).toString() : undefined + return new NextRequest(`https://give.vn/api/email/unsubscribe${query}`, { + method: "POST", + headers: body ? { "content-type": "application/x-www-form-urlencoded" } : {}, + body: form, + }) +} + +beforeEach(() => { + state.result = { data: true } + state.calls.length = 0 + vi.spyOn(console, "error").mockImplementation(() => {}) +}) + +describe("GET /api/email/unsubscribe", () => { + it("only shows the confirmation page, so prefetching unsubscribes nobody", async () => { + const response = GET(new NextRequest(`https://give.vn/api/email/unsubscribe?t=${TOKEN}`)) + expect(response.status).toBe(303) + expect(response.headers.get("location")).toBe(`https://give.vn/email/unsubscribe?t=${TOKEN}`) + expect(state.calls).toHaveLength(0) + }) + + it("drops a malformed token", () => { + const response = GET(new NextRequest("https://give.vn/api/email/unsubscribe?t=abc")) + expect(response.headers.get("location")).toBe("https://give.vn/email/unsubscribe") + }) +}) + +describe("POST /api/email/unsubscribe", () => { + it("answers a mail client's one-click unsubscribe (RFC 8058)", async () => { + const response = await POST(post(`?t=${TOKEN}`, { "List-Unsubscribe": "One-Click" })) + expect(response.status).toBe(200) + expect(state.calls.map((c) => c.target)).toEqual(["rpc:unsubscribe_email"]) + expect(op(state.calls[0], "args")).toEqual([{ p_token: TOKEN }]) + }) + + it("sends the page's form back to the page with the result", async () => { + const response = await POST(post("", { t: TOKEN })) + expect(response.status).toBe(303) + expect(response.headers.get("location")).toBe("https://give.vn/email/unsubscribe?result=done") + }) + + it("reports an unknown or transactional token as invalid", async () => { + state.result = { data: false } + const page = await POST(post("", { t: TOKEN })) + expect(page.headers.get("location")).toBe("https://give.vn/email/unsubscribe?result=invalid") + const oneClick = await POST(post(`?t=${TOKEN}`, { "List-Unsubscribe": "One-Click" })) + expect(oneClick.status).toBe(404) + }) + + it("never calls the database with a malformed token", async () => { + const response = await POST(post("?t=nope", { "List-Unsubscribe": "One-Click" })) + expect(response.status).toBe(400) + expect(state.calls).toHaveLength(0) + }) + + it("asks to try again when the database fails", async () => { + state.result = { error: { code: "57014", message: "timeout" } } + const page = await POST(post("", { t: TOKEN })) + expect(page.headers.get("location")).toBe(`https://give.vn/email/unsubscribe?t=${TOKEN}&result=error`) + const oneClick = await POST(post(`?t=${TOKEN}`, { "List-Unsubscribe": "One-Click" })) + expect(oneClick.status).toBe(503) + }) +}) diff --git a/apps/web/src/app/api/email/unsubscribe/route.ts b/apps/web/src/app/api/email/unsubscribe/route.ts new file mode 100644 index 00000000..66b2108a --- /dev/null +++ b/apps/web/src/app/api/email/unsubscribe/route.ts @@ -0,0 +1,62 @@ +import { NextResponse, type NextRequest } from "next/server" + +import { isUuid } from "@/lib/ids" +import { dbService } from "@/lib/supabase" + +export const dynamic = "force-dynamic" + +/** + * Unsubscribe from Give's notification emails (DOS/Give#254). Mail clients + * POST here for one-click unsubscribe (RFC 8058, the List-Unsubscribe + * header); the page /email/unsubscribe posts its form here too. A GET (a + * link scanner, or a person opening the header link) only shows that page, + * so prefetching an email never unsubscribes anyone. The token is the + * email's own unsubscribe token; give.unsubscribe_email ignores it for + * transactional emails. + */ + +const HEADERS = { "Cache-Control": "no-store", "X-Robots-Tag": "noindex, nofollow", "Referrer-Policy": "no-referrer" } + +function pageUrl(request: NextRequest, query: Record) { + const url = new URL("/email/unsubscribe", request.nextUrl.origin) + for (const [key, value] of Object.entries(query)) url.searchParams.set(key, value) + return url +} + +export function GET(request: NextRequest) { + const token = request.nextUrl.searchParams.get("t") + return NextResponse.redirect(pageUrl(request, isUuid(token ?? "") ? { t: token as string } : {}), { + status: 303, + headers: HEADERS, + }) +} + +export async function POST(request: NextRequest) { + let form: FormData | null = null + try { + form = await request.formData() + } catch { + form = null + } + const fromForm = form?.get("t") + const token = typeof fromForm === "string" && fromForm !== "" ? fromForm : request.nextUrl.searchParams.get("t") + const oneClick = form?.get("List-Unsubscribe") === "One-Click" + + if (!token || !isUuid(token)) { + return oneClick + ? new NextResponse("invalid", { status: 400, headers: HEADERS }) + : NextResponse.redirect(pageUrl(request, { result: "invalid" }), { status: 303, headers: HEADERS }) + } + + const { data, error } = await dbService().rpc("unsubscribe_email", { p_token: token }) + if (error) { + console.error("unsubscribe_email failed", error.code, error.message) + return oneClick + ? new NextResponse("error", { status: 503, headers: HEADERS }) + : NextResponse.redirect(pageUrl(request, { t: token, result: "error" }), { status: 303, headers: HEADERS }) + } + const result = data === true ? "done" : "invalid" + return oneClick + ? new NextResponse(result, { status: data === true ? 200 : 404, headers: HEADERS }) + : NextResponse.redirect(pageUrl(request, { result }), { status: 303, headers: HEADERS }) +} diff --git a/apps/web/src/app/email/unsubscribe/page.tsx b/apps/web/src/app/email/unsubscribe/page.tsx new file mode 100644 index 00000000..d70d9a88 --- /dev/null +++ b/apps/web/src/app/email/unsubscribe/page.tsx @@ -0,0 +1,81 @@ +import type { Metadata } from "next" + +import { Button, ButtonLink } from "@/components/ui/Button" +import { EmptyState } from "@/components/ui/EmptyState" +import { isUuid } from "@/lib/ids" + +export const metadata: Metadata = { + title: "Hủy nhận email tổng kết", + robots: { index: false, follow: false }, + referrer: "no-referrer", +} + +/** + * The unsubscribe link of Give's notification emails (DOS/Give#254). It asks + * before unsubscribing, so a link scanner that opens it changes nothing; the + * form posts to /api/email/unsubscribe, which answers back here. + */ +export default async function UnsubscribePage({ + searchParams, +}: { + searchParams: Promise> +}) { + const params = await searchParams + const token = typeof params.t === "string" && isUuid(params.t) ? params.t : null + const result = typeof params.result === "string" ? params.result : null + + if (result === "done") { + return ( + Khám phá chiến dịch} + > + Give không gửi email tổng kết chiến dịch tới địa chỉ này nữa. Email giao dịch (biên nhận, yêu cầu thanh toán, + quyết định kiểm duyệt) vẫn được gửi. + + ) + } + if (result === "error" && token) { + return ( + + + + + } + > + Give tạm thời chưa xử lý được yêu cầu. Hãy thử lại sau ít phút. + + ) + } + if (!token) { + return ( + Khám phá chiến dịch} + > + Hãy mở lại đường dẫn “Hủy đăng ký” trong email bạn nhận được từ Give. + + ) + } + return ( + + + + + } + > + Give sẽ không gửi email tổng kết chiến dịch tới địa chỉ đã nhận email này nữa. Email giao dịch (biên nhận, yêu cầu + thanh toán, quyết định kiểm duyệt) vẫn được gửi. + + ) +} diff --git a/apps/web/src/lib/email-outbox.ts b/apps/web/src/lib/email-outbox.ts new file mode 100644 index 00000000..f72218b5 --- /dev/null +++ b/apps/web/src/lib/email-outbox.ts @@ -0,0 +1,105 @@ +import type { Db } from "@/lib/campaigns" + +/** + * The email outbox in the admin section (DOS/Give#254). give.outbox is + * service-role only: pages check the admin role with the user's own token + * first, then read with the service client. + */ + +export const OUTBOX_LIST_LIMIT = 50 + +export const OUTBOX_KIND_LABELS: Record = { + donation_received: "Biên nhận ủng hộ", + pledge_payment_due: "Đến hạn thanh toán cam kết", + pledge_payment_reminder: "Nhắc thanh toán cam kết", + pledge_lapsed: "Cam kết quá hạn", + campaign_approved: "Chiến dịch được duyệt", + campaign_changes_requested: "Yêu cầu chỉnh sửa", + campaign_suspended: "Chiến dịch bị tạm dừng", + campaign_ended: "Tổng kết chiến dịch", +} + +export const OUTBOX_STATUS_LABELS: Record = { + pending: "Chờ gửi", + sending: "Đang gửi", + sent: "Đã gửi", + dead: "Không gửi được", + skipped: "Bỏ qua", +} + +export const OUTBOX_SKIP_LABELS: Record = { + no_recipient: "không còn địa chỉ nhận (tài khoản đã xóa)", + unsubscribed: "người nhận đã hủy đăng ký", + payment_requests_stopped: "yêu cầu thanh toán của dự án đang tạm dừng; gửi lại khi được mở lại", + expired: "đã quá lâu nên không còn đúng lúc", + not_received: "khoản ủng hộ không còn ở trạng thái đã nhận", + not_due: "cam kết không còn đến hạn thanh toán", +} + +export interface OutboxRow { + id: string + kind: string + status: string + attempts: number + max_attempts: number + last_error: string | null + recipient_email: string | null + recipient_user_id: string | null + campaign_id: string | null + next_attempt_at: string + created_at: string + updated_at: string + dead_at: string | null +} + +const COLUMNS = + "id, kind, status, attempts, max_attempts, last_error, recipient_email, recipient_user_id, campaign_id, next_attempt_at, created_at, updated_at, dead_at" + +/** Dead rows, newest first, and how many there are. */ +export async function listDeadEmails(service: Db): Promise<{ rows: OutboxRow[]; total: number }> { + const { data, error, count } = await service + .from("outbox") + .select(COLUMNS, { count: "exact" }) + .eq("status", "dead") + .order("dead_at", { ascending: false }) + .limit(OUTBOX_LIST_LIMIT) + if (error) throw error + return { rows: (data ?? []) as OutboxRow[], total: count ?? 0 } +} + +/** Rows waiting for a retry after a failed attempt, oldest first. */ +export async function listRetryingEmails(service: Db): Promise<{ rows: OutboxRow[]; total: number }> { + const { data, error, count } = await service + .from("outbox") + .select(COLUMNS, { count: "exact" }) + .eq("status", "pending") + .gt("attempts", 0) + .order("next_attempt_at", { ascending: true }) + .limit(OUTBOX_LIST_LIMIT) + if (error) throw error + return { rows: (data ?? []) as OutboxRow[], total: count ?? 0 } +} + +/** How many rows are in each status. */ +export async function countEmailsByStatus(service: Db): Promise> { + const statuses = Object.keys(OUTBOX_STATUS_LABELS) + const counts = await Promise.all( + statuses.map(async (status) => { + const { count, error } = await service + .from("outbox") + .select("id", { count: "exact", head: true }) + .eq("status", status) + if (error) throw error + return [status, count ?? 0] as const + }) + ) + return Object.fromEntries(counts) +} + +/** "m•••@example.com": enough for staff to recognise an address without showing it whole. */ +export function maskEmail(email: string | null): string { + if (!email) return "—" + const at = email.lastIndexOf("@") + if (at < 1) return "•••" + return `${email[0]}•••${email.slice(at)}` +} diff --git a/apps/web/src/server/contributions/contributions.test.ts b/apps/web/src/server/contributions/contributions.test.ts index 8eae5d2d..c93a3a1c 100644 --- a/apps/web/src/server/contributions/contributions.test.ts +++ b/apps/web/src/server/contributions/contributions.test.ts @@ -173,6 +173,47 @@ describe("guestContribution", () => { expect(calls).toHaveLength(0) }) + describe("with a tracking token from the receipt email (DOS/Give#254)", () => { + const other = { status_token_hash: `\\x${"0".repeat(64)}` } + const db = (token: { expires_at: string } | null, calls: Call[]) => + fakeDb( + (call) => + call.target === "contributions" + ? { data: row(other) } + : { data: call.target === "contribution_access_tokens" ? token : null }, + calls + ) + + it("accepts an unexpired token of this donation, looked up by its hash", async () => { + const calls: Call[] = [] + const access = await guestContributionAccess( + db({ expires_at: "2026-11-05T00:00:00.000Z" }, calls) as never, + "GVABCDEFG", + TOKEN, + now + ) + expect(access?.donation.reference_code).toBe("GVABCDEFG") + expect(access?.expiresAt).toEqual(new Date("2026-11-05T00:00:00.000Z")) + expect(calls[1].target).toBe("contribution_access_tokens") + expect(calls[1].ops).toContainEqual(["eq", "token_hash", `\\x${TOKEN_SHA256}`]) + expect(calls[1].ops).toContainEqual(["eq", "contribution_id", "33333333-3333-4333-8333-333333333333"]) + expect(calls[1].ops).toContainEqual(["gt", "expires_at", now.toISOString()]) + }) + + it("refuses an unknown or expired one", async () => { + expect(await guestContributionAccess(db(null, []) as never, "GVABCDEFG", TOKEN, now)).toBeNull() + expect( + await guestContributionAccess(db({ expires_at: now.toISOString() }, []) as never, "GVABCDEFG", TOKEN, now) + ).toBeNull() + }) + + it("does not look one up when the status token matches", async () => { + const calls: Call[] = [] + await guestContributionAccess(fakeDb(() => ({ data: row() }), calls) as never, "GVABCDEFG", TOKEN, now) + expect(calls.map((c) => c.target)).toEqual(["contributions"]) + }) + }) + it("does not query for a malformed reference code", async () => { const calls: Call[] = [] expect(await guestContributionAccess(fakeDb(() => undefined, calls) as never, "GV0OIL123", TOKEN, now)).toBeNull() diff --git a/apps/web/src/server/contributions/index.ts b/apps/web/src/server/contributions/index.ts index ee5ffab0..81abf8d9 100644 --- a/apps/web/src/server/contributions/index.ts +++ b/apps/web/src/server/contributions/index.ts @@ -205,6 +205,21 @@ interface GuestRow extends PaymentContribution { // PostgREST returns bytea as a backslash, "x" and the hex digits. const BYTEA_SHA256 = /^\\x([0-9a-f]{64})$/ +/** Expiry of an unexpired receipt tracking token of this contribution, by its hash. */ +async function receiptTokenExpiry(service: Db, contributionId: string, hash: string, now: Date): Promise { + const { data, error } = await service + .from("contribution_access_tokens") + .select("expires_at") + .eq("token_hash", `\\x${hash}`) + .eq("contribution_id", contributionId) + .gt("expires_at", now.toISOString()) + .maybeSingle() + if (error) throw error + const expiresAt = (data as { expires_at?: string } | null)?.expires_at + const date = expiresAt ? new Date(expiresAt) : null + return date && !Number.isNaN(date.getTime()) && date > now ? date : null +} + export interface GuestContributionAccess { donation: PaymentContribution expiresAt: Date @@ -232,10 +247,20 @@ export async function guestContributionAccess( .maybeSingle() if (error) throw error const row = data as GuestRow | null - const stored = BYTEA_SHA256.exec(row?.status_token_hash ?? "")?.[1] - const expiresAt = row?.status_token_expires_at ? new Date(row.status_token_expires_at) : null - if (!row || !stored || !expiresAt || Number.isNaN(expiresAt.getTime()) || expiresAt <= now) return null - if (!timingSafeEqual(Buffer.from(stored, "hex"), Buffer.from(statusTokenHash(token), "hex"))) return null + if (!row) return null + const hash = statusTokenHash(token) + const stored = BYTEA_SHA256.exec(row.status_token_hash ?? "")?.[1] + const statusExpiry = row.status_token_expires_at ? new Date(row.status_token_expires_at) : null + const statusTokenValid = + !!stored && + !!statusExpiry && + !Number.isNaN(statusExpiry.getTime()) && + statusExpiry > now && + timingSafeEqual(Buffer.from(stored, "hex"), Buffer.from(hash, "hex")) + // Otherwise a tracking token from the guest's receipt email (DOS/Give#254): + // the outbox stores only its hash, looked up exactly by that hash. + const expiresAt = statusTokenValid ? statusExpiry : await receiptTokenExpiry(service, row.id, hash, now) + if (!expiresAt) return null return { donation: { id: row.id, diff --git a/apps/web/src/server/email/log-transport.test.ts b/apps/web/src/server/email/log-transport.test.ts new file mode 100644 index 00000000..d8c07313 --- /dev/null +++ b/apps/web/src/server/email/log-transport.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it, vi } from "vitest" + +import { createLogTransport } from "./log-transport" +import type { OutgoingEmail } from "./transport" + +function message(to: string): OutgoingEmail { + return { + from: "Give ", + to, + subject: "Give đã nhận khoản ủng hộ", + text: "secret tracking link", + html: "

secret tracking link

", + headers: { "Message-ID": "" }, + idempotencyKey: "donation_received:1", + } +} + +describe("createLogTransport", () => { + it("mails nobody and logs only the key and a masked recipient", async () => { + const log = vi.fn() + const result = await createLogTransport(log).send(message("mai@example.com")) + expect(result).toEqual({ ok: true, messageId: "log:" }) + expect(log).toHaveBeenCalledTimes(1) + const line = log.mock.calls[0][0] as string + expect(line).toContain("donation_received:1") + expect(line).toContain("m•••@example.com") + expect(line).not.toContain("mai@") + expect(line).not.toContain("secret") + }) + + it("fails on purpose for the reserved test domains", async () => { + const transport = createLogTransport(() => {}) + expect(await transport.send(message("a@retry.invalid"))).toMatchObject({ ok: false, permanent: false }) + expect(await transport.send(message("a@BOUNCE.invalid"))).toMatchObject({ ok: false, permanent: true }) + }) +}) diff --git a/apps/web/src/server/email/log-transport.ts b/apps/web/src/server/email/log-transport.ts new file mode 100644 index 00000000..62e8dc2b --- /dev/null +++ b/apps/web/src/server/email/log-transport.ts @@ -0,0 +1,76 @@ +import "server-only" + +import type { EmailTransport, OutgoingEmail, SendResult } from "./transport" + +/** + * The transport outside Production unless real sending is switched on + * (DOS/Give#254): it mails nobody. It logs that an email would have gone + * (kind of message, masked recipient) and reports success, so beta runs the + * whole outbox without reaching real people. + * + * To exercise retries and dead rows on beta without a provider, two reserved + * domains (RFC 2606 `.invalid`, never deliverable) fail on purpose: + * `…@retry.invalid` fails every attempt as a temporary error (so the row + * retries and ends dead after its last attempt) and `…@bounce.invalid` fails + * permanently (dead at once). + */ + +export const RETRY_TEST_DOMAIN = "retry.invalid" +export const BOUNCE_TEST_DOMAIN = "bounce.invalid" + +function domainOf(address: string): string { + return address.slice(address.lastIndexOf("@") + 1).toLowerCase() +} + +function masked(address: string): string { + const at = address.lastIndexOf("@") + return at < 1 ? "•••" : `${address[0]}•••${address.slice(at)}` +} + +export function createLogTransport(log: (line: string) => void = console.info): EmailTransport { + return { + async send(email: OutgoingEmail): Promise { + const domain = domainOf(email.to) + if (domain === RETRY_TEST_DOMAIN) { + return { ok: false, permanent: false, error: "LOG: test temporary failure" } + } + if (domain === BOUNCE_TEST_DOMAIN) { + return { ok: false, permanent: true, error: "LOG: test permanent failure" } + } + log(`email not sent (log transport): ${email.idempotencyKey} to ${masked(email.to)}`) + return { ok: true, messageId: `log:${email.headers["Message-ID"] ?? email.idempotencyKey}` } + }, + } +} + +/** + * Real sending to allowlisted recipients only, the log transport for everyone + * else. Entries are full addresses or `@domain`, case-insensitive. + */ +export function allowlistTransport( + allowlist: readonly string[], + real: EmailTransport, + fallback: EmailTransport +): EmailTransport { + const entries = allowlist.map((e) => e.trim().toLowerCase()).filter(Boolean) + const allowed = (to: string) => { + const address = to.toLowerCase() + return entries.some((e) => (e.startsWith("@") ? address.endsWith(e) : address === e)) + } + let last: EmailTransport | null = null + return { + send: (email) => { + last = allowed(email.to) ? real : fallback + return last.send(email) + }, + reachedEnvelope: () => last?.reachedEnvelope?.() ?? true, + close: () => { + real.close?.() + fallback.close?.() + }, + abort: () => { + real.abort?.() + fallback.abort?.() + }, + } +} diff --git a/apps/web/src/server/email/outbox.test.ts b/apps/web/src/server/email/outbox.test.ts new file mode 100644 index 00000000..df610985 --- /dev/null +++ b/apps/web/src/server/email/outbox.test.ts @@ -0,0 +1,337 @@ +import { beforeEach, describe, expect, it, vi } from "vitest" + +import { fakeDb, op, type Call, type Handler } from "@/test/fake-db" + +import { + CLAIM_BATCH, + COMPLETE_TRIES, + RPC_TIMEOUT_MS, + RUN_LIMIT_MS, + SEND_DEADLINE_MS, + SEND_TIMEOUT_MS, + sendDueEmails, +} from "./outbox" +import type { EmailTransport, OutgoingEmail, SendResult } from "./transport" + +const OPTIONS = { origin: "https://give.vn", from: "Give ", replyTo: "hi@give.vn" } +const UNSUB = "77777777-7777-4777-8777-777777777777" + +function row(n: number, overrides: Record = {}) { + return { + id: `00000000-0000-4000-8000-${String(n).padStart(12, "0")}`, + kind: "campaign_approved", + category: "transactional", + to_email: `org${n}@example.com`, + payload: { campaign_id: "22222222-2222-4222-8222-222222222222", campaign_title: "Nước sạch" }, + attempt: 1, + idempotency_key: `campaign_status_event:${n}`, + unsubscribe_token: null, + reference_code: null, + tracking_token: null, + ...overrides, + } +} + +let calls: Call[] +let claims: unknown[][] +let completeStatus: string +let sent: OutgoingEmail[] +let result: SendResult | Error + +const transport: EmailTransport = { + close: vi.fn(), + send: vi.fn(async (email: OutgoingEmail) => { + sent.push(email) + if (result instanceof Error) throw result + return result + }), +} + +const handler: Handler = (call) => { + if (call.target === "rpc:claim_outbox") return { data: claims.shift() ?? [] } + if (call.target === "rpc:complete_outbox") return { data: completeStatus } + if (call.target === "rpc:release_outbox") return { data: true } + return undefined +} + +beforeEach(() => { + calls = [] + claims = [] + sent = [] + completeStatus = "sent" + result = { ok: true, messageId: "ses-1" } + vi.spyOn(console, "error").mockImplementation(() => {}) + vi.spyOn(console, "warn").mockImplementation(() => {}) +}) + +const completes = () => calls.filter((c) => c.target === "rpc:complete_outbox").map((c) => op(c, "args")?.[0]) + +describe("sendDueEmails", () => { + it("sends each leased row and records the result for that attempt", async () => { + claims = [[row(1)]] + const outcome = await sendDueEmails(fakeDb(handler, calls) as never, transport, OPTIONS) + + expect(outcome).toEqual({ claimed: 1, sent: 1, retrying: 0, dead: 0, stale: 0, released: 0 }) + expect(op(calls[0], "args")).toEqual([{ p_limit: CLAIM_BATCH }]) + expect(sent[0]).toMatchObject({ + from: OPTIONS.from, + replyTo: "hi@give.vn", + to: "org1@example.com", + subject: "Chiến dịch “Nước sạch” đã được duyệt", + idempotencyKey: "campaign_status_event:1", + }) + expect(sent[0].headers["Message-ID"]).toBe(``) + expect(sent[0].headers["X-Give-Outbox-Id"]).toBe(row(1).id) + expect(sent[0].headers["List-Unsubscribe"]).toBeUndefined() + expect(completes()).toEqual([ + { + p_id: row(1).id, + p_attempt: 1, + p_ok: true, + p_error: null, + p_provider_message_id: "ses-1", + p_permanent: false, + p_outcome_unknown: false, + }, + ]) + }) + + it("adds one-click unsubscribe headers to notification emails", async () => { + claims = [ + [ + row(2, { + kind: "campaign_ended", + category: "notification", + unsubscribe_token: UNSUB, + payload: { campaign_title: "Nước sạch", to_status: "closed", raised_amount: 10 }, + }), + ], + ] + await sendDueEmails(fakeDb(handler, calls) as never, transport, OPTIONS) + expect(sent[0].headers["List-Unsubscribe"]).toBe(``) + expect(sent[0].headers["List-Unsubscribe-Post"]).toBe("List-Unsubscribe=One-Click") + }) + + it("reports a failure without the recipient's address, as permanent only when the provider says so", async () => { + claims = [[row(3, { attempt: 4 })]] + result = { ok: false, permanent: true, error: "SMTP 550: mailbox unavailable" } + completeStatus = "dead" + const outcome = await sendDueEmails(fakeDb(handler, calls) as never, transport, OPTIONS) + expect(outcome.dead).toBe(1) + expect(completes()[0]).toMatchObject({ + p_attempt: 4, + p_ok: false, + p_permanent: true, + p_error: "SMTP 550: <[recipient]> mailbox unavailable", + }) + }) + + it("retries when the transport throws", async () => { + claims = [[row(4)]] + result = new Error("connect ETIMEDOUT") + completeStatus = "pending" + const outcome = await sendDueEmails(fakeDb(handler, calls) as never, transport, OPTIONS) + expect(outcome.retrying).toBe(1) + expect(completes()[0]).toMatchObject({ p_ok: false, p_permanent: false, p_error: "connect ETIMEDOUT" }) + }) + + it("marks a row that cannot be rendered dead without sending it", async () => { + claims = [[row(5, { kind: "marketing" })]] + completeStatus = "dead" + await sendDueEmails(fakeDb(handler, calls) as never, transport, OPTIONS) + expect(sent).toHaveLength(0) + expect(completes()[0]).toMatchObject({ p_ok: false, p_permanent: true, p_error: "render: unknown_kind:marketing" }) + }) + + it("tries again to record a result, then leaves the row to its lease and keeps going", async () => { + vi.useFakeTimers() + try { + claims = [[row(6), row(7), row(9)]] + const failing = new Set([row(6).id]) + let flaky = 0 + const db = fakeDb((call) => { + if (call.target === "rpc:complete_outbox") { + const id = (op(call, "args")?.[0] as { p_id: string }).p_id + if (failing.has(id)) return { error: { code: "57014", message: "timeout" } } + if (id === row(9).id && flaky++ === 0) return { error: { code: "08006", message: "reset" } } + return { data: id === row(7).id ? "stale" : "sent" } + } + return handler(call) + }, calls) + const run = sendDueEmails(db as never, transport, OPTIONS) + await vi.runAllTimersAsync() + const outcome = await run + expect(outcome).toEqual({ claimed: 3, sent: 1, retrying: 0, dead: 0, stale: 1, released: 0 }) + expect(sent).toHaveLength(3) + const tries = (id: string) => completes().filter((a) => (a as { p_id: string }).p_id === id).length + expect(tries(row(6).id)).toBe(COMPLETE_TRIES) + expect(tries(row(9).id)).toBe(2) + } finally { + vi.useRealTimers() + } + }) + + it("a send that timed out before MAIL FROM is a plain failure, not outcome unknown", async () => { + vi.useFakeTimers() + try { + const early: EmailTransport = { + send: () => new Promise(() => {}), + close: vi.fn(), + abort: vi.fn(), + reachedEnvelope: () => false, + } + claims = [[row(94)]] + completeStatus = "pending" + const run = sendDueEmails(fakeDb(handler, calls) as never, early, { ...OPTIONS, now: () => 0 }) + await vi.advanceTimersByTimeAsync(SEND_TIMEOUT_MS) + await run + expect(completes()[0]).toMatchObject({ + p_outcome_unknown: false, + p_error: "send_timeout: before the message was sent", + }) + expect(early.abort).toHaveBeenCalled() + } finally { + vi.useRealTimers() + } + }) + + it("does not retry an error a second try cannot fix", async () => { + claims = [[row(90)]] + const db = fakeDb((call) => { + if (call.target === "rpc:complete_outbox") return { error: { code: "P0002", message: "GIVE_OUTBOX_NOT_FOUND" } } + return handler(call) + }, calls) + const outcome = await sendDueEmails(db as never, transport, OPTIONS) + expect(outcome).toMatchObject({ sent: 0, stale: 0 }) + expect(completes()).toHaveLength(1) + }) + + it("reads the row when a retry finds its earlier try already recorded", async () => { + vi.useFakeTimers() + try { + claims = [[row(91)]] + let n = 0 + const db = fakeDb((call) => { + if (call.target === "rpc:complete_outbox") { + n += 1 + return n === 1 ? { error: { code: "", message: "TypeError: fetch failed" } } : { data: "stale" } + } + if (call.target === "outbox") return { data: { status: "sent", attempts: 1 } } + return handler(call) + }, calls) + const run = sendDueEmails(db as never, transport, OPTIONS) + await vi.runAllTimersAsync() + expect(await run).toMatchObject({ sent: 1, stale: 0 }) + } finally { + vi.useRealTimers() + } + }) + + it("near the function limit, neither retries a result nor releases rows it has no time for", async () => { + vi.useFakeTimers() + try { + const late: EmailTransport = { send: () => new Promise(() => {}), close: vi.fn(), abort: vi.fn() } + claims = [[row(92), row(93)]] + const db = fakeDb((call) => { + if (call.target === "rpc:complete_outbox") return { error: { code: "57014", message: "timeout" } } + return handler(call) + }, calls) + // The send starts in time; after its timeout the clock reads 1 s short of the limit. + let t = 0 + const run = sendDueEmails(db as never, late, { ...OPTIONS, now: () => t }) + t = 0 + await vi.advanceTimersByTimeAsync(1) + t = RUN_LIMIT_MS - RPC_TIMEOUT_MS + 1 + await vi.advanceTimersByTimeAsync(SEND_TIMEOUT_MS) + const outcome = await run + expect(completes()).toHaveLength(1) + expect(calls.filter((c) => c.target === "rpc:release_outbox")).toHaveLength(0) + expect(outcome).toMatchObject({ claimed: 2, released: 0 }) + } finally { + vi.useRealTimers() + } + }) + + it("claims again while batches come back full, and stops at the time budget", async () => { + claims = [Array.from({ length: CLAIM_BATCH }, (_, i) => row(10 + i)), [row(30)]] + const outcome = await sendDueEmails(fakeDb(handler, calls) as never, transport, OPTIONS) + expect(outcome.claimed).toBe(CLAIM_BATCH + 1) + + calls = [] + claims = [Array.from({ length: CLAIM_BATCH }, (_, i) => row(40 + i)), [row(60)]] + const clock = [0, 0, 1000] + const capped = await sendDueEmails(fakeDb(handler, calls) as never, transport, { + ...OPTIONS, + budgetMs: 100, + now: () => clock.shift() ?? 1000, + }) + expect(capped.claimed).toBe(CLAIM_BATCH) + expect(calls.filter((c) => c.target === "rpc:claim_outbox")).toHaveLength(1) + }) + + it("throws when the first claim fails", async () => { + const db = fakeDb(() => ({ error: { code: "42501", message: "denied" } }), calls) + await expect(sendDueEmails(db as never, transport, OPTIONS)).rejects.toMatchObject({ code: "42501" }) + }) + + it("skips a malformed row", async () => { + claims = [[{ id: "x" }, row(8)]] + const outcome = await sendDueEmails(fakeDb(handler, calls) as never, transport, OPTIONS) + expect(outcome.sent).toBe(1) + expect(sent).toHaveLength(1) + }) + + it("gives back the rows it cannot send before its deadline, and closes the transport", async () => { + vi.mocked(transport.close!).mockClear() + claims = [[row(70), row(71, { attempt: 3 }), row(72)]] + // started at 0; the first send starts at 0, the second would start too late. + const clock = [0, 0, 0, SEND_DEADLINE_MS - SEND_TIMEOUT_MS + 1] + const outcome = await sendDueEmails(fakeDb(handler, calls) as never, transport, { + ...OPTIONS, + now: () => clock.shift() ?? SEND_DEADLINE_MS, + }) + expect(outcome).toMatchObject({ claimed: 3, sent: 1, released: 2 }) + expect(sent.map((e) => e.to)).toEqual(["org70@example.com"]) + expect(calls.filter((c) => c.target === "rpc:release_outbox").map((c) => op(c, "args")?.[0])).toEqual([ + { p_id: row(71).id, p_attempt: 3 }, + { p_id: row(72).id, p_attempt: 1 }, + ]) + expect(transport.close).toHaveBeenCalledTimes(1) + }) + + it("after a send times out: cuts the connection first, records outcome unknown, gives back the rest", async () => { + vi.useFakeTimers() + try { + const order: string[] = [] + const stuck: EmailTransport = { + send: () => new Promise(() => {}), + close: vi.fn(), + abort: vi.fn(() => { + order.push("abort") + }), + } + claims = [[row(80), row(81)]] + completeStatus = "pending" + const db = fakeDb((call) => { + if (call.target === "rpc:complete_outbox") order.push("complete") + return handler(call) + }, calls) + const run = sendDueEmails(db as never, stuck, { ...OPTIONS, now: () => 0 }) + await vi.advanceTimersByTimeAsync(SEND_TIMEOUT_MS) + const outcome = await run + expect(outcome).toMatchObject({ claimed: 2, retrying: 1, released: 1 }) + expect(order).toEqual(["abort", "complete"]) + expect(completes()[0]).toMatchObject({ + p_id: row(80).id, + p_ok: false, + p_permanent: false, + p_outcome_unknown: true, + p_error: expect.stringMatching(/^send_timeout: outcome unknown/), + }) + expect(calls.filter((c) => c.target === "rpc:claim_outbox")).toHaveLength(1) + expect(stuck.close).toHaveBeenCalled() + } finally { + vi.useRealTimers() + } + }) +}) diff --git a/apps/web/src/server/email/outbox.ts b/apps/web/src/server/email/outbox.ts new file mode 100644 index 00000000..0a754544 --- /dev/null +++ b/apps/web/src/server/email/outbox.ts @@ -0,0 +1,322 @@ +import "server-only" + +import type { Db } from "@/lib/campaigns" + +import { EmailRenderError, isEmailKind, renderEmail, type OutboxEmail } from "./templates" +import type { EmailTransport, OutgoingEmail } from "./transport" + +/** + * The send-outbox job (DOS/Give#254, design 5.3): leases due rows with + * give.claim_outbox, renders and sends each, and records the result with + * give.complete_outbox, which retries with backoff and marks a row dead + * after its last attempt. A row is leased for 5 minutes, so a run that dies + * mid-send leaves it to the next run, never to two runs at once. + * + * Delivery is at least once, not exactly once. Enqueueing is exactly once + * (one row per event), but a row is sent again when the provider took the + * message and its answer never reached us: a send that timed out, or lost + * its connection after MAIL FROM before the provider answered (recorded as outcome unknown + * and retried only after an hour or more), or a result + * that could not be recorded (complete_outbox is retried a few times, then + * the lease runs out and the next run sends the row again). The recipient + * may then get the same email twice. + */ + +/** Rows leased per claim; small, so a slow provider leaves few rows waiting on their lease. */ +export const CLAIM_BATCH = 10 +/** Stop claiming after this long. */ +export const RUN_BUDGET_MS = 30_000 +/** + * One send may take this long. Then its connection is cut off and the + * attempt is recorded as outcome unknown: the provider may have accepted the + * message just before. + */ +export const SEND_TIMEOUT_MS = 15_000 +/** Tries at recording one result before leaving the row to its lease. */ +export const COMPLETE_TRIES = 3 +const COMPLETE_RETRY_MS = [250, 1_000] +/** Each RPC after a send (complete, release) is abandoned after this long. */ +export const RPC_TIMEOUT_MS = 5_000 +/** A claim is abandoned after this long (it may wait on locks while it settles rows). */ +export const CLAIM_TIMEOUT_MS = 10_000 +/** + * No retry or release starts unless it can finish by this point, under the + * 60 s function limit: a run killed mid-batch loses its results and leaves + * the rest of its rows to their 5-minute lease. A send ends by + * SEND_DEADLINE_MS, its first complete_outbox by 50 s. + */ +export const RUN_LIMIT_MS = 55_000 +/** + * No send starts unless it can time out by this point, well inside the 60 s + * function limit (route maxDuration). Rows the run cannot reach in time are + * given back uncounted (give.release_outbox) instead of waiting out their + * 5-minute lease and spending an attempt. + */ +export const SEND_DEADLINE_MS = 45_000 + +export interface OutboxRunResult { + claimed: number + sent: number + retrying: number + dead: number + stale: number + /** Leased rows given back for the next run. */ + released: number +} + +export interface OutboxRunOptions { + origin: string + from: string + replyTo?: string + now?: () => number + budgetMs?: number +} + +function parseRow(value: unknown): OutboxEmail | null { + if (!value || typeof value !== "object") return null + const row = value as Record + if (typeof row.id !== "string" || typeof row.kind !== "string" || typeof row.to_email !== "string") return null + if (typeof row.attempt !== "number" || !Number.isInteger(row.attempt) || row.attempt < 1) return null + if (row.category !== "transactional" && row.category !== "notification") return null + return { + id: row.id, + kind: row.kind, + category: row.category, + to_email: row.to_email, + payload: row.payload && typeof row.payload === "object" ? (row.payload as Record) : null, + attempt: row.attempt, + idempotency_key: typeof row.idempotency_key === "string" ? row.idempotency_key : row.id, + unsubscribe_token: typeof row.unsubscribe_token === "string" ? row.unsubscribe_token : null, + reference_code: typeof row.reference_code === "string" ? row.reference_code : null, + tracking_token: typeof row.tracking_token === "string" ? row.tracking_token : null, + } +} + +/** The domain of the From address, for a stable Message-ID. */ +function senderDomain(from: string): string { + const match = /@([A-Za-z0-9.-]+)>?\s*$/.exec(from) + return match?.[1]?.toLowerCase() ?? "give.vn" +} + +export function outgoingEmail(row: OutboxEmail, options: OutboxRunOptions): OutgoingEmail { + const rendered = renderEmail(row, options.origin) + const headers: Record = { + // Our Message-ID for the row. SES replaces it with its own on the way + // out, so it does not let mail clients drop a resend; X-Give-Outbox-Id + // is the header that survives and ties a delivered email to its row. + "Message-ID": ``, + "X-Give-Outbox-Id": row.id, + "Auto-Submitted": "auto-generated", + } + if (rendered.oneClickUnsubscribeUrl) { + headers["List-Unsubscribe"] = `<${rendered.oneClickUnsubscribeUrl}>` + headers["List-Unsubscribe-Post"] = "List-Unsubscribe=One-Click" + } + return { + from: options.from, + replyTo: options.replyTo, + to: row.to_email, + subject: rendered.subject, + text: rendered.text, + html: rendered.html, + headers, + idempotencyKey: row.idempotency_key, + } +} + +function withTimeout(promise: Promise, ms: number): Promise { + let timer: ReturnType | undefined + const timeout = new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error("send_timeout")), ms) + }) + return Promise.race([promise, timeout]).finally(() => clearTimeout(timer)) +} + +/** Error text kept on the row: short, and never the recipient's address. */ +function errorText(error: string, row: OutboxEmail): string { + return error.replaceAll(row.to_email, "[recipient]").slice(0, 300) +} + +type Result = + { ok: true; messageId: string | null } | { ok: false; permanent: boolean; error: string; outcomeUnknown?: boolean } + +const pause = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)) + +/** The run's clock: whether another RPC (after `wait` ms) still fits before RUN_LIMIT_MS. */ +interface Clock { + now: () => number + started: number +} +const fits = (clock: Clock, wait = 0) => clock.now() - clock.started + wait + RPC_TIMEOUT_MS <= RUN_LIMIT_MS + +/** + * Errors a second try cannot fix: bad data, constraints, permissions, an + * exception the function raised (GIVE_OUTBOX_NOT_FOUND), a request + * PostgREST refused. Everything else (network, timeout, abort, connection, + * serialization, server overload) is worth another try. + */ +function isTransient(error: { code?: string }): boolean { + return !/^(22|23|42|P0|PGRST1|PGRST2)/.test(error.code ?? "") +} + +async function complete(db: Db, row: OutboxEmail, result: Result, clock: Clock): Promise { + const args = { + p_id: row.id, + p_attempt: row.attempt, + p_ok: result.ok, + p_error: result.ok ? null : errorText(result.error, row), + p_provider_message_id: result.ok ? result.messageId : null, + p_permanent: result.ok ? false : result.permanent, + p_outcome_unknown: result.ok ? false : result.outcomeUnknown === true, + } + for (let tryNo = 1; ; tryNo++) { + const { data, error } = await db.rpc("complete_outbox", args).abortSignal(AbortSignal.timeout(RPC_TIMEOUT_MS)) + if (!error) { + // 'stale' on a later try: an earlier try may have committed and only + // its answer was lost. The row says what that try recorded. + if (data === "stale" && tryNo > 1) return (fits(clock) ? await recorded(db, row) : null) ?? "stale" + return typeof data === "string" ? data : null + } + console.error("complete_outbox failed", row.id, tryNo, error.code, error.message) + const wait = COMPLETE_RETRY_MS[tryNo - 1] ?? 1_000 + if (tryNo >= COMPLETE_TRIES || !isTransient(error) || !fits(clock, wait)) break + await pause(wait) + } + // The lease runs out and the next run takes the row again: a sent email + // goes out a second time. + return null +} + +/** The status this attempt left on the row, if it is settled. */ +async function recorded(db: Db, row: OutboxEmail): Promise { + const { data } = await db + .from("outbox") + .select("status, attempts") + .eq("id", row.id) + .abortSignal(AbortSignal.timeout(RPC_TIMEOUT_MS)) + .maybeSingle() + const settled = data as { status?: unknown; attempts?: unknown } | null + if (settled?.attempts !== row.attempt) return null + return settled.status === "sent" || settled.status === "pending" || settled.status === "dead" ? settled.status : null +} + +type SendOutcome = { status: string | null; timedOut: boolean } + +async function sendOne( + db: Db, + transport: EmailTransport, + row: OutboxEmail, + options: OutboxRunOptions, + clock: Clock +): Promise { + let email: OutgoingEmail + try { + if (!isEmailKind(row.kind)) throw new EmailRenderError(`unknown_kind:${row.kind.slice(0, 40)}`) + email = outgoingEmail(row, options) + } catch (error) { + const reason = error instanceof EmailRenderError ? error.message : "render_failed" + console.error("outbox email could not be rendered", row.id, row.kind, reason) + return { + status: await complete(db, row, { ok: false, permanent: true, error: `render: ${reason}` }, clock), + timedOut: false, + } + } + let result: Result + let timedOut = false + try { + result = await withTimeout(transport.send(email), SEND_TIMEOUT_MS) + } catch (error) { + timedOut = error instanceof Error && error.message === "send_timeout" + if (timedOut) { + // Cut the connection now, before recording anything, so a message + // still in flight cannot land after the failure is on the row. + transport.abort?.() + result = + (transport.reachedEnvelope?.() ?? true) + ? { + ok: false, + permanent: false, + outcomeUnknown: true, + error: "send_timeout: outcome unknown, the provider may have accepted it", + } + : { ok: false, permanent: false, error: "send_timeout: before the message was sent" } + } else { + result = { ok: false, permanent: false, error: error instanceof Error ? error.message : "send_failed" } + } + } + if (!result.ok) console.warn("outbox send failed", row.id, row.kind, result.permanent ? "permanent" : "retry") + return { status: await complete(db, row, result, clock), timedOut } +} + +/** Gives rows back while time allows; the rest wait out their lease. */ +async function release(db: Db, rows: OutboxEmail[], clock: Clock): Promise { + let released = 0 + for (const row of rows) { + if (!fits(clock)) break + const { data, error } = await db + .rpc("release_outbox", { p_id: row.id, p_attempt: row.attempt }) + .abortSignal(AbortSignal.timeout(RPC_TIMEOUT_MS)) + if (error) console.error("release_outbox failed", row.id, error.code, error.message) + else if (data === true) released += 1 + } + return released +} + +/** + * One send-outbox run. Throws only when the first claim fails. After a send + * times out its connection is cut off (transport.abort), the attempt is + * recorded as outcome unknown, and the run stops and gives back the rest of + * its batch: the provider may be stuck. + */ +export async function sendDueEmails( + db: Db, + transport: EmailTransport, + options: OutboxRunOptions +): Promise { + const now = options.now ?? Date.now + const started = now() + const clock: Clock = { now, started } + const budget = options.budgetMs ?? RUN_BUDGET_MS + const result: OutboxRunResult = { claimed: 0, sent: 0, retrying: 0, dead: 0, stale: 0, released: 0 } + + try { + run: while (now() - started < budget) { + const { data, error } = await db + .rpc("claim_outbox", { p_limit: CLAIM_BATCH }) + .abortSignal(AbortSignal.timeout(CLAIM_TIMEOUT_MS)) + if (error) { + if (result.claimed === 0) throw error + console.error("claim_outbox failed", error.code, error.message) + break + } + const raws = Array.isArray(data) ? data : [] + if (raws.length === 0) break + result.claimed += raws.length + const rows: OutboxEmail[] = [] + for (const raw of raws) { + const row = parseRow(raw) + if (row) rows.push(row) + else console.error("claim_outbox returned an unexpected row") + } + for (let i = 0; i < rows.length; i++) { + if (now() - started + SEND_TIMEOUT_MS > SEND_DEADLINE_MS) { + result.released += await release(db, rows.slice(i), clock) + break run + } + const { status, timedOut } = await sendOne(db, transport, rows[i], options, clock) + if (status === "sent") result.sent += 1 + else if (status === "pending") result.retrying += 1 + else if (status === "dead") result.dead += 1 + else if (status === "stale") result.stale += 1 + if (timedOut) { + result.released += await release(db, rows.slice(i + 1), clock) + break run + } + } + if (raws.length < CLAIM_BATCH) break + } + } finally { + transport.close?.() + } + return result +} diff --git a/apps/web/src/server/email/provider.test.ts b/apps/web/src/server/email/provider.test.ts new file mode 100644 index 00000000..afa15e3a --- /dev/null +++ b/apps/web/src/server/email/provider.test.ts @@ -0,0 +1,165 @@ +import { describe, expect, it, vi } from "vitest" + +import type { OutgoingEmail } from "./transport" + +const smtp = vi.hoisted(() => ({ + configs: [] as unknown[], + send: vi.fn(async (_email: unknown) => ({ ok: true, messageId: "ses" })), +})) + +vi.mock("./smtp", () => ({ + createSmtpTransport: (config: unknown) => { + smtp.configs.push(config) + return { send: smtp.send } + }, +})) + +const { emailDelivery, emailLinkOrigin, emailSettingsFromEnv, isSenderAddress, usesProductionDatabase } = + await import("./provider") + +const CREDS = { SMTP_USER: "AKIAEXAMPLE", SMTP_PASS: "not-a-real-password" } +const BETA = { VERCEL_ENV: "preview", EMAIL_LINK_ORIGIN: "https://beta.give.vn/some/path" } +const PROD = { VERCEL_ENV: "production" } + +function message(to: string): OutgoingEmail { + return { from: "x@give.vn", to, subject: "s", text: "t", html: "h", headers: {}, idempotencyKey: "k" } +} + +describe("emailDelivery", () => { + it("sends real mail by default in Production only", () => { + expect(emailDelivery(PROD)).toBe("smtp") + expect(emailDelivery({ VERCEL_ENV: "preview" })).toBe("log") + expect(emailDelivery({})).toBe("log") + expect(emailDelivery({ VERCEL_ENV: "preview", EMAIL_DELIVERY: "SMTP" })).toBe("smtp") + expect(emailDelivery({ ...PROD, EMAIL_DELIVERY: "log" })).toBe("log") + }) +}) + +describe("emailSettingsFromEnv", () => { + it("mails nobody on beta by default, with Give's own sender and no Reply-To", async () => { + smtp.configs.length = 0 + smtp.send.mockClear() + const settings = emailSettingsFromEnv({ ...BETA, ...CREDS }) + expect(settings).toMatchObject({ + ok: true, + delivery: "log", + options: { origin: "https://beta.give.vn", from: "Give " }, + }) + if (!settings.ok) return + expect(settings.options).not.toHaveProperty("replyTo") + expect(smtp.configs).toHaveLength(0) + expect(await settings.transport.send(message("mai@example.com"))).toMatchObject({ ok: true }) + expect(smtp.send).not.toHaveBeenCalled() + }) + + it("outside Production, real sending reaches the allowlist only", async () => { + smtp.send.mockClear() + const settings = emailSettingsFromEnv({ + ...BETA, + ...CREDS, + EMAIL_DELIVERY: "smtp", + EMAIL_ALLOWLIST: " qa@give.vn, @team.give.vn ", + }) + expect(settings.ok).toBe(true) + if (!settings.ok) return + await settings.transport.send(message("QA@give.vn")) + await settings.transport.send(message("lan@team.give.vn")) + await settings.transport.send(message("mai@example.com")) + expect(smtp.send.mock.calls.map(([m]) => (m as OutgoingEmail).to)).toEqual(["QA@give.vn", "lan@team.give.vn"]) + }) + + it("in Production sends through SES with the default endpoint", async () => { + smtp.configs.length = 0 + smtp.send.mockClear() + const settings = emailSettingsFromEnv({ ...PROD, ...CREDS }) + expect(settings).toMatchObject({ ok: true, delivery: "smtp", options: { origin: "https://give.vn" } }) + expect(smtp.configs).toEqual([ + { host: "email-smtp.ap-southeast-1.amazonaws.com", port: 587, user: "AKIAEXAMPLE", pass: "not-a-real-password" }, + ]) + if (settings.ok) await settings.transport.send(message("mai@example.com")) + expect(smtp.send).toHaveBeenCalledTimes(1) + }) + + it("in Production without credentials is off, so emails wait instead of being marked sent", () => { + expect(emailSettingsFromEnv(PROD)).toEqual({ ok: false, missing: ["SMTP_USER", "SMTP_PASS"] }) + }) + + it("in Production refuses the log transport, which would mark every real email sent", () => { + expect(emailSettingsFromEnv({ ...PROD, ...CREDS, EMAIL_DELIVERY: "log" })).toEqual({ + ok: false, + missing: ["EMAIL_DELIVERY_LOG_IN_PRODUCTION"], + }) + }) + + it("refuses a sender with a line break, a bad port, and a missing link origin", () => { + expect(emailSettingsFromEnv({ ...BETA, EMAIL_FROM: "Give \r\nBcc: x@y.z" })).toMatchObject({ + ok: false, + missing: ["EMAIL_FROM"], + }) + expect(emailSettingsFromEnv({ ...PROD, ...CREDS, SMTP_PORT: "smtp" })).toMatchObject({ + ok: false, + missing: ["SMTP_PORT"], + }) + expect(emailSettingsFromEnv({ VERCEL_ENV: "preview" })).toEqual({ ok: false, missing: ["EMAIL_LINK_ORIGIN"] }) + expect(isSenderAddress("Give")).toBe(false) + expect(isSenderAddress("no-reply@give.vn")).toBe(true) + }) +}) + +describe("emailLinkOrigin", () => { + it("prefers EMAIL_LINK_ORIGIN, then the site URL, then give.vn in Production only", () => { + expect(emailLinkOrigin({ EMAIL_LINK_ORIGIN: "https://beta.give.vn", NEXT_PUBLIC_SITE_URL: "https://x.test" })).toBe( + "https://beta.give.vn" + ) + expect(emailLinkOrigin({ NEXT_PUBLIC_SITE_URL: "https://give.vn/" })).toBe("https://give.vn") + expect(emailLinkOrigin(PROD)).toBe("https://give.vn") + expect(emailLinkOrigin({ VERCEL_ENV: "preview" })).toBeNull() + }) + + it("in Production refuses a link origin that is not https", () => { + expect(emailLinkOrigin({ ...PROD, EMAIL_LINK_ORIGIN: "http://give.vn" })).toBeNull() + expect(emailLinkOrigin({ ...PROD, NEXT_PUBLIC_SITE_URL: "http://give.vn" })).toBeNull() + expect(emailLinkOrigin({ ...PROD, EMAIL_LINK_ORIGIN: "https://give.vn/x" })).toBe("https://give.vn") + expect(emailLinkOrigin({ VERCEL_ENV: "preview", EMAIL_LINK_ORIGIN: "http://localhost:3000" })).toBe( + "http://localhost:3000" + ) + expect(emailSettingsFromEnv({ ...PROD, ...CREDS, NEXT_PUBLIC_SITE_URL: "http://give.vn" })).toEqual({ + ok: false, + missing: ["EMAIL_LINK_ORIGIN"], + }) + }) +}) + +describe("a deployment outside Production on the Production database", () => { + it("claims nothing, so it never marks real people's emails sent", () => { + const prodDb = { NEXT_PUBLIC_SUPABASE_URL: "https://gulptwduchsjcsbndmua.supabase.co" } + expect(emailSettingsFromEnv({ ...BETA, ...prodDb })).toEqual({ + ok: false, + missing: ["NON_PRODUCTION_DEPLOYMENT_ON_PRODUCTION_DATABASE"], + }) + expect(emailSettingsFromEnv({ ...prodDb, EMAIL_LINK_ORIGIN: "http://localhost:3000" })).toMatchObject({ ok: false }) + expect(emailSettingsFromEnv({ ...PROD, ...CREDS, ...prodDb })).toMatchObject({ ok: true }) + expect( + emailSettingsFromEnv({ ...BETA, NEXT_PUBLIC_SUPABASE_URL: "https://oyajkbadsykigtfrpdpg.supabase.co" }) + ).toMatchObject({ + ok: true, + }) + }) + + it("knows the Production database by its vanity domain too", () => { + for (const url of [ + "https://dos.supabase.co", + "https://dos.supabase.co.", + "https://DOS.supabase.co/", + "https://gulptwduchsjcsbndmua.supabase.co", + ]) { + expect(usesProductionDatabase({ NEXT_PUBLIC_SUPABASE_URL: url }), url).toBe(true) + } + expect(usesProductionDatabase({ NEXT_PUBLIC_SUPABASE_URL: "https://oyajkbadsykigtfrpdpg.supabase.co" })).toBe(false) + expect(usesProductionDatabase({ NEXT_PUBLIC_SUPABASE_URL: "http://127.0.0.1:54321" })).toBe(false) + expect(emailSettingsFromEnv({ ...BETA, NEXT_PUBLIC_SUPABASE_URL: "https://dos.supabase.co" })).toMatchObject({ + ok: false, + missing: ["NON_PRODUCTION_DEPLOYMENT_ON_PRODUCTION_DATABASE"], + }) + }) +}) diff --git a/apps/web/src/server/email/provider.ts b/apps/web/src/server/email/provider.ts new file mode 100644 index 00000000..3c919e29 --- /dev/null +++ b/apps/web/src/server/email/provider.ts @@ -0,0 +1,123 @@ +import "server-only" + +import { siteOrigin } from "@/lib/auth/origin" + +import { allowlistTransport, createLogTransport } from "./log-transport" +import type { OutboxRunOptions } from "./outbox" +import { createSmtpTransport } from "./smtp" +import type { EmailTransport } from "./transport" + +/** + * Email settings from the environment (DOS/Give#254). Give reuses DOS.Me's + * provider, AWS SES (ap-southeast-1), over SMTP, with its own sender. + * Server-only variables: + * + * - EMAIL_DELIVERY: `smtp` sends real mail; `log` mails nobody (log + * transport). Production defaults to `smtp` and refuses `log` (it would + * mark every real email sent); everything else (beta, previews, local) + * defaults to `log`. + * - EMAIL_ALLOWLIST: outside Production, `smtp` reaches only these + * recipients (comma-separated addresses or `@domain`); everyone else gets + * the log transport. With no allowlist outside Production, nobody is mailed. + * - SMTP_USER, SMTP_PASS: SES SMTP credentials (secrets; owner step). + * - SMTP_HOST, SMTP_PORT: default email-smtp.ap-southeast-1.amazonaws.com:587. + * - EMAIL_FROM: default `Give ` (give.vn verified in SES). + * - EMAIL_LINK_ORIGIN: origin of the links in emails, e.g. https://beta.give.vn + * on beta. Defaults to NEXT_PUBLIC_SITE_URL, then https://give.vn in + * Production. In Production a link origin that is set must be https. + * + * When the settings are not usable the job claims nothing, so queued emails + * wait instead of being marked sent: Production with missing credentials or + * with `log`, and a deployment outside Production that points at the + * Production database. + */ + +export const DEFAULT_SMTP_HOST = "email-smtp.ap-southeast-1.amazonaws.com" +export const DEFAULT_SMTP_PORT = 587 +export const DEFAULT_EMAIL_FROM = "Give " +const PRODUCTION_ORIGIN = "https://give.vn" +/** The Production DOS Supabase project (the shared `dos` project). */ +export const PRODUCTION_SUPABASE_REF = "gulptwduchsjcsbndmua" +/** Every hostname that reaches it: the project's own and its vanity domain. */ +export const PRODUCTION_SUPABASE_HOSTS: readonly string[] = [ + `${PRODUCTION_SUPABASE_REF}.supabase.co`, + "dos.supabase.co", +] + +type Env = Record + +export type EmailDelivery = "smtp" | "log" + +export type EmailSettings = + | { ok: true; delivery: EmailDelivery; transport: EmailTransport; options: OutboxRunOptions } + | { ok: false; missing: string[] } + +/** `Name ` or `local@domain`, on one line. */ +export function isSenderAddress(value: string): boolean { + if (/[\u0000-\u001f\u007f]/.test(value) || value.length > 200) return false + return /^(?:[^<>@]*<[^<>@\s]+@[^<>@\s]+\.[^<>@\s]+>|[^<>@\s]+@[^<>@\s]+\.[^<>@\s]+)$/.test(value.trim()) +} + +export function emailLinkOrigin(env: Env = process.env): string | null { + const production = env.VERCEL_ENV === "production" + for (const value of [env.EMAIL_LINK_ORIGIN, env.NEXT_PUBLIC_SITE_URL]) { + if (!value?.trim()) continue + const origin = siteOrigin(value.trim()) + if (origin && (!production || origin.startsWith("https://"))) return origin + // In Production a set origin that is not https is refused, not skipped: + // links in real emails must not go out over plain http. + if (production) return null + } + return production ? PRODUCTION_ORIGIN : null +} + +export function usesProductionDatabase(env: Env = process.env): boolean { + let host: string + try { + // A trailing dot (fully qualified name) reaches the same host. + host = new URL(env.NEXT_PUBLIC_SUPABASE_URL ?? "").hostname.toLowerCase().replace(/\.+$/, "") + } catch { + return false + } + return PRODUCTION_SUPABASE_HOSTS.includes(host) || host.split(".")[0] === PRODUCTION_SUPABASE_REF +} + +export function emailDelivery(env: Env = process.env): EmailDelivery { + const value = env.EMAIL_DELIVERY?.trim().toLowerCase() + if (value === "smtp" || value === "log") return value + return env.VERCEL_ENV === "production" ? "smtp" : "log" +} + +export function emailSettingsFromEnv(env: Env = process.env): EmailSettings { + const missing: string[] = [] + const production = env.VERCEL_ENV === "production" + const delivery = emailDelivery(env) + const from = env.EMAIL_FROM?.trim() || DEFAULT_EMAIL_FROM + const origin = emailLinkOrigin(env) + // Outside Production the job must not settle Production's outbox: the + // log transport would mark real people's emails sent without sending them. + if (!production && usesProductionDatabase(env)) missing.push("NON_PRODUCTION_DEPLOYMENT_ON_PRODUCTION_DATABASE") + // In Production the log transport would mark every real email sent. + if (production && delivery === "log") missing.push("EMAIL_DELIVERY_LOG_IN_PRODUCTION") + if (!isSenderAddress(from)) missing.push("EMAIL_FROM") + if (!origin) missing.push("EMAIL_LINK_ORIGIN") + + let transport: EmailTransport | null = createLogTransport() + if (delivery === "smtp") { + const user = env.SMTP_USER?.trim() + const pass = env.SMTP_PASS?.trim() + const port = env.SMTP_PORT ? Number(env.SMTP_PORT) : DEFAULT_SMTP_PORT + if (!user) missing.push("SMTP_USER") + if (!pass) missing.push("SMTP_PASS") + if (!Number.isInteger(port) || port < 1 || port > 65535) missing.push("SMTP_PORT") + if (user && pass && missing.length === 0) { + const smtp = createSmtpTransport({ host: env.SMTP_HOST?.trim() || DEFAULT_SMTP_HOST, port, user, pass }) + const allowlist = (env.EMAIL_ALLOWLIST ?? "").split(",") + transport = production ? smtp : allowlistTransport(allowlist, smtp, createLogTransport()) + } else { + transport = null + } + } + if (missing.length > 0 || !transport || !origin) return { ok: false, missing } + return { ok: true, delivery, transport, options: { origin, from } } +} diff --git a/apps/web/src/server/email/purge.ts b/apps/web/src/server/email/purge.ts new file mode 100644 index 00000000..601cf1b2 --- /dev/null +++ b/apps/web/src/server/email/purge.ts @@ -0,0 +1,55 @@ +import "server-only" + +import { NextResponse } from "next/server" + +import { dbService } from "@/lib/supabase" + +/** Calls stop starting after this long, well inside the route's maxDuration. */ +export const PURGE_BUDGET_MS = 45_000 + +interface PurgeCounts { + deleted_accounts: number + cleared: number + expired_tokens: number +} + +function purgeAnswer(data: unknown): (PurgeCounts & { more: boolean }) | null { + if (typeof data !== "object" || data === null || Array.isArray(data)) return null + const { deleted_accounts, cleared, expired_tokens, more } = data as Record + return typeof deleted_accounts === "number" && + typeof cleared === "number" && + typeof expired_tokens === "number" && + typeof more === "boolean" + ? { deleted_accounts, cleared, expired_tokens, more } + : null +} + +/** One purge-outbox run: calls give.purge_outbox while it says there is more, within PURGE_BUDGET_MS. */ +export async function purgeUntilDone(now: () => number): Promise { + const started = now() + const total: PurgeCounts & { calls: number; more: boolean } = { + deleted_accounts: 0, + cleared: 0, + expired_tokens: 0, + calls: 0, + more: true, + } + while (total.more && now() - started < PURGE_BUDGET_MS) { + const { data, error } = await dbService().rpc("purge_outbox") + total.calls += 1 + if (error) { + console.error("purge_outbox failed", error.code, error.message) + return NextResponse.json({ error: "purge_failed", ...total }, { status: 500 }) + } + const answer = purgeAnswer(data) + if (!answer) { + console.error("purge_outbox answered unexpectedly") + return NextResponse.json({ error: "purge_failed", ...total }, { status: 500 }) + } + total.deleted_accounts += answer.deleted_accounts + total.cleared += answer.cleared + total.expired_tokens += answer.expired_tokens + total.more = answer.more + } + return NextResponse.json(total) +} diff --git a/apps/web/src/server/email/smtp.test.ts b/apps/web/src/server/email/smtp.test.ts new file mode 100644 index 00000000..3ea44482 --- /dev/null +++ b/apps/web/src/server/email/smtp.test.ts @@ -0,0 +1,259 @@ +import { EventEmitter } from "node:events" +import { readdirSync, readFileSync, statSync } from "node:fs" +import type { Socket } from "node:net" +import { join, relative } from "node:path" +import { fileURLToPath } from "node:url" + +import { beforeEach, describe, expect, it, vi } from "vitest" + +const mailer = vi.hoisted(() => ({ + options: [] as unknown[], + sendMail: vi.fn(), +})) + +vi.mock("nodemailer", () => ({ + default: { + createTransport: (options: unknown) => { + mailer.options.push(options) + return { sendMail: mailer.sendMail } + }, + }, +})) + +const { createSmtpTransport, envelopeWatch, sesMessageId, smtpFailure, socketTracker } = await import("./smtp") + +const CONFIG = { host: "email-smtp.ap-southeast-1.amazonaws.com", port: 587, user: "u", pass: "p" } +const EMAIL = { + from: "Give ", + to: "mai@example.com", + subject: "s", + text: "t", + html: "

h

", + headers: { "Message-ID": "", "Auto-Submitted": "auto-generated" }, + idempotencyKey: "k", +} + +beforeEach(() => { + mailer.options.length = 0 + mailer.sendMail.mockReset() +}) + +describe("createSmtpTransport", () => { + it("talks STARTTLS to SES with timeouts and sends the stable Message-ID", async () => { + mailer.sendMail.mockResolvedValue({ response: "250 Ok 0100019a-abc", messageId: "", rejected: [] }) + const result = await createSmtpTransport(CONFIG).send(EMAIL) + expect(result).toEqual({ ok: true, messageId: "0100019a-abc" }) + expect(mailer.options[0]).toMatchObject({ host: CONFIG.host, port: 587, secure: false, requireTLS: true }) + expect((mailer.options[0] as { getSocket?: unknown }).getSocket).toBeTypeOf("function") + expect(mailer.options[0]).toMatchObject({ transactionLog: true }) + expect(mailer.sendMail.mock.calls[0][0]).toMatchObject({ + to: "mai@example.com", + messageId: "", + headers: { "Auto-Submitted": "auto-generated" }, + disableUrlAccess: true, + disableFileAccess: true, + }) + }) + + it("reports a refused recipient as permanent", async () => { + mailer.sendMail.mockResolvedValue({ response: "250 Ok", rejected: ["mai@example.com"] }) + expect(await createSmtpTransport(CONFIG).send(EMAIL)).toMatchObject({ ok: false, permanent: true }) + }) + + it("turns a thrown error into a result", async () => { + mailer.sendMail.mockRejectedValue({ responseCode: 454, response: "454 Throttling failure" }) + expect(await createSmtpTransport(CONFIG).send(EMAIL)).toEqual({ + ok: false, + permanent: false, + error: "SMTP 454: 454 Throttling failure", + }) + }) +}) + +describe("smtpFailure", () => { + it.each([ + ["EENVELOPE", "RCPT TO", 550, true], + ["EENVELOPE", "RCPT TO", 553, true], + ["EENVELOPE", "RCPT TO", 452, false], + ["EENVELOPE", "MAIL FROM", 550, false], + ["EENVELOPE", "DATA", 554, false], + ["EMESSAGE", "DATA", 554, false], + [undefined, undefined, 550, false], + ["EAUTH", "AUTH PLAIN", 535, false], + [undefined, undefined, 421, false], + ])("%s at %s with %i is permanent: %s", (code, command, responseCode, permanent) => { + expect(smtpFailure({ code, command, responseCode, response: `${responseCode} x` }).permanent).toBe(permanent) + }) + + it("calls a connection lost before MAIL FROM a plain failure: nothing can have been delivered", () => { + expect(smtpFailure({ code: "ECONNECTION", command: "CONN" }, false).outcomeUnknown).toBeUndefined() + expect(smtpFailure({ code: "ETIMEDOUT", command: "CONN" }, false).outcomeUnknown).toBeUndefined() + }) + + it("watches for MAIL FROM in the transaction log and keeps nothing else", () => { + const watch = envelopeWatch() + watch.logger.debug({ tnx: "client" }, "EHLO host") + watch.logger.debug({ tnx: "client" }, "AUTH PLAIN AHVzZXIAcGFzcw==") + expect(watch.started).toBe(false) + watch.logger.debug({ tnx: "server" }, "MAIL FROM:") + expect(watch.started).toBe(false) + watch.logger.debug({ tnx: "client" }, "MAIL FROM:") + expect(watch.started).toBe(true) + watch.reset() + expect(watch.started).toBe(false) + }) + + it("calls a connection lost mid-conversation outcome unknown, but not a refused connect", () => { + expect(smtpFailure({ code: "ECONNECTION", command: "CONN", message: "Connection closed" })).toMatchObject({ + permanent: false, + outcomeUnknown: true, + }) + expect(smtpFailure({ code: "ETIMEDOUT", command: "CONN", message: "Timeout" }).outcomeUnknown).toBe(true) + expect(smtpFailure({ code: "ECONNREFUSED", message: "connect ECONNREFUSED" }).outcomeUnknown).toBeUndefined() + expect( + smtpFailure({ code: "EMESSAGE", command: "DATA", responseCode: 554, response: "554 rejected" }).outcomeUnknown + ).toBeUndefined() + }) + + it("names connection errors without a reply code", () => { + expect(smtpFailure({ code: "ETIMEDOUT", message: "Connection\ntimeout" })).toEqual({ + ok: false, + permanent: false, + error: "ETIMEDOUT: Connection timeout", + }) + }) +}) + +describe("sesMessageId", () => { + it("keeps SES's id, else nodemailer's", () => { + expect(sesMessageId("250 Ok 0100-abc", "")).toBe("0100-abc") + expect(sesMessageId("250 2.0.0 OK", "")).toBe("") + expect(sesMessageId(undefined, undefined)).toBeNull() + }) +}) + +class FakeSocket extends EventEmitter { + destroyed = false + reset = false + destroy() { + this.destroyed = true + this.emit("close") + return this + } + resetAndDestroy() { + this.reset = true + return this.destroy() + } +} + +describe("socketTracker", () => { + const tracked = () => { + const sockets: FakeSocket[] = [] + const tracker = socketTracker(CONFIG, () => { + const socket = new FakeSocket() + sockets.push(socket) + return socket as unknown as Socket + }) + return { tracker, sockets } + } + + it("hands nodemailer the socket once connected, and abort cuts it off mid-send", () => { + const { tracker, sockets } = tracked() + const callback = vi.fn() + tracker.getSocket({}, callback) + sockets[0].emit("connect") + expect(callback).toHaveBeenCalledWith(null, { connection: sockets[0] }) + expect(tracker.openCount).toBe(1) + tracker.abort() + expect(sockets[0].reset).toBe(true) + expect(tracker.openCount).toBe(0) + }) + + it("abort fails a connection still opening instead of leaving it to its timer", () => { + const { tracker, sockets } = tracked() + const callback = vi.fn() + tracker.getSocket({}, callback) + tracker.abort() + expect(callback).toHaveBeenCalledWith(expect.objectContaining({ code: "ECONNECTION" })) + expect(sockets[0].destroyed).toBe(true) + sockets[0].emit("connect") + expect(callback).toHaveBeenCalledTimes(1) + }) + + it("fails a connection that errors or does not open in time", () => { + vi.useFakeTimers() + try { + const { tracker, sockets } = tracked() + const failed = vi.fn() + tracker.getSocket({}, failed) + sockets[0].emit("error", new Error("ECONNREFUSED")) + expect(failed).toHaveBeenCalledWith(expect.objectContaining({ message: "ECONNREFUSED" })) + expect(sockets[0].destroyed).toBe(true) + + const slow = vi.fn() + tracker.getSocket({}, slow) + vi.advanceTimersByTime(10_000) + expect(slow).toHaveBeenCalledWith(expect.objectContaining({ code: "ETIMEDOUT" })) + expect(sockets[1].destroyed).toBe(true) + sockets[1].emit("connect") + expect(slow).toHaveBeenCalledTimes(1) + } finally { + vi.useRealTimers() + } + }) +}) + +/** Any static, dynamic or require import of nodemailer or a subpath of it. */ +const NODEMAILER_IMPORT = /(from\s+|import\s*\(\s*|require\s*\(\s*|import\s+)["'`]nodemailer(\/[^"'`]*)?["'`]/ + +/** A "use client" directive, allowing comments and blank lines before it. */ +function isClientModule(source: string): boolean { + const body = source.replace(/^(\s|\/\/[^\n]*\n|\/\*[\s\S]*?\*\/)*/, "") + return /^["']use client["']/.test(body) +} + +describe("the import guard itself", () => { + it.each([ + 'import nodemailer from "nodemailer"', + "const m = await import('nodemailer')", + 'import SMTPPool from "nodemailer/lib/smtp-pool"', + 'const m = require ( "nodemailer" )', + 'import "nodemailer"', + "const m = await import(`nodemailer`)", + ])("catches %s", (line) => { + expect(NODEMAILER_IMPORT.test(line)).toBe(true) + }) + + it("finds a use client directive after leading comments", () => { + expect(isClientModule('// a note\n/* block\n */\n\n"use client"\n')).toBe(true) + expect(isClientModule('import x from "y"\n"use client"')).toBe(false) + }) +}) + +describe("nodemailer stays on the server", () => { + const src = fileURLToPath(new URL("../..", import.meta.url)) + const files = (dir: string): string[] => + readdirSync(dir).flatMap((name) => { + const path = join(dir, name) + if (statSync(path).isDirectory()) return files(path) + return /\.(ts|tsx|js|jsx|mjs|cjs)$/.test(name) && !/\.test\.[cm]?[jt]sx?$/.test(name) ? [path] : [] + }) + + it("is imported only by server/email/smtp.ts, which is server-only", () => { + const importers = files(src).filter((f) => NODEMAILER_IMPORT.test(readFileSync(f, "utf8"))) + expect(importers.map((f) => relative(src, f))).toEqual([join("server", "email", "smtp.ts")]) + expect(readFileSync(importers[0], "utf8")).toMatch(/^import "server-only"/) + }) + + it("every module that reaches the SMTP transport is server-only", () => { + const reach = ["smtp.ts", "provider.ts", "outbox.ts", "log-transport.ts", "transport.ts"] + for (const name of reach) { + expect(readFileSync(join(src, "server", "email", name), "utf8"), name).toMatch(/^import "server-only"/) + } + const clientFiles = files(src).filter((f) => isClientModule(readFileSync(f, "utf8"))) + expect(clientFiles.length).toBeGreaterThan(0) + for (const f of clientFiles) { + expect(readFileSync(f, "utf8"), relative(src, f)).not.toMatch(/server\/email|nodemailer/) + } + }) +}) diff --git a/apps/web/src/server/email/smtp.ts b/apps/web/src/server/email/smtp.ts new file mode 100644 index 00000000..2cadf908 --- /dev/null +++ b/apps/web/src/server/email/smtp.ts @@ -0,0 +1,212 @@ +import "server-only" + +import net, { type Socket } from "node:net" + +import nodemailer from "nodemailer" + +import type { EmailTransport, OutgoingEmail, SendResult } from "./transport" + +/** + * SMTP to AWS SES, the provider DOS.Me already uses (apps/api EmailService, + * nodemailer). Only a recipient the server refused outright at RCPT TO + * counts as permanent; every other failure (timeouts, 4xx, throttling, a + * 5xx about the sender, auth or account problems) is retried by the outbox + * and ends 'dead' after the last attempt, where an admin can send it again + * once fixed. + */ + +export interface SmtpConfig { + host: string + port: number + user: string + pass: string +} + +/** Opening the TCP connection may take this long (nodemailer's connectionTimeout covers the rest of its setup). */ +export const CONNECT_TIMEOUT_MS = 10_000 + +/** Connection-level failures with no SMTP reply: the server may have taken the message before the line dropped. */ +const LOST_CONNECTION_CODES = new Set(["ECONNECTION", "ESOCKET", "ETIMEDOUT"]) + +/** Replies to RCPT TO that mean this address can never be delivered to. */ +const PERMANENT_RCPT_CODES = new Set([501, 550, 551, 553]) + +interface SmtpError { + responseCode?: number + code?: string + command?: string + response?: string + message?: string +} + +/** + * afterEnvelope: the message had reached MAIL FROM. A connection lost before + * that (connect, greeting, STARTTLS, AUTH) cannot have delivered anything. + */ +export function smtpFailure(error: unknown, afterEnvelope = true): Extract { + const e = (error ?? {}) as SmtpError + const code = typeof e.responseCode === "number" ? e.responseCode : null + const detail = (e.response ?? e.message ?? "send_failed").replace(/\s+/g, " ").slice(0, 200) + const refusedRecipient = e.code === "EENVELOPE" && e.command === "RCPT TO" + const lost = afterEnvelope && code === null && e.command === "CONN" && LOST_CONNECTION_CODES.has(e.code ?? "") + return { + ok: false, + permanent: refusedRecipient && code !== null && PERMANENT_RCPT_CODES.has(code), + ...(lost ? { outcomeUnknown: true } : {}), + error: code !== null ? `SMTP ${code}: ${detail}` : `${e.code ?? "SMTP"}: ${detail}`, + } +} + +/** SES answers "250 Ok "; keep that id, else nodemailer's Message-ID. */ +export function sesMessageId(response: unknown, fallback: unknown): string | null { + const match = typeof response === "string" ? /^250 Ok (\S+)/.exec(response) : null + if (match) return match[1] + return typeof fallback === "string" && fallback !== "" ? fallback : null +} + +type SocketCallback = (err: Error | null, socketOptions?: { connection: Socket }) => void + +/** + * Opens the connections nodemailer uses and keeps hold of them, so a send + * the outbox gave up on can be cut off (`abort`) instead of finishing later: + * nodemailer's own close() leaves a connection that is mid-send open until + * that message is done. + */ +export function socketTracker( + config: Pick, + connect: (port: number, host: string) => Socket = (port, host) => net.connect({ port, host }), + timeoutMs = CONNECT_TIMEOUT_MS +) { + const open = new Set() + const connecting = new Set<(err: Error) => void>() + return { + getSocket(_options: unknown, callback: SocketCallback): void { + const socket = connect(config.port, config.host) + open.add(socket) + socket.once("close", () => open.delete(socket)) + let settled = false + const finish = (err: Error | null) => { + if (settled) return + settled = true + clearTimeout(timer) + connecting.delete(finish) + socket.off("error", onError) + if (err) { + socket.destroy() + callback(err) + } else { + callback(null, { connection: socket }) + } + } + connecting.add(finish) + const onError = (err: Error) => finish(err) + const timer = setTimeout( + () => finish(Object.assign(new Error("Connection timeout"), { code: "ETIMEDOUT" })), + timeoutMs + ) + socket.once("connect", () => finish(null)) + socket.once("error", onError) + }, + /** + * Resets every connection (TCP RST, so nothing still buffered, such as + * the final "." of a message, goes out) and fails any still opening. + */ + abort(): void { + for (const fail of [...connecting]) fail(Object.assign(new Error("Connection aborted"), { code: "ECONNECTION" })) + for (const socket of open) { + if (typeof socket.resetAndDestroy === "function") socket.resetAndDestroy() + else socket.destroy() + } + open.clear() + }, + get openCount(): number { + return open.size + }, + } +} + +/** + * A logger that keeps nothing: it only notes when a send reaches MAIL FROM + * (nodemailer's transactionLog passes each client command, never the body; + * the AUTH line is ignored like every other). + */ +export function envelopeWatch() { + let started = false + const ignore = () => {} + return { + reset: () => { + started = false + }, + get started() { + return started + }, + logger: { + trace: ignore, + info: ignore, + warn: ignore, + error: ignore, + fatal: ignore, + debug: (entry: unknown, message?: unknown) => { + if ((entry as { tnx?: unknown } | null)?.tnx === "client" && typeof message === "string") { + if (/^MAIL FROM:/i.test(message)) started = true + } + }, + }, + } +} + +export function createSmtpTransport(config: SmtpConfig): EmailTransport { + const sockets = socketTracker(config) + const envelope = envelopeWatch() + const transporter = nodemailer.createTransport({ + // One connection reused for the whole run (closed by the job at its end): + // a new TLS + AUTH handshake per email to ap-southeast-1 is slow. + pool: true, + maxConnections: 1, + maxMessages: 100, + host: config.host, + port: config.port, + secure: config.port === 465, + requireTLS: config.port !== 465, + auth: { user: config.user, pass: config.pass }, + getSocket: sockets.getSocket, + logger: envelope.logger, + transactionLog: true, + connectionTimeout: CONNECT_TIMEOUT_MS, + greetingTimeout: 10_000, + socketTimeout: 15_000, + }) + return { + close: () => transporter.close(), + abort: () => { + sockets.abort() + transporter.close() + }, + reachedEnvelope: () => envelope.started, + async send(email: OutgoingEmail): Promise { + const { "Message-ID": messageId, ...headers } = email.headers + envelope.reset() + try { + const info = await transporter.sendMail({ + from: email.from, + replyTo: email.replyTo, + to: email.to, + subject: email.subject, + text: email.text, + html: email.html, + headers, + messageId, + disableUrlAccess: true, + disableFileAccess: true, + }) + const rejected = Array.isArray(info.rejected) ? info.rejected : [] + if (rejected.length > 0) { + return { ok: false, permanent: true, error: "SMTP: recipient rejected" } + } + return { ok: true, messageId: sesMessageId(info.response, info.messageId) } + } catch (error) { + return smtpFailure(error, envelope.started) + } + }, + } +} diff --git a/apps/web/src/server/email/templates.test.ts b/apps/web/src/server/email/templates.test.ts new file mode 100644 index 00000000..804ec0a6 --- /dev/null +++ b/apps/web/src/server/email/templates.test.ts @@ -0,0 +1,191 @@ +import { describe, expect, it } from "vitest" + +import { EmailRenderError, escapeHtml, renderEmail, type OutboxEmail } from "./templates" + +const ORIGIN = "https://give.vn" +const TOKEN = "ab".repeat(32) +const UNSUB = "77777777-7777-4777-8777-777777777777" +const CAMPAIGN = "22222222-2222-4222-8222-222222222222" + +function email(overrides: Partial = {}): OutboxEmail { + return { + id: "11111111-1111-4111-8111-111111111111", + kind: "donation_received", + category: "transactional", + to_email: "mai@example.com", + payload: { + campaign_id: CAMPAIGN, + campaign_slug: "nuoc-sach", + campaign_title: "Nước sạch cho bản", + campaign_type: "give", + reference_code: "GVABCDEFG", + received_amount: 300000, + asset: "VND", + guest: true, + }, + attempt: 1, + idempotency_key: "donation_received:x", + unsubscribe_token: null, + reference_code: "GVABCDEFG", + tracking_token: TOKEN, + ...overrides, + } +} + +describe("renderEmail: donation_received", () => { + it("gives a guest the amount, the code and their own tracking link", () => { + const r = renderEmail(email(), ORIGIN) + expect(r.subject).toBe("Give đã nhận khoản ủng hộ của bạn cho chiến dịch “Nước sạch cho bản”") + expect(r.text).toContain("300.000") + expect(r.text).toContain("GVABCDEFG") + expect(r.text).toContain(`${ORIGIN}/donations/GVABCDEFG/track?t=${TOKEN}`) + expect(r.text).toContain("hết hạn sau 7 ngày") + expect(r.html).toContain(`href="${ORIGIN}/donations/GVABCDEFG/track?t=${TOKEN}"`) + expect(r.unsubscribeUrl).toBeNull() + expect(r.oneClickUnsubscribeUrl).toBeNull() + expect(r.text).not.toContain("Hủy đăng ký") + }) + + it("states the amount only for a transfer in đồng", () => { + for (const asset of ["USDT", undefined]) { + const r = renderEmail(email({ payload: { ...email().payload, asset } }), ORIGIN) + expect(r.text, String(asset)).not.toContain("300.000") + expect(r.text, String(asset)).toContain("khoản chuyển của bạn") + } + }) + + it("links a guest without a tracking token to the public statement", () => { + const r = renderEmail(email({ tracking_token: null }), ORIGIN) + expect(r.text).toContain(`${ORIGIN}/campaigns/nuoc-sach/statement`) + expect(r.text).not.toContain("/track?") + }) + + it("links a signed-in donor to their contributions", () => { + const r = renderEmail(email({ tracking_token: null, payload: { ...email().payload, guest: false } }), ORIGIN) + expect(r.text).toContain(`${ORIGIN}/me/contributions`) + }) + + it("escapes organizer-written text and keeps headers on one line", () => { + const r = renderEmail( + email({ payload: { ...email().payload, campaign_title: 'Quỹ \r\nBcc: a@b.c' } }), + ORIGIN + ) + expect(r.html).not.toContain(" và
nhãn
.') + + expect(html).not.toContain(" { + const html = render( + [ + "[Bấm vào đây](javascript:alert(1))", + "[Viết hoa](JAVASCRIPT:alert(2))", + "[Tệp nhúng](data:text/html;base64,PHNjcmlwdD5hbGVydCgxKTwvc2NyaXB0Pg==)", + ].join("\n\n") + ) + + expect(html).not.toContain("javascript:") + expect(html).not.toContain("JAVASCRIPT:") + expect(html).not.toContain("data:text/html") + expect(html).toContain('
Bấm vào đây') + expect(html).toContain('Viết hoa') + expect(html).toContain('Tệp nhúng') + }) + + it("disallows and unwraps markdown elements while preserving surrounding content", () => { + const html = render( + "Trước ảnh ![Ảnh theo dõi](https://tracker.example/pixel.gif) sau ảnh và [![Biểu ngữ](https://tracker.example/banner.png)](https://give.vn)." + ) + + expect(html).not.toContain("') + }) +}) diff --git a/apps/web/src/components/ProgressBar.test.ts b/apps/web/src/components/ProgressBar.test.ts new file mode 100644 index 00000000..c9989662 --- /dev/null +++ b/apps/web/src/components/ProgressBar.test.ts @@ -0,0 +1,59 @@ +import { createElement, type ComponentProps } from "react" +import { renderToStaticMarkup } from "react-dom/server" +import { describe, expect, it } from "vitest" + +import { ProgressBar } from "./ProgressBar" + +const render = (props: ComponentProps) => renderToStaticMarkup(createElement(ProgressBar, props)) + +describe("ProgressBar (DOS/Give#270)", () => { + it("renders ARIA progressbar attributes, default label, md height, and fill width", () => { + const html = render({ percent: 64 }) + + expect(html).toContain('role="progressbar"') + expect(html).toContain('aria-label="Tiến độ gây quỹ"') + expect(html).toContain('aria-valuemin="0"') + expect(html).toContain('aria-valuemax="100"') + expect(html).toContain('aria-valuenow="64"') + expect(html).toContain('aria-valuetext="64%"') + expect(html).toContain("h-2") + expect(html).not.toContain("h-1.5") + expect(html).toContain('
') + }) + + it("clamps negative percentages to 0% and percentages above 100 to 100%", () => { + const belowZero = render({ percent: -25 }) + expect(belowZero).toContain('aria-valuenow="0"') + expect(belowZero).toContain('aria-valuetext="0%"') + expect(belowZero).toContain('style="width:0%"') + + const zero = render({ percent: 0 }) + expect(zero).toContain('aria-valuenow="0"') + expect(zero).toContain('style="width:0%"') + + const hundred = render({ percent: 100 }) + expect(hundred).toContain('aria-valuenow="100"') + expect(hundred).toContain('style="width:100%"') + + const overfunded = render({ percent: 185 }) + expect(overfunded).toContain('aria-valuenow="100"') + expect(overfunded).toContain('aria-valuetext="100%"') + expect(overfunded).toContain('style="width:100%"') + }) + + it("supports sm card height, custom accessible label, fractional percentages, and extra className", () => { + const html = render({ + percent: 37.5, + size: "sm", + label: "Tiến độ cam kết dự án", + className: "mt-3", + }) + + expect(html).toContain('aria-label="Tiến độ cam kết dự án"') + expect(html).toContain('aria-valuenow="37.5"') + expect(html).toContain('aria-valuetext="37.5%"') + expect(html).toContain("h-1.5") + expect(html).toContain("mt-3") + expect(html).toContain('style="width:37.5%"') + }) +}) diff --git a/apps/web/src/components/ShareButtons.test.ts b/apps/web/src/components/ShareButtons.test.ts new file mode 100644 index 00000000..1e4b79cc --- /dev/null +++ b/apps/web/src/components/ShareButtons.test.ts @@ -0,0 +1,296 @@ +// @vitest-environment happy-dom +import { act, createElement, type ComponentProps } from "react" +import { createRoot, type Root } from "react-dom/client" +import { renderToStaticMarkup } from "react-dom/server" +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" + +import { ShareButtons } from "./ShareButtons" + +declare global { + var IS_REACT_ACT_ENVIRONMENT: boolean | undefined +} + +let container: HTMLDivElement +let root: Root +let originalShareDescriptor: PropertyDescriptor | undefined +let originalClipboardDescriptor: PropertyDescriptor | undefined + +function setNavigatorShare(share: Navigator["share"] | undefined) { + Object.defineProperty(navigator, "share", { + value: share, + configurable: true, + writable: true, + }) +} + +function setClipboardWriteText(writeText: (data: string) => Promise) { + Object.defineProperty(navigator, "clipboard", { + value: { writeText }, + configurable: true, + writable: true, + }) +} + +function renderShareButtons(props: ComponentProps) { + act(() => { + root.render(createElement(ShareButtons, props)) + }) +} + +beforeEach(() => { + globalThis.IS_REACT_ACT_ENVIRONMENT = true + originalShareDescriptor = Object.getOwnPropertyDescriptor(navigator, "share") + originalClipboardDescriptor = Object.getOwnPropertyDescriptor(navigator, "clipboard") + setNavigatorShare(undefined) + setClipboardWriteText(vi.fn().mockResolvedValue(undefined)) + container = document.createElement("div") + document.body.append(container) + root = createRoot(container) +}) + +afterEach(() => { + act(() => root.unmount()) + container.remove() + if (originalShareDescriptor) { + Object.defineProperty(navigator, "share", originalShareDescriptor) + } else { + Reflect.deleteProperty(navigator, "share") + } + if (originalClipboardDescriptor) { + Object.defineProperty(navigator, "clipboard", originalClipboardDescriptor) + } else { + Reflect.deleteProperty(navigator, "clipboard") + } + vi.useRealTimers() + vi.restoreAllMocks() +}) + +describe("ShareButtons (DOS/Give#270)", () => { + it("uses navigator.share when available without falling back to clipboard", async () => { + const shareMock = vi.fn().mockResolvedValue(undefined) + const writeTextMock = vi.fn().mockResolvedValue(undefined) + setNavigatorShare(shareMock) + setClipboardWriteText(writeTextMock) + + renderShareButtons({ + path: "/campaigns/xay-cau", + title: "Xây cầu nông thôn", + origin: "https://give.vn", + }) + + const shareButton = container.querySelector("button")! + await act(async () => { + shareButton.click() + }) + + expect(shareMock).toHaveBeenCalledTimes(1) + expect(shareMock).toHaveBeenCalledWith({ + title: "Xây cầu nông thôn", + url: "https://give.vn/campaigns/xay-cau", + }) + expect(writeTextMock).not.toHaveBeenCalled() + expect(container.querySelector('[aria-live="polite"]')!.textContent).toBe("") + }) + + it("silently returns on AbortError without copying to clipboard or showing status", async () => { + const shareMock = vi.fn().mockRejectedValue(new DOMException("Share cancelled", "AbortError")) + const writeTextMock = vi.fn().mockResolvedValue(undefined) + setNavigatorShare(shareMock) + setClipboardWriteText(writeTextMock) + + renderShareButtons({ + path: "/campaigns/xay-cau", + title: "Xây cầu nông thôn", + origin: "https://give.vn", + }) + + const shareButton = container.querySelector("button")! + await act(async () => { + shareButton.click() + }) + + expect(shareMock).toHaveBeenCalledTimes(1) + expect(writeTextMock).not.toHaveBeenCalled() + expect(container.querySelector('[aria-live="polite"]')!.textContent).toBe("") + }) + + it("falls back to navigator.clipboard.writeText when navigator.share fails with a non-abort error", async () => { + vi.useFakeTimers() + const shareMock = vi.fn().mockRejectedValue(new DOMException("Permission denied", "NotAllowedError")) + const writeTextMock = vi.fn().mockResolvedValue(undefined) + setNavigatorShare(shareMock) + setClipboardWriteText(writeTextMock) + + renderShareButtons({ + path: "/campaigns/xay-cau", + title: "Xây cầu nông thôn", + origin: "https://give.vn", + }) + + const shareButton = container.querySelector("button")! + await act(async () => { + shareButton.click() + }) + + expect(shareMock).toHaveBeenCalledTimes(1) + expect(writeTextMock).toHaveBeenCalledWith("https://give.vn/campaigns/xay-cau") + expect(container.querySelector('[aria-live="polite"]')!.textContent).toBe("Đã chép đường dẫn") + }) + + it("resets the 3000ms status timer on rapid clicks without premature wipe, handles clipboard errors, and cleans up on unmount", async () => { + vi.useFakeTimers() + const writeTextMock = vi.fn().mockResolvedValue(undefined) + setClipboardWriteText(writeTextMock) + + renderShareButtons({ + path: "/campaigns/xay-cau", + title: "Xây cầu nông thôn", + origin: "https://give.vn", + }) + + const shareButton = container.querySelector("button")! + const liveRegion = container.querySelector('[aria-live="polite"]')! + + await act(async () => { + shareButton.click() + }) + expect(liveRegion.textContent).toBe("Đã chép đường dẫn") + + // Advance 2000ms, then click again; the new 3000ms window must last until t = 5000ms. + act(() => { + vi.advanceTimersByTime(2000) + }) + await act(async () => { + shareButton.click() + }) + expect(writeTextMock).toHaveBeenCalledTimes(2) + + // At t = 3500ms (past the first click's 3000ms mark), status must still be present. + act(() => { + vi.advanceTimersByTime(1500) + }) + expect(liveRegion.textContent).toBe("Đã chép đường dẫn") + + // At t = 5000ms (full 3000ms after the second click), status clears. + act(() => { + vi.advanceTimersByTime(1500) + }) + expect(liveRegion.textContent).toBe("") + + // Clipboard write failure displays fallback instructions and clears on unmount without leaking a timer. + writeTextMock.mockRejectedValueOnce(new Error("Clipboard blocked")) + await act(async () => { + shareButton.click() + }) + expect(liveRegion.textContent).toBe("Không chép được, hãy chép đường dẫn trên thanh địa chỉ") + expect(vi.getTimerCount()).toBe(1) + + act(() => { + root.unmount() + }) + expect(vi.getTimerCount()).toBe(0) + + // Unmounting while clipboard.writeText is still in flight does not schedule a post-unmount timer. + root = createRoot(container) + let resolvePendingCopy!: () => void + writeTextMock.mockImplementationOnce( + () => + new Promise((resolve) => { + resolvePendingCopy = resolve + }) + ) + renderShareButtons({ + path: "/campaigns/xay-cau", + title: "Xây cầu nông thôn", + origin: "https://give.vn", + }) + act(() => { + container.querySelector("button")!.click() + }) + act(() => { + root.unmount() + }) + await act(async () => { + resolvePendingCopy() + }) + expect(vi.getTimerCount()).toBe(0) + }) + + it("renders compact mode with aria-label, sr-only live region, and transient visual status pill", async () => { + vi.useFakeTimers() + const writeTextMock = vi.fn().mockResolvedValue(undefined) + setClipboardWriteText(writeTextMock) + + renderShareButtons({ + path: "/campaigns/xay-cau", + title: "Xây cầu nông thôn", + origin: "https://give.vn", + compact: true, + }) + + const button = container.querySelector("button")! + expect(button.getAttribute("aria-label")).toBe("Chia sẻ") + expect(container.querySelector("a")).toBeNull() + + const srLive = container.querySelector('p.sr-only[aria-live="polite"]')! + expect(srLive.textContent).toBe("") + expect(container.querySelector('p[aria-hidden="true"]')).toBeNull() + + await act(async () => { + button.click() + }) + + expect(writeTextMock).toHaveBeenCalledWith("https://give.vn/campaigns/xay-cau") + expect(srLive.textContent).toBe("Đã chép đường dẫn") + const pill = container.querySelector('p[aria-hidden="true"]')! + expect(pill).not.toBeNull() + expect(pill.textContent).toBe("Đã chép đường dẫn") + + act(() => { + vi.advanceTimersByTime(3000) + }) + expect(srLive.textContent).toBe("") + expect(container.querySelector('p[aria-hidden="true"]')).toBeNull() + }) + + it("encodes the Facebook sharer URL using server origin when provided and window.location.origin otherwise", () => { + const path = "/campaigns/xay-cau?utm_source=give&tag=a b" + + // Server render with canonical origin works before hydration. + const ssrWithOrigin = renderToStaticMarkup( + createElement(ShareButtons, { + path, + title: "Xây cầu", + origin: "https://give.vn", + }) + ) + expect(ssrWithOrigin).toContain( + `href="https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(`https://give.vn${path}`)}"` + ) + + // Hydrated render with explicit server origin ignores window.location.origin. + window.location.href = "https://preview.give.vn/campaigns/xay-cau" + renderShareButtons({ + path, + title: "Xây cầu", + origin: "https://give.vn", + }) + const linkWithOrigin = container.querySelector("a")! + expect(linkWithOrigin.getAttribute("href")).toBe( + `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(`https://give.vn${path}`)}` + ) + expect(linkWithOrigin.getAttribute("target")).toBe("_blank") + expect(linkWithOrigin.getAttribute("rel")).toBe("noopener noreferrer") + expect(linkWithOrigin.querySelector(".sr-only")?.textContent).toBe(" (mở thẻ mới)") + + // Without server origin (preview), client falls back to window.location.origin. + renderShareButtons({ + path, + title: "Xây cầu", + }) + const linkFromWindow = container.querySelector("a")! + expect(linkFromWindow.getAttribute("href")).toBe( + `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(`https://preview.give.vn${path}`)}` + ) + }) +}) diff --git a/apps/web/src/components/ShareButtons.tsx b/apps/web/src/components/ShareButtons.tsx index 91ec7e1f..39d1bab7 100644 --- a/apps/web/src/components/ShareButtons.tsx +++ b/apps/web/src/components/ShareButtons.tsx @@ -1,6 +1,6 @@ "use client" -import { useState, useSyncExternalStore } from "react" +import { useEffect, useRef, useState, useSyncExternalStore } from "react" import { buttonClass } from "@/components/ui/Button" import { ShareIcon } from "@/components/ui/icons" @@ -26,6 +26,20 @@ export function ShareButtons({ compact?: boolean }) { const [status, setStatus] = useState(null) + const timerRef = useRef | null>(null) + const mountedRef = useRef(true) + + useEffect(() => { + mountedRef.current = true + return () => { + mountedRef.current = false + if (timerRef.current !== null) { + clearTimeout(timerRef.current) + timerRef.current = null + } + } + }, []) + // The canonical origin when the server knows it (so the Facebook link works // before hydration), else this page's own origin (previews). const origin = useSyncExternalStore( @@ -45,13 +59,25 @@ export function ShareButtons({ if (error instanceof DOMException && error.name === "AbortError") return } } + if (timerRef.current !== null) { + clearTimeout(timerRef.current) + timerRef.current = null + } try { await navigator.clipboard.writeText(url) + if (!mountedRef.current) return setStatus("Đã chép đường dẫn") } catch { + if (!mountedRef.current) return setStatus("Không chép được, hãy chép đường dẫn trên thanh địa chỉ") } - setTimeout(() => setStatus(null), 3000) + if (timerRef.current !== null) { + clearTimeout(timerRef.current) + } + timerRef.current = setTimeout(() => { + timerRef.current = null + setStatus(null) + }, 3000) } if (compact) { From 25895e40e57559f65f7bf4a07ed8ae46bf2e6eb5 Mon Sep 17 00:00:00 2001 From: JOY <5027251+JOY@users.noreply.github.com> Date: Thu, 19 Nov 2026 10:48:12 +0700 Subject: [PATCH 06/23] feat(campaigns): add privacy-preserving pitch video player and milestone reached display (#268) (#272) Co-authored-by: Qwen-Coder --- .../web/src/app/campaigns/[slug]/page.test.ts | 236 +++++++++++++++++- apps/web/src/app/campaigns/[slug]/page.tsx | 168 ++++++++----- .../components/campaign/CampaignVideo.test.ts | 181 ++++++++++++++ .../src/components/campaign/CampaignVideo.tsx | 91 +++++++ .../components/campaign/MilestoneList.test.ts | 123 +++++++++ .../src/components/campaign/MilestoneList.tsx | 54 ++++ 6 files changed, 781 insertions(+), 72 deletions(-) create mode 100644 apps/web/src/components/campaign/CampaignVideo.test.ts create mode 100644 apps/web/src/components/campaign/CampaignVideo.tsx create mode 100644 apps/web/src/components/campaign/MilestoneList.test.ts create mode 100644 apps/web/src/components/campaign/MilestoneList.tsx diff --git a/apps/web/src/app/campaigns/[slug]/page.test.ts b/apps/web/src/app/campaigns/[slug]/page.test.ts index 1e9d7430..916f2116 100644 --- a/apps/web/src/app/campaigns/[slug]/page.test.ts +++ b/apps/web/src/app/campaigns/[slug]/page.test.ts @@ -99,7 +99,13 @@ beforeEach(() => { state.session = null state.anonHandler = (call) => { if (call.target === "campaigns") return { data: campaignFixture("live") } - if (call.target === "campaign_milestones" || call.target === "campaign_updates") return { data: [] } + if ( + call.target === "campaign_milestones" || + call.target === "campaign_updates" || + call.target === "campaign_media" + ) { + return { data: [] } + } if (call.target === "rpc:public_organizer") return { data: [{ display_name: "Quỹ Bản Mây", kind: "organization", verification_status: "verified" }] } if (call.target === "public_campaigns") @@ -224,7 +230,12 @@ describe("CampaignPage report flow (DOS/Give#98)", () => { state.anonHandler = () => ({ data: null }) state.userHandler = (call) => { if (call.target === "campaigns") return { data: campaignFixture("in_review") } - if (call.target === "campaign_milestones" || call.target === "campaign_updates") return { data: [] } + if ( + call.target === "campaign_milestones" || + call.target === "campaign_updates" || + call.target === "campaign_media" + ) + return { data: [] } return undefined } @@ -428,7 +439,12 @@ describe("CampaignPage halted states, organizer resilience, and stats grid (DOS/ state.userHandler = (call) => { if (call.target === "campaigns") return { data: campaignFixture(status) } - if (call.target === "campaign_milestones" || call.target === "campaign_updates") return { data: [] } + if ( + call.target === "campaign_milestones" || + call.target === "campaign_updates" || + call.target === "campaign_media" + ) + return { data: [] } return undefined } const giveHtml = renderToStaticMarkup(await CampaignPage({ params: Promise.resolve({ slug: SLUG }) })) @@ -440,7 +456,12 @@ describe("CampaignPage halted states, organizer resilience, and stats grid (DOS/ if (call.target === "campaigns") { return { data: { ...campaignFixture(status), type: "back", funding_model: "all_or_nothing" } } } - if (call.target === "campaign_milestones" || call.target === "campaign_updates") return { data: [] } + if ( + call.target === "campaign_milestones" || + call.target === "campaign_updates" || + call.target === "campaign_media" + ) + return { data: [] } if (call.target === "reward_tiers") return { data: [TIER_FIXTURE] } return undefined } @@ -474,7 +495,12 @@ describe("CampaignPage halted states, organizer resilience, and stats grid (DOS/ ]) { state.userHandler = (call) => { if (call.target === "campaigns") return { data: campaignFixture(status) } - if (call.target === "campaign_milestones" || call.target === "campaign_updates") return { data: [] } + if ( + call.target === "campaign_milestones" || + call.target === "campaign_updates" || + call.target === "campaign_media" + ) + return { data: [] } return undefined } const giveHtml = renderToStaticMarkup(await CampaignPage({ params: Promise.resolve({ slug: SLUG }) })) @@ -491,7 +517,12 @@ describe("CampaignPage halted states, organizer resilience, and stats grid (DOS/ if (call.target === "campaigns") { return { data: { ...campaignFixture(status), type: "back", funding_model: "all_or_nothing" } } } - if (call.target === "campaign_milestones" || call.target === "campaign_updates") return { data: [] } + if ( + call.target === "campaign_milestones" || + call.target === "campaign_updates" || + call.target === "campaign_media" + ) + return { data: [] } if (call.target === "reward_tiers") return { data: [TIER_FIXTURE] } return undefined } @@ -613,3 +644,196 @@ describe("CampaignPage halted states, organizer resilience, and stats grid (DOS/ expect(zeroDoc.querySelector('section[aria-label="Ủng hộ chiến dịch"] dl')).toBeNull() }) }) + +describe("CampaignPage pitch video & milestones (DOS/Give#268)", () => { + const VIDEO_ID = "dQw4w9WgXcQ" + const MILESTONES = [ + { + id: "ms-1", + campaign_id: CAMPAIGN, + title: "Đổ móng phòng học", + description: "Hoàn thành nền móng bê tông.", + target_amount: 30_000_000, + unlock_note: "Công bố biên bản nghiệm thu móng\nKèm ảnh công trường tuần 1.", + sort_order: 1, + }, + { + id: "ms-2", + campaign_id: CAMPAIGN, + title: "Lợp mái tôn chống nóng", + description: "Lắp khung kèo thép và mái tôn.", + target_amount: 60_000_000, + unlock_note: "Mở đăng ký tình nguyện viên sơn tường.", + sort_order: 2, + }, + ] + + it("queries campaign_media for youtube pitch video and renders CampaignVideo poster + MilestoneList reached state on public campaigns", async () => { + const baseAnon = state.anonHandler + state.anonHandler = (call) => { + if (call.target === "campaign_media") { + return { + data: [{ id: "media-1", youtube_id: VIDEO_ID, alt: "Phóng sự Điểm trường Bản Mây", sort_order: 0 }], + } + } + if (call.target === "campaign_milestones") return { data: MILESTONES } + if (call.target === "public_campaigns") { + return { + data: { + campaign_id: CAMPAIGN, + paid_amount: 45_000_000, + other_in_amount: 5_000_000, + disbursed_amount: 0, + refunded_amount: 0, + unexplained_out_amount: 0, + unexplained_out_count: 0, + supporters_count: 12, + pledged_amount: 0, + refund_owed_amount: 0, + backers_count: 0, + payments_stopped_at: null, + payments_stopped_note: null, + own_transfer_amount: 0, + }, + } + } + return baseAnon(call) + } + + const html = renderToStaticMarkup(await CampaignPage({ params: Promise.resolve({ slug: SLUG }) })) + const doc = parseDoc(html) + + // Exact query shape on campaign_media. + const mediaCall = state.anonCalls.find((c) => c.target === "campaign_media") + expect(mediaCall?.ops).toEqual([ + ["select", "id, youtube_id, alt, sort_order"], + ["eq", "campaign_id", CAMPAIGN], + ["eq", "kind", "youtube"], + ["order", "sort_order", { ascending: true }], + ["order", "created_at", { ascending: true }], + ["limit", 1], + ]) + + // Story section renders CampaignVideo poster with zero iframe requests. + const storySection = doc.querySelector('section[aria-labelledby="story-heading"]')! + expect(storySection.querySelector("iframe")).toBeNull() + const posterImg = storySection.querySelector("img") + expect(posterImg?.getAttribute("src")).toContain( + `/_next/image?url=${encodeURIComponent(`https://i.ytimg.com/vi/${VIDEO_ID}/hqdefault.jpg`)}` + ) + const playBtn = storySection.querySelector('button[aria-label="Phát video: Phóng sự Điểm trường Bản Mây"]') + expect(playBtn).not.toBeNull() + expect(playBtn?.className).toContain("min-h-11") + expect(storySection.textContent).toContain("Bấm để phát video từ YouTube") + const watchLink = storySection.querySelector(`a[href="https://www.youtube.com/watch?v=${VIDEO_ID}"]`) + expect(watchLink?.textContent).toBe("Mở trên YouTube") + + // Raised = paid_amount (45M) - other_in_amount (5M) = 40M: ms-1 (30M) reached, ms-2 (60M) unreached. + const msItems = [...doc.querySelectorAll('section[aria-labelledby="milestones-heading"] ol > li')] + expect(msItems).toHaveLength(2) + expect(msItems[0].textContent).toContain("Đã đạt mốc") + expect(msItems[0].textContent).toContain("Công bố biên bản nghiệm thu móng") + expect(msItems[1].textContent).not.toContain("Đã đạt mốc") + expect(msItems[1].textContent).not.toContain("Mở đăng ký tình nguyện viên sơn tường.") + }) + + it("uses pledged_amount on public back campaigns and switches MilestoneList to preview mode on unpublished previews", async () => { + const baseAnon = state.anonHandler + state.anonHandler = (call) => { + if (call.target === "campaigns") { + return { data: { ...campaignFixture("live"), type: "back", funding_model: "all_or_nothing" } } + } + if (call.target === "campaign_milestones") return { data: MILESTONES } + if (call.target === "public_campaigns") { + return { + data: { + campaign_id: CAMPAIGN, + paid_amount: 0, + other_in_amount: 0, + disbursed_amount: 0, + refunded_amount: 0, + unexplained_out_amount: 0, + unexplained_out_count: 0, + supporters_count: 0, + pledged_amount: 60_000_000, + refund_owed_amount: 0, + backers_count: 20, + payments_stopped_at: null, + payments_stopped_note: null, + own_transfer_amount: 0, + }, + } + } + if (call.target === "reward_tiers") return { data: [] } + return baseAnon(call) + } + + const backDoc = parseDoc(renderToStaticMarkup(await CampaignPage({ params: Promise.resolve({ slug: SLUG }) }))) + const backItems = [...backDoc.querySelectorAll('section[aria-labelledby="milestones-heading"] ol > li')] + expect(backItems[0].textContent).toContain("Đã đạt mốc") + expect(backItems[1].textContent).toContain("Đã đạt mốc") + expect(backItems[1].textContent).toContain("Mở đăng ký tình nguyện viên sơn tường.") + + // Preview mode: raisedAmount is null -> no 'Đã đạt mốc', unlock_note prefixed with 'Khi đạt mốc:', and pitch video still previews. + state.session = { + user: { id: VIEWER, email: "org@dos.me", name: "Người tổ chức" }, + accessToken: "org-token", + } + state.anonHandler = () => ({ data: null }) + state.userHandler = (call) => { + if (call.target === "campaigns") return { data: campaignFixture("in_review") } + if (call.target === "campaign_media") { + return { data: [{ id: "media-1", youtube_id: VIDEO_ID, alt: null, sort_order: 0 }] } + } + if (call.target === "campaign_milestones") return { data: MILESTONES } + if (call.target === "campaign_updates") return { data: [] } + return undefined + } + + const previewHtml = renderToStaticMarkup(await CampaignPage({ params: Promise.resolve({ slug: SLUG }) })) + const previewDoc = parseDoc(previewHtml) + expect(previewDoc.body.textContent).not.toContain("Đã đạt mốc") + expect(previewDoc.body.textContent).toContain("Khi đạt mốc: Công bố biên bản nghiệm thu móng") + expect(previewDoc.body.textContent).toContain("Khi đạt mốc: Mở đăng ký tình nguyện viên sơn tường.") + expect(previewDoc.querySelector('button[aria-label="Phát video: Xây trường Bản Mây"]')).not.toBeNull() + }) + + it("keeps rendering the campaign page cleanly when campaign_media fails, throws, or returns an invalid youtube_id", async () => { + const baseAnon = state.anonHandler + state.anonHandler = (call) => { + if (call.target === "campaign_media") { + return { data: null, error: { code: "57014", message: "statement timeout" } } + } + return baseAnon(call) + } + + const failedHtml = renderToStaticMarkup(await CampaignPage({ params: Promise.resolve({ slug: SLUG }) })) + expect(failedHtml).toContain("Xây trường Bản Mây") + expect(failedHtml).not.toContain("Bấm để phát video từ YouTube") + expect(failedHtml).not.toContain("Mở trên YouTube") + + state.anonHandler = (call) => { + if (call.target === "campaign_media") { + throw new Error("network reset") + } + return baseAnon(call) + } + + const thrownHtml = renderToStaticMarkup(await CampaignPage({ params: Promise.resolve({ slug: SLUG }) })) + expect(thrownHtml).toContain("Xây trường Bản Mây") + expect(thrownHtml).not.toContain("Bấm để phát video từ YouTube") + expect(thrownHtml).not.toContain("Mở trên YouTube") + + state.anonHandler = (call) => { + if (call.target === "campaign_media") { + return { data: [{ id: "media-bad", youtube_id: "not-valid!!", alt: "Bad", sort_order: 0 }] } + } + return baseAnon(call) + } + + const invalidHtml = renderToStaticMarkup(await CampaignPage({ params: Promise.resolve({ slug: SLUG }) })) + expect(invalidHtml).toContain("Xây trường Bản Mây") + expect(invalidHtml).not.toContain("Bấm để phát video từ YouTube") + expect(invalidHtml).not.toContain("Mở trên YouTube") + }) +}) diff --git a/apps/web/src/app/campaigns/[slug]/page.tsx b/apps/web/src/app/campaigns/[slug]/page.tsx index cdaa3340..6e4a55f2 100644 --- a/apps/web/src/app/campaigns/[slug]/page.tsx +++ b/apps/web/src/app/campaigns/[slug]/page.tsx @@ -7,6 +7,8 @@ import { cache, type ReactNode } from "react" import { AccountChanges } from "@/components/AccountChanges" import { StatusBadge, TypeBadge } from "@/components/badges" +import { CampaignVideo, isValidYoutubeId } from "@/components/campaign/CampaignVideo" +import { MilestoneList } from "@/components/campaign/MilestoneList" import { RecentSupporters } from "@/components/campaign/RecentSupporters" import { StatementPreview } from "@/components/campaign/StatementPreview" import { StickyAside } from "@/components/campaign/StickyAside" @@ -105,6 +107,26 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str /** "Từ thiện" for give, "Dự án sáng tạo" for back, as discovery names them. */ const TYPE_NAMES = { give: "Từ thiện", back: "Dự án sáng tạo" } as const +interface YoutubeMediaRow { + id: string + youtube_id: string | null + alt: string | null + sort_order: number +} + +async function listYoutubeMedia(db: Db, campaignId: string): Promise { + const { data, error } = await db + .from("campaign_media") + .select("id, youtube_id, alt, sort_order") + .eq("campaign_id", campaignId) + .eq("kind", "youtube") + .order("sort_order", { ascending: true }) + .order("created_at", { ascending: true }) + .limit(1) + if (error) throw error + return (data ?? []) as YoutubeMediaRow[] +} + /** * The campaign page (DESIGN.md 8): breadcrumb, H1 and the organizer line, * then an 8/4 grid from 1024px: cover, tabs, story, statement and updates in @@ -124,56 +146,69 @@ export default async function CampaignPage({ params }: { params: Promise<{ slug: const donationsOpen = !preview && acceptsDonations(campaign) const pledgesOpen = !preview && acceptsPledges(campaign) const sessionPromise = getSession() - const [milestones, updates, organizer, account, session, ownCampaign, totals, accountChanges, tiers, statementRows] = - await Promise.all([ - listMilestones(db, campaign.id), - listPublishedUpdates(db, campaign.id), - preview - ? Promise.resolve(null) - : getPublicOrganizer(db, campaign.id).catch((error: unknown) => { - console.error("campaign page: public organizer lookup failed", error) - return null - }), - donationsOpen - ? paymentAccount(dbService(), campaign.id).catch((error: unknown) => { - // The page still renders, without the donate form. - console.error("campaign page: payment account lookup failed", error) - return null - }) - : Promise.resolve(null), - sessionPromise, - // The organizer cannot back or report their own campaign (the database refuses both). - preview - ? Promise.resolve(false) - : sessionPromise.then((s) => - s ? organizesCampaign(dbAs(s.accessToken), campaign.id, s.user.id).catch(() => false) : false - ), - // Public views only: a preview has no public totals yet. - preview ? Promise.resolve(null) : getMoneyTotals(dbAs(), campaign.id), - // A failed read hides the notice rather than the page; the statement shows it too. - preview ? Promise.resolve([]) : listPublicAccountChanges(dbAs(), campaign.id).catch(() => []), - // Reward tiers (DOS/Give#83): the public view, or the organizer's own active tiers in a preview. - // A failed read hides the tiers rather than the page. - isGive - ? Promise.resolve([]) - : (preview - ? listCampaignTiers(db, campaign.id).then(previewTiers) - : listPublicTiers(dbAs(), campaign.id) - ).catch((error: unknown) => { + const [ + milestones, + updates, + youtubeMedia, + organizer, + account, + session, + ownCampaign, + totals, + accountChanges, + tiers, + statementRows, + ] = await Promise.all([ + listMilestones(db, campaign.id), + listPublishedUpdates(db, campaign.id), + listYoutubeMedia(db, campaign.id).catch(() => [] as YoutubeMediaRow[]), + preview + ? Promise.resolve(null) + : getPublicOrganizer(db, campaign.id).catch((error: unknown) => { + console.error("campaign page: public organizer lookup failed", error) + return null + }), + donationsOpen + ? paymentAccount(dbService(), campaign.id).catch((error: unknown) => { + // The page still renders, without the donate form. + console.error("campaign page: payment account lookup failed", error) + return null + }) + : Promise.resolve(null), + sessionPromise, + // The organizer cannot back or report their own campaign (the database refuses both). + preview + ? Promise.resolve(false) + : sessionPromise.then((s) => + s ? organizesCampaign(dbAs(s.accessToken), campaign.id, s.user.id).catch(() => false) : false + ), + // Public views only: a preview has no public totals yet. + preview ? Promise.resolve(null) : getMoneyTotals(dbAs(), campaign.id), + // A failed read hides the notice rather than the page; the statement shows it too. + preview ? Promise.resolve([]) : listPublicAccountChanges(dbAs(), campaign.id).catch(() => []), + // Reward tiers (DOS/Give#83): the public view, or the organizer's own active tiers in a preview. + // A failed read hides the tiers rather than the page. + isGive + ? Promise.resolve([]) + : (preview ? listCampaignTiers(db, campaign.id).then(previewTiers) : listPublicTiers(dbAs(), campaign.id)).catch( + (error: unknown) => { console.error("campaign page: reward tiers lookup failed", error) return [] + } + ), + // The newest rows of the public statement, for its preview and the recent supporters. + // A failed read leaves them out; the statement page has them all. + preview + ? Promise.resolve(null) + : listStatement(dbAs(), campaign.id, "all", 1) + .then(({ rows }) => rows) + .catch((error: unknown) => { + console.error("campaign page: statement lookup failed", error) + return null }), - // The newest rows of the public statement, for its preview and the recent supporters. - // A failed read leaves them out; the statement page has them all. - preview - ? Promise.resolve(null) - : listStatement(dbAs(), campaign.id, "all", 1) - .then(({ rows }) => rows) - .catch((error: unknown) => { - console.error("campaign page: statement lookup failed", error) - return null - }), - ]) + ]) + const pitchVideo = + youtubeMedia.find((m): m is YoutubeMediaRow & { youtube_id: string } => isValidYoutubeId(m.youtube_id)) ?? null const canDonate = donationsOpen && account !== null const ownProject = pledgesOpen && ownCampaign const canPledge = pledgesOpen && !ownProject @@ -480,14 +515,21 @@ export default async function CampaignPage({ params }: { params: Promise<{ slug:

Câu chuyện

- {campaign.story || campaign.summary ? ( -
- {campaign.summary &&

{campaign.summary}

} - {campaign.story && {campaign.story}} -
- ) : ( - Người tổ chức chưa viết nội dung cho chiến dịch này. - )} +
+ {pitchVideo && ( + + )} + {campaign.story || campaign.summary ? ( +
+ {campaign.summary &&

{campaign.summary}

} + {campaign.story && {campaign.story}} +
+ ) : ( + + Người tổ chức chưa viết nội dung cho chiến dịch này. + + )} +
{canDonate && ( @@ -509,17 +551,11 @@ export default async function CampaignPage({ params }: { params: Promise<{ slug:

Các mốc mục tiêu

-
    - {milestones.map((milestone) => ( -
  1. -
    -

    {milestone.title}

    - {formatVnd(milestone.target_amount)} -
    - {milestone.description &&

    {milestone.description}

    } -
  2. - ))} -
+ )}
diff --git a/apps/web/src/components/campaign/CampaignVideo.test.ts b/apps/web/src/components/campaign/CampaignVideo.test.ts new file mode 100644 index 00000000..11f123b6 --- /dev/null +++ b/apps/web/src/components/campaign/CampaignVideo.test.ts @@ -0,0 +1,181 @@ +// @vitest-environment happy-dom +/** + * Covers `CampaignVideo` (DOS/Give#268): strict 11-char YouTube ID validation, + * zero third-party requests before click (Next.js-proxied poster, accessible + * `min-h-11` play button, privacy hint, and external watch fallback), and + * click-to-play `youtube-nocookie.com` iframe mounting. + */ +import { act, createElement } from "react" +import { createRoot, type Root } from "react-dom/client" +import { renderToStaticMarkup } from "react-dom/server" +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" + +vi.mock("next/image", () => ({ + default: ({ fill: _fill, ...rest }: { src: string; alt: string; fill?: boolean; sizes?: string }) => + createElement("img", rest), +})) + +const { CampaignVideo, isValidYoutubeId, YOUTUBE_ID_PATTERN } = await import("./CampaignVideo") + +declare global { + var IS_REACT_ACT_ENVIRONMENT: boolean | undefined +} + +const VALID_ID = "dQw4w9WgXcQ" +const ALT_VALID_ID = "_-09AZaz_12" + +let container: HTMLDivElement +let root: Root + +beforeEach(() => { + globalThis.IS_REACT_ACT_ENVIRONMENT = true + const realError = console.error.bind(console) + vi.spyOn(console, "error").mockImplementation((...args: unknown[]) => { + if (args[0] instanceof DOMException && args[0].message.includes("Iframe page loading is disabled")) return + realError(...args) + }) + container = document.createElement("div") + document.body.append(container) + root = createRoot(container) +}) + +afterEach(() => { + act(() => root.unmount()) + container.remove() + vi.restoreAllMocks() +}) + +describe("CampaignVideo strict YouTube ID validation (DOS/Give#268)", () => { + it("accepts only exact 11-character [A-Za-z0-9_-] IDs and renders null for anything else", () => { + expect(YOUTUBE_ID_PATTERN.source).toBe("^[A-Za-z0-9_-]{11}$") + expect(isValidYoutubeId(VALID_ID)).toBe(true) + expect(isValidYoutubeId(ALT_VALID_ID)).toBe(true) + + for (const invalid of [ + "", + "short12345", + "toolong12345", + ` ${VALID_ID}`, + `${VALID_ID} `, + "https://youtu.be/dQw4w9WgXcQ", + "dQw4w9WgXcQ?t=1", + "../dQw4w9Wg", + 'dQw4w9Wg"<>', + "dQw4w9WgXcĐ", + null, + undefined, + ]) { + expect(isValidYoutubeId(invalid)).toBe(false) + const html = renderToStaticMarkup( + createElement(CampaignVideo, { youtubeId: (invalid ?? "") as string, title: "Xây trường Bản Mây" }) + ) + expect(html).toBe("") + } + }) +}) + +describe("CampaignVideo poster state & click-to-play iframe (DOS/Give#268)", () => { + it("renders a 16:9 Next.js-proxied poster with zero YouTube embed requests before click", () => { + act(() => { + root.render( + createElement(CampaignVideo, { + youtubeId: VALID_ID, + title: "Xây trường Bản Mây", + alt: "Giới thiệu điểm trường Bản Mây", + }) + ) + }) + + expect(container.querySelector("iframe")).toBeNull() + expect(container.innerHTML).not.toContain("youtube-nocookie.com") + + const frame = container.querySelector(".aspect-video") + expect(frame).not.toBeNull() + + const img = container.querySelector("img") + expect(img).not.toBeNull() + expect(img?.getAttribute("alt")).toBe("Giới thiệu điểm trường Bản Mây") + // Next.js proxies i.ytimg.com/vi//hqdefault.jpg server-side via /_next/image. + const imgSrc = decodeURIComponent(img?.getAttribute("src") ?? "") + expect(imgSrc).toContain(`https://i.ytimg.com/vi/${VALID_ID}/hqdefault.jpg`) + + const playBtn = container.querySelector('button[type="button"]') + expect(playBtn).not.toBeNull() + expect(playBtn?.className).toContain("min-h-11") + expect(playBtn?.className).not.toContain("btn-primary") + expect(playBtn?.getAttribute("aria-label")).toBe("Phát video: Giới thiệu điểm trường Bản Mây") + + expect(container.textContent).toContain("Bấm để phát video từ YouTube") + + const watchLink = container.querySelector(`a[href="https://www.youtube.com/watch?v=${VALID_ID}"]`) + expect(watchLink).not.toBeNull() + expect(watchLink?.textContent).toBe("Mở trên YouTube") + expect(watchLink?.getAttribute("target")).toBe("_blank") + expect(watchLink?.getAttribute("rel")).toBe("noopener noreferrer") + expect(watchLink?.className).toContain("min-h-11") + }) + + it("falls back to campaign title in aria-label and iframe title when alt is null or whitespace", () => { + act(() => { + root.render(createElement(CampaignVideo, { youtubeId: VALID_ID, title: "Xây trường Bản Mây", alt: " " })) + }) + + const playBtn = container.querySelector('button[type="button"]')! + expect(playBtn.getAttribute("aria-label")).toBe("Phát video: Xây trường Bản Mây") + expect(container.querySelector("img")?.getAttribute("alt")).toBe("Xây trường Bản Mây") + + act(() => { + playBtn.click() + }) + + const iframe = container.querySelector("iframe") + expect(iframe).not.toBeNull() + expect(iframe?.getAttribute("title")).toBe("Xây trường Bản Mây") + }) + + it("mounts the youtube-nocookie.com iframe on click and resets to poster if youtubeId changes", () => { + act(() => { + root.render( + createElement(CampaignVideo, { + youtubeId: VALID_ID, + title: "Xây trường Bản Mây", + alt: "Video giới thiệu", + }) + ) + }) + + const playBtn = container.querySelector('button[type="button"]')! + act(() => { + playBtn.click() + }) + + expect(container.querySelector("button")).toBeNull() + expect(container.querySelector("img")).toBeNull() + + const iframe = container.querySelector("iframe") + expect(iframe).not.toBeNull() + expect(iframe?.getAttribute("src")).toBe(`https://www.youtube-nocookie.com/embed/${VALID_ID}?autoplay=1&rel=0`) + expect(iframe?.getAttribute("title")).toBe("Video giới thiệu") + expect(iframe?.getAttribute("allow")).toBe( + "accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture; fullscreen" + ) + expect(iframe?.getAttribute("referrerpolicy")).toBe("strict-origin-when-cross-origin") + // External watch fallback stays available when embeds are blocked. + expect(container.querySelector(`a[href="https://www.youtube.com/watch?v=${VALID_ID}"]`)).not.toBeNull() + + // Navigating to another campaign video resets back to the privacy poster. + act(() => { + root.render( + createElement(CampaignVideo, { + youtubeId: ALT_VALID_ID, + title: "Dự án mới", + alt: null, + }) + ) + }) + expect(container.querySelector("iframe")).toBeNull() + expect(container.querySelector('button[type="button"]')?.getAttribute("aria-label")).toBe( + "Phát video: Dự án mới" + ) + }) +}) diff --git a/apps/web/src/components/campaign/CampaignVideo.tsx b/apps/web/src/components/campaign/CampaignVideo.tsx new file mode 100644 index 00000000..66828599 --- /dev/null +++ b/apps/web/src/components/campaign/CampaignVideo.tsx @@ -0,0 +1,91 @@ +"use client" + +import Image from "next/image" +import { useState } from "react" + +export const YOUTUBE_ID_PATTERN = /^[A-Za-z0-9_-]{11}$/ + +export function isValidYoutubeId(value: string | null | undefined): value is string { + return typeof value === "string" && YOUTUBE_ID_PATTERN.test(value) +} + +/** + * Privacy-preserving click-to-play YouTube pitch video (DOS/Give#268). + * + * Before interaction, only the poster image is requested through Next.js's + * image optimizer (`i.ytimg.com/vi//hqdefault.jpg`), so the visitor's + * browser makes zero requests to YouTube or Google. Clicking mounts the + * `youtube-nocookie.com` embed iframe. + */ +export function CampaignVideo({ youtubeId, title, alt }: { youtubeId: string; title: string; alt?: string | null }) { + const [playingId, setPlayingId] = useState(null) + if (!isValidYoutubeId(youtubeId)) return null + + const cleanAlt = alt?.trim() || null + const label = cleanAlt || title.trim() || "Video giới thiệu chiến dịch" + const iframeTitle = cleanAlt || title + const playing = playingId === youtubeId + + return ( +
+
+ {playing ? ( +