An open-source, faster Devin alternative
TypeScript
api-edge: record signup attribution from the oc_ft first-touch cookie (work 087)
utpal nadiger via Computer66dfdcda76b2
diff --git a/cloudflare-workers/api-edge/migrations/0020_signup_attribution.sql b/cloudflare-workers/api-edge/migrations/0020_signup_attribution.sqlnew file mode 100644index 00000000..437f3a42--- /dev/null+++ b/cloudflare-workers/api-edge/migrations/0020_signup_attribution.sql@@ -0,0 +1,28 @@+-- signup_attribution (serverless-agents-ws 087): where each signup came from.+-- One row per user created by a login, written by the edge at signup from the+-- `oc_ft` first-touch cookie (src/signup_attribution.ts). `channel` is+-- signupChannel() of the stored fields; a signup without the cookie (CLI, or+-- cookies blocked) is `unknown`, as is every user from before this table.+-- No personal data: campaign parameters, click ids, the external referrer's+-- origin and path, the landing path.+CREATE TABLE IF NOT EXISTS signup_attribution (+ user_id TEXT PRIMARY KEY,+ utm_source TEXT,+ utm_medium TEXT,+ utm_campaign TEXT,+ utm_term TEXT,+ utm_content TEXT,+ gclid TEXT,+ fbclid TEXT,+ li_fat_id TEXT,+ ref TEXT,+ referrer TEXT,+ landing_path TEXT,+ first_seen_at INTEGER, -- unix seconds the cookie was set+ channel TEXT NOT NULL, -- google_ads | other_paid | organic_search | social | referral | direct | unknown+ client TEXT NOT NULL, -- web | cli+ auth_method TEXT, -- WorkOS authentication_method+ plan_intent TEXT, -- pro | max from the pricing CTA+ created_at INTEGER NOT NULL+);+CREATE INDEX IF NOT EXISTS idx_signup_attribution_created_at ON signup_attribution(created_at);diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.tsindex 77c70f94..e13a67d5 100644--- a/cloudflare-workers/api-edge/src/index.ts+++ b/cloudflare-workers/api-edge/src/index.ts@@ -125,6 +125,7 @@ import {} from "./computer_telemetry";import { computerEnabledFor } from "./computer";import { createdKeyForSync, revokeComputerKey, syncComputerKey } from "./computer_keys";+import { FIRST_TOUCH_COOKIE, readCookie, recordSignupAttribution, withFirstTouchCookie } from "./signup_attribution";export interface Env extends DashboardEnv, AgentFeedbackEnv, BillingEventsEnv {CF_ADMIN_SECRET: string;@@ -3822,6 +3823,8 @@ interface ProvisionedIdentity {name: string;plan: string;};+ /** True when this login created the user row: a signup. */+ created: boolean;}type IdentitySelection = "browser" | "cli";@@ -3966,6 +3969,7 @@ async function provisionWorkOSIdentity(.bind(profile.id).first<{ id: string; email: string; name: string | null }>();+ let created = false;if (!userRow) {const candidateID = crypto.randomUUID();await env.OPENCOMPUTER_DB.prepare(@@ -3990,6 +3994,8 @@ async function provisionWorkOSIdentity(.bind(profile.id).first<{ id: string; email: string; name: string | null }>();if (!userRow) throw new Error("workos user upsert did not resolve");+ // The email-conflict path keeps an existing account: not a signup.+ created = userRow.id === candidateID;}const userID = userRow.id;@@ -4132,6 +4138,7 @@ async function provisionWorkOSIdentity(name: orgRow.name,plan: orgRow.plan,},+ created,};}@@ -4157,7 +4164,7 @@ async function authCallback(req: Request, env: Env): Promise<Response> {const errText = await tokenResp.text();return json({ error: `workos exchange failed: ${tokenResp.status}: ${errText}` }, 401);}- const tokenBody = await tokenResp.json<{ user: WorkOSProfile; organization_id?: string; access_token?: string }>();+ const tokenBody = await tokenResp.json<AuthenticateResponse>();// The code is spent from here on, so a throw would leave the user on a 1101// whose refresh fails with "code already exchanged". Restart the login once// (WorkOS issues a fresh code); a second failure gets a plain retry page.@@ -4197,11 +4204,18 @@ function parseAuthState(raw: string | null): { returnTo: string | null; retried:}}+type AuthenticateResponse = {+ user: WorkOSProfile;+ organization_id?: string;+ access_token?: string;+ authentication_method?: string;+};+async function completeAuthCallback(req: Request,env: Env,reqURL: URL,- tokenBody: { user: WorkOSProfile; organization_id?: string; access_token?: string },+ tokenBody: AuthenticateResponse,): Promise<Response> {const profile = tokenBody.user;// WorkOS session id (sid) for the hosted logout flow — carried in our session JWT.@@ -4209,14 +4223,25 @@ async function completeAuthCallback(// Re-validate here: `state` is attacker-influenceable, so the path is only// trusted after safeReturnTo passes a second time.const returnTo = parseAuthState(reqURL.searchParams.get("state")).returnTo;+ const planIntent = planIntentOf(returnTo);const identity = await provisionWorkOSIdentity(req,env,profile,tokenBody.organization_id ?? profile.organization_id,"browser",- planIntentOf(returnTo),+ planIntent,);+ if (identity.created) {+ await recordSignupAttribution(env, {+ userId: identity.user.id,+ orgId: identity.org.id,+ client: "web",+ authMethod: tokenBody.authentication_method,+ planIntent,+ cookie: readCookie(req.headers.get("cookie"), FIRST_TOUCH_COOKIE),+ });+ }// Mint session JWT — same signing secret as cap-token but a different// Issuer so cell middleware can distinguish.@@ -4684,6 +4709,16 @@ async function authCLIExchange(req: Request, env: Env, ctx?: ExecutionContext):} catch {return finish(cliAuthError("account_provisioning_unavailable", 503), "provisioning_error");}+ if (identity.created) {+ await recordSignupAttribution(env, {+ userId: identity.user.id,+ orgId: identity.org.id,+ client: "cli",+ authMethod: providerBody?.authentication_method,+ planIntent: null,+ cookie: null,+ });+ }let credential;try {@@ -5904,7 +5939,7 @@ export default {}// Browser auth flow.- if (path === "/auth/login") { if (req.method === "GET") return authLogin(req, env); }+ if (path === "/auth/login") { if (req.method === "GET") return withFirstTouchCookie(req, await authLogin(req, env)); }if (path === "/auth/callback") { if (req.method === "GET") return authCallback(req, env); }if (path === "/auth/logout") { if (req.method === "POST") return authLogout(req, env); }if (path === "/auth/refresh") { if (req.method === "POST") return authRefresh(req, env); }@@ -6301,7 +6336,9 @@ export default {// this Worker before checking assets, so we have to explicitly hand// requests off here. The assets binding's not_found_handling=// "single-page-application" serves index.html for client-side routes.- if (env.ASSETS) return env.ASSETS.fetch(req);+ // Visitors who land on the app first get the site's first-touch cookie+ // here (work 087).+ if (env.ASSETS) return withFirstTouchCookie(req, await env.ASSETS.fetch(req));return new Response("not found", { status: 404 });},diff --git a/cloudflare-workers/api-edge/src/signup_attribution.test.ts b/cloudflare-workers/api-edge/src/signup_attribution.test.tsnew file mode 100644index 00000000..531df5ee--- /dev/null+++ b/cloudflare-workers/api-edge/src/signup_attribution.test.ts@@ -0,0 +1,250 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import worker, { type Env } from "./index";+import {+ decodeFirstTouch,+ encodeFirstTouch,+ firstTouchFromRequest,+ firstTouchSetCookie,+ signupAttributionRow,+ signupChannel,+ signupPostHogEvent,+ type FirstTouch,+} from "./signup_attribution";++// The callback test runs the edge's SQL against the real schema: the snapshot,+// then every migration statement it does not already contain, in node:sqlite (see agent_feedback.test.ts for why+// the builtins are reached this way).+interface SqliteStatement {+ get(...params: unknown[]): unknown;+ all(...params: unknown[]): unknown[];+ run(...params: unknown[]): unknown;+}+interface DatabaseSync {+ exec(sql: string): void;+ prepare(sql: string): SqliteStatement;+}+declare const process: { cwd(): string; getBuiltinModule(id: string): unknown };+const { DatabaseSync } = process.getBuiltinModule("node:sqlite") as { DatabaseSync: new (path: string) => DatabaseSync };+const fs = process.getBuiltinModule("node:fs") as {+ readFileSync(path: string, enc: "utf8"): string;+ readdirSync(path: string): string[];+};++class Stmt {+ private params: unknown[] = [];+ constructor(private db: DatabaseSync, private sql: string) {}+ bind(...p: unknown[]): this {+ this.params = p;+ return this;+ }+ private args(): unknown[] {+ return this.params.map((v) => (v === undefined ? null : v));+ }+ async first<T>(): Promise<T | null> {+ return (this.db.prepare(this.sql).get(...this.args()) as T | undefined) ?? null;+ }+ async all<T>(): Promise<{ results: T[] }> {+ return { results: this.db.prepare(this.sql).all(...this.args()) as T[] };+ }+ async run(): Promise<{ success: true; meta: object }> {+ this.db.prepare(this.sql).run(...this.args());+ return { success: true, meta: {} };+ }+}++function schemaDB(): DatabaseSync {+ const db = new DatabaseSync(":memory:");+ const root = process.cwd();+ db.exec(fs.readFileSync(`${root}/schema-snapshots/current_schema.sql`, "utf8"));+ for (const file of fs.readdirSync(`${root}/migrations`).filter((f) => f.endsWith(".sql")).sort()) {+ const sql = fs.readFileSync(`${root}/migrations/${file}`, "utf8").replace(/^\s*--.*$/gm, "");+ for (const statement of sql.split(/;\s*$/m).filter((s) => s.trim())) {+ try {+ db.exec(statement);+ } catch (err) {+ if (!/already exists|duplicate column/.test(String(err))) throw err;+ }+ }+ }+ return db;+}++const NOW = Date.UTC(2026, 9, 27, 12, 0, 0);+const NOW_SEC = NOW / 1000;++const nav = (url: string, headers: Record<string, string> = {}) =>+ new Request(url, { headers: { "sec-fetch-dest": "document", ...headers } });++describe("first-touch cookie", () => {+ it("captures campaign parameters, the external referrer and the landing path", () => {+ const ft = firstTouchFromRequest(+ nav("https://opencomputer.dev/pricing?utm_source=google&utm_medium=cpc&utm_campaign=launch&gclid=abc&[email protected]", {+ referer: "https://www.google.com/search?q=sandboxes",+ }),+ NOW,+ );+ expect(ft).toEqual({+ utm_source: "google",+ utm_medium: "cpc",+ utm_campaign: "launch",+ gclid: "abc",+ referrer: "https://www.google.com/search",+ landing: "/pricing",+ ts: NOW_SEC,+ });+ });++ it("drops internal referrers", () => {+ for (const referer of ["https://opencomputer.dev/", "https://app.opencomputer.dev/x", "https://docs.opencomputer.dev/"]) {+ expect(firstTouchFromRequest(nav("https://app.opencomputer.dev/", { referer }), NOW).referrer).toBeUndefined();+ }+ });++ it("round-trips and caps values", () => {+ const ft = firstTouchFromRequest(nav(`https://opencomputer.dev/?utm_campaign=${"x".repeat(500)}&ref=ünï`), NOW);+ const back = decodeFirstTouch(encodeFirstTouch(ft))!;+ expect(back.utm_campaign).toHaveLength(100);+ expect(back.ref).toBe("ünï");+ expect(back.ts).toBe(NOW_SEC);+ });++ it("decodes bad cookies to null, never throwing", () => {+ for (const raw of [null, "", "!!!", "e30", btoa("[1]"), btoa("not json"), "A".repeat(5000), "_-_-"]) {+ const out = decodeFirstTouch(raw);+ expect(out === null || Object.keys(out).length === 0).toBe(true);+ }+ expect(decodeFirstTouch(encodeFirstTouch({ utm_source: 5, evil: "x", ts: "now" } as unknown as FirstTouch))).toEqual({});+ });++ it("is set on a first page view only, on the shared domain", () => {+ const cookie = firstTouchSetCookie(nav("https://opencomputer.dev/?utm_source=test"), NOW)!;+ expect(cookie).toMatch(/^oc_ft=[A-Za-z0-9_-]+; Domain=\.opencomputer\.dev; Path=\/; Max-Age=7776000; Secure; SameSite=Lax$/);+ expect(firstTouchSetCookie(nav("https://opencomputer.dev/", { cookie: "a=1; oc_ft=xyz" }))).toBeNull();+ expect(firstTouchSetCookie(new Request("https://opencomputer.dev/x.js", { headers: { "sec-fetch-dest": "script" } }))).toBeNull();+ expect(firstTouchSetCookie(new Request("https://opencomputer.dev/", { method: "POST", headers: { "sec-fetch-dest": "document" } }))).toBeNull();+ // Off opencomputer.dev (dev environments) the cookie is host-only.+ expect(firstTouchSetCookie(nav("https://app2.opensandbox.ai/"))).not.toContain("Domain=");+ });+});++describe("signupChannel", () => {+ it.each<[FirstTouch | null, string]>([+ [null, "unknown"],+ [{ ts: 1 }, "direct"],+ [{ landing: "/" }, "direct"],+ [{ gclid: "x" }, "google_ads"],+ [{ utm_source: "google", utm_medium: "cpc" }, "google_ads"],+ [{ utm_source: "Google", utm_medium: "paid_search" }, "google_ads"],+ [{ utm_source: "linkedin", utm_medium: "paid_social" }, "other_paid"],+ [{ utm_source: "bing", utm_medium: "cpc" }, "other_paid"],+ [{ li_fat_id: "x" }, "other_paid"],+ [{ utm_source: "google" }, "organic_search"],+ [{ utm_source: "google", utm_medium: "organic" }, "organic_search"],+ [{ referrer: "https://www.google.co.uk/" }, "organic_search"],+ [{ referrer: "https://duckduckgo.com/" }, "organic_search"],+ [{ utm_source: "x" }, "social"],+ [{ utm_source: "newsletter", utm_medium: "social" }, "social"],+ [{ ref: "hn" }, "social"],+ [{ fbclid: "x" }, "social"],+ [{ referrer: "https://t.co/abc" }, "social"],+ [{ referrer: "https://www.linkedin.com/feed/" }, "social"],+ [{ referrer: "https://old.reddit.com/r/x" }, "social"],+ [{ referrer: "https://news.ycombinator.com/item" }, "social"],+ [{ referrer: "https://github.com/diggerhq/opencomputer" }, "referral"],+ [{ ref: "producthunt" }, "referral"],+ [{ utm_source: "newsletter", utm_medium: "email" }, "referral"],+ ])("%j is %s", (ft, channel) => {+ expect(signupChannel(ft)).toBe(channel);+ });+});++describe("signup row and PostHog event", () => {+ it("stores the cookie's fields and sends click ids as booleans only", () => {+ const cookie = encodeFirstTouch({ utm_source: "test", gclid: "g1", landing: "/", ts: 100 });+ const row = signupAttributionRow(+ { userId: "u1", orgId: "o1", client: "web", authMethod: "GoogleOAuth", planIntent: "pro", cookie },+ NOW_SEC,+ );+ expect(row).toMatchObject({ utm_source: "test", gclid: "g1", channel: "google_ads", auth_method: "GoogleOAuth", first_seen_at: 100 });+ const event = signupPostHogEvent("phc", row, "o1");+ expect(event).toMatchObject({ event: "signed_up", distinct_id: "u1" });+ expect(event.properties).toMatchObject({ has_gclid: true, utm_source: "test", channel: "google_ads", plan_intent: "pro" });+ expect(JSON.stringify(event)).not.toContain("g1");+ });++ it("records no cookie as unknown", () => {+ const row = signupAttributionRow({ userId: "u1", orgId: "o1", client: "cli", authMethod: 7, planIntent: null, cookie: null }, NOW_SEC);+ expect(row).toMatchObject({ channel: "unknown", client: "cli", auth_method: null, utm_source: null });+ });+});++describe("browser signup records attribution", () => {+ let db: DatabaseSync;+ let posthog: Array<Record<string, unknown>>;+ let env: Env;+ const ctx = { waitUntil: vi.fn(), passThroughOnException: vi.fn() } as unknown as ExecutionContext;++ beforeEach(() => {+ db = schemaDB();+ posthog = [];+ env = {+ OPENCOMPUTER_DB: {+ prepare: (sql: string) => new Stmt(db, sql),+ batch: async (stmts: Stmt[]) => Promise.all(stmts.map((s) => s.run())),+ },+ SESSION_JWT_SECRET: "test-secret",+ WORKOS_API_KEY: "sk_test",+ WORKOS_CLIENT_ID: "client_test",+ WORKER_ENV: "test",+ POSTHOG_PROJECT_TOKEN: "phc_test",+ } as unknown as Env;+ vi.stubGlobal("fetch", async (url: string, init?: RequestInit) => {+ if (String(url).includes("posthog")) {+ posthog.push(JSON.parse(String(init?.body)));+ return new Response("{}");+ }+ return Response.json({+ user: { id: "wos_1", email: "[email protected]", first_name: "New" },+ access_token: "x.e30.y",+ authentication_method: "GitHubOAuth",+ });+ });+ });+ afterEach(() => vi.unstubAllGlobals());++ const callback = (cookie?: string) =>+ worker.fetch(+ new Request("https://app.opencomputer.dev/auth/callback?code=c1", cookie ? { headers: { cookie } } : {}),+ env,+ ctx,+ );++ it("stores the first touch and auth method once, for the new user only", async () => {+ const ft = encodeFirstTouch({ utm_source: "test", landing: "/", ts: 100 });+ const res = await callback(`oc_ft=${ft}`);+ expect(res.status).toBe(302);+ const rows = db.prepare("SELECT * FROM signup_attribution").all() as Array<Record<string, unknown>>;+ expect(rows).toHaveLength(1);+ expect(rows[0]).toMatchObject({ utm_source: "test", channel: "referral", client: "web", auth_method: "GitHubOAuth", landing_path: "/" });+ expect(posthog.map((e) => e.event)).toEqual(["signed_up"]);++ // A second login by the same user is not a signup.+ await callback(`oc_ft=${encodeFirstTouch({ utm_source: "other" })}`);+ expect(db.prepare("SELECT utm_source FROM signup_attribution").all()).toEqual([{ utm_source: "test" }]);+ expect(posthog).toHaveLength(1);+ });++ it("logs in with a garbage cookie, recording unknown fields", async () => {+ const res = await callback("oc_ft=%%%garbage");+ expect(res.status).toBe(302);+ expect(res.headers.get("location")).toBe("https://app.opencomputer.dev/dashboard");+ expect(db.prepare("SELECT channel FROM signup_attribution").all()).toEqual([{ channel: "unknown" }]);+ });++ it("logs in when the attribution insert fails", async () => {+ db.exec("DROP TABLE signup_attribution");+ const res = await callback(`oc_ft=${encodeFirstTouch({ utm_source: "test" })}`);+ expect(res.status).toBe(302);+ expect(res.headers.get("set-cookie")).toContain("oc_session=");+ });+});diff --git a/cloudflare-workers/api-edge/src/signup_attribution.ts b/cloudflare-workers/api-edge/src/signup_attribution.tsnew file mode 100644index 00000000..584fcbc2--- /dev/null+++ b/cloudflare-workers/api-edge/src/signup_attribution.ts@@ -0,0 +1,315 @@+// Signup attribution (serverless-agents-ws 087): where each signup came from.+//+// The site worker (opencomputer-site-v1 `worker/first-touch.ts`) sets `oc_ft`+// on `.opencomputer.dev` on a visitor's first page view; this edge sets the+// same cookie for visitors who land on the app first. The value is base64url+// compact JSON of the campaign parameters, the external referrer, the landing+// path and the first-seen time: no personal data, never overwritten.+//+// At a browser signup the callback reads the cookie defensively (a bad or+// missing cookie never blocks login), stores one `signup_attribution` row with+// its channel, and sends PostHog a `signed_up` event with the same non-PII+// properties. Keep the encoding in step with the site's copy.++import type { BillingEventsEnv } from "./billing_events";++export const FIRST_TOUCH_COOKIE = "oc_ft";+export const FIRST_TOUCH_MAX_AGE_SEC = 90 * 24 * 60 * 60;+const FIRST_TOUCH_MAX_COOKIE_CHARS = 3072;+const PARAM_MAX_CHARS = 100;+const URL_MAX_CHARS = 200;++export const FIRST_TOUCH_PARAMS = [+ "utm_source",+ "utm_medium",+ "utm_campaign",+ "utm_term",+ "utm_content",+ "gclid",+ "fbclid",+ "li_fat_id",+ "ref",+] as const;++type FirstTouchParam = (typeof FIRST_TOUCH_PARAMS)[number];++export type FirstTouch = Partial<Record<FirstTouchParam | "referrer" | "landing", string>> & {+ /** First-seen time, unix seconds. */+ ts?: number;+};++function clean(value: string | null | undefined, max: number): string | undefined {+ if (typeof value !== "string") return undefined;+ const out = value.replace(/[\u0000-\u001f\u007f]/g, "").trim().slice(0, max);+ return out || undefined;+}++function isOwnHost(host: string, requestHost: string): boolean {+ return host === requestHost || host === "opencomputer.dev" || host.endsWith(".opencomputer.dev");+}++/** The first touch a request represents: its campaign parameters, external referrer and path. */+export function firstTouchFromRequest(req: Request, now = Date.now()): FirstTouch {+ const url = new URL(req.url);+ const ft: FirstTouch = {};+ for (const key of FIRST_TOUCH_PARAMS) {+ const value = clean(url.searchParams.get(key), PARAM_MAX_CHARS);+ if (value) ft[key] = value;+ }+ const referer = req.headers.get("referer");+ if (referer) {+ try {+ const ref = new URL(referer);+ // Origin and path only: a query string can carry anything.+ if ((ref.protocol === "https:" || ref.protocol === "http:") && !isOwnHost(ref.hostname, url.hostname)) {+ ft.referrer = clean(`${ref.origin}${ref.pathname}`, URL_MAX_CHARS);+ }+ } catch {+ // Unparseable referrer: leave it out.+ }+ }+ ft.landing = clean(url.pathname, URL_MAX_CHARS);+ ft.ts = Math.floor(now / 1000);+ return ft;+}++function toBase64Url(text: string): string {+ let binary = "";+ for (const byte of new TextEncoder().encode(text)) binary += String.fromCharCode(byte);+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");+}++function fromBase64Url(value: string): string {+ const b64 = value.replace(/-/g, "+").replace(/_/g, "/");+ const binary = atob(b64 + "=".repeat((4 - (b64.length % 4)) % 4));+ return new TextDecoder("utf-8", { fatal: true, ignoreBOM: false }).decode(Uint8Array.from(binary, (c) => c.charCodeAt(0)));+}++export function encodeFirstTouch(ft: FirstTouch): string {+ return toBase64Url(JSON.stringify(ft));+}++/** Parses a cookie value; anything malformed is null, unknown keys are dropped. */+export function decodeFirstTouch(raw: string | null | undefined): FirstTouch | null {+ if (!raw || raw.length > FIRST_TOUCH_MAX_COOKIE_CHARS || !/^[A-Za-z0-9_-]+$/.test(raw)) return null;+ let parsed: unknown;+ try {+ parsed = JSON.parse(fromBase64Url(raw));+ } catch {+ return null;+ }+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;+ const obj = parsed as Record<string, unknown>;+ const ft: FirstTouch = {};+ for (const key of FIRST_TOUCH_PARAMS) {+ const value = clean(obj[key] as string | undefined, PARAM_MAX_CHARS);+ if (value) ft[key] = value;+ }+ const referrer = clean(obj.referrer as string | undefined, URL_MAX_CHARS);+ if (referrer) ft.referrer = referrer;+ const landing = clean(obj.landing as string | undefined, URL_MAX_CHARS);+ if (landing) ft.landing = landing;+ if (typeof obj.ts === "number" && Number.isFinite(obj.ts) && obj.ts > 0) ft.ts = Math.floor(obj.ts);+ return ft;+}++export function readCookie(header: string | null, name: string): string | null {+ if (!header) return null;+ for (const part of header.split(";")) {+ const eq = part.indexOf("=");+ if (eq > 0 && part.slice(0, eq).trim() === name) return part.slice(eq + 1).trim();+ }+ return null;+}++function isPageNavigation(req: Request): boolean {+ if (req.method !== "GET") return false;+ const dest = req.headers.get("sec-fetch-dest");+ if (dest) return dest === "document";+ return (req.headers.get("accept") ?? "").includes("text/html");+}++/**+ * The Set-Cookie header for a visitor's first page view, or null when the+ * request already carries `oc_ft` or is not a page navigation.+ */+export function firstTouchSetCookie(req: Request, now = Date.now()): string | null {+ if (!isPageNavigation(req)) return null;+ if (readCookie(req.headers.get("cookie"), FIRST_TOUCH_COOKIE) !== null) return null;+ const host = new URL(req.url).hostname;+ const domain = host === "opencomputer.dev" || host.endsWith(".opencomputer.dev") ? "; Domain=.opencomputer.dev" : "";+ const value = encodeFirstTouch(firstTouchFromRequest(req, now));+ return `${FIRST_TOUCH_COOKIE}=${value}${domain}; Path=/; Max-Age=${FIRST_TOUCH_MAX_AGE_SEC}; Secure; SameSite=Lax`;+}++/** Adds the first-touch cookie to a page response when the visitor has none. */+export function withFirstTouchCookie(req: Request, res: Response, now = Date.now()): Response {+ const cookie = firstTouchSetCookie(req, now);+ if (!cookie) return res;+ const out = new Response(res.body, res);+ out.headers.append("set-cookie", cookie);+ return out;+}++export type SignupChannel =+ | "google_ads"+ | "other_paid"+ | "organic_search"+ | "social"+ | "referral"+ | "direct"+ | "unknown";++const PAID_MEDIUM = /^(cpc|ppc|cpm|cpv|cpa|paid|display|banner|retargeting|ads?)$|paid/;+const GOOGLE_SOURCE = /^(google|adwords|googleads|google_ads|google-ads)$/;+const SOCIAL_SOURCE =+ /^(x|twitter|t\.co|linkedin|lnkd\.in|reddit|hn|hackernews|hacker_news|hacker-news|ycombinator|news\.ycombinator\.com|facebook|fb|instagram|threads|bluesky|bsky|mastodon|youtube)$/;+const SOCIAL_HOST =+ /(^|\.)(x\.com|twitter\.com|t\.co|linkedin\.com|lnkd\.in|reddit\.com|news\.ycombinator\.com|facebook\.com|instagram\.com|threads\.net|bsky\.app|youtube\.com)$/;+const SEARCH_SOURCE = /^(google|bing|duckduckgo|ddg|yahoo|baidu|yandex|ecosia|brave|kagi|startpage)$/;+const SEARCH_HOST =+ /(^|\.)(google\.[a-z.]+|bing\.com|duckduckgo\.com|search\.yahoo\.com|baidu\.com|yandex\.[a-z.]+|ecosia\.org|search\.brave\.com|kagi\.com|startpage\.com)$/;++function hostOf(url: string | null | undefined): string | null {+ if (!url) return null;+ try {+ return new URL(url).hostname.toLowerCase();+ } catch {+ return null;+ }+}++/**+ * The channel of one signup. `null` (no row, or a signup that arrived without+ * a first-touch cookie) is unknown; a cookie with no campaign or referrer is+ * direct.+ */+export function signupChannel(ft: FirstTouch | null): SignupChannel {+ if (!ft) return "unknown";+ const source = ft.utm_source?.toLowerCase() ?? "";+ const medium = ft.utm_medium?.toLowerCase() ?? "";+ const ref = ft.ref?.toLowerCase() ?? "";+ const referrerHost = hostOf(ft.referrer);+ const paid = medium !== "" && PAID_MEDIUM.test(medium);++ if (ft.gclid || (paid && GOOGLE_SOURCE.test(source))) return "google_ads";+ if (paid || ft.li_fat_id) return "other_paid";+ if (SOCIAL_SOURCE.test(source) || medium === "social" || SOCIAL_SOURCE.test(ref) || ft.fbclid) return "social";+ if (SEARCH_SOURCE.test(source) && (medium === "" || medium === "organic")) return "organic_search";+ if (!source && !ref && referrerHost) {+ if (SOCIAL_HOST.test(referrerHost)) return "social";+ if (SEARCH_HOST.test(referrerHost)) return "organic_search";+ }+ if (source || ref || referrerHost) return "referral";+ return "direct";+}++export interface SignupAttributionInput {+ userId: string;+ orgId: string;+ client: "web" | "cli";+ /** WorkOS `authentication_method` (GoogleOAuth, GitHubOAuth, MagicAuth, …). */+ authMethod: unknown;+ planIntent: string | null;+ /** The raw `oc_ft` cookie value; null when the signup carried none. */+ cookie: string | null;+}++export interface SignupAttributionEnv extends BillingEventsEnv {+ OPENCOMPUTER_DB: D1Database;+}++const POSTHOG_TIMEOUT_MS = 2_000;+const DEFAULT_POSTHOG_HOST = "https://us.i.posthog.com";++/** The stored row for one signup. */+export function signupAttributionRow(input: SignupAttributionInput, nowSec: number) {+ const ft = decodeFirstTouch(input.cookie);+ return {+ user_id: input.userId,+ utm_source: ft?.utm_source ?? null,+ utm_medium: ft?.utm_medium ?? null,+ utm_campaign: ft?.utm_campaign ?? null,+ utm_term: ft?.utm_term ?? null,+ utm_content: ft?.utm_content ?? null,+ gclid: ft?.gclid ?? null,+ fbclid: ft?.fbclid ?? null,+ li_fat_id: ft?.li_fat_id ?? null,+ ref: ft?.ref ?? null,+ referrer: ft?.referrer ?? null,+ landing_path: ft?.landing ?? null,+ first_seen_at: ft?.ts ?? null,+ channel: signupChannel(ft),+ client: input.client,+ auth_method: clean(typeof input.authMethod === "string" ? input.authMethod : null, 40) ?? null,+ plan_intent: input.planIntent,+ created_at: nowSec,+ };+}++export type SignupAttributionRow = ReturnType<typeof signupAttributionRow>;++/** The PostHog `signed_up` capture: the row minus click ids, which become booleans. */+export function signupPostHogEvent(token: string, row: SignupAttributionRow, orgId: string): Record<string, unknown> {+ const properties: Record<string, unknown> = {+ channel: row.channel,+ client: row.client,+ has_gclid: row.gclid !== null,+ has_fbclid: row.fbclid !== null,+ has_li_fat_id: row.li_fat_id !== null,+ org_id: orgId,+ $groups: { organization: orgId },+ };+ for (const key of [+ "utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content",+ "ref", "referrer", "landing_path", "auth_method", "plan_intent",+ ] as const) {+ if (row[key] !== null) properties[key] = row[key];+ }+ if (row.first_seen_at !== null) properties.first_seen_at = new Date(row.first_seen_at * 1000).toISOString();+ return {+ api_key: token,+ event: "signed_up",+ distinct_id: row.user_id,+ timestamp: new Date(row.created_at * 1000).toISOString(),+ properties,+ };+}++/** Stores the signup's attribution and tells PostHog. Never throws. */+export async function recordSignupAttribution(env: SignupAttributionEnv, input: SignupAttributionInput): Promise<void> {+ let row: SignupAttributionRow;+ try {+ row = signupAttributionRow(input, Math.floor(Date.now() / 1000));+ await env.OPENCOMPUTER_DB.prepare(+ `INSERT INTO signup_attribution (+ user_id, utm_source, utm_medium, utm_campaign, utm_term, utm_content,+ gclid, fbclid, li_fat_id, ref, referrer, landing_path, first_seen_at,+ channel, client, auth_method, plan_intent, created_at)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18)+ ON CONFLICT(user_id) DO NOTHING`,+ )+ .bind(+ row.user_id, row.utm_source, row.utm_medium, row.utm_campaign, row.utm_term, row.utm_content,+ row.gclid, row.fbclid, row.li_fat_id, row.ref, row.referrer, row.landing_path, row.first_seen_at,+ row.channel, row.client, row.auth_method, row.plan_intent, row.created_at,+ )+ .run();+ } catch (err) {+ console.error(`signup attribution: insert failed for ${input.userId}`, err instanceof Error ? err.message : "");+ return;+ }+ const token = env.POSTHOG_PROJECT_TOKEN?.trim();+ if (!token) return;+ try {+ const res = await fetch(`${(env.POSTHOG_HOST?.trim() || DEFAULT_POSTHOG_HOST).replace(/\/+$/, "")}/i/v0/e/`, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify(signupPostHogEvent(token, row, input.orgId)),+ signal: AbortSignal.timeout(POSTHOG_TIMEOUT_MS),+ });+ await res.body?.cancel().catch(() => {});+ } catch {+ // Telemetry never fails the login.+ }+}