From d5e79852012844bef66dbce6e2efe3a4b3df831a Mon Sep 17 00:00:00 2001 From: JOY <5027251+JOY@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:31:08 +0700 Subject: [PATCH 1/5] feat(embed): clickjacking-safe /embed/[slug] campaign widget & iframe snippet (Refs #335) --- apps/web/next.config.ts | 14 +- .../web/src/app/campaigns/[slug]/page.test.ts | 64 ++++ apps/web/src/app/campaigns/[slug]/page.tsx | 14 + .../src/app/embed/[slug]/not-found.test.ts | 22 ++ apps/web/src/app/embed/[slug]/not-found.tsx | 25 ++ apps/web/src/app/embed/[slug]/page.test.ts | 297 ++++++++++++++++++ apps/web/src/app/embed/[slug]/page.tsx | 233 ++++++++++++++ apps/web/src/app/globals.css | 47 +++ apps/web/src/app/layout.test.ts | 88 ++++++ apps/web/src/app/layout.tsx | 17 +- .../components/EmbedWidgetDisclosure.test.ts | 148 +++++++++ .../src/components/EmbedWidgetDisclosure.tsx | 191 +++++++++++ .../src/components/layout/LayoutShell.test.ts | 101 ++++++ .../web/src/components/layout/LayoutShell.tsx | 45 +++ apps/web/src/components/ui/icons.tsx | 6 + apps/web/src/lib/embed.test.ts | 91 ++++++ apps/web/src/lib/embed.ts | 114 +++++++ apps/web/src/proxy.test.ts | 26 ++ apps/web/src/proxy.ts | 25 +- apps/web/src/test/next-config.test.ts | 50 ++- 20 files changed, 1606 insertions(+), 12 deletions(-) create mode 100644 apps/web/src/app/embed/[slug]/not-found.test.ts create mode 100644 apps/web/src/app/embed/[slug]/not-found.tsx create mode 100644 apps/web/src/app/embed/[slug]/page.test.ts create mode 100644 apps/web/src/app/embed/[slug]/page.tsx create mode 100644 apps/web/src/app/layout.test.ts create mode 100644 apps/web/src/components/EmbedWidgetDisclosure.test.ts create mode 100644 apps/web/src/components/EmbedWidgetDisclosure.tsx create mode 100644 apps/web/src/components/layout/LayoutShell.test.ts create mode 100644 apps/web/src/components/layout/LayoutShell.tsx create mode 100644 apps/web/src/lib/embed.test.ts create mode 100644 apps/web/src/lib/embed.ts diff --git a/apps/web/next.config.ts b/apps/web/next.config.ts index 598c5b49..0d0a2048 100644 --- a/apps/web/next.config.ts +++ b/apps/web/next.config.ts @@ -21,13 +21,25 @@ const nextConfig: NextConfig = { async headers() { return [ { - source: "/:path*", + // Global defaults with X-Frame-Options: DENY, excluding /embed and /embed/* + // which are intentionally frameable read-only widgets (DOS/Give#335). + source: "/((?!embed(?:/|$)).*)", headers: [ { key: "X-Content-Type-Options", value: "nosniff" }, { key: "X-Frame-Options", value: "DENY" }, { key: "Referrer-Policy", value: "strict-origin-when-cross-origin" }, ], }, + { + // Embeddable campaign widget (DOS/Give#335): allows third-party framing + // via CSP frame-ancestors * and omits X-Frame-Options. + source: "/embed/:path*", + headers: [ + { key: "X-Content-Type-Options", value: "nosniff" }, + { key: "Content-Security-Policy", value: "frame-ancestors *" }, + { key: "Referrer-Policy", value: "strict-origin-when-cross-origin" }, + ], + }, { // Guest donation and tracking URLs carry reference codes or status // tokens: never send a Referer from them and never store them in diff --git a/apps/web/src/app/campaigns/[slug]/page.test.ts b/apps/web/src/app/campaigns/[slug]/page.test.ts index c603e259..4c6dd964 100644 --- a/apps/web/src/app/campaigns/[slug]/page.test.ts +++ b/apps/web/src/app/campaigns/[slug]/page.test.ts @@ -2294,3 +2294,67 @@ describe("DonorWishesWall on /campaigns/[slug] (DOS/Give#320)", () => { expect(state.userCalls.some((c) => c.target === "rpc:list_hidden_campaign_wishes")).toBe(false) }) }) + +describe("EmbedWidgetDisclosure on /campaigns/[slug] (DOS/Give#335)", () => { + it("renders 'Nhúng vào website / báo chí' on public live and pre-launch campaigns, and hides it on draft/suspended previews", async () => { + const baseAnon = state.anonHandler + state.anonHandler = (call) => { + if (call.target === "rpc:public_ambassador_ref") { + return { data: [{ ref_code: "ab23cd45ef", display_name: "CLB Sinh viên Xanh" }] } + } + return baseAnon(call) + } + + const liveDoc = parseDoc( + renderToStaticMarkup( + await CampaignPage({ + params: Promise.resolve({ slug: SLUG }), + searchParams: Promise.resolve({ ref: "AB23CD45EF" }), + }) + ) + ) + const liveSummary = [...liveDoc.querySelectorAll("summary")].find((s) => + s.textContent?.includes("Nhúng vào website / báo chí") + ) + expect(liveSummary).toBeDefined() + expect(liveSummary!.closest("details")?.querySelector("textarea")?.textContent).toContain( + `/embed/${SLUG}?ref=ab23cd45ef` + ) + + // Public pre-launch teaser also offers embed snippet without money leakage. + state.anonHandler = (call) => { + if (call.target === "campaigns") { + return { + data: { + ...campaignFixture("approved"), + prelaunch_public: true, + starts_at: "2099-06-01T00:00:00.000Z", + }, + } + } + return baseAnon(call) + } + const preDoc = parseDoc(renderToStaticMarkup(await CampaignPage({ params: Promise.resolve({ slug: SLUG }) }))) + expect( + [...preDoc.querySelectorAll("summary")].some((s) => s.textContent?.includes("Nhúng vào website / báo chí")) + ).toBe(true) + + // Suspended preview hides embed disclosure. + state.session = { user: { id: VIEWER, email: "mod@dos.me", name: "Kiểm duyệt viên" }, accessToken: "mod-jwt" } + state.anonHandler = () => ({ data: null }) + state.userHandler = (call) => { + if (call.target === "campaigns") return { data: campaignFixture("suspended") } + if ( + call.target === "campaign_milestones" || + call.target === "campaign_updates" || + call.target === "campaign_media" || + call.target === "campaign_faqs" + ) { + return { data: [] } + } + return undefined + } + const suspendedHtml = renderToStaticMarkup(await CampaignPage({ params: Promise.resolve({ slug: SLUG }) })) + expect(suspendedHtml).not.toContain("Nhúng vào website / báo chí") + }) +}) diff --git a/apps/web/src/app/campaigns/[slug]/page.tsx b/apps/web/src/app/campaigns/[slug]/page.tsx index 5d6ac1c8..168f3876 100644 --- a/apps/web/src/app/campaigns/[slug]/page.tsx +++ b/apps/web/src/app/campaigns/[slug]/page.tsx @@ -19,6 +19,7 @@ import { RecentSupporters } from "@/components/campaign/RecentSupporters" import { StatementPreview } from "@/components/campaign/StatementPreview" import { StickyAside } from "@/components/campaign/StickyAside" import { TransparencySummaryBox } from "@/components/campaign/TransparencySummaryBox" +import { EmbedWidgetDisclosure } from "@/components/EmbedWidgetDisclosure" import { FollowButton } from "@/components/FollowButton" import { Markdown } from "@/components/Markdown" import { ProgressBar } from "@/components/ProgressBar" @@ -809,6 +810,12 @@ export default async function CampaignPage({ size="lg" /> + {ambassadorLinkEligible && ( + {ambassadorLinkEligible && ( { + it("renders a compact chrome-free card linking out to /campaigns in a new tab", () => { + const html = renderToStaticMarkup(createElement(EmbedNotFound)) + const doc = parser.parseFromString(html, "text/html") + + expect(doc.querySelector("h1")?.textContent.trim()).toBe("Không tìm thấy chiến dịch") + const link = doc.querySelector('a[href="/campaigns"]')! + expect(link).toBeTruthy() + expect(link.getAttribute("target")).toBe("_blank") + expect(link.getAttribute("rel")).toBe("noopener noreferrer") + expect(doc.querySelectorAll("form")).toHaveLength(0) + }) +}) diff --git a/apps/web/src/app/embed/[slug]/not-found.tsx b/apps/web/src/app/embed/[slug]/not-found.tsx new file mode 100644 index 00000000..b8d8660e --- /dev/null +++ b/apps/web/src/app/embed/[slug]/not-found.tsx @@ -0,0 +1,25 @@ +import { buttonClass } from "@/components/ui/Button" + +/** Compact chrome-free not-found card sized for `/embed/[slug]` iframes. */ +export default function EmbedNotFound() { + return ( +
+
+

Give

+

Không tìm thấy chiến dịch

+

Chiến dịch này không tồn tại, chưa công khai hoặc đang tạm dừng.

+
+ +
+ ) +} diff --git a/apps/web/src/app/embed/[slug]/page.test.ts b/apps/web/src/app/embed/[slug]/page.test.ts new file mode 100644 index 00000000..61a43677 --- /dev/null +++ b/apps/web/src/app/embed/[slug]/page.test.ts @@ -0,0 +1,297 @@ +// @vitest-environment happy-dom +import { Window } from "happy-dom" +import { renderToStaticMarkup } from "react-dom/server" +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" + +import type { CampaignStatus, PublicCampaign } from "@/lib/campaigns" +import { fakeDb, type Call, type Handler } from "@/test/fake-db" + +const CAMPAIGN_ID = "33333333-3333-4333-8333-333333333333" +const SLUG = "xay-truong-ban-may" + +const state = vi.hoisted(() => ({ + anonHandler: (() => undefined) as Handler, + anonCalls: [] as Call[], + serviceCalls: [] as Call[], +})) + +vi.mock("next/navigation", () => ({ + notFound: vi.fn((): never => { + throw new Error("NEXT_NOT_FOUND") + }), +})) + +const getSessionSpy = vi.fn(async () => { + throw new Error("getSession must NEVER be called by /embed/[slug]") +}) +vi.mock("@/lib/auth/session", () => ({ + getSession: getSessionSpy, +})) + +vi.mock("@/lib/supabase", () => ({ + dbAs: (token?: string) => { + if (token) throw new Error("embed/[slug] must NEVER pass a user token to dbAs()") + return fakeDb((call) => state.anonHandler(call), state.anonCalls) + }, + dbService: () => { + state.serviceCalls.push({ target: "dbService", ops: [] }) + throw new Error("embed/[slug] must NEVER use dbService()") + }, +})) + +const { default: EmbedCampaignPage, generateMetadata } = await import("./page") + +function campaignFixture(overrides: Partial = {}): PublicCampaign { + return { + id: CAMPAIGN_ID, + slug: SLUG, + type: "give", + funding_model: "flexible", + category_id: "cat-1", + title: "Xây trường Bản Mây", + summary: "Cùng dựng lớp học mới cho các em nhỏ vùng cao.", + story: "Nội dung chi tiết", + beneficiary_name: null, + beneficiary_relation: null, + cover_media_id: "cov-1", + asset: "VND", + goal_amount: 100_000_000, + min_contribution: 20_000, + stretch_goal_amount: null, + display_options: { progress_bar: true, backers_count: true, time_remaining: true }, + starts_at: "2026-11-01T00:00:00.000Z", + ends_at: "2099-12-31T00:00:00.000Z", + payment_window_days: 7, + status: "live", + prelaunch_public: false, + submitted_at: "2026-11-10T00:00:00.000Z", + approved_at: "2026-11-11T00:00:00.000Z", + outcome_at: null, + created_at: "2026-11-01T00:00:00.000Z", + updated_at: "2026-11-11T00:00:00.000Z", + category: { id: "cat-1", slug: "giao-duc", name: "Giáo dục", icon: null, color: null }, + cover: { storage_path: "campaigns/33333333/cover.webp", alt: "Ảnh trường Bản Mây" }, + ...overrides, + } +} + +function totalsFixture(overrides: Record = {}) { + return { + id: CAMPAIGN_ID, + type: "give", + asset: "VND", + goal_amount: 100_000_000, + pledged_amount: 0, + paid_amount: 45_000_000, + disbursable_amount: 45_000_000, + disbursed_amount: 0, + refunded_amount: 0, + unexplained_out_amount: 0, + unexplained_out_count: 0, + supporters_count: 18, + other_in_amount: 0, + refund_owed_amount: 0, + backers_count: 0, + payments_stopped_at: null, + payments_stopped_note: null, + own_transfer_amount: 0, + ...overrides, + } +} + +function parseDoc(html: string) { + const win = new Window() + win.document.body.innerHTML = html + return win.document +} + +beforeEach(() => { + vi.stubEnv("NEXT_PUBLIC_SITE_URL", "https://give.vn") + state.anonCalls.length = 0 + state.serviceCalls.length = 0 + getSessionSpy.mockClear() + state.anonHandler = (call) => { + if (call.target === "campaigns") return { data: campaignFixture() } + 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") return { data: totalsFixture() } + return undefined + } +}) + +afterEach(() => { + vi.unstubAllEnvs() +}) + +describe("/embed/[slug] metadata (DOS/Give#335)", () => { + it("sets noindex/nofollow and canonical for public campaigns and hides unpublished slugs", async () => { + const publicMeta = await generateMetadata({ params: Promise.resolve({ slug: SLUG }) }) + expect(publicMeta.title).toBe("Xây trường Bản Mây") + expect(publicMeta.robots).toEqual({ index: false, follow: false }) + expect(publicMeta.alternates?.canonical).toBe(`/campaigns/${SLUG}`) + + state.anonHandler = () => ({ data: campaignFixture({ status: "draft" }) }) + const draftMeta = await generateMetadata({ params: Promise.resolve({ slug: SLUG }) }) + expect(draftMeta.title).toBe("Không tìm thấy") + expect(draftMeta.robots).toEqual({ index: false, follow: false }) + expect(draftMeta.alternates).toBeUndefined() + + const badSlugMeta = await generateMetadata({ params: Promise.resolve({ slug: 'bad">' }) }) + ).rejects.toThrow("NEXT_NOT_FOUND") + await expect(EmbedCampaignPage({ params: Promise.resolve({ slug: "a".repeat(81) }) })).rejects.toThrow( + "NEXT_NOT_FOUND" + ) + expect(state.anonCalls).toEqual([]) + }) +}) diff --git a/apps/web/src/app/embed/[slug]/page.tsx b/apps/web/src/app/embed/[slug]/page.tsx new file mode 100644 index 00000000..5e15f322 --- /dev/null +++ b/apps/web/src/app/embed/[slug]/page.tsx @@ -0,0 +1,233 @@ +import clsx from "clsx" +import type { Metadata } from "next" +import Image from "next/image" +import { notFound } from "next/navigation" + +import { StatusBadge, TypeBadge } from "@/components/badges" +import { ProgressBar } from "@/components/ProgressBar" +import { Badge } from "@/components/ui/Badge" +import { buttonClass } from "@/components/ui/Button" +import { CheckIcon } from "@/components/ui/icons" +import { siteOrigin } from "@/lib/auth/origin" +import { + getCampaignBySlug, + getPublicOrganizer, + isPublicCampaignVisible, + isPublicStatus, + type DisplayOptions, +} from "@/lib/campaigns" +import { publicCoverUrl } from "@/lib/cover-urls" +import { buildCampaignOutboundUrl, parseEmbedOptions } from "@/lib/embed" +import { daysLeft, formatDate, formatVnd, progressPercent } from "@/lib/format" +import { SLUG_PATTERN } from "@/lib/slug" +import { getMoneyTotals, raisedAmount } from "@/lib/statement" +import { dbAs } from "@/lib/supabase" + +export const dynamic = "force-dynamic" + +async function loadPublicEmbedCampaign(slug: string) { + if (!SLUG_PATTERN.test(slug) || slug.length > 80) return null + const db = dbAs() + const campaign = await getCampaignBySlug(db, slug) + if (!campaign || !isPublicCampaignVisible(campaign)) return null + return { campaign, db } +} + +export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }): Promise { + const loaded = await loadPublicEmbedCampaign((await params).slug) + if (!loaded) { + return { + title: "Không tìm thấy", + robots: { index: false, follow: false }, + } + } + const { campaign } = loaded + return { + title: campaign.title, + ...(campaign.summary ? { description: campaign.summary } : {}), + alternates: { canonical: `/campaigns/${encodeURIComponent(campaign.slug)}` }, + robots: { index: false, follow: false }, + } +} + +/** + * Clickjacking-safe, chrome-free, strictly read-only campaign widget for + * third-party `' + ) + + const compactBtn = [...container.querySelectorAll("button")].find((b) => b.textContent?.includes("Thu gọn"))! + const darkBtn = [...container.querySelectorAll("button")].find((b) => b.textContent === "Tối")! + act(() => { + compactBtn.click() + darkBtn.click() + }) + + expect(textarea.value).toContain( + 'src="https://give.vn/embed/xay-truong?theme=dark&compact=1&ref=ab23cd45ef"' + ) + expect(textarea.value).toContain('height="180"') + + const copyBtn = [...container.querySelectorAll("button")].find((b) => b.textContent?.includes("Sao chép mã nhúng"))! + await act(async () => { + copyBtn.click() + }) + await Promise.resolve() + + expect(writeTextMock).toHaveBeenCalledWith(textarea.value) + expect(container.querySelector('[aria-live="polite"]')?.textContent).toBe("Đã sao chép mã nhúng") + expect(sendBeacon).toHaveBeenCalledTimes(1) + expect(JSON.parse(sentBodies[0])).toEqual({ + campaignId: "33333333-3333-4333-8333-333333333333", + event: "share_click", + }) + + act(() => { + vi.advanceTimersByTime(3000) + }) + expect(container.querySelector('[aria-live="polite"]')?.textContent).toBe("") + }) + + it("handles clipboard errors gracefully and cleans up pending timer on unmount", async () => { + vi.useFakeTimers() + const writeTextMock = vi.fn().mockRejectedValue(new Error("Blocked")) + setClipboardWriteText(writeTextMock) + + renderDisclosure({ + slug: "xay-truong", + title: "Xây trường", + origin: "https://give.vn", + ambassadorRef: "bad!!ref", + }) + + const textarea = container.querySelector("textarea")! + expect(textarea.value).toContain('src="https://give.vn/embed/xay-truong"') + + const copyBtn = [...container.querySelectorAll("button")].find((b) => b.textContent?.includes("Sao chép mã nhúng"))! + await act(async () => { + copyBtn.click() + }) + expect(container.querySelector('[aria-live="polite"]')?.textContent).toContain("Không chép được tự động") + expect(vi.getTimerCount()).toBe(1) + + act(() => { + root.unmount() + }) + expect(vi.getTimerCount()).toBe(0) + }) +}) diff --git a/apps/web/src/components/EmbedWidgetDisclosure.tsx b/apps/web/src/components/EmbedWidgetDisclosure.tsx new file mode 100644 index 00000000..60f5bf62 --- /dev/null +++ b/apps/web/src/components/EmbedWidgetDisclosure.tsx @@ -0,0 +1,191 @@ +"use client" + +import clsx from "clsx" +import { useEffect, useId, useRef, useState, useSyncExternalStore } from "react" + +import { buttonClass } from "@/components/ui/Button" +import { CheckIcon, CodeIcon } from "@/components/ui/icons" +import { trackShareClick } from "@/lib/analytics-client" +import { + buildEmbedIframeCode, + EMBED_HEIGHT_COMPACT, + EMBED_HEIGHT_DEFAULT, + EMBED_THEME_LABELS, + EMBED_THEMES, + type EmbedTheme, +} from "@/lib/embed" + +const noSubscribe = () => () => {} + +/** + * Collapsible `"Nhúng vào website / báo chí"` panel inside the campaign + * sidebar (DOS/Give#335). Builds a copyable, HTML-escaped `' + ) + expect(defaultSnippet).toContain(`height="${EMBED_HEIGHT_DEFAULT}"`) + + const compactDark = buildEmbedIframeCode({ + slug: "xay-truong", + title: "Xây trường\nBản Mây", + origin: "https://give.vn", + theme: "dark", + compact: true, + ref: "AB23CD45EF", + }) + expect(compactDark).toContain('src="https://give.vn/embed/xay-truong?theme=dark&compact=1&ref=ab23cd45ef"') + expect(compactDark).toContain('title="Xây trường Bản Mây · Give"') + expect(compactDark).toContain(`height="${EMBED_HEIGHT_COMPACT}"`) + expect(compactDark).toContain('referrerpolicy="strict-origin-when-cross-origin"') + }) +}) diff --git a/apps/web/src/lib/embed.ts b/apps/web/src/lib/embed.ts new file mode 100644 index 00000000..7540ad25 --- /dev/null +++ b/apps/web/src/lib/embed.ts @@ -0,0 +1,114 @@ +import { sanitizeAmbassadorRef } from "./ambassadors" + +/** + * Pure helpers for the clickjacking-safe `/embed/[slug]` widget and its + * copy-paste `` +} diff --git a/apps/web/src/proxy.test.ts b/apps/web/src/proxy.test.ts index a6ebdb15..f71602b1 100644 --- a/apps/web/src/proxy.test.ts +++ b/apps/web/src/proxy.test.ts @@ -193,6 +193,32 @@ describe("proxy session refresh", () => { }) expect(loggedText()).not.toContain("rt-1") }) + + it("skips cookie refresh and marks x-give-embed on /embed and /embed/*, while stripping spoofed headers elsewhere (DOS/Give#335)", async () => { + for (const path of ["/embed", "/embed/xay-truong-ban-may"]) { + const response = await proxy( + new NextRequest(`https://give.example${path}`, { headers: { cookie: "__Host-give_rt=rt-1" } }) + ) + expect(fetchMock).not.toHaveBeenCalled() + expectCookiesKept(response) + expect(response.headers.get("x-middleware-request-x-give-embed")).toBe("1") + } + + const spoofed = await proxy( + new NextRequest("https://give.example/campaigns/xay-truong", { + headers: { "x-give-embed": "1" }, + }) + ) + expect(fetchMock).not.toHaveBeenCalled() + expect(spoofed.headers.get("x-middleware-request-x-give-embed")).toBeNull() + + const spoofedEmbedded = await proxy( + new NextRequest("https://give.example/embedded", { + headers: { "x-give-embed": "1" }, + }) + ) + expect(spoofedEmbedded.headers.get("x-middleware-request-x-give-embed")).toBeNull() + }) }) describe("proxy matcher exclusions", () => { diff --git a/apps/web/src/proxy.ts b/apps/web/src/proxy.ts index c2e97c54..9b04338e 100644 --- a/apps/web/src/proxy.ts +++ b/apps/web/src/proxy.ts @@ -5,21 +5,42 @@ import { isDeadRefreshToken, loadOidcConfig, refreshTokens, tokenFailureLog } fr import { appOrigin } from "@/lib/auth/origin" import { needsRefresh } from "@/lib/auth/token" +const EMBED_HEADER = "x-give-embed" + +export function isEmbedPath(pathname: string): boolean { + return pathname === "/embed" || pathname.startsWith("/embed/") +} + /** * Keeps the session's access token fresh. When it is missing or about to * expire and a refresh token exists, rotate both and hand the new access * token to this request too, so server components render signed in. The * refresh call gives up after TOKEN_TIMEOUT_MS (set in oidc.ts) and never * follows a redirect. + * + * Embed widget routes (`/embed`, `/embed/*`) are strictly anonymous and + * read-only (DOS/Give#335): they never read/refresh session cookies, and carry + * a proxy-controlled `x-give-embed` header so `RootLayout` can skip `getSession()`. */ export async function proxy(request: NextRequest) { + if (isEmbedPath(request.nextUrl.pathname)) { + const requestHeaders = new Headers(request.headers) + requestHeaders.set(EMBED_HEADER, "1") + return NextResponse.next({ request: { headers: requestHeaders } }) + } + + const hadSpoofedEmbedHeader = request.headers.has(EMBED_HEADER) + if (hadSpoofedEmbedHeader) request.headers.delete(EMBED_HEADER) + const { hostname } = request.nextUrl const accessName = cookieName(SESSION_ACCESS, hostname) const refreshName = cookieName(SESSION_REFRESH, hostname) const access = request.cookies.get(accessName)?.value const refresh = request.cookies.get(refreshName)?.value - if (!refresh || !needsRefresh(access)) return NextResponse.next() + if (!refresh || !needsRefresh(access)) { + return hadSpoofedEmbedHeader ? NextResponse.next({ request }) : NextResponse.next() + } try { const tokens = await refreshTokens(loadOidcConfig(appOrigin(request.nextUrl.origin)), refresh) @@ -37,7 +58,7 @@ export async function proxy(request: NextRequest) { // config mistake fails loudly instead of signing everyone out. if (!isDeadRefreshToken(error)) { console.warn("auth.refresh.failed", tokenFailureLog(error)) - return NextResponse.next() + return hadSpoofedEmbedHeader ? NextResponse.next({ request }) : NextResponse.next() } request.cookies.delete(accessName) const response = NextResponse.next({ request }) diff --git a/apps/web/src/test/next-config.test.ts b/apps/web/src/test/next-config.test.ts index 8466c79a..eb2c9d86 100644 --- a/apps/web/src/test/next-config.test.ts +++ b/apps/web/src/test/next-config.test.ts @@ -1,3 +1,4 @@ +import { getPathMatch } from "next/dist/shared/lib/router/utils/path-match" import { describe, expect, it } from "vitest" import nextConfig from "../../next.config" @@ -19,6 +20,21 @@ function globToRegExp(glob: string): RegExp { const patterns = (nextConfig.images?.localPatterns ?? []).map((p) => globToRegExp(p.pathname ?? "**")) const optimizable = (path: string) => patterns.some((re) => re.test(path)) +/** Resolves all headers Next.js applies to `pathname` in rule order (later matching rules override by key). */ +async function resolveHeadersForPath(pathname: string): Promise> { + const rules = (await nextConfig.headers?.()) ?? [] + const resolved = new Map() + for (const rule of rules) { + const matcher = getPathMatch(rule.source) + if (matcher(pathname)) { + for (const header of rule.headers) { + resolved.set(header.key.toLowerCase(), header.value) + } + } + } + return resolved +} + describe("image optimizer allow-list", () => { it("optimizes public covers only, never evidence (its cache would outlive a staff hide, DOS/Give#58)", () => { const uuid = "22222222-2222-4222-8222-222222222222" @@ -30,9 +46,32 @@ describe("image optimizer allow-list", () => { }) describe("response headers", () => { + it("keeps X-Frame-Options: DENY on all non-embed routes while excluding /embed and /embed/* (DOS/Give#335)", async () => { + const rules = (await nextConfig.headers?.()) ?? [] + const globalIdx = rules.findIndex((r) => r.source === "/((?!embed(?:/|$)).*)") + const embedIdx = rules.findIndex((r) => r.source === "/embed/:path*") + expect(globalIdx).toBeGreaterThanOrEqual(0) + expect(embedIdx).toBeGreaterThan(globalIdx) + + for (const path of ["/", "/campaigns/abc", "/me", "/admin", "/donations/GV123", "/invites/tok123", "/embedded"]) { + const headers = await resolveHeadersForPath(path) + expect(headers.get("x-frame-options"), path).toBe("DENY") + expect(headers.get("x-content-type-options"), path).toBe("nosniff") + expect(headers.get("content-security-policy"), path).toBeUndefined() + } + + for (const embedPath of ["/embed", "/embed/", "/embed/abc", "/embed/abc/nested"]) { + const headers = await resolveHeadersForPath(embedPath) + expect(headers.get("x-frame-options"), embedPath).toBeUndefined() + expect(headers.get("content-security-policy"), embedPath).toBe("frame-ancestors *") + expect(headers.get("x-content-type-options"), embedPath).toBe("nosniff") + expect(headers.get("referrer-policy"), embedPath).toBe("strict-origin-when-cross-origin") + } + }) + it("strips Referer and disables caching on /donations/* after the site-wide defaults (DOS/Give#50)", async () => { const rules = (await nextConfig.headers?.()) ?? [] - const globalIdx = rules.findIndex((r) => r.source === "/:path*") + const globalIdx = rules.findIndex((r) => r.source === "/((?!embed(?:/|$)).*)") const donationsIdx = rules.findIndex((r) => r.source === "/donations/:path*") expect(globalIdx).toBeGreaterThanOrEqual(0) expect(donationsIdx).toBeGreaterThan(globalIdx) @@ -42,11 +81,15 @@ describe("response headers", () => { { key: "Cache-Control", value: "private, no-store" }, ]) ) + const resolved = await resolveHeadersForPath("/donations/GV123") + expect(resolved.get("x-frame-options")).toBe("DENY") + expect(resolved.get("referrer-policy")).toBe("no-referrer") + expect(resolved.get("cache-control")).toBe("private, no-store") }) it("strips Referer, disables caching, and sets noindex on /invites/* after the site-wide defaults (DOS/Give#253)", async () => { const rules = (await nextConfig.headers?.()) ?? [] - const globalIdx = rules.findIndex((r) => r.source === "/:path*") + const globalIdx = rules.findIndex((r) => r.source === "/((?!embed(?:/|$)).*)") const invitesIdx = rules.findIndex((r) => r.source === "/invites/:path*") expect(globalIdx).toBeGreaterThanOrEqual(0) expect(invitesIdx).toBeGreaterThan(globalIdx) @@ -57,5 +100,8 @@ describe("response headers", () => { { key: "X-Robots-Tag", value: "noindex, nofollow" }, ]) ) + const resolved = await resolveHeadersForPath("/invites/tok123") + expect(resolved.get("x-frame-options")).toBe("DENY") + expect(resolved.get("x-robots-tag")).toBe("noindex, nofollow") }) }) From edab363a67a592348a499c68310d6f8b41307d61 Mon Sep 17 00:00:00 2001 From: JOY <5027251+JOY@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:42:30 +0700 Subject: [PATCH 2/5] fix(embed): harden proxy matcher, compact layout, radius, and fallback routes (Refs #335) --- .../src/app/embed/[slug]/[...rest]/page.tsx | 7 ++ .../src/app/embed/[slug]/not-found.test.ts | 22 ----- apps/web/src/app/embed/[slug]/not-found.tsx | 25 ------ apps/web/src/app/embed/[slug]/page.test.ts | 54 ++++++++++++ apps/web/src/app/embed/[slug]/page.tsx | 82 +++++++++++-------- apps/web/src/app/embed/not-found.test.ts | 78 ++++++++++++++++++ apps/web/src/app/embed/not-found.tsx | 7 ++ apps/web/src/app/embed/page.tsx | 7 ++ apps/web/src/app/layout.test.ts | 49 +++++------ apps/web/src/app/layout.tsx | 10 +-- apps/web/src/components/EmbedNotFoundCard.tsx | 51 ++++++++++++ .../components/EmbedWidgetDisclosure.test.ts | 2 +- .../src/components/EmbedWidgetDisclosure.tsx | 4 +- .../src/components/layout/LayoutShell.test.ts | 4 +- .../web/src/components/layout/LayoutShell.tsx | 3 +- apps/web/src/lib/embed.test.ts | 2 +- apps/web/src/lib/embed.ts | 2 +- apps/web/src/proxy.test.ts | 60 +++++++++++--- apps/web/src/proxy.ts | 45 ++++++---- apps/web/src/test/next-config.test.ts | 18 +++- 20 files changed, 383 insertions(+), 149 deletions(-) create mode 100644 apps/web/src/app/embed/[slug]/[...rest]/page.tsx delete mode 100644 apps/web/src/app/embed/[slug]/not-found.test.ts delete mode 100644 apps/web/src/app/embed/[slug]/not-found.tsx create mode 100644 apps/web/src/app/embed/not-found.test.ts create mode 100644 apps/web/src/app/embed/not-found.tsx create mode 100644 apps/web/src/app/embed/page.tsx create mode 100644 apps/web/src/components/EmbedNotFoundCard.tsx diff --git a/apps/web/src/app/embed/[slug]/[...rest]/page.tsx b/apps/web/src/app/embed/[slug]/[...rest]/page.tsx new file mode 100644 index 00000000..2782075d --- /dev/null +++ b/apps/web/src/app/embed/[slug]/[...rest]/page.tsx @@ -0,0 +1,7 @@ +import { notFound } from "next/navigation" + +export const dynamic = "force-dynamic" + +export default function EmbedNestedNotFoundPage(): never { + notFound() +} diff --git a/apps/web/src/app/embed/[slug]/not-found.test.ts b/apps/web/src/app/embed/[slug]/not-found.test.ts deleted file mode 100644 index bbb793cd..00000000 --- a/apps/web/src/app/embed/[slug]/not-found.test.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { Window } from "happy-dom" -import { createElement } from "react" -import { renderToStaticMarkup } from "react-dom/server" -import { describe, expect, it } from "vitest" - -import EmbedNotFound from "./not-found" - -const parser = new new Window().DOMParser() - -describe("/embed/[slug] EmbedNotFound (DOS/Give#335)", () => { - it("renders a compact chrome-free card linking out to /campaigns in a new tab", () => { - const html = renderToStaticMarkup(createElement(EmbedNotFound)) - const doc = parser.parseFromString(html, "text/html") - - expect(doc.querySelector("h1")?.textContent.trim()).toBe("Không tìm thấy chiến dịch") - const link = doc.querySelector('a[href="/campaigns"]')! - expect(link).toBeTruthy() - expect(link.getAttribute("target")).toBe("_blank") - expect(link.getAttribute("rel")).toBe("noopener noreferrer") - expect(doc.querySelectorAll("form")).toHaveLength(0) - }) -}) diff --git a/apps/web/src/app/embed/[slug]/not-found.tsx b/apps/web/src/app/embed/[slug]/not-found.tsx deleted file mode 100644 index b8d8660e..00000000 --- a/apps/web/src/app/embed/[slug]/not-found.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { buttonClass } from "@/components/ui/Button" - -/** Compact chrome-free not-found card sized for `/embed/[slug]` iframes. */ -export default function EmbedNotFound() { - return ( -
-
-

Give

-

Không tìm thấy chiến dịch

-

Chiến dịch này không tồn tại, chưa công khai hoặc đang tạm dừng.

-
- -
- ) -} diff --git a/apps/web/src/app/embed/[slug]/page.test.ts b/apps/web/src/app/embed/[slug]/page.test.ts index 61a43677..90ffb2bf 100644 --- a/apps/web/src/app/embed/[slug]/page.test.ts +++ b/apps/web/src/app/embed/[slug]/page.test.ts @@ -210,7 +210,9 @@ describe("/embed/[slug] page (DOS/Give#335)", () => { ) ) expect(darkCompactDoc.querySelector("article")?.getAttribute("data-embed-theme")).toBe("dark") + expect(darkCompactDoc.querySelector("article")?.className).toContain("rounded-md") expect(darkCompactDoc.querySelector("h1")?.className).toContain("truncate") + expect(darkCompactDoc.body.textContent).not.toContain("Mục tiêu") expect(darkCompactDoc.querySelector("a")?.getAttribute("href")).toBe( `https://give.vn/campaigns/${SLUG}?ref=ab23cd45ef` ) @@ -294,4 +296,56 @@ describe("/embed/[slug] page (DOS/Give#335)", () => { ) expect(state.anonCalls).toEqual([]) }) + + it("calls notFound() when prelaunch_public=true approved campaign has past starts_at", async () => { + state.anonHandler = () => ({ + data: campaignFixture({ + status: "approved", + prelaunch_public: true, + starts_at: "2020-01-01T00:00:00.000Z", + }), + }) + await expect(EmbedCampaignPage({ params: Promise.resolve({ slug: SLUG }) })).rejects.toThrow("NEXT_NOT_FOUND") + }) + + it("handles missing totals, goal_amount=0, expired live campaigns, and display_options=false safely", async () => { + // 1. totals === null on live campaign omits 0 ₫ and progressbar + state.anonHandler = (call) => { + if (call.target === "campaigns") return { data: campaignFixture({ status: "live" }) } + if (call.target === "rpc:public_organizer") return { data: [] } + if (call.target === "public_campaigns") return { data: null } + return undefined + } + const noTotalsDoc = parseDoc( + renderToStaticMarkup(await EmbedCampaignPage({ params: Promise.resolve({ slug: SLUG }) })) + ) + expect(noTotalsDoc.querySelector('[role="progressbar"]')).toBeNull() + expect(noTotalsDoc.body.textContent).not.toContain("đã nhận") + expect(noTotalsDoc.body.textContent).toContain("Mục tiêu 100.000.000") + + // 2. Expired live campaign shows "Đã hết hạn" and "Xem chi tiết" instead of "Ủng hộ ngay" + state.anonHandler = (call) => { + if (call.target === "campaigns") { + return { + data: campaignFixture({ + status: "live", + ends_at: "2020-01-01T00:00:00.000Z", + goal_amount: 0, + display_options: { progress_bar: false, backers_count: false, time_remaining: true }, + }), + } + } + if (call.target === "rpc:public_organizer") return { data: [] } + if (call.target === "public_campaigns") return { data: totalsFixture({ paid_amount: 0, supporters_count: 5 }) } + return undefined + } + const expiredDoc = parseDoc( + renderToStaticMarkup(await EmbedCampaignPage({ params: Promise.resolve({ slug: SLUG }) })) + ) + expect(expiredDoc.querySelector('[role="progressbar"]')).toBeNull() + expect(expiredDoc.body.textContent).not.toContain("5 người ủng hộ") + expect(expiredDoc.body.textContent).toContain("Đã hết hạn") + expect(expiredDoc.querySelector("a")?.textContent).toContain("Xem chi tiết") + expect(expiredDoc.querySelector("a")?.textContent).not.toContain("Ủng hộ ngay") + }) }) diff --git a/apps/web/src/app/embed/[slug]/page.tsx b/apps/web/src/app/embed/[slug]/page.tsx index 5e15f322..2925d1c8 100644 --- a/apps/web/src/app/embed/[slug]/page.tsx +++ b/apps/web/src/app/embed/[slug]/page.tsx @@ -90,53 +90,63 @@ export default async function EmbedCampaignPage({ const showBackers = displayOptions.backers_count !== false const showTime = displayOptions.time_remaining !== false - const raised = publicStatus ? raisedAmount(totals, campaign.type) : 0 - const percent = publicStatus ? progressPercent(raised, campaign.goal_amount) : 0 - const people = publicStatus && totals ? (isGive ? totals.supporters_count : totals.backers_count) : null - const days = publicStatus ? daysLeft(campaign.ends_at) : null + const hasTotals = publicStatus && totals !== null + const raised = hasTotals ? raisedAmount(totals, campaign.type) : 0 + const percent = hasTotals ? progressPercent(raised, campaign.goal_amount) : 0 + const people = hasTotals ? (isGive ? totals.supporters_count : totals.backers_count) : null + const now = new Date() + const days = publicStatus ? daysLeft(campaign.ends_at, now) : null + const notStarted = + campaign.starts_at !== null && + !Number.isNaN(Date.parse(campaign.starts_at)) && + new Date(campaign.starts_at).getTime() > now.getTime() + const expired = days !== null && days <= 0 + const canSupportNow = publicStatus && campaign.status === "live" && !expired && !notStarted const validStartsAt = campaign.starts_at && !Number.isNaN(Date.parse(campaign.starts_at)) ? campaign.starts_at : null const metaParts = publicStatus - ? [ - `Mục tiêu ${formatVnd(campaign.goal_amount)}`, - !options.compact && showBackers && people !== null - ? `${people} ${isGive ? "người ủng hộ" : "người đồng hành"}` - : null, - !options.compact && campaign.status === "live" && showTime && days !== null - ? days > 0 - ? `Còn ${days} ngày` - : "Đã hết hạn" - : null, - ].filter(Boolean) + ? options.compact + ? [] + : [ + `Mục tiêu ${formatVnd(campaign.goal_amount)}`, + hasTotals && showBackers && people !== null + ? `${people} ${isGive ? "người ủng hộ" : "người đồng hành"}` + : null, + campaign.status === "live" && showTime && days !== null + ? days > 0 + ? `Còn ${days} ngày` + : "Đã hết hạn" + : null, + ].filter(Boolean) : [] - const ctaLabel = publicStatus ? (campaign.status === "live" ? "Ủng hộ ngay" : "Xem chi tiết") : "Xem chi tiết" + const ctaLabel = canSupportNow ? "Ủng hộ ngay" : "Xem chi tiết" return (
{coverSrc && ( )}
-
-
+
+
{publicStatus ? : Sắp ra mắt}
@@ -168,25 +178,31 @@ export default async function EmbedCampaignPage({
-
+
{publicStatus ? ( <> - {showProgress && } + {hasTotals && showProgress && }
-

- {formatVnd(raised)}{" "} - - {isGive ? "đã nhận" : "đã cam kết"} - {showProgress && ` · ${percent}%`} - -

+ {hasTotals ? ( +

+ + {formatVnd(raised)} + {" "} + + {isGive ? "đã nhận" : "đã cam kết"} + {showProgress && ` · ${percent}%`} + +

+ ) : ( +

Mục tiêu {formatVnd(campaign.goal_amount)}

+ )} {metaParts.length > 0 &&

{metaParts.join(" · ")}

}
) : ( -
+

Sắp ra mắt

diff --git a/apps/web/src/app/embed/not-found.test.ts b/apps/web/src/app/embed/not-found.test.ts new file mode 100644 index 00000000..a53e0df2 --- /dev/null +++ b/apps/web/src/app/embed/not-found.test.ts @@ -0,0 +1,78 @@ +// @vitest-environment happy-dom +import { Window } from "happy-dom" +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" + +const state = vi.hoisted(() => ({ + theme: null as string | null, +})) + +vi.mock("next/navigation", () => ({ + useSearchParams: () => new URLSearchParams(state.theme ? `theme=${state.theme}` : ""), + notFound: vi.fn((): never => { + throw new Error("NEXT_NOT_FOUND") + }), +})) + +const { default: EmbedNotFound } = await import("./not-found") +const { default: EmbedRootPage } = await import("./page") +const { default: EmbedNestedNotFoundPage } = await import("./[slug]/[...rest]/page") +const { EmbedNotFoundCard } = await import("@/components/EmbedNotFoundCard") + +declare global { + var IS_REACT_ACT_ENVIRONMENT: boolean | undefined +} + +const parser = new new Window().DOMParser() +let container: HTMLDivElement +let root: Root + +beforeEach(() => { + globalThis.IS_REACT_ACT_ENVIRONMENT = true + state.theme = null + vi.stubEnv("NEXT_PUBLIC_SITE_URL", "https://give.vn") + container = document.createElement("div") + document.body.append(container) + root = createRoot(container) +}) + +afterEach(() => { + act(() => root.unmount()) + container.remove() + vi.unstubAllEnvs() +}) + +describe("/embed fallback routes and EmbedNotFound (DOS/Give#335)", () => { + it("calls notFound() on /embed root and /embed/[slug]/[...rest] nested paths", () => { + expect(() => EmbedRootPage()).toThrow("NEXT_NOT_FOUND") + expect(() => EmbedNestedNotFoundPage()).toThrow("NEXT_NOT_FOUND") + }) + + it("renders compact chrome-free not-found card linking out in a new tab and honors ?theme=", () => { + const html = renderToStaticMarkup(createElement(EmbedNotFound)) + const doc = parser.parseFromString(html, "text/html") + + expect(doc.querySelector("h1")?.textContent.trim()).toBe("Không tìm thấy chiến dịch") + const card = doc.querySelector("[data-embed-theme]")! + expect(card.className).toContain("rounded-md") + const link = doc.querySelector('a[href="https://give.vn/campaigns"]')! + expect(link).toBeTruthy() + expect(link.getAttribute("target")).toBe("_blank") + expect(link.getAttribute("rel")).toBe("noopener noreferrer") + expect(doc.querySelectorAll("form")).toHaveLength(0) + + state.theme = "dark" + act(() => { + root.render(createElement(EmbedNotFoundCard, { campaignsUrl: "https://give.vn/campaigns" })) + }) + expect(container.querySelector("[data-embed-theme]")?.getAttribute("data-embed-theme")).toBe("dark") + + state.theme = "invalid" + act(() => { + root.render(createElement(EmbedNotFoundCard, { campaignsUrl: "https://give.vn/campaigns" })) + }) + expect(container.querySelector("[data-embed-theme]")?.getAttribute("data-embed-theme")).toBe("light") + }) +}) diff --git a/apps/web/src/app/embed/not-found.tsx b/apps/web/src/app/embed/not-found.tsx new file mode 100644 index 00000000..1d182e55 --- /dev/null +++ b/apps/web/src/app/embed/not-found.tsx @@ -0,0 +1,7 @@ +import { EmbedNotFoundCard } from "@/components/EmbedNotFoundCard" +import { siteOrigin } from "@/lib/auth/origin" + +export default function EmbedNotFound() { + const origin = siteOrigin() + return +} diff --git a/apps/web/src/app/embed/page.tsx b/apps/web/src/app/embed/page.tsx new file mode 100644 index 00000000..c9645376 --- /dev/null +++ b/apps/web/src/app/embed/page.tsx @@ -0,0 +1,7 @@ +import { notFound } from "next/navigation" + +export const dynamic = "force-dynamic" + +export default function EmbedRootPage(): never { + notFound() +} diff --git a/apps/web/src/app/layout.test.ts b/apps/web/src/app/layout.test.ts index 3033a06d..5e588346 100644 --- a/apps/web/src/app/layout.test.ts +++ b/apps/web/src/app/layout.test.ts @@ -3,7 +3,6 @@ import { renderToStaticMarkup } from "react-dom/server" import { beforeEach, describe, expect, it, vi } from "vitest" const state = vi.hoisted(() => ({ - headers: new Headers(), pathname: "/", session: null as { user: { id: string; email: string | null; name: string | null }; accessToken: string } | null, })) @@ -12,10 +11,6 @@ vi.mock("next/font/google", () => ({ Be_Vietnam_Pro: () => ({ variable: "--font-be-vietnam-pro" }), })) -vi.mock("next/headers", () => ({ - headers: vi.fn(async () => state.headers), -})) - vi.mock("next/navigation", () => ({ usePathname: () => state.pathname, })) @@ -50,9 +45,8 @@ vi.mock("@/components/layout/RingBoxScroll", () => ({ const { default: RootLayout } = await import("./layout") -describe("RootLayout chrome & session isolation (DOS/Give#335)", () => { +describe("RootLayout chrome isolation (DOS/Give#335)", () => { beforeEach(() => { - state.headers = new Headers() state.pathname = "/" state.session = { user: { id: "user-1", email: "user@dos.me", name: "Nguyễn An" }, @@ -62,27 +56,28 @@ describe("RootLayout chrome & session isolation (DOS/Give#335)", () => { countUnreadNoticesMock.mockClear() }) - it("renders SiteHeader, SiteFooter, and RingBoxScroll with session on normal routes", async () => { - const html = renderToStaticMarkup(await RootLayout({ children: createElement("div", null, "Page") as ReactNode })) - expect(getSessionMock).toHaveBeenCalledTimes(1) - expect(countUnreadNoticesMock).toHaveBeenCalledTimes(1) - expect(html).toContain("SignedIn(3)") - expect(html).toContain("SiteFooter") - expect(html).toContain("ring-box-scroll") - expect(html).toContain("Page") + it("renders SiteHeader, SiteFooter, and RingBoxScroll on normal routes", async () => { + for (const path of ["/", "/campaigns/xay-truong", "/embedded"]) { + state.pathname = path + const html = renderToStaticMarkup(await RootLayout({ children: createElement("div", null, "Page") as ReactNode })) + expect(html).toContain("SignedIn(3)") + expect(html).toContain("SiteFooter") + expect(html).toContain("ring-box-scroll") + expect(html).toContain("Page") + } }) - it("skips getSession() and omits chrome completely when x-give-embed is 1", async () => { - state.headers = new Headers({ "x-give-embed": "1" }) - state.pathname = "/embed/xay-truong" - - const html = renderToStaticMarkup(await RootLayout({ children: createElement("div", null, "Embed") as ReactNode })) - expect(getSessionMock).not.toHaveBeenCalled() - expect(countUnreadNoticesMock).not.toHaveBeenCalled() - expect(html).not.toContain("SignedIn") - expect(html).not.toContain("SignedOut") - expect(html).not.toContain("SiteFooter") - expect(html).not.toContain("ring-box-scroll") - expect(html).toContain("Embed") + it("omits SiteHeader, SiteFooter, and RingBoxScroll on /embed and /embed/*", async () => { + for (const path of ["/embed", "/embed/xay-truong", "/Embed/xay-truong"]) { + state.pathname = path + const html = renderToStaticMarkup( + await RootLayout({ children: createElement("div", null, "Embed") as ReactNode }) + ) + expect(html).not.toContain("SignedIn") + expect(html).not.toContain("SignedOut") + expect(html).not.toContain("SiteFooter") + expect(html).not.toContain("ring-box-scroll") + expect(html).toContain("Embed") + } }) }) diff --git a/apps/web/src/app/layout.tsx b/apps/web/src/app/layout.tsx index 65361e7b..e23da9ee 100644 --- a/apps/web/src/app/layout.tsx +++ b/apps/web/src/app/layout.tsx @@ -1,6 +1,5 @@ import type { Metadata } from "next" import { Be_Vietnam_Pro } from "next/font/google" -import { headers } from "next/headers" import type { ReactNode } from "react" import { LayoutShell } from "@/components/layout/LayoutShell" @@ -40,18 +39,13 @@ async function unreadNotices(session: Session): Promise { } export default async function RootLayout({ children }: { children: ReactNode }) { - // Embed widget requests set x-give-embed in proxy.ts and stay strictly anonymous (DOS/Give#335). - const isEmbed = (await headers()).get("x-give-embed") === "1" - const session = isEmbed ? null : await getSession() + const session = await getSession() const unread = session ? await unreadNotices(session) : null return ( - } - footer={isEmbed ? null : } - > + } footer={}> {children} diff --git a/apps/web/src/components/EmbedNotFoundCard.tsx b/apps/web/src/components/EmbedNotFoundCard.tsx new file mode 100644 index 00000000..36cbd856 --- /dev/null +++ b/apps/web/src/components/EmbedNotFoundCard.tsx @@ -0,0 +1,51 @@ +"use client" + +import { useSearchParams } from "next/navigation" +import { Suspense } from "react" + +import { buttonClass } from "@/components/ui/Button" +import { parseEmbedOptions, type EmbedTheme } from "@/lib/embed" + +function EmbedNotFoundCardBody({ campaignsUrl, theme }: { campaignsUrl: string; theme: EmbedTheme }) { + return ( +

+ ) +} + +function EmbedNotFoundWithSearch({ campaignsUrl }: { campaignsUrl: string }) { + const searchParams = useSearchParams() + const { theme } = parseEmbedOptions({ theme: searchParams.get("theme") ?? undefined }) + return +} + +/** + * Compact chrome-free not-found card sized for `/embed/*` iframes (including + * 180px compact embeds) and honoring `?theme=light|dark|auto` (DOS/Give#335). + */ +export function EmbedNotFoundCard({ campaignsUrl = "/campaigns" }: { campaignsUrl?: string }) { + return ( + }> + + + ) +} diff --git a/apps/web/src/components/EmbedWidgetDisclosure.test.ts b/apps/web/src/components/EmbedWidgetDisclosure.test.ts index 8c3a18c6..17dd858f 100644 --- a/apps/web/src/components/EmbedWidgetDisclosure.test.ts +++ b/apps/web/src/components/EmbedWidgetDisclosure.test.ts @@ -83,7 +83,7 @@ describe("EmbedWidgetDisclosure (DOS/Give#335)", () => { const textarea = container.querySelector("textarea")! expect(textarea.value).toBe( - '' + '' ) const compactBtn = [...container.querySelectorAll("button")].find((b) => b.textContent?.includes("Thu gọn"))! diff --git a/apps/web/src/components/EmbedWidgetDisclosure.tsx b/apps/web/src/components/EmbedWidgetDisclosure.tsx index 60f5bf62..59dbb4da 100644 --- a/apps/web/src/components/EmbedWidgetDisclosure.tsx +++ b/apps/web/src/components/EmbedWidgetDisclosure.tsx @@ -126,7 +126,7 @@ export function EmbedWidgetDisclosure({ }} className={clsx( "min-h-9 rounded px-2 text-sm font-semibold transition-colors duration-150 focus-visible:-outline-offset-2", - active ? "border border-border bg-raised text-fg" : "text-muted hover:text-fg" + active ? "bg-raised text-fg ring-1 ring-border ring-inset" : "text-muted hover:text-fg" )} > {option.label} @@ -152,7 +152,7 @@ export function EmbedWidgetDisclosure({ }} className={clsx( "min-h-9 rounded px-2 text-sm font-semibold transition-colors duration-150 focus-visible:-outline-offset-2", - active ? "border border-border bg-raised text-fg" : "text-muted hover:text-fg" + active ? "bg-raised text-fg ring-1 ring-border ring-inset" : "text-muted hover:text-fg" )} > {EMBED_THEME_LABELS[option]} diff --git a/apps/web/src/components/layout/LayoutShell.test.ts b/apps/web/src/components/layout/LayoutShell.test.ts index 0a0ca75e..0f6a59f5 100644 --- a/apps/web/src/components/layout/LayoutShell.test.ts +++ b/apps/web/src/components/layout/LayoutShell.test.ts @@ -39,9 +39,11 @@ afterEach(() => { }) describe("LayoutShell (DOS/Give#335)", () => { - it("recognizes /embed and /embed/* without matching /embedded", () => { + it("recognizes /embed and /embed/* case-insensitively without matching /embedded", () => { expect(isEmbedRoute("/embed")).toBe(true) expect(isEmbedRoute("/embed/xay-truong")).toBe(true) + expect(isEmbedRoute("/Embed/xay-truong")).toBe(true) + expect(isEmbedRoute("/EMBED")).toBe(true) expect(isEmbedRoute("/embedded")).toBe(false) expect(isEmbedRoute("/campaigns/xay-truong")).toBe(false) expect(isEmbedRoute(null)).toBe(false) diff --git a/apps/web/src/components/layout/LayoutShell.tsx b/apps/web/src/components/layout/LayoutShell.tsx index 2ae87a00..81928387 100644 --- a/apps/web/src/components/layout/LayoutShell.tsx +++ b/apps/web/src/components/layout/LayoutShell.tsx @@ -6,7 +6,8 @@ import type { ReactNode } from "react" import { RingBoxScroll } from "@/components/layout/RingBoxScroll" export function isEmbedRoute(pathname: string | null): boolean { - return pathname === "/embed" || Boolean(pathname?.startsWith("/embed/")) + const normalized = pathname?.toLowerCase() ?? "" + return normalized === "/embed" || normalized.startsWith("/embed/") } /** diff --git a/apps/web/src/lib/embed.test.ts b/apps/web/src/lib/embed.test.ts index b01ddc0e..8de0fe1d 100644 --- a/apps/web/src/lib/embed.test.ts +++ b/apps/web/src/lib/embed.test.ts @@ -71,7 +71,7 @@ describe("embed helpers (DOS/Give#335)", () => { origin: "https://give.vn", }) expect(defaultSnippet).toBe( - '' + '' ) expect(defaultSnippet).toContain(`height="${EMBED_HEIGHT_DEFAULT}"`) diff --git a/apps/web/src/lib/embed.ts b/apps/web/src/lib/embed.ts index 7540ad25..38aafa35 100644 --- a/apps/web/src/lib/embed.ts +++ b/apps/web/src/lib/embed.ts @@ -110,5 +110,5 @@ export function buildEmbedIframeCode({ const cleanTitle = title.replace(/\s+/g, " ").trim() const iframeTitle = cleanTitle ? `${cleanTitle} · Give` : "Chiến dịch Give" - return `` + return `` } diff --git a/apps/web/src/proxy.test.ts b/apps/web/src/proxy.test.ts index f71602b1..e71e5622 100644 --- a/apps/web/src/proxy.test.ts +++ b/apps/web/src/proxy.test.ts @@ -2,7 +2,7 @@ import { AsyncLocalStorage } from "node:async_hooks" import { NextRequest } from "next/server" import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" -import { config, proxy } from "./proxy" +import { config, EMBED_HEADER, proxy } from "./proxy" const ISSUER = "https://issuer.example/auth/v1" @@ -194,30 +194,62 @@ describe("proxy session refresh", () => { expect(loggedText()).not.toContain("rt-1") }) - it("skips cookie refresh and marks x-give-embed on /embed and /embed/*, while stripping spoofed headers elsewhere (DOS/Give#335)", async () => { - for (const path of ["/embed", "/embed/xay-truong-ban-may"]) { + it("marks lowercase /embed* with x-give-embed without refreshing cookies, strips spoofed headers elsewhere, and blocks mixed-case /Embed* with 404 DENY (DOS/Give#335)", async () => { + for (const path of ["/embed", "/embed/test-slug"]) { const response = await proxy( new NextRequest(`https://give.example${path}`, { headers: { cookie: "__Host-give_rt=rt-1" } }) ) expect(fetchMock).not.toHaveBeenCalled() expectCookiesKept(response) + expect(response.status).toBe(200) expect(response.headers.get("x-middleware-request-x-give-embed")).toBe("1") } - const spoofed = await proxy( - new NextRequest("https://give.example/campaigns/xay-truong", { - headers: { "x-give-embed": "1" }, + // Spoofed x-give-embed without token refresh is dropped cleanly. + const spoofedNoRefresh = await proxy( + new NextRequest("https://give.example/campaigns", { + headers: { [EMBED_HEADER]: "1", host: "give.example" }, }) ) expect(fetchMock).not.toHaveBeenCalled() - expect(spoofed.headers.get("x-middleware-request-x-give-embed")).toBeNull() + expect(spoofedNoRefresh.headers.get("x-middleware-request-x-give-embed")).toBeNull() + expect( + (spoofedNoRefresh.headers.get("x-middleware-override-headers") ?? "") + .split(",") + .map((h) => h.trim().toLowerCase()) + ).not.toContain(EMBED_HEADER) - const spoofedEmbedded = await proxy( - new NextRequest("https://give.example/embedded", { - headers: { "x-give-embed": "1" }, + // Spoofed x-give-embed with token refresh is ALSO dropped cleanly while refreshing cookies. + fetchMock.mockResolvedValueOnce( + Response.json({ access_token: "at-2", refresh_token: "rt-2", expires_in: 3600, token_type: "bearer" }) + ) + const spoofedWithRefresh = await proxy( + new NextRequest("https://give.example/campaigns", { + headers: { cookie: "__Host-give_rt=rt-1", [EMBED_HEADER]: "1", host: "give.example" }, }) ) - expect(spoofedEmbedded.headers.get("x-middleware-request-x-give-embed")).toBeNull() + expect(fetchMock).toHaveBeenCalledTimes(1) + expect(spoofedWithRefresh.cookies.get("__Host-give_at")?.value).toBe("at-2") + expect(spoofedWithRefresh.headers.get("x-middleware-request-x-give-embed")).toBeNull() + expect( + (spoofedWithRefresh.headers.get("x-middleware-override-headers") ?? "") + .split(",") + .map((h) => h.trim().toLowerCase()) + ).not.toContain(EMBED_HEADER) + + // Mixed-case /Embed* returns 404 with DENY & frame-ancestors 'none' without refreshing cookies. + for (const mixedCasePath of ["/EMBED", "/Embed/test-slug"]) { + const response = await proxy( + new NextRequest(`https://give.example${mixedCasePath}`, { headers: { cookie: "__Host-give_rt=rt-1" } }) + ) + expect(fetchMock).toHaveBeenCalledTimes(1) + expectCookiesKept(response) + expect(response.status).toBe(404) + expect(response.headers.get("x-frame-options")).toBe("DENY") + expect(response.headers.get("content-security-policy")).toBe("frame-ancestors 'none'") + expect(response.headers.get("x-robots-tag")).toBe("noindex, nofollow") + expect(response.headers.get("x-content-type-options")).toBe("nosniff") + } }) }) @@ -305,5 +337,11 @@ describe("proxy matcher exclusions", () => { url: "https://give.example/admin", }) ).toBe(true) + expect( + unstable_doesMiddlewareMatch({ + config, + url: "https://give.example/embed/test-slug", + }) + ).toBe(true) }) }) diff --git a/apps/web/src/proxy.ts b/apps/web/src/proxy.ts index 9b04338e..09f8f415 100644 --- a/apps/web/src/proxy.ts +++ b/apps/web/src/proxy.ts @@ -5,11 +5,10 @@ import { isDeadRefreshToken, loadOidcConfig, refreshTokens, tokenFailureLog } fr import { appOrigin } from "@/lib/auth/origin" import { needsRefresh } from "@/lib/auth/token" -const EMBED_HEADER = "x-give-embed" +export const EMBED_HEADER = "x-give-embed" -export function isEmbedPath(pathname: string): boolean { - return pathname === "/embed" || pathname.startsWith("/embed/") -} +const EXACT_EMBED_RE = /^\/embed(?:\/|$)/ +const ANY_CASE_EMBED_RE = /^\/embed(?:\/|$)/i /** * Keeps the session's access token fresh. When it is missing or about to @@ -18,19 +17,33 @@ export function isEmbedPath(pathname: string): boolean { * refresh call gives up after TOKEN_TIMEOUT_MS (set in oidc.ts) and never * follows a redirect. * - * Embed widget routes (`/embed`, `/embed/*`) are strictly anonymous and - * read-only (DOS/Give#335): they never read/refresh session cookies, and carry - * a proxy-controlled `x-give-embed` header so `RootLayout` can skip `getSession()`. + * Embed widget routes (`/embed`, `/embed/*`) stay strictly anonymous: `proxy()` + * marks them with a trusted internal `x-give-embed` request header and returns + * before touching cookies or OIDC refresh, while stripping any client-supplied + * `x-give-embed` on every other route and rejecting mixed-case `/Embed*` paths + * with 404 + `X-Frame-Options: DENY` (DOS/Give#335). */ export async function proxy(request: NextRequest) { - if (isEmbedPath(request.nextUrl.pathname)) { - const requestHeaders = new Headers(request.headers) - requestHeaders.set(EMBED_HEADER, "1") - return NextResponse.next({ request: { headers: requestHeaders } }) + const { pathname } = request.nextUrl + if (ANY_CASE_EMBED_RE.test(pathname) && !EXACT_EMBED_RE.test(pathname)) { + return new NextResponse("Not Found", { + status: 404, + headers: { + "X-Content-Type-Options": "nosniff", + "X-Frame-Options": "DENY", + "Content-Security-Policy": "frame-ancestors 'none'", + "X-Robots-Tag": "noindex, nofollow", + }, + }) + } + if (EXACT_EMBED_RE.test(pathname)) { + const embedHeaders = new Headers(request.headers) + embedHeaders.set(EMBED_HEADER, "1") + return NextResponse.next({ request: { headers: embedHeaders } }) } - const hadSpoofedEmbedHeader = request.headers.has(EMBED_HEADER) - if (hadSpoofedEmbedHeader) request.headers.delete(EMBED_HEADER) + const hadSpoofedEmbed = request.headers.has(EMBED_HEADER) + if (hadSpoofedEmbed) request.headers.delete(EMBED_HEADER) const { hostname } = request.nextUrl const accessName = cookieName(SESSION_ACCESS, hostname) @@ -39,7 +52,7 @@ export async function proxy(request: NextRequest) { const refresh = request.cookies.get(refreshName)?.value if (!refresh || !needsRefresh(access)) { - return hadSpoofedEmbedHeader ? NextResponse.next({ request }) : NextResponse.next() + return hadSpoofedEmbed ? NextResponse.next({ request: { headers: new Headers(request.headers) } }) : NextResponse.next() } try { @@ -58,7 +71,9 @@ export async function proxy(request: NextRequest) { // config mistake fails loudly instead of signing everyone out. if (!isDeadRefreshToken(error)) { console.warn("auth.refresh.failed", tokenFailureLog(error)) - return hadSpoofedEmbedHeader ? NextResponse.next({ request }) : NextResponse.next() + return hadSpoofedEmbed + ? NextResponse.next({ request: { headers: new Headers(request.headers) } }) + : NextResponse.next() } request.cookies.delete(accessName) const response = NextResponse.next({ request }) diff --git a/apps/web/src/test/next-config.test.ts b/apps/web/src/test/next-config.test.ts index eb2c9d86..7a54973d 100644 --- a/apps/web/src/test/next-config.test.ts +++ b/apps/web/src/test/next-config.test.ts @@ -53,7 +53,16 @@ describe("response headers", () => { expect(globalIdx).toBeGreaterThanOrEqual(0) expect(embedIdx).toBeGreaterThan(globalIdx) - for (const path of ["/", "/campaigns/abc", "/me", "/admin", "/donations/GV123", "/invites/tok123", "/embedded"]) { + for (const path of [ + "/", + "/campaigns/abc", + "/campaigns/embed", + "/me", + "/admin", + "/donations/GV123", + "/invites/tok123", + "/embedded", + ]) { const headers = await resolveHeadersForPath(path) expect(headers.get("x-frame-options"), path).toBe("DENY") expect(headers.get("x-content-type-options"), path).toBe("nosniff") @@ -67,6 +76,13 @@ describe("response headers", () => { expect(headers.get("x-content-type-options"), embedPath).toBe("nosniff") expect(headers.get("referrer-policy"), embedPath).toBe("strict-origin-when-cross-origin") } + + // Next.js pathToRegexp defaults to case-insensitive matching; proxy.ts explicitly + // rejects mixed-case /Embed/* and /EMBED with 404 + X-Frame-Options: DENY. + for (const mixedCaseEmbed of ["/Embed/abc", "/EMBED"]) { + const headers = await resolveHeadersForPath(mixedCaseEmbed) + expect(headers.get("x-frame-options"), mixedCaseEmbed).toBeUndefined() + } }) it("strips Referer and disables caching on /donations/* after the site-wide defaults (DOS/Give#50)", async () => { From 313d1eb8560c3c6dd9d9eca91bc19169a41e9e78 Mon Sep 17 00:00:00 2001 From: JOY <5027251+JOY@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:51:58 +0700 Subject: [PATCH 3/5] fix(embed): polish compact badges, goal deduplication, and not-found clamp (Refs #335) --- apps/web/src/app/embed/[slug]/page.test.ts | 1 + apps/web/src/app/embed/[slug]/page.tsx | 11 ++++++++--- apps/web/src/components/EmbedNotFoundCard.tsx | 4 +++- 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/apps/web/src/app/embed/[slug]/page.test.ts b/apps/web/src/app/embed/[slug]/page.test.ts index 90ffb2bf..6d4b4a53 100644 --- a/apps/web/src/app/embed/[slug]/page.test.ts +++ b/apps/web/src/app/embed/[slug]/page.test.ts @@ -321,6 +321,7 @@ describe("/embed/[slug] page (DOS/Give#335)", () => { ) expect(noTotalsDoc.querySelector('[role="progressbar"]')).toBeNull() expect(noTotalsDoc.body.textContent).not.toContain("đã nhận") + expect(noTotalsDoc.body.textContent?.match(/Mục tiêu/g)).toHaveLength(1) expect(noTotalsDoc.body.textContent).toContain("Mục tiêu 100.000.000") // 2. Expired live campaign shows "Đã hết hạn" and "Xem chi tiết" instead of "Ủng hộ ngay" diff --git a/apps/web/src/app/embed/[slug]/page.tsx b/apps/web/src/app/embed/[slug]/page.tsx index 2925d1c8..c8673087 100644 --- a/apps/web/src/app/embed/[slug]/page.tsx +++ b/apps/web/src/app/embed/[slug]/page.tsx @@ -55,7 +55,7 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str * third-party `