Open source CapCut alternative.
TypeScript
feat(site): report page views to Meta from the server
David Lea26de93531c3
diff --git a/docs/guides/backend-apis.md b/docs/guides/backend-apis.mdindex 621f521d..c9c72920 100644--- a/docs/guides/backend-apis.md+++ b/docs/guides/backend-apis.md@@ -4,13 +4,12 @@ Backend APIs are the Next.js route handlers under the site project. They servethe site's own client views, signed in with a session cookie.**The one rule:** every route handler is wrapped in `withDonkeyAuth`. A public-endpoint is a deliberate exception with a product reason — today only Better-Auth's own routes, the signature-verified Stripe webhook, the-HMAC-token-verified one-click email unsubscribe and promotion button redirect,-the token-authorized Cut project and library share viewers, the scoped OAuth-ChatGPT MCP endpoint and its OAuth discovery/exchange endpoints, authenticated-cron jobs, and a plain health check. Ship-a handler without the wrapper and the endpoint is open to anyone.+endpoint is a deliberate exception with a product reason — today Better Auth's+routes, the signature-verified Stripe webhook, the HMAC-token email unsubscribe+and promotion redirect, the token-authorized share viewers, the ChatGPT MCP+endpoint and its OAuth endpoints, the Meta page view beacon, authenticated cron+jobs, and a health check. Ship a handler without the wrapper and the endpoint+is open to anyone.## Authenticationdiff --git a/site/scripts/meta-test-event.ts b/site/scripts/meta-test-event.tsnew file mode 100644index 00000000..f676163b--- /dev/null+++ b/site/scripts/meta-test-event.ts@@ -0,0 +1,33 @@+#!/usr/bin/env bun+/**+ * Sends one CompleteRegistration through the production Conversions API path+ * to the Donkey Cut dataset's Test events tab, which shows it within seconds+ * and keeps it out of reporting. The test code is on that tab.+ *+ * Run from site/ with META_PIXEL_ID and META_CAPI_ACCESS_TOKEN in the environment:+ * bun run scripts/meta-test-event.ts <TEST_CODE>+ */++import { sendMetaEvent } from "../src/lib/meta/conversions";++const testCode = process.argv[2];+if (!testCode) {+ console.error("usage: bun run scripts/meta-test-event.ts <TEST_CODE>");+ process.exit(1);+}++await sendMetaEvent(+ {+ browser: {+ fbp: `fb.1.${Date.now()}.1234567890`,+ ip: "203.0.113.7",+ userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 Safari/605.1.15",+ },+ id: `test-${crypto.randomUUID()}`,+ name: "CompleteRegistration",+ url: "https://donkeycut.com/sign-up",+ user: { email: "[email protected]", id: "meta-test-event" },+ },+ testCode,+);+console.log("sent; check the Test events tab");diff --git a/site/src/app/_components/MetaPageView.tsx b/site/src/app/_components/MetaPageView.tsxnew file mode 100644index 00000000..d86dbc6b--- /dev/null+++ b/site/src/app/_components/MetaPageView.tsx@@ -0,0 +1,26 @@+"use client";++import { usePathname } from "next/navigation";+import { useEffect } from "react";++import { UNTRACKED_PAGES } from "@/lib/meta/identity";++// The first-party route that reports a page view to Meta (app/p/route.ts).+const BEACON_PATH = "/p";++// Reports each page the browser shows to Meta through this site's own server.+// Production builds only, like the rest of analytics.+export function MetaPageView() {+ const pathname = usePathname();++ useEffect(() => {+ if (process.env.NODE_ENV !== "production" || UNTRACKED_PAGES.test(window.location.pathname)) {+ return;+ }+ // The address without its query or fragment, which can carry tokens.+ const { origin, pathname: path } = window.location;+ navigator.sendBeacon(BEACON_PATH, JSON.stringify({ url: `${origin}${path}` }));+ }, [pathname]);++ return null;+}diff --git a/site/src/app/layout.tsx b/site/src/app/layout.tsxindex 374dc4df..ec84f1e8 100644--- a/site/src/app/layout.tsx+++ b/site/src/app/layout.tsx@@ -1,10 +1,12 @@import type { Metadata } from "next";+import { Suspense } from "react";import { GeistMono } from "geist/font/mono";import { GeistSans } from "geist/font/sans";import "./globals.css";import { DONKEYCUT_CANONICAL } from "@/cut/lib/hosts";import { QueryProvider } from "@/queries/QueryProvider";+import { MetaPageView } from "./_components/MetaPageView";import { PostHogProvider } from "./_components/PostHogProvider";export const metadata: Metadata = {@@ -44,6 +46,9 @@ export default function RootLayout({<body className="min-h-full flex flex-col"><PostHogProvider><QueryProvider>{children}</QueryProvider>+ <Suspense fallback={null}>+ <MetaPageView />+ </Suspense></PostHogProvider></body></html>diff --git a/site/src/app/legal/PrivacyPolicy.mdx b/site/src/app/legal/PrivacyPolicy.mdxindex b72a2449..0419ed97 100644--- a/site/src/app/legal/PrivacyPolicy.mdx+++ b/site/src/app/legal/PrivacyPolicy.mdx@@ -1,6 +1,6 @@# Privacy Policy-**_Last updated September 23, 2026_**+**_Last updated October 19, 2026_**This privacy notice for Hey Salesman Inc, the company that operates Donkey Cut (**_"Company"_**, **_"we"_**, **_"us"_**, or **_"our"_**), describes how and why we might collect, store, use, and/or share (**_"process"_**) your information when you use our services (**_"Services"_**), such as when you:@@ -196,6 +196,8 @@ The Services may link to third-party websites, online services, APIs, model provWe may use cookies and similar tracking technologies (like web beacons, pixels, and local storage) to access or store information. We may use these technologies to keep you signed in, remember preferences, secure the Services, support billing or checkout flows, understand website usage, and improve the Services. You can usually configure your browser to remove or reject cookies, but doing so may affect certain features or services of our Services.+**Advertising measurement.** Our website sets two first-party cookies: one identifies your browser, and one records the ad click if you arrived from an ad on Facebook or Instagram. When you visit a page, create an account, start a checkout, or make a purchase, our servers send that event to Meta Platforms with these identifiers, your IP address, your browser's user agent, and hashed forms of your email address and account ID, so we can measure and improve our ads. The Donkey Cut editor and shared project pages send no page views. You can remove these cookies in your browser, and you can manage how Meta uses this information in your Facebook or Instagram ad preferences.+### 7. HOW DO WE HANDLE YOUR SOCIAL LOGINS?**In Short:** _If you choose to register or log in to our services using a third-party account, we may have access to certain information about you._diff --git a/site/src/app/p/route.ts b/site/src/app/p/route.tsnew file mode 100644index 00000000..2d8fa800--- /dev/null+++ b/site/src/app/p/route.ts@@ -0,0 +1,58 @@+import { NextResponse, type NextRequest } from "next/server";+import { z } from "zod";++import { auth } from "@/lib/auth";+import { clientIp } from "@/lib/client-ip";+import { checkInMemoryRateLimit } from "@/lib/inference/rate-limit";+import { META_LIVE, metaBrowser, trackMetaEvent } from "@/lib/meta/conversions";+import { UNTRACKED_PAGES } from "@/lib/meta/identity";++// The page view beacon. Public by design: a signed-out visitor landing from an+// ad is the view it exists for. It lives at a short first-party address on+// this host so the page reports through Donkey's own server, and it only+// reports pages on this host outside the untracked ones.+const bodySchema = z.object({ url: z.string().url().max(2048) }).strict();++// A person reads a page or two a second at most; past this, an address is+// scripting the beacon and its views stay out of the dataset.+const VIEWS_PER_MINUTE = 60;+const MINUTE_MS = 60_000;++const NO_CONTENT = 204;+const BAD_REQUEST = 400;+const TOO_MANY_REQUESTS = 429;++export async function POST(request: NextRequest) {+ const parsed = bodySchema.safeParse(await request.json().catch(() => null));+ if (!parsed.success) {+ return NextResponse.json({ error: "Invalid request" }, { status: BAD_REQUEST });+ }++ const page = new URL(parsed.data.url);+ if (page.host !== request.headers.get("host") || UNTRACKED_PAGES.test(page.pathname)) {+ return NextResponse.json({ error: "Invalid request" }, { status: BAD_REQUEST });+ }++ // Previews and local dev report nothing, so they skip the session read too.+ if (!META_LIVE) {+ return new NextResponse(null, { status: NO_CONTENT });+ }++ const ip = clientIp(request.headers);+ const limit = checkInMemoryRateLimit({ key: `meta-view:${ip}`, limit: VIEWS_PER_MINUTE, windowMs: MINUTE_MS });+ if (!limit.ok) {+ return NextResponse.json({ error: "Too many requests" }, { status: TOO_MANY_REQUESTS });+ }++ // Meta gets the page without its query or fragment, which can carry+ // tokens and return addresses; the ad click rides the _fbc cookie.+ const session = await auth.api.getSession({ headers: request.headers });+ trackMetaEvent({+ browser: metaBrowser(request.headers),+ id: crypto.randomUUID(),+ name: "PageView",+ url: `${page.origin}${page.pathname}`,+ user: session?.user,+ });+ return new NextResponse(null, { status: NO_CONTENT });+}diff --git a/site/src/lib/meta/conversions.test.ts b/site/src/lib/meta/conversions.test.tsnew file mode 100644index 00000000..42603614--- /dev/null+++ b/site/src/lib/meta/conversions.test.ts@@ -0,0 +1,21 @@+import { expect, test } from "bun:test";++import { metaBrowser } from "./conversions";++test("the browser reads from cookies and forwarding headers", () => {+ const headers = new Headers({+ cookie: "session=x; _fbp=fb.1.1.42; _fbc=fb.1.2.click",+ "user-agent": "Mozilla/5.0",+ "x-forwarded-for": "203.0.113.7, 10.0.0.1",+ });+ expect(metaBrowser(headers)).toEqual({+ fbc: "fb.1.2.click",+ fbp: "fb.1.1.42",+ ip: "203.0.113.7",+ userAgent: "Mozilla/5.0",+ });+});++test("an address that is not one stays off the event", () => {+ expect(metaBrowser(new Headers({ "x-forwarded-for": "unknown" })).ip).toBeUndefined();+});diff --git a/site/src/lib/meta/conversions.ts b/site/src/lib/meta/conversions.tsnew file mode 100644index 00000000..381a2f5a--- /dev/null+++ b/site/src/lib/meta/conversions.ts@@ -0,0 +1,127 @@+import { createHash } from "node:crypto";++import { parseCookies } from "better-auth/cookies";+import { after } from "next/server";++import { clientIp } from "@/lib/client-ip";+import { BROWSER_ID_COOKIE, CLICK_ID_COOKIE } from "@/lib/meta/identity";++// The Graph API version the Conversions API is called at. The dataset id and+// its token ride the environment.+const GRAPH_VERSION = "v26.0";++// Production deploys report; previews and local dev send nothing, so test+// traffic never trains the ad account.+export const META_LIVE = process.env.VERCEL_ENV === "production";++// Every event this site reports happens on the website.+const ACTION_SOURCE = "website";++// The browser an event came from, as Meta's matching wants it.+export type MetaBrowser = {+ ip?: string;+ userAgent?: string;+ fbp?: string;+ fbc?: string;+};++export type MetaEventName = "PageView" | "CompleteRegistration" | "InitiateCheckout" | "Purchase";++export type MetaEvent = {+ name: MetaEventName;+ // Meta drops a second event with the same name and id, so a retried+ // webhook reports once. For example "signup-<userId>".+ id: string;+ url: string;+ browser: MetaBrowser;+ user?: { id: string; email?: string | null };+ value?: { amount: number; currency: string };+ content?: string;+};++/**+ * Reports an event after the response is sent. A failure is logged and goes+ * no further: the signup or payment it describes has already happened.+ */+export function trackMetaEvent(event: MetaEvent): void {+ if (!META_LIVE) {+ return;+ }++ // after() throws outside a request (a script creating an account), which+ // is the same failure: log it and let the caller finish.+ try {+ after(async () => {+ try {+ await sendMetaEvent(event);+ } catch (error) {+ console.error("[meta] event not reported", { error, id: event.id, name: event.name });+ }+ });+ } catch (error) {+ console.error("[meta] event not reported", { error, id: event.id, name: event.name });+ }+}++/** The ids, address, and user agent of the browser behind a request. */+export function metaBrowser(headers: Headers): MetaBrowser {+ const cookies = parseCookies(headers.get("cookie") ?? "");+ return {+ fbc: cookies.get(CLICK_ID_COOKIE),+ fbp: cookies.get(BROWSER_ID_COOKIE),+ ip: clientIp(headers) ?? undefined,+ userAgent: headers.get("user-agent") ?? undefined,+ };+}++/**+ * Sends one event to the Conversions API. A test code routes it to the+ * dataset's Test events tab and keeps it out of reporting.+ */+export async function sendMetaEvent(event: MetaEvent, testCode?: string): Promise<void> {+ const pixelId = process.env.META_PIXEL_ID;+ const token = process.env.META_CAPI_ACCESS_TOKEN;+ if (!pixelId || !token) {+ throw new Error("META_PIXEL_ID and META_CAPI_ACCESS_TOKEN must both be set");+ }++ // The token rides the body so it stays out of request logs.+ const res = await fetch(`https://graph.facebook.com/${GRAPH_VERSION}/${pixelId}/events`, {+ body: JSON.stringify({ access_token: token, data: [serverEvent(event)], test_event_code: testCode }),+ headers: { "Content-Type": "application/json" },+ method: "POST",+ });+ if (!res.ok) {+ throw new Error(`Meta rejected ${event.name} (${res.status}): ${await res.text()}`);+ }+}++// The event in the Conversions API's shape. Email and account id leave+// hashed, as Meta requires; JSON drops the fields an event lacks.+function serverEvent(event: MetaEvent) {+ const { browser, user, value } = event;+ return {+ action_source: ACTION_SOURCE,+ custom_data: {+ content_name: event.content,+ currency: value?.currency.toUpperCase(),+ value: value?.amount,+ },+ event_id: event.id,+ event_name: event.name,+ event_source_url: event.url,+ event_time: Math.floor(Date.now() / 1000),+ user_data: {+ client_ip_address: browser.ip,+ client_user_agent: browser.userAgent,+ em: user?.email ? [sha256(user.email.trim().toLowerCase())] : undefined,+ external_id: user ? [sha256(user.id)] : undefined,+ fbc: browser.fbc,+ fbp: browser.fbp,+ },+ };+}++function sha256(value: string): string {+ return createHash("sha256").update(value).digest("hex");+}diff --git a/site/src/lib/meta/identity.test.ts b/site/src/lib/meta/identity.test.tsnew file mode 100644index 00000000..789dfd54--- /dev/null+++ b/site/src/lib/meta/identity.test.ts@@ -0,0 +1,51 @@+import { expect, test } from "bun:test";++import { metaCookies, UNTRACKED_PAGES } from "./identity";++const NOW = 1_760_000_000_000;++function jar(values: Record<string, string>) {+ return { get: (name: string) => (name in values ? { value: values[name] } : undefined) };+}++test("a first visit gets a browser id", () => {+ const set = metaCookies(new URL("https://donkeycut.com/"), jar({}), NOW);+ expect(set).toHaveLength(1);+ expect(set[0].name).toBe("_fbp");+ expect(set[0].value).toMatch(/^fb\.1\.1760000000000\.\d{10}$/);+});++test("an ad click sets the click id, verbatim", () => {+ const url = new URL("https://donkeycut.com/?fbclid=IwAR2xYz-AbC");+ const set = metaCookies(url, jar({ _fbp: "fb.1.1.1234567890" }), NOW);+ expect(set).toEqual([{ name: "_fbc", value: "fb.1.1760000000000.IwAR2xYz-AbC" }]);+});++test("the same click reloaded keeps its cookie", () => {+ const url = new URL("https://donkeycut.com/?fbclid=abc");+ const held = jar({ _fbc: "fb.1.1700000000000.abc", _fbp: "fb.1.1.1234567890" });+ expect(metaCookies(url, held, NOW)).toEqual([]);+});++test("a new click replaces the old one", () => {+ const url = new URL("https://donkeycut.com/?fbclid=new");+ const held = jar({ _fbc: "fb.1.1700000000000.old", _fbp: "fb.1.1.1234567890" });+ expect(metaCookies(url, held, NOW)).toEqual([{ name: "_fbc", value: "fb.1.1760000000000.new" }]);+});++test("a malformed click id sets no cookie", () => {+ const held = jar({ _fbp: "fb.1.1.1234567890" });+ for (const click of ["a b", "x".repeat(501), "<script>"]) {+ const url = new URL(`https://donkeycut.com/?fbclid=${encodeURIComponent(click)}`);+ expect(metaCookies(url, held, NOW)).toEqual([]);+ }+});++test("the editor, shared player, and unsubscribe page report no page views", () => {+ for (const path of ["/app", "/app/p/abc", "/s/token", "/cut/app/settings", "/unsubscribe"]) {+ expect(UNTRACKED_PAGES.test(path)).toBe(true);+ }+ for (const path of ["/", "/sign-up", "/blog/post", "/apps", "/install"]) {+ expect(UNTRACKED_PAGES.test(path)).toBe(false);+ }+});diff --git a/site/src/lib/meta/identity.ts b/site/src/lib/meta/identity.tsnew file mode 100644index 00000000..6e1e2ecb--- /dev/null+++ b/site/src/lib/meta/identity.ts@@ -0,0 +1,60 @@+// Meta matches a server-sent event to the person who saw an ad through two+// ids: the browser id (_fbp) and the ad click id (_fbc). Meta's own pixel+// script writes them from JavaScript, where Safari caps a cookie at seven+// days; this server writes them instead, as first-party cookies, and reads+// them back on every event it sends (conversions.ts). Edge-safe: the proxy+// imports this.++export const BROWSER_ID_COOKIE = "_fbp";+export const CLICK_ID_COOKIE = "_fbc";++// The query parameter Meta appends to an ad's landing URL, and the shape a+// real click id has. Anything else is ignored, so a crafted value never lands+// in a cookie that rides every request for 90 days.+const CLICK_ID_PARAM = "fbclid";+const CLICK_ID = /^[A-Za-z0-9_-]{1,500}$/;++// Meta's id format: "fb", the format version, the cookie's domain index (1 for+// an apex host like donkeycut.com), its creation time in ms, then the value.+// For example fb.1.1760000000000.1234567890.+const ID_PREFIX = "fb.1";++// Meta keeps the ids for 90 days.+export const META_COOKIE_MAX_AGE_S = 90 * 24 * 60 * 60;++// The pages that never report a page view: the editor, the shared player, and+// the unsubscribe page, whose addresses carry project ids and tokens.+export const UNTRACKED_PAGES = /^\/(?:(?:cut\/)?(?:app|s)|unsubscribe)(?:\/|$)/;++type CookieValue = { name: string; value: string };++type CookieReader = { get(name: string): { value: string } | undefined };++/**+ * The id cookies a page response sets: a browser id the first time a browser+ * arrives, and a click id whenever it lands from an ad with a click it has not+ * seen. A browser that already holds both gets none.+ */+export function metaCookies(url: URL, cookies: CookieReader, now: number): CookieValue[] {+ const set: CookieValue[] = [];++ if (!cookies.get(BROWSER_ID_COOKIE)) {+ set.push({ name: BROWSER_ID_COOKIE, value: `${ID_PREFIX}.${now}.${randomDigits()}` });+ }++ // A new ad click replaces the old one; the same click reloaded keeps its+ // first timestamp.+ const click = url.searchParams.get(CLICK_ID_PARAM);+ const held = cookies.get(CLICK_ID_COOKIE)?.value;+ if (click && CLICK_ID.test(click) && !held?.endsWith(`.${click}`)) {+ set.push({ name: CLICK_ID_COOKIE, value: `${ID_PREFIX}.${now}.${click}` });+ }++ return set;+}++// Ten random digits, the browser id's random part.+function randomDigits(): string {+ const [n] = crypto.getRandomValues(new Uint32Array(1));+ return String(n).padStart(10, "0");+}diff --git a/site/src/proxy.test.ts b/site/src/proxy.test.tsindex ba8b5fc4..5c464e96 100644--- a/site/src/proxy.test.ts+++ b/site/src/proxy.test.ts@@ -44,3 +44,21 @@ test("www canonicalizes to the product host", async () => {expect(res.status).toBe(308);expect(res.headers.get("location")).toBe("https://donkeycut.com/app/p/example");});++test("a landing from an ad gets Meta's ids as first-party cookies", async () => {+ const res = await proxy(request("https://donkeycut.com/?fbclid=abc"));+ const set = res.headers.getSetCookie().join("\n");+ expect(set).toMatch(/_fbp=fb\.1\.\d+\.\d{10};.*HttpOnly/);+ expect(set).toMatch(/_fbc=fb\.1\.\d+\.abc;.*HttpOnly/);+});++test("API calls set no Meta cookies", async () => {+ const res = await proxy(request("https://donkeycut.com/api/credits/balance"));+ expect(res.headers.getSetCookie()).toEqual([]);+});++test("the page view beacon passes through", async () => {+ const res = await proxy(request("https://donkeycut.com/p"));+ expect(res.headers.get("x-middleware-next")).toBe("1");+ expect(res.headers.get("x-middleware-rewrite")).toBeNull();+});diff --git a/site/src/proxy.ts b/site/src/proxy.tsindex df4be265..a5a8fa53 100644--- a/site/src/proxy.ts+++ b/site/src/proxy.ts@@ -2,6 +2,7 @@ import { NextResponse, type NextRequest } from "next/server";import { allowedOrigin, corsHeaders, preflightHeaders } from "@/cut/server/cors";import { DONKEYCUT_CANONICAL, isDonkeycutHost } from "@/cut/lib/hosts";+import { META_COOKIE_MAX_AGE_S, metaCookies } from "@/lib/meta/identity";// Cut (the video editor, publicly "Donkey Cut") lives under /cut in this single// site app: the marketing landing at /cut and the app under /cut/app. The@@ -61,6 +62,8 @@ const PASSTHROUGH = ["/sign-up",// Email-footer unsubscribe page; the back office's emails link here."/unsubscribe",+ // The first-party page view beacon (app/p/route.ts).+ "/p",];// Whole-segment prefix match, so "/cut" covers "/cut/…" but not "/cut-app".@@ -70,6 +73,21 @@ const underPath = (pathname: string, prefix: string) =>const passesThrough = (pathname: string) =>PASSTHROUGH.some((p) => underPath(pathname, p));+// Every page response gives the browser Meta's ids as first-party cookies the+// server wrote (see lib/meta/identity.ts). Only the server reads them.+function withMetaCookies(req: NextRequest, res: NextResponse): NextResponse {+ for (const { name, value } of metaCookies(req.nextUrl, req.cookies, Date.now())) {+ res.cookies.set(name, value, {+ httpOnly: true,+ maxAge: META_COOKIE_MAX_AGE_S,+ path: "/",+ sameSite: "lax",+ secure: req.nextUrl.protocol === "https:",+ });+ }+ return res;+}+export function proxy(req: NextRequest) {const { pathname } = req.nextUrl;if (isCutApi(pathname)) return cutApi(req);@@ -94,14 +112,16 @@ export function proxy(req: NextRequest) {}if (underPath(pathname, "/api")) return NextResponse.next();- if (passesThrough(pathname)) return NextResponse.next();+ if (passesThrough(pathname)) {+ return withMetaCookies(req, NextResponse.next());+ }const url = new URL(req.url);url.pathname =pathname === "/sitemap.xml"? "/cut/sitemap.xml": `/cut${pathname === "/" ? "" : pathname}`;- return NextResponse.rewrite(url);+ return withMetaCookies(req, NextResponse.rewrite(url));}export const config = {