Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix(analytics): remove the event ledger and report from the browser (#944)
Gustavo Yec2b30ba6204b
diff --git a/src/shared/src/db/index.ts b/src/shared/src/db/index.tsindex 62c83930d..566f2029c 100644--- a/src/shared/src/db/index.ts+++ b/src/shared/src/db/index.ts@@ -5,9 +5,8 @@ import * as communityMachineSchema from "./community-machine-schema";import * as billingSchema from "./billing-schema";import * as productPlanSchema from "./product-plan-schema";import * as communityFunnelAnalyticsSchema from "./community-funnel-analytics-schema";-import * as productAnalyticsSchema from "./product-analytics-schema";-const allSchema = { ...schema, ...communitySchema, ...communityMachineSchema, ...productPlanSchema, ...billingSchema, ...communityFunnelAnalyticsSchema, ...productAnalyticsSchema };+const allSchema = { ...schema, ...communitySchema, ...communityMachineSchema, ...productPlanSchema, ...billingSchema, ...communityFunnelAnalyticsSchema };export function createDb(d1: AnyD1Database) {return drizzle(d1, { schema: allSchema });diff --git a/src/shared/src/db/product-analytics-schema.ts b/src/shared/src/db/product-analytics-schema.tsdeleted file mode 100644index c8aefc8c1..000000000--- a/src/shared/src/db/product-analytics-schema.ts+++ /dev/null@@ -1,41 +0,0 @@-import { index, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";-import { user } from "./schema";-import { communityServer } from "./community-schema";--export const PRODUCT_ANALYTICS_EVENTS = [- "landing_cta_clicked",- "login_page_view",- "sign_up",- "sign_in_success",- "sign_in_failed",- "onboarding_enter_clicked",- "onboarding_first_message",- "invitation_link_visit",-] as const;--export type ProductAnalyticsEventName = typeof PRODUCT_ANALYTICS_EVENTS[number];-export type ProductAnalyticsDeliveryStatus = "pending" | "sending" | "accepted" | "failed" | "uncertain" | "denied";--export const productAnalyticsEvent = sqliteTable("product_analytics_event", {- id: text("id").primaryKey(),- eventName: text("event_name").notNull().$type<ProductAnalyticsEventName>(),- actorUserId: text("actor_user_id").references(() => user.id, { onDelete: "cascade" }),- serverId: text("server_id").references(() => communityServer.id, { onDelete: "cascade" }),- sourceId: text("source_id"),- dedupeKey: text("dedupe_key").notNull(),- clientId: text("client_id").notNull(),- sessionId: text("session_id").notNull(),- method: text("method"),- accountKind: text("account_kind").$type<"new" | "existing">(),- ctaName: text("cta_name"),- failureStage: text("failure_stage").$type<"send_code" | "verify_code" | "social_start" | "provider_callback">(),- createdAt: text("created_at").notNull(),- deliveryStatus: text("delivery_status").notNull().default("pending").$type<ProductAnalyticsDeliveryStatus>(),- deliveryReason: text("delivery_reason"),- attemptedAt: text("attempted_at"),-}, (t) => [- uniqueIndex("uq_product_analytics_dedupe").on(t.dedupeKey),- index("idx_product_analytics_actor_server_event").on(t.actorUserId, t.serverId, t.eventName),-]);--export type ProductAnalyticsEvent = typeof productAnalyticsEvent.$inferSelect;diff --git a/src/shared/src/db/queries-index.ts b/src/shared/src/db/queries-index.tsindex aa49715c0..82c7cd49c 100644--- a/src/shared/src/db/queries-index.ts+++ b/src/shared/src/db/queries-index.ts@@ -70,7 +70,6 @@ export * as communityBotAuditLog from "./queries/community/bot-audit-log";export * as communityMessageTag from "./queries/community/message-tag";export * as communityDiagnosticReport from "./queries/community/diagnostic-report";export * as communityFunnelAnalytics from "./queries/community/funnel-analytics";-export * as productAnalytics from "./queries/community/product-analytics";export const nativeOauth = nativeOauthQueries;export * as billing from "./queries/billing";diff --git a/src/shared/src/db/queries/community/product-analytics.test.ts b/src/shared/src/db/queries/community/product-analytics.test.tsdeleted file mode 100644index b77bae24b..000000000--- a/src/shared/src/db/queries/community/product-analytics.test.ts+++ /dev/null@@ -1,135 +0,0 @@-import Sqlite from "better-sqlite3"-import { readFileSync } from "node:fs"-import { resolve } from "node:path"-import { getTableName } from "drizzle-orm"-import { getTableConfig } from "drizzle-orm/sqlite-core"-import { productAnalyticsEvent } from "../../product-analytics-schema"-import { drizzle } from "drizzle-orm/better-sqlite3"-import { afterEach, beforeEach, describe, expect, it } from "vitest"-import type { Database } from "../../index"-import { claimDelivery, claimSignupSession, finishDelivery, getInviteSource, getOwnedServer, notePendingReason, recordEvent, recordFirstHumanMessage } from "./product-analytics"--const time = "2026-10-12T05:00:00.000Z"-const identity = { clientId: "100.200", sessionId: "1791781200" }--describe("product analytics durable ledger", () => {- let sqlite: Sqlite.Database- let db: Database- beforeEach(() => {- sqlite = new Sqlite(":memory:")- sqlite.exec(`- PRAGMA foreign_keys = ON;- CREATE TABLE user (id TEXT PRIMARY KEY, isBot INTEGER, deletedAt TEXT);- CREATE TABLE community_server (id TEXT PRIMARY KEY, owner_id TEXT);- CREATE TABLE community_server_invite (id TEXT PRIMARY KEY, token TEXT, server_id TEXT, created_by TEXT);- CREATE TABLE community_channel (id TEXT PRIMARY KEY, server_id TEXT);- CREATE TABLE community_message (id TEXT PRIMARY KEY, author_id TEXT, channel_id TEXT, type TEXT, created_at TEXT);- INSERT INTO user VALUES ('owner', 0, NULL), ('other', 0, NULL), ('bot', 1, NULL), ('deleted', 0, '2026-10-10');- INSERT INTO community_server VALUES ('server', 'owner'), ('other-server', 'other');- INSERT INTO community_server_invite VALUES ('invite', 'private-token', 'server', 'owner');- INSERT INTO community_channel VALUES ('channel', 'server'), ('other-channel', 'other-server'), ('dm', NULL);- `)- sqlite.exec(readFileSync(resolve(import.meta.dirname, "../../../../../web/migrations/0107_product_analytics_event.sql"), "utf8"))- db = drizzle(sqlite) as unknown as Database- })- afterEach(() => sqlite.close())- const entry = () => recordEvent(db, { eventName: "onboarding_enter_clicked", actorUserId: "owner", serverId: "server", dedupeKey: "entry", ...identity, createdAt: time })- function message(id: string, author = "owner", channel = "channel", createdAt = "2026-10-12T05:00:01.000Z", type = "default") {- sqlite.prepare("INSERT INTO community_message VALUES (?, ?, ?, ?, ?)").run(id, author, channel, type, createdAt)- }-- it("keeps migration foreign keys and dedupe/scope indexes aligned with the Drizzle schema", () => {- const config = getTableConfig(productAnalyticsEvent)- const declaredKeys = config.foreignKeys.map(key => {- const ref = key.reference()- return { from: ref.columns[0].name, table: getTableName(ref.foreignTable), to: ref.foreignColumns[0].name, on_delete: key.onDelete?.toUpperCase() }- }).sort((a, b) => a.from.localeCompare(b.from))- const actualKeys = (sqlite.pragma("foreign_key_list(product_analytics_event)") as { from: string; table: string; to: string; on_delete: string }[])- .map(({ from, table, to, on_delete }) => ({ from, table, to, on_delete })).sort((a, b) => a.from.localeCompare(b.from))- expect(actualKeys).toEqual(declaredKeys)- const actualIndexes = sqlite.pragma("index_list(product_analytics_event)") as { name: string; unique: number; origin: string }[]- expect(actualIndexes.filter(index => index.origin === "c").map(index => index.name).sort())- .toEqual(config.indexes.map(index => index.config.name).sort())- for (const { config: index } of config.indexes) {- expect(actualIndexes.find(item => item.name === index.name)?.unique).toBe(index.unique ? 1 : 0)- const columns = sqlite.pragma(`index_info('${index.name}')`) as { name: string }[]- expect(columns.map(column => column.name)).toEqual(index.columns.map(column => "name" in column ? column.name : null))- }- })- it("scopes onboarding servers to the actual owner", async () => {- expect(await getOwnedServer(db, "owner", "server")).toEqual({ id: "server" })- expect(await getOwnedServer(db, "other", "server")).toBeNull()- })- it("resolves invitation source only through the capability token", async () => {- expect(await getInviteSource(db, "private-token")).toEqual({ id: "invite", serverId: "server", createdBy: "owner" })- expect(await getInviteSource(db, "unknown")).toBeNull()- })- it("deduplicates identical events without exposing another actor's row", async () => {- const first = await entry()- expect((await entry())?.row.id).toBe(first?.row.id)- expect((await entry())?.inserted).toBe(false)- expect(await recordEvent(db, { eventName: "onboarding_enter_clicked", actorUserId: "other", serverId: "server", dedupeKey: "entry", ...identity, createdAt: time })).toBeNull()- })- it("does not invent a first-message event without an Enter click", async () => {- message("first")- expect(await recordFirstHumanMessage(db, "owner", "server", identity, "first")).toBeNull()- })- it("excludes before-click messages and records the first subsequent human message", async () => {- message("old", "owner", "channel", "2026-10-12T04:59:00.000Z")- await entry()- message("first")- message("second", "owner", "channel", "2026-10-12T05:00:02.000Z")- const result = await recordFirstHumanMessage(db, "owner", "server", identity, "first")- expect(result?.row).toMatchObject({ sourceId: "first", createdAt: "2026-10-12T05:00:01.000Z", eventName: "onboarding_first_message" })- expect((await recordFirstHumanMessage(db, "owner", "server", identity, "first"))?.row.id).toBe(result?.row.id)- })- it("excludes bot, DM, other-server and other-user messages", async () => {- await entry()- message("bot", "bot")- message("other", "other")- message("dm", "owner", "dm")- message("other-server", "owner", "other-channel")- message("system", "owner", "channel", undefined, "system")- expect(await recordFirstHumanMessage(db, "owner", "server", identity, "first")).toBeNull()- })- it("does not backfill a prior untracked message from a later successful write", async () => {- await entry()- message("first")- message("second", "owner", "channel", "2026-10-12T05:00:02.000Z")- expect(await recordFirstHumanMessage(db, "owner", "server", identity, "second")).toBeNull()- })- it("does not count deleted human accounts", async () => {- await recordEvent(db, { eventName: "onboarding_enter_clicked", actorUserId: "deleted", serverId: "server", dedupeKey: "deleted-entry", ...identity, createdAt: time })- message("deleted-message", "deleted")- expect(await recordFirstHumanMessage(db, "deleted", "server", identity, "deleted-message")).toBeNull()- })- it("uses the current message session instead of the prior click session", async () => {- await entry()- message("late", "owner", "channel", "2026-10-15T05:00:01.000Z")- expect((await recordFirstHumanMessage(db, "owner", "server", { ...identity, sessionId: "1792040400" }, "late"))?.row.sessionId).toBe("1792040400")- })- it("claims the registration's first session atomically and only once", async () => {- await recordEvent(db, { eventName: "sign_up", actorUserId: "owner", dedupeKey: "signup:owner", ...identity, createdAt: time })- expect(await claimSignupSession(db, "owner", "session-1")).toBe(true)- expect(await claimSignupSession(db, "owner", "session-1")).toBe(true)- expect(await claimSignupSession(db, "owner", "session-2")).toBe(false)- expect(await claimSignupSession(db, "other", "session-1")).toBe(false)- })- it("allows only one transport claim and never retries an ambiguous send", async () => {- const event = (await entry())!.row- expect(await claimDelivery(db, event.id)).toMatchObject({ deliveryStatus: "sending" })- expect(await claimDelivery(db, event.id)).toBeNull()- await finishDelivery(db, event.id, "uncertain", "collection_transport_ambiguous")- expect(await claimDelivery(db, event.id)).toBeNull()- expect(sqlite.prepare("SELECT delivery_status FROM product_analytics_event").get()).toEqual({ delivery_status: "uncertain" })- })- it("records missing config without erasing a completed status", async () => {- const event = (await entry())!.row- await notePendingReason(db, event.id, "configuration_missing")- expect(sqlite.prepare("SELECT delivery_reason FROM product_analytics_event").get()).toEqual({ delivery_reason: "configuration_missing" })- await claimDelivery(db, event.id)- await finishDelivery(db, event.id, "accepted", "http_accepted")- await notePendingReason(db, event.id, "configuration_missing")- expect(sqlite.prepare("SELECT delivery_reason FROM product_analytics_event").get()).toEqual({ delivery_reason: "http_accepted" })- })-})diff --git a/src/shared/src/db/queries/community/product-analytics.ts b/src/shared/src/db/queries/community/product-analytics.tsdeleted file mode 100644index 1ea9d9def..000000000--- a/src/shared/src/db/queries/community/product-analytics.ts+++ /dev/null@@ -1,84 +0,0 @@-import { and, asc, eq, gte, isNull } from "drizzle-orm";-import { nanoid } from "nanoid";-import { communityChannel, communityServerInvite, communityMessage, communityServer } from "../../community-schema";-import { user } from "../../schema";-import { productAnalyticsEvent, type ProductAnalyticsDeliveryStatus } from "../../product-analytics-schema";-import type { Database } from "../../index";--export async function getOwnedServer(db: Database, actorUserId: string, serverId: string) {- const rows = await db.select({ id: communityServer.id }).from(communityServer).where(and(- eq(communityServer.id, serverId), eq(communityServer.ownerId, actorUserId),- )).limit(1);- return rows[0] ?? null;-}--export async function getInviteSource(db: Database, token: string) {- const rows = await db.select({- id: communityServerInvite.id, serverId: communityServerInvite.serverId, createdBy: communityServerInvite.createdBy,- }).from(communityServerInvite).innerJoin(communityServer, eq(communityServer.id, communityServerInvite.serverId))- .where(eq(communityServerInvite.token, token)).limit(1);- return rows[0] ?? null;-}--export async function recordEvent(db: Database, input: Omit<typeof productAnalyticsEvent.$inferInsert,- "id" | "deliveryStatus" | "deliveryReason" | "attemptedAt">) {- const rows = await db.insert(productAnalyticsEvent).values({ ...input, id: nanoid() }).onConflictDoNothing().returning();- if (rows[0]) return { row: rows[0], inserted: true };- const existing = await db.select().from(productAnalyticsEvent)- .where(and(eq(productAnalyticsEvent.dedupeKey, input.dedupeKey),- input.actorUserId ? eq(productAnalyticsEvent.actorUserId, input.actorUserId) : isNull(productAnalyticsEvent.actorUserId),- input.serverId ? eq(productAnalyticsEvent.serverId, input.serverId) : isNull(productAnalyticsEvent.serverId),- )).limit(1);- return existing[0] ? { row: existing[0], inserted: false } : null;-}--export async function recordFirstHumanMessage(db: Database, actorUserId: string, serverId: string, identity: { clientId: string; sessionId: string }, messageId: string) {- const entered = await db.select().from(productAnalyticsEvent).where(and(- eq(productAnalyticsEvent.actorUserId, actorUserId), eq(productAnalyticsEvent.serverId, serverId),- eq(productAnalyticsEvent.eventName, "onboarding_enter_clicked"),- )).limit(1);- const entry = entered[0];- if (!entry) return null;- const messages = await db.select({ id: communityMessage.id, createdAt: communityMessage.createdAt })- .from(communityMessage)- .innerJoin(communityChannel, eq(communityChannel.id, communityMessage.channelId))- .innerJoin(user, eq(user.id, communityMessage.authorId))- .where(and(eq(communityMessage.authorId, actorUserId), eq(communityChannel.serverId, serverId),- gte(communityMessage.createdAt, entry.createdAt), eq(communityMessage.type, "default"), eq(user.isBot, false), isNull(user.deletedAt)))- .orderBy(asc(communityMessage.createdAt), asc(communityMessage.id)).limit(1);- const message = messages[0];- if (!message || message.id !== messageId) return null;- return recordEvent(db, {- eventName: "onboarding_first_message", actorUserId, serverId, sourceId: message.id,- dedupeKey: `onboarding-first-message:${actorUserId}:${serverId}`,- clientId: identity.clientId, sessionId: identity.sessionId, createdAt: message.createdAt,- });-}--export async function claimDelivery(db: Database, id: string) {- const rows = await db.update(productAnalyticsEvent).set({- deliveryStatus: "sending", attemptedAt: new Date().toISOString(),- }).where(and(eq(productAnalyticsEvent.id, id), eq(productAnalyticsEvent.deliveryStatus, "pending"))).returning();- return rows[0] ?? null;-}--export async function finishDelivery(db: Database, id: string, deliveryStatus: ProductAnalyticsDeliveryStatus, deliveryReason: string) {- await db.update(productAnalyticsEvent).set({ deliveryStatus, deliveryReason })- .where(and(eq(productAnalyticsEvent.id, id), eq(productAnalyticsEvent.deliveryStatus, "sending")));-}--export async function claimSignupSession(db: Database, actorUserId: string, sessionId: string) {- const claimed = await db.update(productAnalyticsEvent).set({ sourceId: sessionId })- .where(and(eq(productAnalyticsEvent.actorUserId, actorUserId),- eq(productAnalyticsEvent.eventName, "sign_up"), isNull(productAnalyticsEvent.sourceId))).returning();- if (claimed[0]) return true;- const previous = await db.select({ id: productAnalyticsEvent.id }).from(productAnalyticsEvent)- .where(and(eq(productAnalyticsEvent.actorUserId, actorUserId),- eq(productAnalyticsEvent.eventName, "sign_up"), eq(productAnalyticsEvent.sourceId, sessionId))).limit(1);- return previous.length > 0;-}--export async function notePendingReason(db: Database, id: string, deliveryReason: string) {- await db.update(productAnalyticsEvent).set({ deliveryReason })- .where(and(eq(productAnalyticsEvent.id, id), eq(productAnalyticsEvent.deliveryStatus, "pending")));-}diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex b18db3d20..c5e47fc4c 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -192,7 +192,6 @@ export * from "./provider-telemetry";export * from "./product-entitlements";export * from "./billing";export type { CheckoutAttempt } from "./db/billing-schema";-export type { ProductAnalyticsEvent, ProductAnalyticsEventName } from "./db/product-analytics-schema";export type {CommunityFunnelAnalyticsEvent,CommunityFunnelConversationType,diff --git a/src/web/public/analytics-events.html b/src/web/public/analytics-events.htmlnew file mode 100644index 000000000..bda564ab0--- /dev/null+++ b/src/web/public/analytics-events.html@@ -0,0 +1,15 @@+<!doctype html>+<title>Alook</title>+<script>+window.dataLayer = [];+function gtag() { window.dataLayer.push(arguments); }+gtag('consent', 'default', { analytics_storage: 'granted', ad_storage: 'denied', ad_user_data: 'denied', ad_personalization: 'denied' });+gtag('js', new Date());+const fields = { page_location: 'https://alook.ai/analytics/product', page_referrer: '', page_title: 'Alook' };+gtag('config', 'G-STBCL8F4ZY', { send_page_view: false, allow_google_signals: false, allow_ad_personalization_signals: false, ...fields });+window.sendProductEvent = function ({ event, params }) {+ if (!['landing_cta_clicked', 'login_page_view', 'sign_up', 'sign_in_success', 'sign_in_failed', 'onboarding_enter_clicked', 'onboarding_first_message', 'invitation_link_visit'].includes(event)) return;+ gtag('event', event, { ...params, ...fields, send_to: 'G-STBCL8F4ZY' });+};+</script>+<script async src="https://www.googletagmanager.com/gtag/js?id=G-STBCL8F4ZY"></script>diff --git a/src/web/src/app/(auth)/sign-in/sign-in-client.dom.test.ts b/src/web/src/app/(auth)/sign-in/sign-in-client.dom.test.tsindex 859a5d641..680811e01 100644--- a/src/web/src/app/(auth)/sign-in/sign-in-client.dom.test.ts+++ b/src/web/src/app/(auth)/sign-in/sign-in-client.dom.test.ts@@ -64,7 +64,7 @@ describe("sign-in client Apple availability", () => {it("counts login entry once and records only bounded OTP failure dimensions", async () => {render(createElement(SignInPageClient, { isProd: true, appleEnabled: false }))- expect(mocks.capture).toHaveBeenCalledWith({ event: "login_page_view" }, expect.any(String))+ expect(mocks.capture).toHaveBeenCalledWith({ event: "login_page_view" })await setupUser().click(screen.getByRole("button", { name: "Send Code" }))expect(mocks.capture).toHaveBeenCalledTimes(1)await act(async () => { await mocks.verifyInput!("123456") })diff --git a/src/web/src/app/(auth)/sign-in/sign-in-client.tsx b/src/web/src/app/(auth)/sign-in/sign-in-client.tsxindex 87a16fe85..02b025363 100644--- a/src/web/src/app/(auth)/sign-in/sign-in-client.tsx+++ b/src/web/src/app/(auth)/sign-in/sign-in-client.tsx@@ -4,7 +4,7 @@ import { captureProductAnalytics } from "@/lib/product-analytics"import { startAction, finishAction } from "@/lib/observability/context"import { ObservedStaticContent } from "@/lib/observability/regions"import { useAtom, useCreateAtom } from "@tanstack/react-store";-import { useEffect, useMemo } from "react"+import { useEffect } from "react"import { useSearchParams } from "next/navigation"import { signIn, signUp, authClient } from "@/lib/auth-client"import { parseRetryAfterSeconds } from "@/lib/retry-after"@@ -50,8 +50,7 @@ function SignInForm({accountDeleted: booleanappleEnabled: boolean}) {- const viewId = useMemo(() => crypto.randomUUID(), [])- useEffect(() => { void captureProductAnalytics({ event: "login_page_view" }, viewId) }, [viewId])+ useEffect(() => { void captureProductAnalytics({ event: "login_page_view" }) }, [])const failed = (failureStage: "send_code" | "verify_code") => {void captureProductAnalytics({ event: "sign_in_failed", method: "email_otp", failureStage })}diff --git a/src/web/src/app/api/community/analytics/product-events/route.test.ts b/src/web/src/app/api/community/analytics/product-events/route.test.tsdeleted file mode 100644index 5ba5c3126..000000000--- a/src/web/src/app/api/community/analytics/product-events/route.test.ts+++ /dev/null@@ -1,109 +0,0 @@-import { NextRequest } from "next/server"-import { beforeEach, describe, expect, it, vi } from "vitest"-const mocks = vi.hoisted(() => ({- userId: undefined as string | undefined, env: { DB: {}, BETTER_AUTH_SECRET: "local-auth", NODE_ENV: "development" },- consent: vi.fn(), owned: vi.fn(), invite: vi.fn(), record: vi.fn(), live: vi.fn(), note: vi.fn(),-}))-vi.mock("@/lib/middleware/auth", () => ({ withOptionalAuth: (handler: (req: NextRequest, ctx: unknown) => Promise<Response>) =>- (req: NextRequest) => handler(req, { userId: mocks.userId, env: mocks.env }) }))-vi.mock("@/lib/db", () => ({ getPrimaryDb: () => mocks.env.DB }))-vi.mock("@opennextjs/cloudflare", () => ({ getCloudflareContext: async () => ({ ctx: { waitUntil: () => {} } }) }))-vi.mock("@alook/shared", async original => ({ ...await original<typeof import("@alook/shared")>(), queries: {- user: { getUserInternal: mocks.live }, billing: { getAnalyticsConsent: mocks.consent },- productAnalytics: { getOwnedServer: mocks.owned, getInviteSource: mocks.invite, recordEvent: mocks.record, notePendingReason: mocks.note },-} }))-import { POST } from "./route"-const id = "ee27bb80-e6dc-4cc3-97d7-c7bf2f1c13d2"-function request(body: unknown, headers: Record<string, string> = {}) {- return new NextRequest("https://alook.ai/api/community/analytics/product-events", {- method: "POST", body: JSON.stringify(body), headers: { origin: "https://alook.ai", "content-type": "application/json", ...headers },- })-}-beforeEach(() => {- vi.clearAllMocks(); mocks.userId = undefined- mocks.live.mockResolvedValue({ id: "owner", isBot: false, deletedAt: null })- mocks.consent.mockResolvedValue(null); mocks.owned.mockResolvedValue({ id: "server" })- mocks.invite.mockResolvedValue({ id: "invite", serverId: "server", createdBy: "creator" })- mocks.record.mockImplementation(async (_db, input) => ({ row: { ...input, id: "event" }, inserted: true }))-})--describe("restricted browser product-event endpoint", () => {- it("rejects oversized streamed bodies before parsing or recording", async () => {- const req = request({ event: "login_page_view", requestId: id, extra: "x".repeat(4096) }, { "content-length": "1" })- expect((await POST(req)).status).toBe(400)- expect(mocks.record).not.toHaveBeenCalled()- })- it("rejects cross-origin and bearer callers", async () => {- const body = { event: "login_page_view", requestId: id }- expect((await POST(request(body, { origin: "https://other.test" }))).status).toBe(403)- expect((await POST(request(body, { authorization: "Bearer synthetic" }))).status).toBe(403)- expect(mocks.record).not.toHaveBeenCalled()- })- it("rejects missing and malformed Origin before recording an event", async () => {- for (const origin of [undefined, "not a URL"]) {- const req = request({ event: "login_page_view", requestId: id })- if (origin === undefined) req.headers.delete("origin")- else req.headers.set("origin", origin)- expect((await POST(req)).status).toBe(403)- }- expect(mocks.record).not.toHaveBeenCalled()- })- it("rejects forged success, arbitrary private events, extra dimensions and invalid nonce", async () => {- for (const body of [- { event: "sign_in_success", requestId: id }, { event: "page_view", requestId: id },- { event: "login_page_view", requestId: id, email: "[email protected]" },- { event: "login_page_view", requestId: "bad" }, { event: "landing_cta_clicked", requestId: id, ctaName: "private-channel-name" },- ]) expect((await POST(request(body))).status).toBe(400)- expect(mocks.record).not.toHaveBeenCalled()- })- it("does not degrade a failed cookie session into an anonymous visit", async () => {- expect((await POST(request({ event: "invitation_link_visit", requestId: id, token: "token" }, { cookie: "better-auth.session_token=synthetic" }))).status).toBe(503)- expect(mocks.record).not.toHaveBeenCalled()- })- it("excludes live bot or deleted users even if optional session resolution accepted them", async () => {- mocks.userId = "owner"- for (const live of [{ isBot: true, deletedAt: null }, { isBot: false, deletedAt: "deleted" }]) {- mocks.live.mockResolvedValue(live)- expect((await POST(request({ event: "login_page_view", requestId: id }))).status).toBe(401)- }- expect(mocks.record).not.toHaveBeenCalled()- })- it("preserves anonymous explicit denial without writing identity cookies or ledger", async () => {- const response = await POST(request({ event: "login_page_view", requestId: id }, { cookie: "alook_analytics_consent=v1.denied" }))- expect(await response.json()).toEqual({ recorded: false })- expect(response.headers.getSetCookie()).toEqual([])- expect(mocks.record).not.toHaveBeenCalled()- })- it("requires human authentication and server ownership for Enter", async () => {- const body = { event: "onboarding_enter_clicked", requestId: id, serverId: "server" }- expect((await POST(request(body))).status).toBe(401)- mocks.userId = "owner"; mocks.owned.mockResolvedValue(null)- expect((await POST(request(body))).status).toBe(404)- expect(mocks.owned).toHaveBeenCalledWith(mocks.env.DB, "owner", "server")- })- it("records the Enter click with a server-scoped durable dedupe key before navigation", async () => {- mocks.userId = "owner"- const response = await POST(request({ event: "onboarding_enter_clicked", requestId: id, serverId: "server" }))- expect(response.status).toBe(200)- expect(mocks.record).toHaveBeenCalledWith(mocks.env.DB, expect.objectContaining({ eventName: "onboarding_enter_clicked", dedupeKey: "onboarding-enter:owner:server" }))- expect(response.headers.getSetCookie().some(cookie => cookie.startsWith("_ga="))).toBe(true)- })- it("counts known invitation page entries, including expired sources, without token payload", async () => {- await POST(request({ event: "invitation_link_visit", requestId: id, token: "private-token" }))- expect(mocks.record).toHaveBeenCalledWith(mocks.env.DB, expect.objectContaining({ eventName: "invitation_link_visit", sourceId: "invite", dedupeKey: `invite-visit:invite:${id}`, actorUserId: null }))- expect(JSON.stringify(mocks.record.mock.calls)).not.toContain("private-token")- })- it("excludes invalid sources and signed inviter self-preview", async () => {- mocks.invite.mockResolvedValueOnce(null)- expect(await (await POST(request({ event: "invitation_link_visit", requestId: id, token: "invalid" }))).json()).toEqual({ recorded: false })- mocks.userId = "creator"- expect(await (await POST(request({ event: "invitation_link_visit", requestId: id, token: "valid" }))).json()).toEqual({ recorded: false })- expect(mocks.record).not.toHaveBeenCalled()- })- it("records only bounded public entry and failure dimensions", async () => {- await POST(request({ event: "landing_cta_clicked", requestId: id, ctaName: "get_started" }))- expect(mocks.record).toHaveBeenLastCalledWith(mocks.env.DB, expect.objectContaining({ eventName: "landing_cta_clicked", ctaName: "get_started" }))- await POST(request({ event: "sign_in_failed", requestId: id, method: "email_otp", failureStage: "verify_code" }))- expect(mocks.record).toHaveBeenLastCalledWith(mocks.env.DB, expect.objectContaining({ eventName: "sign_in_failed", method: "email_otp", failureStage: "verify_code" }))- })-})diff --git a/src/web/src/app/api/community/analytics/product-events/route.ts b/src/web/src/app/api/community/analytics/product-events/route.tsdeleted file mode 100644index 8157f889a..000000000--- a/src/web/src/app/api/community/analytics/product-events/route.ts+++ /dev/null@@ -1,95 +0,0 @@-import { NextResponse, type NextRequest } from "next/server"-import { z } from "zod"-import { queries } from "@alook/shared"-import { withOptionalAuth } from "@/lib/middleware/auth"-import { getPrimaryDb } from "@/lib/db"-import { LANDING_CTA_NAMES } from "@/lib/product-analytics-contract"-import {- deliverProductAnalytics, productAnalyticsAllowed, productAnalyticsIdentity, productAnalyticsMeasurementId,- scheduleProductAnalytics, setProductAnalyticsCookies,-} from "@/lib/product-analytics-server"--const requestId = z.uuid()-const requestSchema = z.discriminatedUnion("event", [- z.object({ event: z.literal("landing_cta_clicked"), requestId, ctaName: z.enum(LANDING_CTA_NAMES) }).strict(),- z.object({ event: z.literal("login_page_view"), requestId }).strict(),- z.object({ event: z.literal("sign_in_failed"), requestId,- method: z.enum(["email_otp", "github", "google", "apple"]),- failureStage: z.enum(["send_code", "verify_code", "social_start"]),- }).strict(),- z.object({ event: z.literal("onboarding_enter_clicked"), requestId, serverId: z.string().min(1).max(100) }).strict(),- z.object({ event: z.literal("invitation_link_visit"), requestId, token: z.string().min(1).max(200) }).strict(),-])--function sameOrigin(req: NextRequest) {- try {- const header = req.headers.get("origin")- const origin = new URL(header ?? "")- const host = req.headers.get("x-forwarded-host")?.split(",", 1)[0]?.trim() || req.headers.get("host") || req.nextUrl.host- return header === origin.origin && ["http:", "https:"].includes(origin.protocol) && origin.host.toLowerCase() === host.toLowerCase()- } catch { return false }-}--async function readBoundedBody(req: NextRequest): Promise<string | null> {- if (!req.body || Number(req.headers.get("content-length")) > 2048) return null- const reader = req.body.getReader()- const decoder = new TextDecoder()- let size = 0, body = ""- try {- while (true) {- const chunk = await reader.read()- if (chunk.done) return body + decoder.decode()- size += chunk.value.byteLength- if (size > 2048) { await reader.cancel(); return null }- body += decoder.decode(chunk.value, { stream: true })- }- } catch { return null } finally { reader.releaseLock() }-}--export const POST = withOptionalAuth(async (req, ctx) => {- const headers = { "Cache-Control": "no-store" }- if (!sameOrigin(req) || req.headers.has("authorization")) return NextResponse.json({ error: "forbidden" }, { status: 403, headers })- if ((req.headers.get("content-type") ?? "").split(";", 1)[0] !== "application/json") return NextResponse.json({ error: "invalid body" }, { status: 400, headers })- const text = await readBoundedBody(req)- if (text === null) return NextResponse.json({ error: "invalid body" }, { status: 400, headers })- const parsed = requestSchema.safeParse(await Promise.resolve().then(() => JSON.parse(text)).catch(() => null))- if (!parsed.success) return NextResponse.json({ error: "invalid body" }, { status: 400, headers })- const hasSession = req.cookies.has("better-auth.session_token") || req.cookies.has("__Secure-better-auth.session_token")- if (hasSession && !ctx.userId) return NextResponse.json({ error: "session unavailable" }, { status: 503, headers })- const db = getPrimaryDb(ctx.env.DB)- if (ctx.userId) {- const live = await queries.user.getUserInternal(db, ctx.userId)- if (!live || live.isBot || live.deletedAt !== null) return NextResponse.json({ error: "unauthorized" }, { status: 401, headers })- }- const cookies = req.headers.get("cookie") ?? ""- if (!await productAnalyticsAllowed(db, ctx.env, cookies, ctx.userId)) return NextResponse.json({ recorded: false }, { headers })- const input = parsed.data- let serverId: string | undefined- let sourceId: string | undefined- let dedupeKey = `${input.event}:${input.requestId}`- if (input.event === "onboarding_enter_clicked") {- if (!ctx.userId) return NextResponse.json({ error: "unauthorized" }, { status: 401, headers })- const server = await queries.productAnalytics.getOwnedServer(db, ctx.userId, input.serverId)- if (!server) return NextResponse.json({ error: "not found" }, { status: 404, headers })- serverId = server.id- dedupeKey = `onboarding-enter:${ctx.userId}:${server.id}`- }- if (input.event === "invitation_link_visit") {- const invite = await queries.productAnalytics.getInviteSource(db, input.token)- if (!invite || (ctx.userId && invite.createdBy === ctx.userId)) return NextResponse.json({ recorded: false }, { headers })- serverId = invite.serverId- sourceId = invite.id- dedupeKey = `invite-visit:${invite.id}:${input.requestId}`- }- const identity = productAnalyticsIdentity(cookies, Date.now(), productAnalyticsMeasurementId(ctx.env))- const event = await queries.productAnalytics.recordEvent(db, {- eventName: input.event, actorUserId: ctx.userId ?? null, serverId, sourceId, dedupeKey,- clientId: identity.clientId, sessionId: identity.sessionId, createdAt: new Date().toISOString(),- ...(input.event === "landing_cta_clicked" ? { ctaName: input.ctaName } : {}),- ...(input.event === "sign_in_failed" ? { method: input.method, failureStage: input.failureStage } : {}),- })- if (event) await scheduleProductAnalytics(() => deliverProductAnalytics(db, ctx.env, event.row))- const response = NextResponse.json({ recorded: Boolean(event) }, { headers })- setProductAnalyticsCookies(response.cookies.set.bind(response.cookies), identity, req.nextUrl.protocol === "https:")- return response-})diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.test.ts b/src/web/src/app/api/community/channels/[id]/messages/route.test.tsindex 745aef73f..933b8ffeb 100644--- a/src/web/src/app/api/community/channels/[id]/messages/route.test.ts+++ b/src/web/src/app/api/community/channels/[id]/messages/route.test.ts@@ -63,14 +63,6 @@ const mockBroadcastToUser = vi.fn()const mockCheckMessageRateLimit = vi.fn()const mockGetDb = vi.fn(() => ({}))const mockGetPrimaryDb = vi.fn(() => ({}))-const mockOnboardingCookies = vi.fn(async (response: import("next/server").NextResponse) => {- response.cookies.set("alook_ga_session", "1791792000", { httpOnly: true })-})--vi.mock("@/lib/product-analytics-server", () => ({- setOnboardingFirstMessageCookies: (...args: unknown[]) => mockOnboardingCookies(...args as Parameters<typeof mockOnboardingCookies>),-}))-vi.mock("@/lib/db", () => ({getDb: (...a: unknown[]) => mockGetDb(...a),getPrimaryDb: (...a: unknown[]) => mockGetPrimaryDb(...a),@@ -301,9 +293,7 @@ describe("POST /api/community/channels/[id]/messages", () => {const response = await POST(request, ctx)expect(response.status).toBe(replay ? 200 : 201)expect(response.headers.get("x-alook-community-contract")).toBe("3")- expect(response.cookies.get("alook_ga_session")?.value).toBe(replay ? undefined : "1791792000")- if (replay) expect(mockOnboardingCookies).not.toHaveBeenCalled()- else expect(mockOnboardingCookies).toHaveBeenCalledWith(response, expect.anything(), expect.anything(), "u1", "s1", "_ga=GA1.1.123.456", "m1")+ expect(response.cookies.get("alook_ga_session")).toBeUndefined()expect(await response.json()).toEqual({ contractVersion: 3, channelId: "c1", deduped: replay, message: {id: "m1", channelId: "c1", seq: 12, authorId: "u1", authorName: "Alice", authorAvatar: null, authorAvatarVersion: 0,content: "hello", type: "chat", mentionType: null, replyToId: null, clientNonce: "v3-nonce", createdAt: "now", attachments: [],@@ -432,7 +422,7 @@ describe("POST /api/community/channels/[id]/messages", () => {expect(mockDuplicateCheck).not.toHaveBeenCalled()})- it.each([1, 3])("accepts a forum opener with contract %s and keeps analytics cookies on the confirmation", async (contract) => {+ it.each([1, 3])("accepts a forum opener with contract %s without server analytics cookies", async (contract) => {mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1", type: "forum", parentChannelId: null })mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1", type: "forum", parentChannelId: null })const request = postReq({ content: "a post's opener message" })@@ -440,7 +430,7 @@ describe("POST /api/community/channels/[id]/messages", () => {const res = await POST(request, ctx)expect(res.status).toBe(201)expect(mockCreateMessage).toHaveBeenCalled()- expect(res.cookies.get("alook_ga_session")?.value).toBe("1791792000")+ expect(res.cookies.get("alook_ga_session")).toBeUndefined()expect(res.headers.get("x-alook-community-contract")).toBe(contract === 3 ? "3" : null)const confirmation = await res.json()expect(confirmation).toMatchObject({ message: { id: "m1" }, threadId: "thread_1", ...(contract === 3 ? { contractVersion: 3, channelId: "c1", deduped: false } : {}) })@@ -596,7 +586,7 @@ describe("POST /api/community/channels/[id]/messages", () => {expect(response.status).toBe(201)expect(response.headers.get("x-alook-community-contract")).toBeNull()- expect(response.cookies.get("alook_ga_session")?.value).toBe("1791792000")+ expect(response.cookies.get("alook_ga_session")).toBeUndefined()expect(await response.json()).toEqual({ message: row })})diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.ts b/src/web/src/app/api/community/channels/[id]/messages/route.tsindex cd08b76bd..ec5903304 100644--- a/src/web/src/app/api/community/channels/[id]/messages/route.ts+++ b/src/web/src/app/api/community/channels/[id]/messages/route.ts@@ -1,4 +1,3 @@-import { setOnboardingFirstMessageCookies } from "@/lib/product-analytics-server"import { flattenError } from "zod"import { NextRequest, NextResponse } from "next/server"import { withCommunityActor } from "@/lib/middleware/community-actor"@@ -219,7 +218,7 @@ export const POST = withCommunityActor(async (req: NextRequest, ctx) => {if (ctx.actor.kind === "bot") {return handleBotSend(db, ctx.actor.userId, ctx.env, raw)}- return handleHumanSend(db, ctx.actor.userId, ctx.env, ctx.params?.id, raw, requestedCommunityContract(req.headers) ?? 1, req.headers.get("cookie") ?? "")+ return handleHumanSend(db, ctx.actor.userId, ctx.env, ctx.params?.id, raw, requestedCommunityContract(req.headers) ?? 1)})/**@@ -235,7 +234,6 @@ async function handleHumanSend(pathId: string | undefined,raw: unknown,contract: CommunityContract,- cookies: string,): Promise<NextResponse> {if (!pathId || pathId === REF_PLACEHOLDER_ID) {return NextResponse.json({ error: "missing channel id" }, { status: 400 })@@ -283,7 +281,6 @@ async function handleHumanSend(threadId: created.thread.id,deduped: created.deduped,}, created.deduped ? 200 : 201)- if (!created.deduped) await setOnboardingFirstMessageCookies(response, db, env, userId, target.serverId, cookies, created.message.id)return response}@@ -309,7 +306,6 @@ async function handleHumanSend(})if (!result.ok) return NextResponse.json({ error: result.error }, { status: result.status })const response = humanMessageConfirmation(contract, target.channelId, { message: await mapPostedMessageForApi(db, target.channelId, result.row, contract), deduped: result.deduped }, 201)- if (!result.deduped && target.kind !== "dm") await setOnboardingFirstMessageCookies(response, db, env, userId, target.serverId, cookies, result.row.id)return response}diff --git a/src/web/src/app/api/privacy/analytics-consent/route.test.ts b/src/web/src/app/api/privacy/analytics-consent/route.test.tsindex e1d5f90be..86b4360f0 100644--- a/src/web/src/app/api/privacy/analytics-consent/route.test.ts+++ b/src/web/src/app/api/privacy/analytics-consent/route.test.ts@@ -44,7 +44,7 @@ describe("POST /api/privacy/analytics-consent", () => {expect(response.status).toBe(200)expect(response.headers.get("Cache-Control")).toBe("no-store, max-age=0")expect(await response.json()).toEqual({ decision })- expect(cookies).toHaveLength(decision === "granted" ? 4 : 2)+ expect(cookies).toHaveLength(2)expect(cookies[0]).toContain(`alook_analytics_consent=v1.${decision}`)expect(cookies[0]).toContain("Path=/")expect(cookies[0]).toContain("Max-Age=15552000")diff --git a/src/web/src/app/api/privacy/analytics-consent/route.ts b/src/web/src/app/api/privacy/analytics-consent/route.tsindex 09342450f..60d2e363b 100644--- a/src/web/src/app/api/privacy/analytics-consent/route.ts+++ b/src/web/src/app/api/privacy/analytics-consent/route.ts@@ -11,7 +11,6 @@ import {} from "@/lib/analytics-consent"import { createAnalyticsConsentProof } from "@/lib/analytics-consent-server"-import { productAnalyticsIdentity, productAnalyticsMeasurementId, setProductAnalyticsCookies } from "@/lib/product-analytics-server"function sameOriginUrl(request: NextRequest): URL | null {const origin = request.headers.get("Origin")@@ -80,10 +79,6 @@ export const POST = withOptionalAuth(async (request, ctx) => {await createAnalyticsConsentProof(decision, ctx.env.BETTER_AUTH_SECRET, issuedAtMs),{ ...shared, httpOnly: true },)- if (decision === "granted") {- const identity = productAnalyticsIdentity(request.headers.get("cookie") ?? "", issuedAtMs, productAnalyticsMeasurementId(ctx.env))- setProductAnalyticsCookies(response.cookies.set.bind(response.cookies), identity, origin.protocol === "https:")- }response.headers.set("Cache-Control", "no-store, max-age=0")return response})diff --git a/src/web/src/app/c/invite/[token]/invite-accept-client.tsx b/src/web/src/app/c/invite/[token]/invite-accept-client.tsxindex 970186b26..5b5aacc0a 100644--- a/src/web/src/app/c/invite/[token]/invite-accept-client.tsx+++ b/src/web/src/app/c/invite/[token]/invite-accept-client.tsx@@ -42,16 +42,15 @@ function isDeadInvite(err: unknown): boolean {* Fetches invite info, displays server preview, and joins on button click.*/export function InviteAcceptClient({ token }: { token: string }) {- const visitId = useMemo(() => ({ token, id: crypto.randomUUID() }), [token]).id- return <PublicQueryProvider><InviteAcceptInner token={token} visitId={visitId} /></PublicQueryProvider>+ return <PublicQueryProvider><InviteAcceptInner token={token} /></PublicQueryProvider>}-function InviteAcceptInner({ token, visitId }: { token: string; visitId: string }) {+function InviteAcceptInner({ token }: { token: string }) {const router = useRouter()const searchParams = useSearchParams()const source = useApplicationViewSource(`community-invite:${token}`)const { owner } = source- useEffect(() => { void captureProductAnalytics({ event: "invitation_link_visit", token }, visitId) }, [token, visitId])+ useEffect(() => { void captureProductAnalytics({ event: "invitation_link_visit", token }) }, [token])const query = useQuery({ queryKey: applicationKey(owner, "community-invite", token), retry: false,queryFn: ({ signal }) => runApplicationRequest(owner, (options) => apiFetch<InviteInfo>(`/api/community/invites/${token}/info`, {...options, onUnauthorized: async () => { options.assertActive?.(); return false },diff --git a/src/web/src/components/analytics-consent.dom.test.tsx b/src/web/src/components/analytics-consent.dom.test.tsxindex 9eb471048..0198b4340 100644--- a/src/web/src/components/analytics-consent.dom.test.tsx+++ b/src/web/src/components/analytics-consent.dom.test.tsx@@ -123,7 +123,7 @@ describe("AnalyticsConsent", () => {expect(screen.getByTestId(tid.ahrefsAnalyticsFrame)).toBeInTheDocument()expect(getComputedStyle(screen.getByTestId("consent-page")).height).toBe("100dvh")expect(document.cookie).not.toContain("alook_analytics_consent=")- expect(document.cookie).toMatch(/_ga=GA1\.1\.\d+\.\d+/u)+ expect(document.cookie).not.toContain("_ga=")})it("does not resave an existing grant", async () => {@@ -240,11 +240,15 @@ describe("AnalyticsConsent", () => {render(<AnalyticsConsent />)cookie.change()expect(navigation.reload).not.toHaveBeenCalled()+ const events = document.getElementById("alook-product-events") ?? document.createElement("iframe")+ events.id = "alook-product-events"+ document.body.appendChild(events)document.cookie = "alook_analytics_consent=v1.denied; Path=/"cookie.change()fireEvent(window, new Event("focus"))fireEvent(window, new CustomEvent("alook:analytics-consent-change", { detail: "granted" }))expect(navigation.reload).toHaveBeenCalledTimes(pathname.startsWith("/c") ? 0 : 1)+ expect(document.getElementById("alook-product-events")).toBeNull()expect(screen.queryByTestId(tid.ahrefsAnalyticsFrame)).not.toBeInTheDocument()})diff --git a/src/web/src/components/analytics-consent.tsx b/src/web/src/components/analytics-consent.tsxindex 26cb71f78..2fe9a78dc 100644--- a/src/web/src/components/analytics-consent.tsx+++ b/src/web/src/components/analytics-consent.tsx@@ -40,6 +40,7 @@ function useStoredAnalyticsConsent(syncGoogleConsent = false) {const native = isTauri()const refresh = (announce = false, initial = false) => {const next = readAnalyticsConsent()+ if (syncGoogleConsent && next === "denied") document.getElementById("alook-product-events")?.remove()const changed = next !== decisionRef.currentif (syncGoogleConsent && (changed || initial)) {if (!native) applyGoogleConsent(isPublicAnalyticsPath(window.location.pathname) ? next ?? "granted" : "denied")@@ -197,7 +198,6 @@ export function AnalyticsConsent() {const googleAllowed = ready && !!pathname && isPublicAnalyticsPath(pathname) && (!isTauri() || decision === "granted")const allowed = googleAllowed && (isTauri() ? decision === "granted" : decision !== "denied")-useEffect(() => {if (!isTauri()) returnObject.defineProperty(window, GA_DISABLE, {diff --git a/src/web/src/components/community/onboarding/community-onboarding-form.navigation.dom.test.ts b/src/web/src/components/community/onboarding/community-onboarding-form.navigation.dom.test.tsindex 2b464d9b1..5110265ee 100644--- a/src/web/src/components/community/onboarding/community-onboarding-form.navigation.dom.test.ts+++ b/src/web/src/components/community/onboarding/community-onboarding-form.navigation.dom.test.ts@@ -28,7 +28,7 @@ const mocks = vi.hoisted(() => ({} as Record<string, unknown>,}))-vi.mock("@/lib/product-analytics", () => ({ captureProductAnalytics: mocks.capture }))+vi.mock("@/lib/product-analytics", () => ({ beginOnboardingAnalytics: (_userId: string, serverId: string) => mocks.capture({ event: "onboarding_enter_clicked", serverId }) }))vi.mock("next/navigation", () => ({usePathname: () => mocks.pathname,}))diff --git a/src/web/src/components/community/onboarding/community-onboarding-form.tsx b/src/web/src/components/community/onboarding/community-onboarding-form.tsxindex 4007f0afa..b297ec769 100644--- a/src/web/src/components/community/onboarding/community-onboarding-form.tsx+++ b/src/web/src/components/community/onboarding/community-onboarding-form.tsx@@ -19,7 +19,7 @@ import {ONBOARDING_HARNESSES,ONBOARDING_IDENTITIES,} from "./onboarding-form-options"-import { captureProductAnalytics } from "@/lib/product-analytics"+import { beginOnboardingAnalytics } from "@/lib/product-analytics"import { initializeCommunityOnboarding } from "./initialize-community-onboarding"import { tid } from "@/lib/community/testids"import { useCurrentUser } from "@/contexts/community/current-user"@@ -244,7 +244,7 @@ export function CommunityOnboardingForm() {const destination = `/c/channels/${initializationResult.serverId}/${initializationResult.publicChannelId}`const assert = source.capture()assert()- await captureProductAnalytics({ event: "onboarding_enter_clicked", serverId: initializationResult.serverId })+ beginOnboardingAnalytics(currentUser.id, initializationResult.serverId)if (!communityRuntime.lifecycle.get().active) returntry { assert() } catch { return }const navigate = communityRuntime.ui.get().uiHandlers.navigatediff --git a/src/web/src/components/signup-tracker.dom.test.tsx b/src/web/src/components/signup-tracker.dom.test.tsxindex d78fff247..b6bc7e2b9 100644--- a/src/web/src/components/signup-tracker.dom.test.tsx+++ b/src/web/src/components/signup-tracker.dom.test.tsx@@ -9,13 +9,15 @@ import { SignupTracker } from "./signup-tracker"const mocks = vi.hoisted(() => ({ breakpoint: "desktop", replace: vi.fn(), track: vi.fn() }))vi.mock("next/navigation", () => ({ useRouter: () => ({ replace: mocks.replace }) }))vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => mocks.breakpoint }))-vi.mock("@/lib/analytics", () => ({ trackSignUp: mocks.track, trackCommunityOnboardingStarted: vi.fn() }))+vi.mock("@/lib/analytics", () => ({ trackCommunityOnboardingStarted: vi.fn() }))+vi.mock("@/lib/product-analytics", () => ({ captureProductAnalytics: mocks.track }))beforeEach(() => {vi.clearAllMocks()mocks.replace.mockReset()mocks.breakpoint = "desktop"document.cookie = "is_new_signup=; max-age=0; path=/"+ document.cookie = "is_sign_in=; max-age=0; path=/"})function mount(redirectTo?: string) {@@ -42,7 +44,7 @@ describe("SignupTracker account-owned initiation", () => {const { registry, rerender } = mount("/c/me/machines")mocks.breakpoint = "mobile"; rerender()mocks.breakpoint = "desktop"; rerender()- expect(mocks.track).not.toHaveBeenCalled()+ expect(mocks.track).toHaveBeenCalledWith({ event: "sign_up", method: "email" })expect(registry.runtime.ui.get().onboardingState).toBeNull()expect(mocks.replace).not.toHaveBeenCalled()})@@ -53,7 +55,7 @@ describe("SignupTracker account-owned initiation", () => {const { registry, rerender } = mount("/c/me/machines")mocks.replace.mockImplementation(() => expect(registry.runtime.ui.get().onboardingState).toMatchObject({ stage: "harness" }))mocks.breakpoint = "desktop"; rerender()- expect(mocks.track).not.toHaveBeenCalled()+ expect(mocks.track).toHaveBeenCalledWith({ event: "sign_up", method: "email" })expect(registry.runtime.ui.get().onboardingState).toMatchObject({ stage: "harness" })expect(mocks.replace).toHaveBeenCalledWith("/c/me/machines")})@@ -62,7 +64,7 @@ describe("SignupTracker account-owned initiation", () => {mocks.breakpoint = "mobile"document.cookie = "is_new_signup=email; path=/"const { registry } = mount("/c/me/machines")- expect(mocks.track).not.toHaveBeenCalled()+ expect(mocks.track).toHaveBeenCalledWith({ event: "sign_up", method: "email" })expect(registry.runtime.ui.get().onboardingState).toBeNull()expect(mocks.replace).not.toHaveBeenCalled()})@@ -71,14 +73,14 @@ describe("SignupTracker account-owned initiation", () => {document.cookie = "is_new_signup=email; path=/"const { rerender } = mount("/c/me/machines")rerender()- expect(mocks.track).not.toHaveBeenCalled()+ expect(mocks.track).toHaveBeenCalledWith({ event: "sign_up", method: "email" })expect(mocks.replace).toHaveBeenCalledOnce()})- it("does not duplicate server signup tracking on a public entry without an owner", () => {+ it("reports an existing signup success marker even without an onboarding owner", () => {document.cookie = "is_new_signup=github; path=/"render(<SignupTracker />)- expect(mocks.track).not.toHaveBeenCalled()+ expect(mocks.track).toHaveBeenCalledWith({ event: "sign_up", method: "github" })expect(mocks.replace).not.toHaveBeenCalled()})@@ -99,4 +101,15 @@ describe("SignupTracker account-owned initiation", () => {expect(mocks.replace).toHaveBeenCalledOnce()write.mockRestore()})+ it("reports existing sign-in success and leaves onboarding untouched", () => {+ document.cookie = "is_sign_in=email_otp; path=/"+ const { registry, rerender } = mount("/c/me/machines")+ rerender()+ expect(mocks.track).toHaveBeenCalledOnce()+ expect(mocks.track).toHaveBeenCalledWith({ event: "sign_in_success", method: "email_otp" })+ expect(document.cookie).not.toContain("is_sign_in=")+ expect(registry.runtime.ui.get().onboardingState).toBeNull()+ expect(mocks.replace).not.toHaveBeenCalled()+ })+})diff --git a/src/web/src/components/signup-tracker.tsx b/src/web/src/components/signup-tracker.tsxindex dd3c4bb10..39d238632 100644--- a/src/web/src/components/signup-tracker.tsx+++ b/src/web/src/components/signup-tracker.tsx@@ -1,6 +1,7 @@"use client"import { useEffect } from "react"+import { captureProductAnalytics } from "@/lib/product-analytics"import { useRouter } from "next/navigation"import { useBreakpoint } from "@/hooks/use-mobile"import { startCommunityOnboarding } from "@/lib/community-onboarding"@@ -13,9 +14,15 @@ export function SignupTracker({ redirectTo }: { redirectTo?: string } = {}) {useEffect(() => {if (breakpoint === "unknown") return+ const signedIn = document.cookie.match(/(?:^|; )is_sign_in=([^;]*)/)+ if (signedIn) {+ document.cookie = "is_sign_in=; max-age=0; path=/"+ void captureProductAnalytics({ event: "sign_in_success", method: signedIn[1] })+ }const match = document.cookie.match(/(?:^|; )is_new_signup=([^;]*)/)if (!match) returndocument.cookie = "is_new_signup=; max-age=0; path=/"+ void captureProductAnalytics({ event: "sign_up", method: match[1] })if (breakpoint === "mobile") returnif (redirectTo) {if (redirectTo.startsWith("/c/")) {diff --git a/src/web/src/env.d.ts b/src/web/src/env.d.tsindex 691e6de9b..9abcd2965 100644--- a/src/web/src/env.d.ts+++ b/src/web/src/env.d.ts@@ -4,8 +4,6 @@ interface RuntimeEnv {STRIPE_PORTAL_CONFIGURATION_ID?: stringSTRIPE_RETURN_ORIGIN?: stringGA4_API_SECRET?: string- DEV_PRODUCT_ANALYTICS_COLLECTOR?: string- DEV_PRODUCT_ANALYTICS_MEASUREMENT_ID?: stringENCRYPTION_KEY: stringAPP_REVIEW_EMAIL?: stringAPP_REVIEW_OTP?: stringdiff --git a/src/web/src/hooks/community/mutations/messages.ts b/src/web/src/hooks/community/mutations/messages.tsindex 1090f5a05..788b91658 100644--- a/src/web/src/hooks/community/mutations/messages.ts+++ b/src/web/src/hooks/community/mutations/messages.ts@@ -1,5 +1,7 @@"use client"+import { captureOnboardingFirstMessage } from "@/lib/product-analytics"+import { useNativeMutationFacade } from "@/hooks/use-native-mutation-facade"import { useCallback } from "react"@@ -278,6 +280,7 @@ function useSendScopedMessage<Args extends SendMessageArgs | SendDmMessageArgs>(},onSuccess: (data, args) => {try { origin.assert(args.original); args.assertCommand?.() } catch { return }+ if ("serverId" in args) captureOnboardingFirstMessage(args.author.id, args.serverId)if ("serverId" in args && args.forumParentChannelId &&isForumSidebarParent(queryClient, args.serverId, args.forumParentChannelId)diff --git a/src/web/src/lib/analytics-consent.ts b/src/web/src/lib/analytics-consent.tsindex 0b0eca02a..aca20b840 100644--- a/src/web/src/lib/analytics-consent.ts+++ b/src/web/src/lib/analytics-consent.ts@@ -1,5 +1,3 @@-import { ensureBrowserAnalyticsIdentity } from "@/lib/product-analytics-identity"-export const ANALYTICS_CONSENT_COOKIE = "alook_analytics_consent"export const ANALYTICS_CONSENT_PROOF_COOKIE = "alook_analytics_consent_proof"export const ANALYTICS_CONSENT_VERSION = "v1"@@ -10,7 +8,7 @@ export type AnalyticsConsentDecision = "granted" | "denied"export const isPublicAnalyticsPath = (path: string) => /^\/(?:pricing|contact|privacy|templates(?:\/[^/]+)?|blog(?:\/.*)?)?$/.test(path)-function googleCommand(..._args: unknown[]): void {+export function googleCommand(..._args: unknown[]): void {window.dataLayer ??= []// eslint-disable-next-line prefer-rest-params -- Google commands use dataLayer.push(arguments).window.dataLayer.push(arguments)@@ -41,7 +39,6 @@ export function bootstrapGoogleAnalytics(): void {configurable: true,get: () => !isPublicAnalyticsPath(window.location.pathname),})- if (isPublicAnalyticsPath(window.location.pathname) && readAnalyticsConsent() !== "denied") ensureBrowserAnalyticsIdentity()applyGoogleConsent(isPublicAnalyticsPath(window.location.pathname) ? readAnalyticsConsent() ?? "granted" : "denied", "default")updateGooglePageFields(window.location.href)}@@ -94,7 +91,6 @@ let pendingConsentSave = Promise.resolve()export function persistAnalyticsConsent(decision: AnalyticsConsentDecision): Promise<void> {const save = pendingConsentSave.then(async () => {- if (decision === "granted") ensureBrowserAnalyticsIdentity()const response = await fetch("/api/privacy/analytics-consent", {method: "POST",credentials: "same-origin",diff --git a/src/web/src/lib/auth.test.ts b/src/web/src/lib/auth.test.tsindex e933a113e..33042ce54 100644--- a/src/web/src/lib/auth.test.ts+++ b/src/web/src/lib/auth.test.ts@@ -1,9 +1,5 @@import { afterEach, describe, it, expect, vi, beforeEach } from "vitest"-const productMocks = vi.hoisted(() => ({ capture: vi.fn(async () => undefined), failure: vi.fn(async () => undefined), serverContext: vi.fn(), currentSession: vi.fn<() => Promise<null | { user: { id: string } }>>(async () => null), oauthState: vi.fn<() => Promise<null | { callbackURL: string; serverContext?: Record<string, unknown> }>>(async () => null) }))-vi.mock("@/lib/product-analytics-server", async original => ({ ...await original<typeof import("@/lib/product-analytics-server")>(), captureAuthentication: productMocks.capture, captureOAuthCallbackFailure: productMocks.failure }))-vi.mock("better-auth/api", async original => ({ ...await original<typeof import("better-auth/api")>(), getOAuthState: productMocks.oauthState, addOAuthServerContext: productMocks.serverContext, getSessionFromCtx: productMocks.currentSession, createAuthMiddleware: (handler: unknown) => handler }))-const appleMocks = vi.hoisted(() => ({generateClientSecret: vi.fn(async () => "signed-apple-client-secret"),}))@@ -941,29 +937,7 @@ describe("createAuth databaseHooks — user.create.before", () => {})-describe("auth funnel committed hooks", () => {- beforeEach(() => { vi.clearAllMocks(); productMocks.capture.mockResolvedValue(undefined); productMocks.oauthState.mockResolvedValue(null) })- function context(path: string) {- return { request: new Request(`https://alook.ai/api/auth${path}`, { headers: { cookie: "_ga=GA1.1.100.200; is_new_signup=forged" } }),- responseHeaders: new Headers(), setCookie: vi.fn(), getCookie: vi.fn(() => "forged") }- }- it("captures saved account/session rows even if the readable signup cookie is forged", async () => {- const createAuth = await loadCreateAuth()- const hooks = (createAuth(makeEnv({ NODE_ENV: "production" }) as never) as { __options: AuthOptions }).__options.databaseHooks!- const createdAt = new Date("2026-10-12T05:00:00.000Z")- await hooks.user!.create!.after!({ id: "owner", createdAt }, context("/sign-in/email-otp"))- expect(productMocks.capture).toHaveBeenLastCalledWith(expect.anything(), expect.objectContaining({ actorUserId: "owner", createdAt }))- await hooks.session!.create!.after!({ id: "saved-session", userId: "owner", createdAt }, context("/sign-in/email-otp"))- expect(productMocks.capture).toHaveBeenLastCalledWith(expect.anything(), expect.objectContaining({ sessionId: "saved-session", actorUserId: "owner", createdAt }))- })- it("does not break successful auth or cookie behavior when analytics fails", async () => {- productMocks.capture.mockRejectedValueOnce(new Error("D1 unavailable"))- const createAuth = await loadCreateAuth()- const hooks = (createAuth(makeEnv({ NODE_ENV: "production" }) as never) as { __options: AuthOptions }).__options.databaseHooks!- const ctx = context("/sign-in/email-otp")- await expect(hooks.user!.create!.after!({ id: "owner", createdAt: new Date() }, ctx)).resolves.toBeUndefined()- expect(ctx.setCookie).toHaveBeenCalledWith("is_new_signup", "email", expect.anything())- })+describe("development OTP opt-in", () => {it("allows real OTP only under the explicit development QA opt-in", async () => {const createAuth = await loadCreateAuth()const options = (createAuth(makeEnv({ NODE_ENV: "development", DEV_AUTH_OTP: "1" }) as never) as { __options: AuthOptions }).__options@@ -972,83 +946,3 @@ describe("auth funnel committed hooks", () => {expect(defaultOptions.plugins).not.toContainEqual(expect.objectContaining({ __plugin: "emailOTP" }))})})---describe("verified web OAuth callback failure hooks", () => {- const attempt = "12345678-1234-4234-8234-123456789abc"- beforeEach(() => { vi.clearAllMocks(); productMocks.oauthState.mockResolvedValue(null); productMocks.failure.mockResolvedValue(undefined); productMocks.currentSession.mockResolvedValue(null) })- async function hooks() {- const createAuth = await loadCreateAuth()- return (createAuth(makeEnv({ NODE_ENV: "production", BETTER_AUTH_URL: "https://alook.ai" }) as never) as { __options: AuthOptions }).__options.hooks!- }- function ctx(path = "/callback/:id") {- return { path, params: { id: "github" }, request: new Request(`https://alook.ai/api/auth${path.replace(":id", "github")}`, { headers: { origin: "https://alook.ai", cookie: "_ga=GA1.1.100.200" } }),- body: { callbackURL: "/c/me" }, context: { responseHeaders: new Headers({ location: "https://alook.ai/api/auth/error?error=access_denied&error_description=private-value" }), returned: { statusCode: 302 }, newSession: null as unknown }, setCookie: vi.fn() }- }- it("marks same-origin web social starts in server-controlled state", async () => {- await (await hooks()).before(ctx("/sign-in/social"))- expect(productMocks.serverContext).toHaveBeenCalledWith({ productAnalyticsWebAttempt: expect.stringMatching(/^[a-f0-9-]{36}$/u) })- })- it("does not mark native continuations or foreign-origin starts as web", async () => {- const h = await hooks()- const native = ctx("/sign-in/social"); native.body.callbackURL = "/auth/native/callback?attempt=private"- await h.before(native)- const foreign = ctx("/sign-in/social"); foreign.request = new Request("https://alook.ai/api/auth/sign-in/social", { headers: { origin: "https://foreign.invalid" } })- await h.before(foreign)- expect(productMocks.serverContext).not.toHaveBeenCalled()- })- it("does not fail web social start if analytics provenance storage fails", async () => {- productMocks.serverContext.mockRejectedValueOnce(new Error("state context unavailable"))- await expect((await hooks()).before(ctx("/sign-in/social"))).resolves.toBeUndefined()- expect(authLogMocks.warn).toHaveBeenCalledWith("OAuth analytics provenance unavailable")- })- it("counts cancellation and exchange failure only after verified web state", async () => {- productMocks.oauthState.mockResolvedValue({ callbackURL: "https://alook.ai/c/me", serverContext: { productAnalyticsWebAttempt: attempt } })- const h = await hooks()- for (const error of ["access_denied", "invalid_code", "unable_to_get_user_info"]) {- const c = ctx(); c.context.responseHeaders.set("location", `https://alook.ai/api/auth/error?error=${error}`)- await h.after(c)- }- expect(productMocks.failure).toHaveBeenCalledTimes(3)- expect(productMocks.failure).toHaveBeenLastCalledWith(expect.anything(), { method: "github", attemptId: attempt, cookies: "_ga=GA1.1.100.200", actorUserId: undefined })- })- it("does not count unsupported providers or another endpoint as provider callbacks", async () => {- productMocks.oauthState.mockResolvedValue({ callbackURL: "https://alook.ai/c/me", serverContext: { productAnalyticsWebAttempt: attempt } })- const h = await hooks()- const unsupported = ctx(); unsupported.params.id = "unsupported"- await h.after(unsupported)- await h.after(ctx("/sign-in/social"))- expect(productMocks.failure).not.toHaveBeenCalled()- })- it("passes a validated existing session actor so cross-device account denial can win", async () => {- productMocks.oauthState.mockResolvedValue({ callbackURL: "https://alook.ai/c/me", serverContext: { productAnalyticsWebAttempt: attempt } })- productMocks.currentSession.mockResolvedValue({ user: { id: "current-owner" } })- await (await hooks()).after(ctx())- expect(productMocks.currentSession).toHaveBeenCalledWith(expect.anything(), { disableRefresh: true })- expect(productMocks.failure).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ actorUserId: "current-owner" }))- })- it("does not classify missing/invalid state, native callbacks or committed success as web failures", async () => {- const h = await hooks()- await h.after(ctx())- productMocks.oauthState.mockResolvedValue({ callbackURL: "https://alook.ai/auth/native/callback", serverContext: { productAnalyticsWebAttempt: attempt } })- await h.after(ctx())- productMocks.oauthState.mockResolvedValue({ callbackURL: "https://alook.ai/c/me", serverContext: { productAnalyticsWebAttempt: attempt } })- const success = ctx(); success.context.newSession = { session: { id: "committed" } }- await h.after(success)- expect(productMocks.failure).not.toHaveBeenCalled()- })- it("does not turn non-error redirects into failure", async () => {- productMocks.oauthState.mockResolvedValue({ callbackURL: "https://alook.ai/c/me", serverContext: { productAnalyticsWebAttempt: attempt } })- const c = ctx(); c.context.responseHeaders.set("location", "https://alook.ai/c/me")- await (await hooks()).after(c)- expect(productMocks.failure).not.toHaveBeenCalled()- })- it("preserves auth error behavior when the failure ledger is unavailable", async () => {- productMocks.oauthState.mockResolvedValue({ callbackURL: "https://alook.ai/c/me", serverContext: { productAnalyticsWebAttempt: attempt } })- productMocks.failure.mockRejectedValueOnce(new Error("D1 unavailable"))- const c = ctx()- await expect((await hooks()).after(c)).resolves.toBeUndefined()- expect(c.context.responseHeaders.get("location")).toContain("access_denied")- expect(c.setCookie).not.toHaveBeenCalled()- })-})diff --git a/src/web/src/lib/auth.ts b/src/web/src/lib/auth.tsindex 734ee4bd3..c06df3694 100644--- a/src/web/src/lib/auth.ts+++ b/src/web/src/lib/auth.ts@@ -1,6 +1,5 @@import { annotateWorkerSpan, observeWorkerOperation } from "./observability/worker"import { betterAuth } from "better-auth"-import { addOAuthServerContext, createAuthMiddleware, getOAuthState, getSessionFromCtx } from "better-auth/api"import { emailOTP, deviceAuthorization, bearer, oneTimeToken } from "better-auth/plugins"import { getCloudflareContext } from "@opennextjs/cloudflare"import { nanoid } from "nanoid"@@ -25,7 +24,6 @@ import {import { appleOauthHardeningPlugin } from "@/lib/apple-oauth-hardening"import { getOtpSubject, renderOtpEmail, type OtpType } from "./email-templates"-import { analyticsCookiesAfterResponse, captureAuthentication, captureOAuthCallbackFailure, setProductAnalyticsCookies } from "@/lib/product-analytics-server"const log = createLogger({ service: "auth" })@@ -111,13 +109,6 @@ export async function sendOtpEmail(}}-async function nativeAuthenticationFlow(requestUrl: string) {- if (!/\/callback\/(?:github|google|apple)(?:\?|$)/u.test(requestUrl)) return false- const state = await getOAuthState()- if (!state?.callbackURL) return false- try { return new URL(state.callbackURL, requestUrl).pathname === "/auth/native/callback" } catch { return false }-}-export function createAuth(env: Env) {const mode = resolveMode({ nodeEnv: env.NODE_ENV ?? process.env.NODE_ENV })const isProd = mode === "production"@@ -223,36 +214,6 @@ export function createAuth(env: Env) {rateLimit: {enabled: false,},- hooks: {- before: createAuthMiddleware(async ctx => {- if (ctx.path !== "/sign-in/social" || !ctx.request) return- try {- const origin = new URL(env.BETTER_AUTH_URL).origin- const callback = new URL(ctx.body?.callbackURL ?? origin, origin)- if (ctx.request.headers.get("origin") !== origin || callback.origin !== origin- || callback.pathname === "/auth/native/callback") return- await addOAuthServerContext({ productAnalyticsWebAttempt: crypto.randomUUID() })- } catch { log.warn("OAuth analytics provenance unavailable") }- }),- after: createAuthMiddleware(async ctx => {- const method = ctx.params?.id- if (ctx.path !== "/callback/:id" || (method !== "github" && method !== "google" && method !== "apple") || ctx.context.newSession) return- try {- const state = await getOAuthState()- const attemptId = state?.serverContext?.productAnalyticsWebAttempt- if (typeof attemptId !== "string" || !/^[a-f0-9-]{36}$/u.test(attemptId)- || await nativeAuthenticationFlow(ctx.request?.url ?? "")) return- const location = ctx.context.responseHeaders?.get("location")- const failedRedirect = location && new URL(location, env.BETTER_AUTH_URL).searchParams.has("error")- const returned = ctx.context.returned as { statusCode?: number } | undefined- if (!failedRedirect && !(returned?.statusCode && returned.statusCode >= 400)) return- const cookies = analyticsCookiesAfterResponse(ctx.request?.headers.get("cookie") ?? "", ctx.context.responseHeaders?.getSetCookie() ?? [])- const session = await getSessionFromCtx(ctx, { disableRefresh: true })- const identity = await captureOAuthCallbackFailure(env, { method, attemptId, cookies, actorUserId: session?.user.id })- if (identity) setProductAnalyticsCookies((...args) => ctx.setCookie(...args), identity, env.BETTER_AUTH_URL.startsWith("https:"))- } catch { log.warn("OAuth callback failure analytics capture failed") }- }),- },databaseHooks: {user: {create: {@@ -288,13 +249,6 @@ export function createAuth(env: Env) {},after: async (user, ctx) => {if (!ctx) return- try {- const cookies = analyticsCookiesAfterResponse(ctx.request?.headers.get("cookie") ?? "", ctx.responseHeaders?.getSetCookie() ?? [])- const identity = await captureAuthentication(env, { actorUserId: user.id, cookies,- path: ctx.request?.url ? new URL(ctx.request.url).pathname : "",- nativeFlow: await nativeAuthenticationFlow(ctx.request?.url ?? ""), createdAt: user.createdAt })- if (identity) setProductAnalyticsCookies(ctx.setCookie, identity, isProd)- } catch { log.warn("signup analytics capture failed") }const path = ctx.request?.url ? new URL(ctx.request.url).pathname : ""let method = "unknown"if (path.includes("email-otp")) method = "email"@@ -347,13 +301,6 @@ export function createAuth(env: Env) {},after: async (session, ctx) => {if (!ctx) return- try {- const cookies = analyticsCookiesAfterResponse(ctx.request?.headers.get("cookie") ?? "", ctx.responseHeaders?.getSetCookie() ?? [])- const identity = await captureAuthentication(env, { actorUserId: session.userId, sessionId: session.id, cookies,- path: ctx.request?.url ? new URL(ctx.request.url).pathname : "",- nativeFlow: await nativeAuthenticationFlow(ctx.request?.url ?? ""), createdAt: session.createdAt })- if (identity) setProductAnalyticsCookies(ctx.setCookie, identity, isProd)- } catch { log.warn("login analytics capture failed") }const signupCookie = ctx.getCookie("is_new_signup")if (signupCookie) returnconst path = ctx.request?.url ? new URL(ctx.request.url).pathname : ""@@ -477,9 +424,6 @@ function authConfiguration(env: Env): readonly (string | undefined)[] {env.APP_REVIEW_EMAIL,env.APP_REVIEW_OTP,env.DEV_AUTH_OTP,- env.GA4_API_SECRET,- env.DEV_PRODUCT_ANALYTICS_COLLECTOR,- env.DEV_PRODUCT_ANALYTICS_MEASUREMENT_ID,env.AUTH_OTP_RATE_LIMIT_MAX,env.AUTH_OTP_RATE_LIMIT_WINDOW_SEC,]diff --git a/src/web/src/lib/product-analytics-identity.ts b/src/web/src/lib/product-analytics-identity.tsdeleted file mode 100644index e51b4409b..000000000--- a/src/web/src/lib/product-analytics-identity.ts+++ /dev/null@@ -1,10 +0,0 @@-import { isTauri } from "@alook/shared"--export function ensureBrowserAnalyticsIdentity() {- if (typeof document === "undefined" || typeof window === "undefined" || isTauri()) return- const cookie = document.cookie.match(/(?:^|;\s*)_ga=([^;]*)/u)?.[1]- if (cookie && /^GA\d+\.\d+\.\d{1,20}\.\d{1,20}$/u.test(cookie)) return- const random = crypto.getRandomValues(new Uint32Array(2))- const secure = window.location.protocol === "https:" ? "; Secure" : ""- document.cookie = `_ga=GA1.1.${random[0]}.${random[1]}; Path=/; Max-Age=15552000; SameSite=Lax${secure}`-}diff --git a/src/web/src/lib/product-analytics-server.test.ts b/src/web/src/lib/product-analytics-server.test.tsdeleted file mode 100644index 726101b8f..000000000--- a/src/web/src/lib/product-analytics-server.test.ts+++ /dev/null@@ -1,202 +0,0 @@-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"-import type { Database, ProductAnalyticsEvent } from "@alook/shared"-import { createAnalyticsConsentProof } from "./analytics-consent-server"--const mocks = vi.hoisted(() => ({ consent: vi.fn(), claim: vi.fn(), finish: vi.fn(), note: vi.fn(), first: vi.fn(), record: vi.fn(), signup: vi.fn(), waitUntil: vi.fn(), context: vi.fn() }))-vi.mock("@alook/shared", async original => ({ ...await original<typeof import("@alook/shared")>(), queries: {- billing: { getAnalyticsConsent: mocks.consent }, productAnalytics: { claimDelivery: mocks.claim, finishDelivery: mocks.finish,- notePendingReason: mocks.note, recordFirstHumanMessage: mocks.first, recordEvent: mocks.record, claimSignupSession: mocks.signup },-} }))-vi.mock("@opennextjs/cloudflare", () => ({ getCloudflareContext: mocks.context }))-vi.mock("@/lib/db", () => ({ getPrimaryDb: () => ({}) }))-import { analyticsCookiesAfterResponse, captureAuthentication, captureOAuthCallbackFailure, captureOnboardingFirstMessage, deliverProductAnalytics, productAnalyticsAllowed,- productAnalyticsIdentity, productAnalyticsMeasurementId, productAnalyticsPayload, setProductAnalyticsCookies, setOnboardingFirstMessageCookies, webAuthenticationMethod } from "./product-analytics-server"--const db = {} as Database-const env = { BETTER_AUTH_SECRET: "fixture-auth-secret", GA4_API_SECRET: "fixture-only", NODE_ENV: "development", DEV_PRODUCT_ANALYTICS_COLLECTOR: "http://127.0.0.1:3345/collect" } as Env-const event: ProductAnalyticsEvent = { id: "event", actorUserId: "private-user", serverId: "private-server", sourceId: "private-token",- eventName: "onboarding_enter_clicked", clientId: "100.200", sessionId: "1791781200", createdAt: "2026-10-12T05:00:00.000Z",- dedupeKey: "private-dedupe", deliveryStatus: "pending", deliveryReason: null, attemptedAt: null, method: null, accountKind: null, ctaName: null, failureStage: null }-const cookies = "_ga=GA1.1.100.200; alook_product_analytics_session=1791781200.1791781220"--beforeEach(() => {- vi.clearAllMocks()- mocks.context.mockResolvedValue({ ctx: { waitUntil: mocks.waitUntil } })- mocks.consent.mockResolvedValue(null)- mocks.claim.mockResolvedValue(event)- mocks.record.mockResolvedValue({ row: event, inserted: true })- mocks.first.mockResolvedValue({ row: event, inserted: true })- mocks.signup.mockResolvedValue(true)- vi.stubGlobal("fetch", vi.fn(async () => new Response(null, { status: 204 })))-})-afterEach(() => { vi.unstubAllGlobals(); vi.useRealTimers() })--describe("product analytics server boundaries", () => {- it("defaults absent choice to allowed but respects browser and account denial", async () => {- expect(await productAnalyticsAllowed(db, env, "")).toBe(true)- expect(await productAnalyticsAllowed(db, env, "alook_analytics_consent=v1.denied")).toBe(false)- mocks.consent.mockResolvedValue({ decision: "denied" })- expect(await productAnalyticsAllowed(db, env, "", "owner")).toBe(false)- })- it("rejects invalid or signed denied proof and accepts signed granted proof", async () => {- expect(await productAnalyticsAllowed(db, env, "alook_analytics_consent_proof=invalid")).toBe(false)- for (const decision of ["denied", "granted"] as const) {- const proof = await createAnalyticsConsentProof(decision, env.BETTER_AUTH_SECRET)- expect(await productAnalyticsAllowed(db, env, `alook_analytics_consent_proof=${proof}`)).toBe(decision === "granted")- }- })- it("reuses fresh GS2 and GS1 public sessions and client id", () => {- const now = 1791781230000- expect(productAnalyticsIdentity("_ga=GA1.1.100.200; _ga_STBCL8F4ZY=GS2.1.s1791781200$o1$g1$t1791781220$j0", now)).toMatchObject(identity("1791781200"))- expect(productAnalyticsIdentity("_ga=GA1.1.100.200; _ga_STBCL8F4ZY=GS1.1.1791781200.1.1.1791781220.0.0.0", now)).toMatchObject(identity("1791781200"))- })- it("expires idle, future and more-than-24h sessions while preserving browser identity", () => {- for (const value of ["1791781200.1791781220", "1792040401.1792040401", "1.1792040399"]) {- expect(productAnalyticsIdentity(`_ga=GA1.1.100.200; alook_product_analytics_session=${value}`, 1792040400000)).toMatchObject(identity("1792040400"))- }- })- it("creates a random client for fresh visitors and persists fallback identity", () => {- const value = productAnalyticsIdentity("", 1791781230000)- expect(value.clientId).toMatch(/^\d+\.\d+$/u)- const set = vi.fn()- setProductAnalyticsCookies(set, value, true)- expect(set).toHaveBeenCalledWith("_ga", `GA1.1.${value.clientId}`, expect.objectContaining({ httpOnly: false, secure: true }))- expect(set).toHaveBeenCalledWith("alook_product_analytics_session", "1791781230.1791781230", expect.objectContaining({ httpOnly: true }))- })- it("joins new account and session through response cookies without trusting signup UI cookies", () => {- expect(analyticsCookiesAfterResponse("_ga=GA1.1.1.2; is_new_signup=forged", ["_ga=GA1.1.100.200; Path=/", "alook_product_analytics_session=1791781200.1791781220; HttpOnly", "secret-session=not-copied; HttpOnly"]))- .toBe("_ga=GA1.1.100.200; is_new_signup=forged; alook_product_analytics_session=1791781200.1791781220")- })- it("emits only sanitized dimensions and pseudonymous account identity, without fabricated engagement", async () => {- const payload = await productAnalyticsPayload(event, env.BETTER_AUTH_SECRET)- expect(payload.user_id).toMatch(/^[a-f0-9]{64}$/u)- expect(payload.events[0].params).toEqual({ session_id: 1791781200, measurement_definition: "enter_my_room_click", page_location: "https://alook.ai/analytics/onboarding" })- expect(JSON.stringify(payload)).not.toContain("private-")- expect(JSON.stringify(payload)).not.toContain("engagement_time")- })- it("keeps missing credentials explicit and performs no transport", async () => {- expect(await deliverProductAnalytics(db, { ...env, GA4_API_SECRET: undefined }, event)).toBe("configuration_missing")- expect(mocks.note).toHaveBeenCalledWith(db, "event", "configuration_missing")- expect(fetch).not.toHaveBeenCalled()- })- it("sends once to the local collector and records HTTP acceptance only", async () => {- expect(await deliverProductAnalytics(db, env, event)).toBe("http_accepted")- expect(String(vi.mocked(fetch).mock.calls[0][0])).toContain("http://127.0.0.1:3345/collect?")- expect(mocks.finish).toHaveBeenCalledWith(db, "event", "accepted", "http_accepted")- mocks.claim.mockResolvedValue(null)- expect(await deliverProductAnalytics(db, env, event)).toBe("already_claimed")- expect(fetch).toHaveBeenCalledOnce()- })- it("rechecks account denial before dispatch", async () => {- mocks.consent.mockResolvedValue({ decision: "denied" })- expect(await deliverProductAnalytics(db, env, event)).toBe("denied")- expect(fetch).not.toHaveBeenCalled()- })- it("records non2xx as failure and network ambiguity without automatic retry", async () => {- vi.mocked(fetch).mockResolvedValueOnce(new Response(null, { status: 403 }))- expect(await deliverProductAnalytics(db, env, event)).toBe("http_failed")- vi.mocked(fetch).mockRejectedValueOnce(new Error("timeout"))- expect(await deliverProductAnalytics(db, env, event)).toBe("uncertain")- expect(mocks.finish).toHaveBeenLastCalledWith(db, "event", "uncertain", "collection_transport_ambiguous")- })- it("rejects non-loopback development collectors", async () => {- for (const collector of ["https://127.0.0.1/collect", "http://example.com/collect", "http://127.0.0.1/collect?extra=1", "http://[email protected]/collect"]) {- expect(await deliverProductAnalytics(db, { ...env, DEV_PRODUCT_ANALYTICS_COLLECTOR: collector }, event)).toBe("configuration_invalid")- }- expect(fetch).not.toHaveBeenCalled()- })- it("isolates the test measurement target and ignores development overrides in production", async () => {- const test = { ...env, DEV_PRODUCT_ANALYTICS_MEASUREMENT_ID: "G-TEST123" }- expect(productAnalyticsMeasurementId(test)).toBe("G-TEST123")- expect(productAnalyticsMeasurementId({ ...test, NODE_ENV: "production" })).toBe("G-STBCL8F4ZY")- await deliverProductAnalytics(db, { ...test, NODE_ENV: "production" }, event)- expect(String(vi.mocked(fetch).mock.calls[0][0])).toContain("https://www.google-analytics.com/mp/collect?measurement_id=G-STBCL8F4ZY")- })- it("passes current request denial to first-message capture after anonymous rejection", async () => {- await captureOnboardingFirstMessage(db, env, "private-user", "private-server", `${cookies}; alook_analytics_consent=v1.denied`, "first")- expect(mocks.first).not.toHaveBeenCalled()- expect(fetch).not.toHaveBeenCalled()- })- it("passes current identity into the durable human-message query", async () => {- vi.useFakeTimers(); vi.setSystemTime(1791781230000)- await captureOnboardingFirstMessage(db, env, "private-user", "private-server", cookies, "first")- expect(mocks.first).toHaveBeenCalledWith(db, "private-user", "private-server", expect.objectContaining(identity("1791781200")), "first")- })- it("returns a new late session in the eligible human response without waiting for collection", async () => {- vi.useFakeTimers(); vi.setSystemTime(1792040400000)- vi.mocked(fetch).mockImplementation(() => new Promise(() => {}))- const response = { cookies: { set: vi.fn() } }- await setOnboardingFirstMessageCookies(response, db, env, "owner", "server", cookies, "first")- expect(mocks.first).toHaveBeenCalledWith(db, "owner", "server", expect.objectContaining(identity("1792040400")), "first")- expect(response.cookies.set).toHaveBeenCalledWith("alook_product_analytics_session", "1792040400.1792040400", expect.objectContaining({ httpOnly: true }))- expect(mocks.waitUntil).toHaveBeenCalledOnce()- expect(productAnalyticsIdentity(analyticsCookiesAfterResponse(cookies, ["alook_product_analytics_session=1792040400.1792040400; HttpOnly"]), 1792040405000).sessionId).toBe("1792040400")- })- it("does not change response cookies for ineligible or duplicate first-message records", async () => {- const response = { cookies: { set: vi.fn() } }- for (const result of [null, { row: event, inserted: false }]) {- mocks.first.mockResolvedValueOnce(result)- await setOnboardingFirstMessageCookies(response, db, env, "owner", "server", cookies, "later")- }- expect(response.cookies.set).not.toHaveBeenCalled()- expect(mocks.waitUntil).not.toHaveBeenCalled()- })- it("preserves an eligible human response when background execution context is unavailable", async () => {- mocks.context.mockRejectedValueOnce(new Error("context unavailable"))- const response = { cookies: { set: vi.fn() } }- await expect(setOnboardingFirstMessageCookies(response, db, env, "owner", "server", cookies, "first")).resolves.toBeUndefined()- expect(response.cookies.set).toHaveBeenCalledWith("alook_product_analytics_session", expect.any(String), expect.objectContaining({ httpOnly: true }))- expect(mocks.waitUntil).not.toHaveBeenCalled()- expect(fetch).not.toHaveBeenCalled()- })- it("isolates first-message ledger errors from the committed human response", async () => {- mocks.first.mockRejectedValueOnce(new Error("database unavailable"))- const response = { cookies: { set: vi.fn() } }- await expect(setOnboardingFirstMessageCookies(response, db, env, "owner", "server", cookies, "first")).resolves.toBeUndefined()- expect(response.cookies.set).not.toHaveBeenCalled()- })- it("records bounded callback failures without exporting the state or provider error", async () => {- await captureOAuthCallbackFailure(env, { method: "github", attemptId: "private-attempt", cookies })- expect(mocks.record).toHaveBeenLastCalledWith(expect.anything(), expect.objectContaining({- eventName: "sign_in_failed", method: "github", failureStage: "provider_callback", sourceId: "private-attempt",- }))- const input = mocks.record.mock.calls.at(-1)![1]- const payload = await productAnalyticsPayload({ ...event, ...input }, env.BETTER_AUTH_SECRET)- expect(payload.events[0].params).toMatchObject({ method: "github", failure_stage: "provider_callback" })- expect(JSON.stringify(payload)).not.toContain("private-attempt")- })- it("suppresses denied and duplicate OAuth failure delivery and cookie updates", async () => {- expect(await captureOAuthCallbackFailure(env, { method: "github", attemptId: "attempt", cookies: `${cookies}; alook_analytics_consent=v1.denied` })).toBeUndefined()- expect(mocks.record).not.toHaveBeenCalled()- mocks.record.mockResolvedValueOnce({ row: event, inserted: false })- expect(await captureOAuthCallbackFailure(env, { method: "github", attemptId: "attempt", cookies })).toBeUndefined()- expect(mocks.waitUntil).not.toHaveBeenCalled()- })- it("rechecks primary denial for an identified account before OAuth failure capture", async () => {- mocks.consent.mockResolvedValue({ decision: "denied" })- expect(await captureOAuthCallbackFailure(env, { method: "github", attemptId: "attempt", cookies, actorUserId: "owner" })).toBeUndefined()- expect(mocks.consent).toHaveBeenCalledWith(expect.anything(), "owner")- expect(mocks.record).not.toHaveBeenCalled()- expect(fetch).not.toHaveBeenCalled()- })- it("records real auth outcomes from durable registration/session association", async () => {- const input = { actorUserId: "private-user", cookies, path: "/api/auth/sign-in/email-otp", createdAt: new Date(event.createdAt) }- await captureAuthentication(env, input)- expect(mocks.record).toHaveBeenLastCalledWith(expect.anything(), expect.objectContaining({ eventName: "sign_up", accountKind: "new", method: "email_otp" }))- await captureAuthentication(env, { ...input, sessionId: "real-session" })- expect(mocks.signup).toHaveBeenCalledWith(expect.anything(), "private-user", "real-session")- expect(mocks.record).toHaveBeenLastCalledWith(expect.anything(), expect.objectContaining({ eventName: "sign_in_success", accountKind: "new", sourceId: "real-session" }))- mocks.signup.mockResolvedValue(false)- await captureAuthentication(env, { ...input, sessionId: "next-session" })- expect(mocks.record).toHaveBeenLastCalledWith(expect.anything(), expect.objectContaining({ accountKind: "existing" }))- })- it("excludes native provider handoffs from web authentication metrics", async () => {- await captureAuthentication(env, { actorUserId: "owner", cookies, nativeFlow: true, path: "/api/auth/callback/github", createdAt: new Date() })- expect(mocks.record).not.toHaveBeenCalled()- })- it("ignores OTP send, social redirect start, device and native exchange as login success", () => {- for (const path of ["/api/auth/email-otp/send-verification-otp", "/api/auth/sign-in/social", "/api/auth/device/token", "/api/auth/one-time-token/verify", "/api/auth/native/exchange"]) expect(webAuthenticationMethod(path)).toBeNull()- for (const provider of ["github", "google", "apple"]) expect(webAuthenticationMethod(`/api/auth/callback/${provider}`)).toBe(provider)- })-})-function identity(sessionId: string) { return { clientId: "100.200", sessionId, needsClientCookie: false } }diff --git a/src/web/src/lib/product-analytics-server.ts b/src/web/src/lib/product-analytics-server.tsdeleted file mode 100644index 0fa928a33..000000000--- a/src/web/src/lib/product-analytics-server.ts+++ /dev/null@@ -1,216 +0,0 @@-import { getCloudflareContext } from "@opennextjs/cloudflare"-import { createLogger, queries, type Database, type ProductAnalyticsEvent, type ProductAnalyticsEventName } from "@alook/shared"-import { getPrimaryDb } from "@/lib/db"-import { readAnalyticsConsent, ANALYTICS_CONSENT_MAX_AGE_SECONDS, ANALYTICS_CONSENT_PROOF_COOKIE } from "@/lib/analytics-consent"-import { GA4_MEASUREMENT_ID, parseGaClientId, parseGaSessionId, verifyAnalyticsConsentProof } from "@/lib/analytics-consent-server"--const PRODUCT_SESSION_COOKIE = "alook_product_analytics_session"-const log = createLogger({ service: "product-analytics" })-const idleSeconds = 30 * 60--function analyticsCookieValue(header: string, name: string): string | null {- for (const part of header.split(";")) {- const separator = part.indexOf("=")- if (separator < 0 || part.slice(0, separator).trim() !== name) continue- try { return decodeURIComponent(part.slice(separator + 1).trim()) } catch { return null }- }- return null-}--export async function productAnalyticsAllowed(db: Database, env: Env, cookies: string, actorUserId?: string) {- if (readAnalyticsConsent(cookies) === "denied") return false- const proof = analyticsCookieValue(cookies, ANALYTICS_CONSENT_PROOF_COOKIE)- if (proof) {- if (!env.BETTER_AUTH_SECRET) return false- const verified = await verifyAnalyticsConsentProof(proof, env.BETTER_AUTH_SECRET)- if (!verified || verified.decision === "denied") return false- }- if (actorUserId && (await queries.billing.getAnalyticsConsent(db, actorUserId))?.decision === "denied") return false- return true-}--export function productAnalyticsMeasurementId(env: Env) {- const development = (env.NODE_ENV ?? process.env.NODE_ENV) === "development"- return development && /^G-[A-Z0-9]+$/u.test(env.DEV_PRODUCT_ANALYTICS_MEASUREMENT_ID ?? "")- ? env.DEV_PRODUCT_ANALYTICS_MEASUREMENT_ID! : GA4_MEASUREMENT_ID-}--export function productAnalyticsIdentity(cookies: string, nowMs = Date.now(), measurementId = GA4_MEASUREMENT_ID) {- const now = Math.floor(nowMs / 1000)- const currentClient = parseGaClientId(analyticsCookieValue(cookies, "_ga"))- const random = crypto.getRandomValues(new Uint32Array(2))- const clientId = currentClient ?? `${random[0]}.${random[1]}`- const gaCookie = analyticsCookieValue(cookies, `_ga_${measurementId.slice(2).replaceAll("-", "_")}`)- const gaSession = parseGaSessionId(gaCookie)- const gaLastActive = gaCookie?.startsWith("GS2.")- ? Number(/(?:\.|\$)t(\d+)(?:\$|$)/u.exec(gaCookie)?.[1]) : Number(gaCookie?.split(".")[5])- const fallback = analyticsCookieValue(cookies, PRODUCT_SESSION_COOKIE)?.split(".") ?? []- const recent = (session: string | null | undefined, active: number) => Boolean(session && /^\d{1,20}$/u.test(session)- && Number.isSafeInteger(Number(session)) && Number(session) > 0 && Number(session) <= now- && now - Number(session) < 24 * 60 * 60 && Number.isSafeInteger(active)- && active >= Number(session) && active <= now && now - active < idleSeconds)- const sessionId = currentClient && recent(gaSession, gaLastActive) ? gaSession!- : currentClient && recent(fallback[0], Number(fallback[1])) ? fallback[0] : String(now)- return { clientId, sessionId, sessionCookie: `${sessionId}.${now}`, needsClientCookie: !currentClient }-}--async function pseudonymousUserId(secret: string, actorUserId: string) {- const encoder = new TextEncoder()- const key = await crypto.subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"])- const digest = await crypto.subtle.sign("HMAC", key, encoder.encode(`product-analytics-user:${actorUserId}`))- return Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, "0")).join("")-}--export async function productAnalyticsPayload(event: ProductAnalyticsEvent, secret: string) {- const definitions: Record<ProductAnalyticsEventName, string> = {- landing_cta_clicked: "public_entry_click", login_page_view: "login_page_entry",- sign_up: "account_committed", sign_in_success: "session_committed", sign_in_failed: "login_step_failed",- onboarding_enter_clicked: "enter_my_room_click", onboarding_first_message: "first_committed_human_message",- invitation_link_visit: "invited_visitor_page_entry",- }- const path = event.eventName === "invitation_link_visit" ? "/analytics/invitation"- : event.eventName === "landing_cta_clicked" ? "/" : ["login_page_view", "sign_up", "sign_in_success", "sign_in_failed"].includes(event.eventName)- ? "/sign-in" : "/analytics/onboarding"- return {- client_id: event.clientId,- ...(event.actorUserId ? { user_id: await pseudonymousUserId(secret, event.actorUserId) } : {}),- timestamp_micros: Date.parse(event.createdAt) * 1000,- consent: { ad_user_data: "DENIED", ad_personalization: "DENIED" },- events: [{ name: event.eventName, params: {- session_id: Number(event.sessionId), measurement_definition: definitions[event.eventName],- page_location: `https://alook.ai${path}`,- ...(event.method ? { method: event.method } : {}),- ...(event.accountKind ? { account_kind: event.accountKind } : {}),- ...(event.ctaName ? { cta_name: event.ctaName } : {}),- ...(event.failureStage ? { failure_stage: event.failureStage } : {}),- } }],- }-}--function collectionUrl(env: Env) {- const query = new URLSearchParams({ measurement_id: productAnalyticsMeasurementId(env), api_secret: env.GA4_API_SECRET! })- if ((env.NODE_ENV ?? process.env.NODE_ENV) === "development" && env.DEV_PRODUCT_ANALYTICS_COLLECTOR) {- const url = new URL(env.DEV_PRODUCT_ANALYTICS_COLLECTOR)- if (url.protocol !== "http:" || !["127.0.0.1", "localhost", "[::1]"].includes(url.hostname)- || url.username || url.password || url.hash || url.search) throw new Error("invalid local collector")- url.search = query.toString()- return url.toString()- }- return `https://www.google-analytics.com/mp/collect?${query}`-}--export async function deliverProductAnalytics(db: Database, env: Env, event: ProductAnalyticsEvent) {- if (!env.GA4_API_SECRET || !env.BETTER_AUTH_SECRET) {- await queries.productAnalytics.notePendingReason(db, event.id, "configuration_missing")- return "configuration_missing"- }- const claimed = await queries.productAnalytics.claimDelivery(db, event.id)- if (!claimed) return "already_claimed"- try {- if (claimed.actorUserId && (await queries.billing.getAnalyticsConsent(db, claimed.actorUserId))?.decision === "denied") {- await queries.productAnalytics.finishDelivery(db, claimed.id, "denied", "consent_revoked")- return "denied"- }- let url: string- try { url = collectionUrl(env) } catch {- await queries.productAnalytics.finishDelivery(db, claimed.id, "failed", "collector_configuration_invalid")- return "configuration_invalid"- }- const response = await fetch(url, {- method: "POST", headers: { "Content-Type": "application/json" },- body: JSON.stringify(await productAnalyticsPayload(claimed, env.BETTER_AUTH_SECRET)),- signal: AbortSignal.timeout(2500),- })- await queries.productAnalytics.finishDelivery(db, claimed.id, response.ok ? "accepted" : "failed",- response.ok ? "http_accepted" : `collection_http_${response.status}`)- return response.ok ? "http_accepted" : "http_failed"- } catch {- await queries.productAnalytics.finishDelivery(db, claimed.id, "uncertain", "collection_transport_ambiguous")- return "uncertain"- }-}--export async function scheduleProductAnalytics(work: () => Promise<unknown>) {- try {- const { ctx } = await getCloudflareContext({ async: true })- ctx.waitUntil(work().catch(() => { log.warn("analytics background operation failed") }))- } catch { log.warn("analytics execution context unavailable") }-}--export async function captureOnboardingFirstMessage(db: Database, env: Env, actorUserId: string, serverId: string, cookies: string, messageId: string) {- if (!parseGaClientId(analyticsCookieValue(cookies, "_ga")) || !await productAnalyticsAllowed(db, env, cookies, actorUserId)) return- const identity = productAnalyticsIdentity(cookies, Date.now(), productAnalyticsMeasurementId(env))- const event = await queries.productAnalytics.recordFirstHumanMessage(db, actorUserId, serverId, identity, messageId)- if (!event?.inserted) return- await scheduleProductAnalytics(() => deliverProductAnalytics(db, env, event.row))- return identity-}--export async function setOnboardingFirstMessageCookies(response: { cookies: { set: Parameters<typeof setProductAnalyticsCookies>[0] } }, db: Database, env: Env, actorUserId: string, serverId: string, cookies: string, messageId: string) {- try {- const identity = await captureOnboardingFirstMessage(db, env, actorUserId, serverId, cookies, messageId)- if (identity) setProductAnalyticsCookies((...args) => response.cookies.set(...args), identity, env.BETTER_AUTH_URL?.startsWith("https:") ?? false)- } catch { log.warn("first-message analytics capture failed") }-}--export function webAuthenticationMethod(path: string): string | null {- if (path.endsWith("/sign-in/email-otp")) return "email_otp"- const provider = /\/(?:callback|oauth2\/callback)\/(github|google|apple)$/u.exec(path)?.[1]- if (provider) return provider- if (process.env.NODE_ENV !== "production" && /\/(?:sign-in|sign-up)\/email$/u.test(path)) return "development_password"- return null-}--export async function captureAuthentication(env: Env, input: {- actorUserId: string; sessionId?: string; cookies: string; path: string; nativeFlow?: boolean; createdAt: Date;-}) {- const method = webAuthenticationMethod(input.path)- if (!method || input.nativeFlow) return- const db = getPrimaryDb(env.DB)- if (!await productAnalyticsAllowed(db, env, input.cookies, input.actorUserId)) return- const identity = productAnalyticsIdentity(input.cookies, input.createdAt.getTime(), productAnalyticsMeasurementId(env))- const accountKind = input.sessionId- ? await queries.productAnalytics.claimSignupSession(db, input.actorUserId, input.sessionId) ? "new" : "existing"- : "new"- const event = await queries.productAnalytics.recordEvent(db, {- eventName: input.sessionId ? "sign_in_success" : "sign_up", actorUserId: input.actorUserId,- sourceId: input.sessionId ?? null, dedupeKey: input.sessionId ? `auth-session:${input.sessionId}` : `signup:${input.actorUserId}`,- clientId: identity.clientId, sessionId: identity.sessionId, createdAt: input.createdAt.toISOString(), method, accountKind,- })- if (event) await scheduleProductAnalytics(() => deliverProductAnalytics(db, env, event.row))- return identity-}--export async function captureOAuthCallbackFailure(env: Env, input: { method: "github" | "google" | "apple"; attemptId: string; cookies: string; actorUserId?: string }) {- const db = getPrimaryDb(env.DB)- if (!await productAnalyticsAllowed(db, env, input.cookies, input.actorUserId)) return- const identity = productAnalyticsIdentity(input.cookies, Date.now(), productAnalyticsMeasurementId(env))- const event = await queries.productAnalytics.recordEvent(db, {- eventName: "sign_in_failed", actorUserId: input.actorUserId, sourceId: input.attemptId, dedupeKey: `oauth-callback-failed:${input.attemptId}`,- clientId: identity.clientId, sessionId: identity.sessionId, createdAt: new Date().toISOString(),- method: input.method, failureStage: "provider_callback",- })- if (!event?.inserted) return- await scheduleProductAnalytics(() => deliverProductAnalytics(db, env, event.row))- return identity-}--export function setProductAnalyticsCookies(- setCookie: (name: string, value: string, options: { path: string; sameSite: "lax"; secure: boolean; maxAge: number; httpOnly?: boolean }) => unknown,- identity: ReturnType<typeof productAnalyticsIdentity>, secure: boolean,-) {- const options = { path: "/", sameSite: "lax" as const, secure, maxAge: idleSeconds, httpOnly: true }- setCookie(PRODUCT_SESSION_COOKIE, identity.sessionCookie, options)- if (identity.needsClientCookie) setCookie("_ga", `GA1.1.${identity.clientId}`, { ...options, httpOnly: false, maxAge: ANALYTICS_CONSENT_MAX_AGE_SECONDS })-}--export function analyticsCookiesAfterResponse(cookies: string, responseCookies: string[]) {- const values = new Map(cookies.split(";").map(part => { const i = part.indexOf("="); return [part.slice(0, i).trim(), part.slice(i + 1)] }))- for (const cookie of responseCookies) {- const pair = cookie.split(";", 1)[0]- const i = pair.indexOf("=")- const name = pair.slice(0, i)- if (name === "_ga" || name === PRODUCT_SESSION_COOKIE) values.set(name, pair.slice(i + 1))- }- return [...values].map(([name, value]) => `${name}=${value}`).join("; ")-}diff --git a/src/web/src/lib/product-analytics.dom.test.ts b/src/web/src/lib/product-analytics.dom.test.tsindex e2585da03..257ffcd35 100644--- a/src/web/src/lib/product-analytics.dom.test.ts+++ b/src/web/src/lib/product-analytics.dom.test.ts@@ -1,38 +1,112 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"-import { waitFor } from "@/test/react-dom-harness"+import { fireEvent } from "@/test/react-dom-harness"const mocks = vi.hoisted(() => ({ native: false, consent: null as string | null }))vi.mock("@alook/shared", async original => ({ ...await original<typeof import("@alook/shared")>(), isTauri: () => mocks.native }))-vi.mock("@/lib/analytics-consent", () => ({ readAnalyticsConsent: () => mocks.consent }))-import { captureProductAnalytics } from "./product-analytics"+vi.mock("@/lib/analytics-consent", async original => ({ ...await original<typeof import("@/lib/analytics-consent")>(), readAnalyticsConsent: () => mocks.consent }))+import { beginOnboardingAnalytics, captureOnboardingFirstMessage, captureProductAnalytics } from "./product-analytics"-beforeEach(() => { document.cookie = "_ga=; Max-Age=0; Path=/"; mocks.native = false; mocks.consent = null; vi.stubGlobal("fetch", vi.fn(async () => new Response(null, { status: 200 }))) })+beforeEach(() => {+ window.history.replaceState(null, "", "/sign-in")+ window.dataLayer = []+ document.getElementById("alook-product-events")?.remove()+ document.cookie = "_ga=; Max-Age=0; Path=/"+ sessionStorage.clear()+ mocks.native = false; mocks.consent = null+ vi.stubGlobal("fetch", vi.fn())+})afterEach(() => vi.unstubAllGlobals())-describe("product analytics browser transport", () => {- it("sends keepalive fixed events with a reusable mount nonce", async () => {- await captureProductAnalytics({ event: "login_page_view" }, "fixed-mount-id")- await waitFor(() => expect(fetch).toHaveBeenCalledWith("/api/community/analytics/product-events", expect.objectContaining({- keepalive: true, credentials: "include", body: JSON.stringify({ event: "login_page_view", requestId: "fixed-mount-id" }),- })))- })- it("seeds one browser id before delayed requests and reuses it on fast navigation", async () => {- let resolve: (() => void) | undefined- const pending = new Promise<void>(done => { resolve = done })- const capturedCookies: string[] = []- vi.mocked(fetch).mockImplementation(async () => { capturedCookies.push(document.cookie); await pending; return new Response(null, { status: 200 }) })- const first = captureProductAnalytics({ event: "landing_cta_clicked", ctaName: "get_started" })- const next = captureProductAnalytics({ event: "login_page_view" })- expect(capturedCookies).toHaveLength(2)- expect(capturedCookies[0]).toMatch(/_ga=GA1\.1\.\d+\.\d+/u)- expect(capturedCookies[1]).toBe(capturedCookies[0])- resolve!(); await Promise.all([first, next])- })- it("does not send from native or explicitly denied browsers", async () => {+function loadFrame() {+ const frame = document.getElementById("alook-product-events") as HTMLIFrameElement+ const send = vi.fn()+ Object.defineProperty(frame.contentWindow, "sendProductEvent", { value: send, configurable: true })+ fireEvent.load(frame)+ return { frame, send }+}++describe("frontend product analytics", () => {+ it("uses only a static GA4 document and never the backend collection endpoint", async () => {+ await captureProductAnalytics({ event: "login_page_view" })+ const { frame, send } = loadFrame()+ expect(frame.getAttribute("src")).toBe("/analytics-events.html")+ expect(frame.referrerPolicy).toBe("no-referrer")+ expect(send).toHaveBeenCalledWith({ event: "login_page_view", params: {} })+ expect(fetch).not.toHaveBeenCalled()+ })+ it("reuses the existing public Google tag without loading another document", async () => {+ window.history.replaceState(null, "", "/")+ await captureProductAnalytics({ event: "landing_cta_clicked", ctaName: "get_started" })+ expect(Array.from(window.dataLayer![0])).toEqual(["event", "landing_cta_clicked", { cta_name: "get_started", send_to: "G-STBCL8F4ZY" }])+ expect(document.getElementById("alook-product-events")).toBeNull()+ expect(fetch).not.toHaveBeenCalled()+ })+ it("does not wait for the document or network before finishing the event call", async () => {+ await expect(captureProductAnalytics({ event: "onboarding_enter_clicked", serverId: "private-server" })).resolves.toBeUndefined()+ expect(document.getElementById("alook-product-events")?.getAttribute("data-ready")).toBeNull()+ expect(fetch).not.toHaveBeenCalled()+ })+ it("reuses normal browser identity and accepts repeated events without dedupe", async () => {+ document.cookie = "_ga=GA1.1.100.200; Path=/"+ await captureProductAnalytics({ event: "landing_cta_clicked", ctaName: "get_started" })+ const { send } = loadFrame()+ const identity = document.cookie+ await captureProductAnalytics({ event: "landing_cta_clicked", ctaName: "get_started" })+ expect(send).toHaveBeenCalledTimes(2)+ expect(send.mock.calls[0][0]).toEqual(send.mock.calls[1][0])+ expect(document.cookie).toBe(identity)+ })+ it("does not pass private ids, tokens or unapproved dimension values to GA4", async () => {+ await captureProductAnalytics({ event: "onboarding_enter_clicked", serverId: "private-server" })+ const { send } = loadFrame()+ await captureProductAnalytics({ event: "invitation_link_visit", token: "private-token" })+ await captureProductAnalytics({ event: "sign_up", method: "[email protected]" })+ expect(JSON.stringify(send.mock.calls)).not.toContain("private-")+ expect(send.mock.calls.map(([event]) => event.params)).toEqual([{}, {}, {}])+ })+ it("does not load or send in native and explicitly denied browsers", async () => {mocks.native = true; await captureProductAnalytics({ event: "login_page_view" })mocks.native = false; mocks.consent = "denied"; await captureProductAnalytics({ event: "login_page_view" })+ expect(document.getElementById("alook-product-events")).toBeNull()expect(fetch).not.toHaveBeenCalled()})- it("isolates a rejected analytics request from product navigation", async () => {- vi.mocked(fetch).mockRejectedValueOnce(new Error("offline"))+ it("rechecks denial before a delayed document can send", async () => {+ await captureProductAnalytics({ event: "login_page_view" })+ mocks.consent = "denied"+ const { send } = loadFrame()+ expect(send).not.toHaveBeenCalled()+ expect(document.getElementById("alook-product-events")).toBeNull()+ })+ it("isolates a failing frontend sender from product navigation", async () => {+ await captureProductAnalytics({ event: "login_page_view" })+ const { send } = loadFrame()+ send.mockImplementation(() => { throw new Error("offline") })await expect(captureProductAnalytics({ event: "onboarding_enter_clicked", serverId: "server" })).resolves.toBeUndefined()})+ it("finishes without a backend fallback when the analytics document cannot attach", async () => {+ const append = vi.spyOn(document.body, "appendChild").mockImplementationOnce(() => { throw new Error("DOM insertion blocked") })+ try {+ await expect(captureProductAnalytics({ event: "onboarding_enter_clicked", serverId: "server" })).resolves.toBeUndefined()+ expect(append).toHaveBeenCalledOnce()+ expect(document.getElementById("alook-product-events")).toBeNull()+ expect(fetch).not.toHaveBeenCalled()+ } finally { append.mockRestore() }+ })+ it("reports only the current onboarding room's first successful message", () => {+ beginOnboardingAnalytics("owner", "onboarding-server")+ const { send } = loadFrame()+ captureOnboardingFirstMessage("owner", "other-server")+ captureOnboardingFirstMessage("other", "onboarding-server")+ expect(send).toHaveBeenCalledOnce()+ captureOnboardingFirstMessage("owner", "onboarding-server")+ captureOnboardingFirstMessage("owner", "onboarding-server")+ expect(send.mock.calls.map(([input]) => input.event)).toEqual(["onboarding_enter_clicked", "onboarding_first_message"])+ })+ it("allows another session or onboarding journey for the same user to emit again", () => {+ beginOnboardingAnalytics("owner", "server")+ const { send } = loadFrame()+ captureOnboardingFirstMessage("owner", "server")+ sessionStorage.clear()+ beginOnboardingAnalytics("owner", "server")+ captureOnboardingFirstMessage("owner", "server")+ expect(send.mock.calls.map(([input]) => input.event)).toEqual(["onboarding_enter_clicked", "onboarding_first_message", "onboarding_enter_clicked", "onboarding_first_message"])+ })})diff --git a/src/web/src/lib/product-analytics.ts b/src/web/src/lib/product-analytics.tsindex 7054e548a..e22298770 100644--- a/src/web/src/lib/product-analytics.ts+++ b/src/web/src/lib/product-analytics.ts@@ -1,24 +1,74 @@"use client"-import { ensureBrowserAnalyticsIdentity } from "@/lib/product-analytics-identity"import { isTauri } from "@alook/shared"-import { readAnalyticsConsent } from "@/lib/analytics-consent"+import { googleCommand, isPublicAnalyticsPath, readAnalyticsConsent } from "@/lib/analytics-consent"+import { LANDING_CTA_NAMES } from "@/lib/product-analytics-contract"export type ProductAnalyticsInput =| { event: "landing_cta_clicked"; ctaName: string }| { event: "login_page_view" }- | { event: "sign_in_failed"; method: "email_otp" | "github" | "google" | "apple"; failureStage: "send_code" | "verify_code" | "social_start" }+ | { event: "sign_up" | "sign_in_success"; method: string }+ | { event: "sign_in_failed"; method: string; failureStage: "send_code" | "verify_code" | "social_start" | "provider_callback" }| { event: "onboarding_enter_clicked"; serverId: string }+ | { event: "onboarding_first_message" }| { event: "invitation_link_visit"; token: string }-export async function captureProductAnalytics(input: ProductAnalyticsInput, requestId = crypto.randomUUID()): Promise<void> {- if (typeof window === "undefined" || isTauri() || readAnalyticsConsent() === "denied") return- ensureBrowserAnalyticsIdentity()+type EventPayload = { event: ProductAnalyticsInput["event"]; params: Record<string, string> }+type EventFrameWindow = Window & { sendProductEvent?: (input: EventPayload) => void }+const onboardingKey = "alook:onboarding-event"++function prepareProductAnalytics(): HTMLIFrameElement | null {+ if (typeof window === "undefined" || isTauri() || readAnalyticsConsent() === "denied") return null+ try {+ let frame = document.getElementById("alook-product-events") as HTMLIFrameElement | null+ if (!frame) {+ frame = document.createElement("iframe")+ frame.id = "alook-product-events"+ frame.hidden = true+ frame.title = "Alook event analytics"+ frame.setAttribute("sandbox", "allow-scripts allow-same-origin")+ frame.referrerPolicy = "no-referrer"+ frame.src = "/analytics-events.html"+ const created = frame+ frame.addEventListener("load", () => { created.dataset.ready = "true" }, { once: true })+ document.body.appendChild(frame)+ }+ return frame+ } catch { return null }+}++export async function captureProductAnalytics(input: ProductAnalyticsInput): Promise<void> {+ try {+ if (typeof window === "undefined" || isTauri() || readAnalyticsConsent() === "denied") return+ const params: Record<string, string> = {}+ if ("ctaName" in input && LANDING_CTA_NAMES.some(name => name === input.ctaName)) params.cta_name = input.ctaName+ if ("method" in input && ["email", "email_otp", "github", "google", "apple", "development_password"].includes(input.method)) params.method = input.method+ if ("failureStage" in input) params.failure_stage = input.failureStage+ if (isPublicAnalyticsPath(window.location.pathname)) {+ googleCommand("event", input.event, { ...params, send_to: "G-STBCL8F4ZY" })+ return+ }+ const frame = prepareProductAnalytics()+ if (!frame) return+ const target = frame+ const send = () => {+ if (readAnalyticsConsent() === "denied") { target.remove(); return }+ try { (target.contentWindow as EventFrameWindow | null)?.sendProductEvent?.({ event: input.event, params }) } catch {}+ }+ if (frame.dataset.ready === "true") send()+ else frame.addEventListener("load", send, { once: true })+ } catch {}+}++export function beginOnboardingAnalytics(userId: string, serverId: string) {+ try { sessionStorage.setItem(onboardingKey, JSON.stringify([userId, serverId])) } catch {}+ void captureProductAnalytics({ event: "onboarding_enter_clicked", serverId })+}++export function captureOnboardingFirstMessage(userId: string, serverId: string) {try {- await fetch("/api/community/analytics/product-events", {- method: "POST", credentials: "include", keepalive: true,- headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ...input, requestId }),- signal: AbortSignal.timeout(5000),- })+ if (sessionStorage.getItem(onboardingKey) !== JSON.stringify([userId, serverId])) return+ sessionStorage.removeItem(onboardingKey)+ void captureProductAnalytics({ event: "onboarding_first_message" })} catch {}}