Skip to content

Open source CapCut alternative.

TypeScript

fix(site): keep Meta ids 90 days past the last visit

David Le07d8f3ba366f
diff --git a/site/src/app/_components/MetaPageView.tsx b/site/src/app/_components/MetaPageView.tsx
index d86dbc6b..a7f43b96 100644
--- a/site/src/app/_components/MetaPageView.tsx
+++ b/site/src/app/_components/MetaPageView.tsx
@@ -3,10 +3,7 @@
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";
+import { BEACON_PATH, UNTRACKED_PAGES } from "@/lib/meta/identity";
// Reports each page the browser shows to Meta through this site's own server.
// Production builds only, like the rest of analytics.
diff --git a/site/src/lib/meta/identity.test.ts b/site/src/lib/meta/identity.test.ts
index 789dfd54..bfc69a51 100644
--- a/site/src/lib/meta/identity.test.ts
+++ b/site/src/lib/meta/identity.test.ts
@@ -9,7 +9,7 @@ function jar(values: Record<string, string>) {
}
test("a first visit gets a browser id", () => {
- const set = metaCookies(new URL("https://donkeycut.com/"), jar({}), NOW);
+ const set = metaCookies(new URL("https://donkeycut.com/"), jar({}), NOW, "new");
expect(set).toHaveLength(1);
expect(set[0].name).toBe("_fbp");
expect(set[0].value).toMatch(/^fb\.1\.1760000000000\.\d{10}$/);
@@ -17,27 +17,36 @@ test("a first visit gets a browser id", () => {
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);
+ const set = metaCookies(url, jar({ _fbp: "fb.1.1.1234567890" }), NOW, "new");
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([]);
+ expect(metaCookies(url, held, NOW, "new")).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" }]);
+ expect(metaCookies(url, held, NOW, "new")).toEqual([{ name: "_fbc", value: "fb.1.1760000000000.new" }]);
+});
+
+test("a page view renews the ids the browser holds", () => {
+ const url = new URL("https://donkeycut.com/p");
+ const held = jar({ _fbc: "fb.1.1700000000000.abc", _fbp: "fb.1.1.1234567890" });
+ expect(metaCookies(url, held, NOW, "renew")).toEqual([
+ { name: "_fbp", value: "fb.1.1.1234567890" },
+ { name: "_fbc", value: "fb.1.1700000000000.abc" },
+ ]);
});
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([]);
+ expect(metaCookies(url, held, NOW, "new")).toEqual([]);
}
});
diff --git a/site/src/lib/meta/identity.ts b/site/src/lib/meta/identity.ts
index 6e1e2ecb..b864f80e 100644
--- a/site/src/lib/meta/identity.ts
+++ b/site/src/lib/meta/identity.ts
@@ -19,9 +19,12 @@ const CLICK_ID = /^[A-Za-z0-9_-]{1,500}$/;
// For example fb.1.1760000000000.1234567890.
const ID_PREFIX = "fb.1";
-// Meta keeps the ids for 90 days.
+// Meta keeps the ids for 90 days after a browser's last page view.
export const META_COOKIE_MAX_AGE_S = 90 * 24 * 60 * 60;
+// The first-party route every page view reports through (app/p/route.ts).
+export const BEACON_PATH = "/p";
+
// 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)(?:\/|$)/;
@@ -30,16 +33,24 @@ type CookieValue = { name: string; value: string };
type CookieReader = { get(name: string): { value: string } | undefined };
+// "new" writes only the ids a browser lacks. "renew" also writes back the ids
+// it holds, so their 90 days restart; the page view beacon renews, page loads
+// stay free of cookie headers for a returning browser.
+export type MetaCookieScope = "new" | "renew";
+
/**
- * The id cookies a page response sets: a browser id the first time a browser
+ * The id cookies a 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.
+ * seen, plus the held ids when the scope renews them.
*/
-export function metaCookies(url: URL, cookies: CookieReader, now: number): CookieValue[] {
+export function metaCookies(url: URL, cookies: CookieReader, now: number, scope: MetaCookieScope): CookieValue[] {
const set: CookieValue[] = [];
- if (!cookies.get(BROWSER_ID_COOKIE)) {
+ const browserId = cookies.get(BROWSER_ID_COOKIE)?.value;
+ if (!browserId) {
set.push({ name: BROWSER_ID_COOKIE, value: `${ID_PREFIX}.${now}.${randomDigits()}` });
+ } else if (scope === "renew") {
+ set.push({ name: BROWSER_ID_COOKIE, value: browserId });
}
// A new ad click replaces the old one; the same click reloaded keeps its
@@ -48,6 +59,8 @@ export function metaCookies(url: URL, cookies: CookieReader, now: number): Cooki
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}` });
+ } else if (held && scope === "renew") {
+ set.push({ name: CLICK_ID_COOKIE, value: held });
}
return set;
diff --git a/site/src/proxy.test.ts b/site/src/proxy.test.ts
index 5c464e96..06673bf8 100644
--- a/site/src/proxy.test.ts
+++ b/site/src/proxy.test.ts
@@ -4,8 +4,8 @@ import nextConfig from "../next.config";
import { proxy } from "./proxy";
// skipProxyUrlNormalize supplies the original URL to the proxy at runtime.
-function request(url: string) {
- const req = new NextRequest(url, { headers: { host: new URL(url).host } });
+function request(url: string, cookie = "") {
+ const req = new NextRequest(url, { headers: { cookie, host: new URL(url).host } });
Object.defineProperty(req, "url", { value: url });
return req;
}
@@ -62,3 +62,15 @@ test("the page view beacon passes through", async () => {
expect(res.headers.get("x-middleware-next")).toBe("1");
expect(res.headers.get("x-middleware-rewrite")).toBeNull();
});
+
+test("the page view beacon restarts the ids' 90 days", async () => {
+ const res = await proxy(request("https://donkeycut.com/p", "_fbp=fb.1.1.1234567890; _fbc=fb.1.2.abc"));
+ const set = res.headers.getSetCookie().join("\n");
+ expect(set).toMatch(/_fbp=fb\.1\.1\.1234567890;.*Max-Age=7776000/);
+ expect(set).toMatch(/_fbc=fb\.1\.2\.abc;.*Max-Age=7776000/);
+});
+
+test("a page a returning browser opens leaves its ids alone", async () => {
+ const res = await proxy(request("https://donkeycut.com/", "_fbp=fb.1.1.1234567890"));
+ expect(res.headers.getSetCookie()).toEqual([]);
+});
diff --git a/site/src/proxy.ts b/site/src/proxy.ts
index a5a8fa53..46c8cf7e 100644
--- a/site/src/proxy.ts
+++ b/site/src/proxy.ts
@@ -2,7 +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";
+import { BEACON_PATH, 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
@@ -63,7 +63,7 @@ const PASSTHROUGH = [
// Email-footer unsubscribe page; the back office's emails link here.
"/unsubscribe",
// The first-party page view beacon (app/p/route.ts).
- "/p",
+ BEACON_PATH,
];
// Whole-segment prefix match, so "/cut" covers "/cut/…" but not "/cut-app".
@@ -74,9 +74,11 @@ 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.
+// server wrote (see lib/meta/identity.ts). Only the server reads them. Each
+// page view's beacon renews them, so they last 90 days past the last visit.
function withMetaCookies(req: NextRequest, res: NextResponse): NextResponse {
- for (const { name, value } of metaCookies(req.nextUrl, req.cookies, Date.now())) {
+ const scope = req.nextUrl.pathname === BEACON_PATH ? "renew" : "new";
+ for (const { name, value } of metaCookies(req.nextUrl, req.cookies, Date.now(), scope)) {
res.cookies.set(name, value, {
httpOnly: true,
maxAge: META_COOKIE_MAX_AGE_S,