Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

Default public analytics and add onboarding and invitation funnel signals (#936)

Gustavo Ye8520e334dd02
diff --git a/src/shared/src/db/index.ts b/src/shared/src/db/index.ts
index 566f2029c..62c83930d 100644
--- a/src/shared/src/db/index.ts
+++ b/src/shared/src/db/index.ts
@@ -5,8 +5,9 @@ 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 };
+const allSchema = { ...schema, ...communitySchema, ...communityMachineSchema, ...productPlanSchema, ...billingSchema, ...communityFunnelAnalyticsSchema, ...productAnalyticsSchema };
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.ts
new file mode 100644
index 000000000..c8aefc8c1
--- /dev/null
+++ b/src/shared/src/db/product-analytics-schema.ts
@@ -0,0 +1,41 @@
+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.ts
index 82c7cd49c..aa49715c0 100644
--- a/src/shared/src/db/queries-index.ts
+++ b/src/shared/src/db/queries-index.ts
@@ -70,6 +70,7 @@ 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.ts
new file mode 100644
index 000000000..b77bae24b
--- /dev/null
+++ b/src/shared/src/db/queries/community/product-analytics.test.ts
@@ -0,0 +1,135 @@
+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.ts
new file mode 100644
index 000000000..1ea9d9def
--- /dev/null
+++ b/src/shared/src/db/queries/community/product-analytics.ts
@@ -0,0 +1,84 @@
+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.ts
index c5e47fc4c..b18db3d20 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -192,6 +192,7 @@ 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/blog/src/instrumentation-client.dom.test.tsx b/src/web/blog/src/instrumentation-client.dom.test.tsx
index 36a4892a3..3aaa28942 100644
--- a/src/web/blog/src/instrumentation-client.dom.test.tsx
+++ b/src/web/blog/src/instrumentation-client.dom.test.tsx
@@ -67,7 +67,7 @@ it("boots the actual Blog entry with the native resumed session and exports its
});
-it.each(["", "v1.denied", "v0.granted", "v1.granted"])("boots the actual Blog document from %s without adding an optional telemetry grant", async value => {
+it.each(["", "v1.denied", "v0.granted", "v1.granted"])("boots the actual Blog document from %s with default public collection and saved denial preserved", async value => {
vi.resetModules();
vi.stubEnv("NEXT_PUBLIC_FARO_COLLECTOR_URL", "");
window.history.replaceState(null, "", "/blog/public?secret=query#hash");
@@ -77,7 +77,7 @@ it.each(["", "v1.denied", "v0.granted", "v1.granted"])("boots the actual Blog do
vi.stubGlobal("fetch", fetcher);
const { onRouterTransitionStart } = await import("./instrumentation-client");
expect(window.dataLayer.map(command => Array.from(command as IArguments))).toEqual([
- ["consent", "default", { analytics_storage: value === "v1.granted" ? "granted" : "denied", ad_storage: "denied", ad_user_data: "denied", ad_personalization: "denied" }],
+ ["consent", "default", { analytics_storage: value === "v1.denied" ? "denied" : "granted", ad_storage: "denied", ad_user_data: "denied", ad_personalization: "denied" }],
["set", { page_location: `${window.location.origin}/blog/public`, page_referrer: `${window.location.origin}/` }],
]);
onRouterTransitionStart("/blog/other?secret=route#hash");
diff --git a/src/web/migrations/0107_product_analytics_event.sql b/src/web/migrations/0107_product_analytics_event.sql
new file mode 100644
index 000000000..8d47ee268
--- /dev/null
+++ b/src/web/migrations/0107_product_analytics_event.sql
@@ -0,0 +1,20 @@
+CREATE TABLE product_analytics_event (
+ id TEXT PRIMARY KEY NOT NULL,
+ event_name TEXT NOT NULL,
+ actor_user_id TEXT REFERENCES user(id) ON DELETE CASCADE,
+ server_id TEXT REFERENCES community_server(id) ON DELETE CASCADE,
+ source_id TEXT,
+ dedupe_key TEXT NOT NULL,
+ client_id TEXT NOT NULL,
+ session_id TEXT NOT NULL,
+ method TEXT,
+ account_kind TEXT,
+ cta_name TEXT,
+ failure_stage TEXT,
+ created_at TEXT NOT NULL,
+ delivery_status TEXT NOT NULL DEFAULT 'pending',
+ delivery_reason TEXT,
+ attempted_at TEXT
+);
+CREATE UNIQUE INDEX uq_product_analytics_dedupe ON product_analytics_event(dedupe_key);
+CREATE INDEX idx_product_analytics_actor_server_event ON product_analytics_event(actor_user_id, server_id, event_name);
diff --git a/src/web/src/app/(auth)/sign-in/page.test.ts b/src/web/src/app/(auth)/sign-in/page.test.ts
index e0131226f..16a0e1ef9 100644
--- a/src/web/src/app/(auth)/sign-in/page.test.ts
+++ b/src/web/src/app/(auth)/sign-in/page.test.ts
@@ -41,6 +41,11 @@ describe("sign-in server configuration", () => {
expect(JSON.stringify(page.props)).not.toContain("private-key-never-passed-to-the-client")
})
+ it("shows the real OTP form for the explicit local QA configuration", async () => {
+ mocks.getCloudflareContext.mockResolvedValueOnce({ env: { NODE_ENV: "development", DEV_AUTH_OTP: "1" } })
+ expect((await SignInPage()).props.isProd).toBe(true)
+ })
+
it("fails closed instead of rendering with partial Apple configuration", async () => {
mocks.getCloudflareContext.mockResolvedValueOnce({
env: { APPLE_CLIENT_ID: "ai.alook.web" },
diff --git a/src/web/src/app/(auth)/sign-in/page.tsx b/src/web/src/app/(auth)/sign-in/page.tsx
index 5bd1433c0..9ebe1c50c 100644
--- a/src/web/src/app/(auth)/sign-in/page.tsx
+++ b/src/web/src/app/(auth)/sign-in/page.tsx
@@ -6,7 +6,7 @@ import SignInPageClient from "./sign-in-client"
export default async function SignInPage() {
const { env } = await getCloudflareContext({ async: true })
const mode = resolveMode({ nodeEnv: env.NODE_ENV ?? process.env.NODE_ENV })
- const isProd = mode === "production"
+ const isProd = mode === "production" || (mode === "dev" && env.DEV_AUTH_OTP === "1")
const appleEnabled = resolveAppleAuthConfig(env).enabled
return <SignInPageClient isProd={isProd} appleEnabled={appleEnabled} />
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.ts
index 071a9342c..859a5d641 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
@@ -1,22 +1,27 @@
import { createElement } from "react"
import { beforeEach, describe, expect, it, vi } from "vitest"
-import { render, screen } from "@/test/react-dom-harness"
+import { act, render, screen, setupUser } from "@/test/react-dom-harness"
const mocks = vi.hoisted(() => ({
searchParams: new URLSearchParams(),
+ capture: vi.fn(),
+ send: vi.fn(),
+ verify: vi.fn(),
+ verifyInput: undefined as undefined | ((value: string) => Promise<void>),
}))
+vi.mock("@/lib/product-analytics", () => ({ captureProductAnalytics: mocks.capture }))
vi.mock("next/navigation", () => ({
useSearchParams: () => mocks.searchParams,
}))
vi.mock("@/lib/auth-client", () => ({
- authClient: {},
+ authClient: { emailOtp: { sendVerificationOtp: mocks.send }, signIn: { emailOtp: mocks.verify } },
signIn: {},
signUp: {},
}))
vi.mock("./sign-in-fields", () => ({
SignInEmailField: () => null,
- SignInOtpField: () => null,
+ SignInOtpField: ({ onChange }: { onChange: (value: string) => Promise<void> }) => { mocks.verifyInput = onChange; return null },
}))
vi.mock("./social-sign-in", () => ({
SocialSignIn: ({
@@ -48,6 +53,7 @@ import SignInPageClient from "./sign-in-client"
describe("sign-in client Apple availability", () => {
beforeEach(() => {
+ vi.clearAllMocks(); mocks.send.mockResolvedValue({}); mocks.verify.mockResolvedValue({ error: { message: "bad code" } }); mocks.verifyInput = undefined
mocks.searchParams = new URLSearchParams("redirect=%2Fc%2Fme")
window.matchMedia = vi.fn(() => ({
matches: false,
@@ -56,6 +62,26 @@ describe("sign-in client Apple availability", () => {
})) as never
})
+ 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))
+ await setupUser().click(screen.getByRole("button", { name: "Send Code" }))
+ expect(mocks.capture).toHaveBeenCalledTimes(1)
+ await act(async () => { await mocks.verifyInput!("123456") })
+ expect(mocks.capture).toHaveBeenLastCalledWith({ event: "sign_in_failed", method: "email_otp", failureStage: "verify_code" })
+ expect(JSON.stringify(mocks.capture.mock.calls)).not.toContain("123456")
+ expect(JSON.stringify(mocks.capture.mock.calls)).not.toContain("bad code")
+ })
+
+ it("records send-code failure without mistaking it for successful authentication", async () => {
+ mocks.send.mockResolvedValueOnce({ error: { message: "private detail" } })
+ render(createElement(SignInPageClient, { isProd: true, appleEnabled: false }))
+ await setupUser().click(screen.getByRole("button", { name: "Send Code" }))
+ expect(mocks.capture).toHaveBeenLastCalledWith({ event: "sign_in_failed", method: "email_otp", failureStage: "send_code" })
+ expect(JSON.stringify(mocks.capture.mock.calls)).not.toContain("private detail")
+ expect(JSON.stringify(mocks.capture.mock.calls)).not.toContain("sign_in_success")
+ })
+
it.each([true, false])("passes server-derived appleEnabled=%s unchanged", (appleEnabled) => {
render(createElement(SignInPageClient, { isProd: true, appleEnabled }))
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.tsx
index cf9a9ec1f..87a16fe85 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
@@ -1,9 +1,10 @@
"use client"
+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 } from "react"
+import { useEffect, useMemo } from "react"
import { useSearchParams } from "next/navigation"
import { signIn, signUp, authClient } from "@/lib/auth-client"
import { parseRetryAfterSeconds } from "@/lib/retry-after"
@@ -49,6 +50,11 @@ function SignInForm({
accountDeleted: boolean
appleEnabled: boolean
}) {
+ const viewId = useMemo(() => crypto.randomUUID(), [])
+ useEffect(() => { void captureProductAnalytics({ event: "login_page_view" }, viewId) }, [viewId])
+ const failed = (failureStage: "send_code" | "verify_code") => {
+ void captureProductAnalytics({ event: "sign_in_failed", method: "email_otp", failureStage })
+ }
const [email, setEmail] = useAtom(useCreateAtom(""))
const [emailError, setEmailError] = useAtom(useCreateAtom(""))
const [otpError, setOtpError] = useAtom(useCreateAtom(""))
@@ -91,6 +97,7 @@ function SignInForm({
})
finishAction(observation, error ? "error" : "success")
if (error) {
+ failed("send_code")
if (error.status !== 429) setEmailError(error.message ?? "Failed to send code")
} else {
setEmailError("")
@@ -99,6 +106,7 @@ function SignInForm({
}
} catch {
finishAction(observation, "error")
+ failed("send_code")
setEmailError("Failed to send code")
}
setLoading(false)
@@ -118,6 +126,7 @@ function SignInForm({
})
finishAction(observation, error ? "error" : "success")
if (error) {
+ failed("verify_code")
setOtpError(error.message ?? "Invalid code")
setCode("")
} else {
@@ -127,6 +136,7 @@ function SignInForm({
}
} catch {
finishAction(observation, "error")
+ failed("verify_code")
setOtpError("Invalid code")
setCode("")
}
diff --git a/src/web/src/app/(auth)/sign-in/social-sign-in.dom.test.ts b/src/web/src/app/(auth)/sign-in/social-sign-in.dom.test.ts
index 20309e232..bbb2bb5c2 100644
--- a/src/web/src/app/(auth)/sign-in/social-sign-in.dom.test.ts
+++ b/src/web/src/app/(auth)/sign-in/social-sign-in.dom.test.ts
@@ -11,6 +11,7 @@ const webRoot = existsSync(resolve(process.cwd(), "next.config.ts"))
: resolve(process.cwd(), "src/web")
const mocks = vi.hoisted(() => ({
+ capture: vi.fn(),
tauri: false,
social: vi.fn(),
start: vi.fn(),
@@ -19,6 +20,7 @@ const mocks = vi.hoisted(() => ({
emit: undefined as undefined | ((view: NativeOauthView) => void),
}))
+vi.mock("@/lib/product-analytics", () => ({ captureProductAnalytics: mocks.capture }))
vi.mock("@alook/shared", async importOriginal => ({
...await importOriginal<typeof import("@alook/shared")>(),
isTauri: () => mocks.tauri,
diff --git a/src/web/src/app/(auth)/sign-in/social-sign-in.tsx b/src/web/src/app/(auth)/sign-in/social-sign-in.tsx
index 4968c2861..fbd747e4b 100644
--- a/src/web/src/app/(auth)/sign-in/social-sign-in.tsx
+++ b/src/web/src/app/(auth)/sign-in/social-sign-in.tsx
@@ -1,5 +1,7 @@
"use client"
+import { captureProductAnalytics } from "@/lib/product-analytics"
+
import { startAction, finishAction, type Action } from "@/lib/observability/context"
import { useAtom, useCreateAtom } from "@tanstack/react-store";
@@ -53,7 +55,14 @@ export function SocialSignIn({
observed.current = startAction("auth_social", { capability: "limited", phase: "auth" })
lastProvider.current = provider
const action = observed.current
- if (!isTauri()) { void signIn.social({ provider, callbackURL: postLoginUrl }).then(result => finishAction(action, result.error ? "error" : "observed"), () => finishAction(action, "error")); return }
+ if (!isTauri()) {
+ const failed = () => { void captureProductAnalytics({ event: "sign_in_failed", method: provider, failureStage: "social_start" }) }
+ void signIn.social({ provider, callbackURL: postLoginUrl }).then(result => {
+ finishAction(action, result.error ? "error" : "observed")
+ if (result.error) failed()
+ }, () => { finishAction(action, "error"); failed() })
+ return
+ }
if (controller.current) void controller.current.start(provider, safeRedirectPath(postLoginUrl))
}
const busy = native?.phase === "initializing" || native?.phase === "preparing" || native?.phase === "exchanging" || native?.phase === "checking_status"
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.ts
new file mode 100644
index 000000000..5ba5c3126
--- /dev/null
+++ b/src/web/src/app/api/community/analytics/product-events/route.test.ts
@@ -0,0 +1,109 @@
+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.ts
new file mode 100644
index 000000000..8157f889a
--- /dev/null
+++ b/src/web/src/app/api/community/analytics/product-events/route.ts
@@ -0,0 +1,95 @@
+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.ts
index 751f49d38..745aef73f 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,6 +63,13 @@ 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),
@@ -290,9 +297,13 @@ describe("POST /api/community/channels/[id]/messages", () => {
mockGetMessageByAuthorAndNonce.mockResolvedValue(replay ? row : null)
const request = postReq({ content: "hello", nonce: "v3-nonce" })
request.headers.set("x-alook-community-contract", "3")
+ request.headers.set("cookie", "_ga=GA1.1.123.456")
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(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: [],
@@ -421,12 +432,19 @@ describe("POST /api/community/channels/[id]/messages", () => {
expect(mockDuplicateCheck).not.toHaveBeenCalled()
})
- it("accepts a bare message to a forum top-level (phase2 forum≡thread write-guard reversal — forum is now directly sendable)", async () => {
+ it.each([1, 3])("accepts a forum opener with contract %s and keeps analytics cookies on the confirmation", async (contract) => {
mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1", type: "forum", parentChannelId: null })
mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1", type: "forum", parentChannelId: null })
- const res = await POST(postReq({ content: "a post's opener message" }), ctx)
+ const request = postReq({ content: "a post's opener message" })
+ request.headers.set("x-alook-community-contract", String(contract))
+ 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.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 } : {}) })
+ if (contract === 1) expect(confirmation).not.toHaveProperty("deduped")
})
it("a DM id via the door routes to the DM arm — the block gate runs (blocked peer → 403, not a silent channel-route bypass)", async () => {
@@ -577,6 +595,8 @@ describe("POST /api/community/channels/[id]/messages", () => {
const response = await POST(postReq({ content: "canonical content", nonce: "client-1" }), ctx)
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(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.ts
index 168b7e17d..cd08b76bd 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,3 +1,4 @@
+import { setOnboardingFirstMessageCookies } from "@/lib/product-analytics-server"
import { flattenError } from "zod"
import { NextRequest, NextResponse } from "next/server"
import { withCommunityActor } from "@/lib/middleware/community-actor"
@@ -218,7 +219,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)
+ return handleHumanSend(db, ctx.actor.userId, ctx.env, ctx.params?.id, raw, requestedCommunityContract(req.headers) ?? 1, req.headers.get("cookie") ?? "")
})
/**
@@ -234,6 +235,7 @@ 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 })
@@ -276,11 +278,13 @@ async function handleHumanSend(
source: "web",
})
if (!created.ok) return NextResponse.json({ error: created.error }, { status: created.status })
- return humanMessageConfirmation(contract, target.channelId, {
+ const response = humanMessageConfirmation(contract, target.channelId, {
message: contract === 3 ? await mapPostedMessageForApi(db, target.channelId, created.message, contract) : created.message,
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
}
const replay = await getCommunityMessageReplay({
@@ -304,7 +308,9 @@ async function handleHumanSend(
attachmentIds: attachmentIds.length > 0 ? attachmentIds : undefined,
})
if (!result.ok) return NextResponse.json({ error: result.error }, { status: result.status })
- return humanMessageConfirmation(contract, target.channelId, { message: await mapPostedMessageForApi(db, target.channelId, result.row, contract), deduped: result.deduped }, 201)
+ 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
}
function humanMessageConfirmation(contract: CommunityContract, channelId: string, payload: { message: unknown; deduped?: boolean; threadId?: string }, status: number): NextResponse {
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.ts
index e77bfdd66..e1d5f90be 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
@@ -13,7 +13,7 @@ vi.mock("@/lib/middleware/auth", () => ({
(request: NextRequest) => handler(request, { env: mocks.env, userId: mocks.userId }),
}))
vi.mock("@/lib/db", () => ({ getPrimaryDb: () => mocks.env.DB }))
-vi.mock("@alook/shared", () => ({ queries: { billing: { recordAnalyticsConsent: mocks.recordAnalyticsConsent } } }))
+vi.mock("@alook/shared", async original => ({ ...await original<typeof import("@alook/shared")>(), queries: { billing: { recordAnalyticsConsent: mocks.recordAnalyticsConsent } } }))
import { POST } from "./route"
@@ -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(2)
+ expect(cookies).toHaveLength(decision === "granted" ? 4 : 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.ts
index 16c3160bd..09342450f 100644
--- a/src/web/src/app/api/privacy/analytics-consent/route.ts
+++ b/src/web/src/app/api/privacy/analytics-consent/route.ts
@@ -11,6 +11,8 @@ 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")
if (!origin) return null
@@ -60,6 +62,7 @@ export const POST = withOptionalAuth(async (request, ctx) => {
}
const response = NextResponse.json({ decision })
+
const secure = origin.protocol === "https:"
const shared = {
path: "/",
@@ -77,6 +80,10 @@ 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.tsx
index 9d6581c3c..970186b26 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
@@ -16,6 +16,7 @@ import { apiFetch } from "@/lib/api/client"
import { ApiError } from "@/lib/errors"
import { ServerIcon } from "@/components/community/server-icon"
import { Avatar } from "@/components/community/avatar"
+import { captureProductAnalytics } from "@/lib/product-analytics"
import { tid } from "@/lib/community/testids"
type InviteInfo = {
@@ -41,14 +42,16 @@ function isDeadInvite(err: unknown): boolean {
* Fetches invite info, displays server preview, and joins on button click.
*/
export function InviteAcceptClient({ token }: { token: string }) {
- return <PublicQueryProvider><InviteAcceptInner token={token} /></PublicQueryProvider>
+ const visitId = useMemo(() => ({ token, id: crypto.randomUUID() }), [token]).id
+ return <PublicQueryProvider><InviteAcceptInner token={token} visitId={visitId} /></PublicQueryProvider>
}
-function InviteAcceptInner({ token }: { token: string }) {
+function InviteAcceptInner({ token, visitId }: { token: string; visitId: 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])
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/app/pricing/pricing-client.dom.test.tsx b/src/web/src/app/pricing/pricing-client.dom.test.tsx
index 985b4cc96..133a078b5 100644
--- a/src/web/src/app/pricing/pricing-client.dom.test.tsx
+++ b/src/web/src/app/pricing/pricing-client.dom.test.tsx
@@ -1,4 +1,4 @@
-import { beforeEach, expect, it, vi } from "vitest"
+import { afterEach, beforeEach, expect, it, vi } from "vitest"
import { render, setupUser, waitFor } from "@/test/react-dom-harness"
import PricingClient from "./pricing-client"
@@ -7,17 +7,17 @@ vi.mock("./pricing.module.css", () => ({ default: new Proxy({}, { get: (_target,
const state = vi.hoisted(() => ({
session: { data: null as null | { user: { id: string } }, isPending: false, error: null },
search: new URLSearchParams(),
- push: vi.fn(), api: vi.fn(), checkout: vi.fn(), portal: vi.fn(), refresh: vi.fn(),
+ assign: vi.fn(), api: vi.fn(), checkout: vi.fn(), portal: vi.fn(), refresh: vi.fn(),
billing: {} as Record<string, unknown>,
- pricingView: vi.fn(), pricingCta: vi.fn(),
+ landing: vi.fn(), pricingView: vi.fn(), pricingCta: vi.fn(),
}))
vi.mock("@/lib/auth-client", () => { const sessionSDK = { useSession: () => state.session }; return { ...sessionSDK, currentSessionViewer: () => { const value = sessionSDK.useSession(); return !value || value.isPending || value.error ? undefined : value.data?.user.id ?? null } } })
-vi.mock("next/navigation", () => ({ useRouter: () => ({ push: state.push }), useSearchParams: () => state.search }))
+vi.mock("next/navigation", () => ({ useSearchParams: () => state.search }))
vi.mock("@/lib/api/client", () => ({ apiFetch: state.api }))
vi.mock("@/hooks/community/use-billing", () => ({ useBilling: () => ({ ...state.billing, checkout: state.checkout, portal: state.portal, refresh: state.refresh }) }))
vi.mock("@/lib/analytics", async (importOriginal) => {
const original = await importOriginal<typeof import("@/lib/analytics")>()
- return { ...original, trackPricingView: state.pricingView, trackPricingCtaClick: state.pricingCta }
+ return { ...original, trackLandingCtaClicked: state.landing, trackPricingView: state.pricingView, trackPricingCtaClick: state.pricingCta }
})
const offers = [
@@ -28,7 +28,15 @@ const catalog = { free: { plan: { id: "free", displayName: "Free" }, botLimit: 3
const free = { plan: catalog.free.plan, isFounder: false, subscription: null, offers }
const subscription = { plan: offers[0].plan, status: "active", currentPeriodEnd: null, cancelAt: null, scheduledChange: null }
+afterEach(() => vi.unstubAllGlobals())
+
beforeEach(() => {
+ const originalWindow = window
+ vi.stubGlobal("window", new Proxy(originalWindow, {
+ get: (target, key) => key === "location" ? new Proxy({}, {
+ get: (_location, field) => field === "assign" ? state.assign : Reflect.get(originalWindow.location, field, originalWindow.location),
+ }) : Reflect.get(target, key, target),
+ }))
vi.clearAllMocks()
state.session = { data: null, isPending: false, error: null }
state.search = new URLSearchParams()
@@ -39,13 +47,22 @@ beforeEach(() => {
it("sends guests to sign-in with a valid selected plan preserved", async () => {
const view = render(<PricingClient />)
await setupUser().click(await view.findByRole("button", { name: "Choose Studio" }))
- const url = new URL(state.push.mock.calls[0][0], "https://alook.ai")
+ const url = new URL(state.assign.mock.calls[0][0], "https://alook.ai")
expect(url.pathname).toBe("/sign-in")
+ expect(state.landing).toHaveBeenCalledWith({ cta_name: "pricing_get_started" })
expect(url.searchParams.get("redirect")).toBe("/pricing?plan=studio")
expect(state.checkout).not.toHaveBeenCalled()
expect(state.pricingCta).toHaveBeenCalledWith({ plan_id: "studio", cta_action: "choose_plan", auth_state: "guest", current_plan: "none", entry_point: "pricing_page" })
})
+it("opens the free product with document navigation rather than leaving public trackers alive", async () => {
+ state.session.data = { user: { id: "buyer" } }
+ state.billing.data = free
+ const view = render(<PricingClient />)
+ await setupUser().click(await view.findByRole("button", { name: "Open Alook" }))
+ expect(state.assign).toHaveBeenCalledWith("/c/me/bots")
+})
+
it("preserves selected plan after sign-in without automatically starting payment", async () => {
state.session.data = { user: { id: "buyer" } }
state.billing.data = free
diff --git a/src/web/src/app/pricing/pricing-client.tsx b/src/web/src/app/pricing/pricing-client.tsx
index 113e63f5f..342b8a3d5 100644
--- a/src/web/src/app/pricing/pricing-client.tsx
+++ b/src/web/src/app/pricing/pricing-client.tsx
@@ -1,9 +1,11 @@
"use client"
+/* eslint-disable @next/next/no-location-assign-relative-destination -- Product entrances require a new document to unload public tracking. */
+
import { useObservedRegion } from "@/lib/observability/regions"
import { useEffect, useRef, type RefObject } from "react"
-import { useRouter, useSearchParams } from "next/navigation"
+import { useSearchParams } from "next/navigation"
import { useQuery } from "@tanstack/react-query"
import { PublicPricingSchema, type PublicPricing, type BillingOffer } from "@alook/shared"
import { useSession } from "@/lib/auth-client"
@@ -12,7 +14,7 @@ import { useBilling } from "@/hooks/community/use-billing"
import { PublicQueryProvider, useApplicationOwner } from "@/lib/application-owner"
import { useAtom, useCreateAtom } from "@tanstack/react-store"
import { FounderPlanChangeDialog } from "@/components/community/billing/founder-plan-change-dialog"
-import { toAnalyticsCurrentPlan, toAnalyticsPlanId, trackPricingCtaClick, trackPricingView, type PricingCtaAction } from "@/lib/analytics"
+import { trackLandingCtaClicked, toAnalyticsCurrentPlan, toAnalyticsPlanId, trackPricingCtaClick, trackPricingView, type PricingCtaAction } from "@/lib/analytics"
import { PricingView } from "./pricing-view"
function PricingContent({ signedIn, sessionPending, sessionError, viewTrackedRef }: {
@@ -21,7 +23,6 @@ function PricingContent({ signedIn, sessionPending, sessionError, viewTrackedRef
sessionError: boolean
viewTrackedRef: RefObject<boolean>
}) {
- const router = useRouter()
const search = useSearchParams()
const catalog = useQuery({
queryKey: ["public-pricing"],
@@ -74,13 +75,14 @@ function PricingContent({ signedIn, sessionPending, sessionError, viewTrackedRef
})
}
if (!signedIn) {
+ trackLandingCtaClicked({ cta_name: "pricing_get_started" })
const destination = plan === "free" ? "/c/me/bots" : `/pricing?${new URLSearchParams({ plan })}`
- router.push(`/sign-in?${new URLSearchParams({ redirect: destination })}`)
+ window.location.assign(`/sign-in?${new URLSearchParams({ redirect: destination })}`)
return
}
if (plan === "free") {
if (summary?.subscription && !summary.isFounder) void billing.portal()
- else router.push("/c/me/bots")
+ else { trackLandingCtaClicked({ cta_name: "pricing_open_app" }); window.location.assign("/c/me/bots") }
return
}
const item = paymentOffer(plan)
diff --git a/src/web/src/app/privacy/page.tsx b/src/web/src/app/privacy/page.tsx
index 11df1eb54..e7f486e80 100644
--- a/src/web/src/app/privacy/page.tsx
+++ b/src/web/src/app/privacy/page.tsx
@@ -27,7 +27,7 @@ export default function PrivacyPage() {
<h1 className="mb-4 text-4xl font-semibold tracking-tight sm:text-5xl">
{PRIVACY_POLICY.title}
</h1>
- <PrivacyPolicyContent />
+ <PrivacyPolicyContent showAnalyticsChoices />
</main></>
)
}
diff --git a/src/web/src/app/templates/[id]/client.tsx b/src/web/src/app/templates/[id]/client.tsx
index c8082f860..1443590dd 100644
--- a/src/web/src/app/templates/[id]/client.tsx
+++ b/src/web/src/app/templates/[id]/client.tsx
@@ -1,6 +1,10 @@
"use client";
+/* eslint-disable @next/next/no-html-link-for-pages -- Product entrances require a new document to unload public tracking. */
+
import Link from "next/link";
+import { trackLandingCtaClicked } from "@/lib/analytics"
+
import { Check } from "lucide-react";
import { PublicLayout } from "@/components/public-layout";
import { MemberCard } from "./_components/member-card";
@@ -38,19 +42,21 @@ export function TemplateDetailClient({
Blog
</a>
{isLoggedIn ? (
- <Link
+ <a
href="/c/me"
+ onClick={() => trackLandingCtaClicked({ cta_name: "templates_open_app" })}
className="inline-flex items-center gap-2 px-4 py-2 text-xs uppercase tracking-widest font-mono border border-current transition-opacity hover:opacity-70"
>
App
- </Link>
+ </a>
) : (
- <Link
+ <a
href="/sign-in"
+ onClick={() => trackLandingCtaClicked({ cta_name: "templates_get_started" })}
className="inline-flex items-center gap-2 px-4 py-2 text-xs uppercase tracking-widest font-mono bg-foreground text-background transition-opacity hover:opacity-70"
>
Get Started
- </Link>
+ </a>
)}
</>
}
diff --git a/src/web/src/app/templates/client.tsx b/src/web/src/app/templates/client.tsx
index 7afdf903b..b8ed6ea1d 100644
--- a/src/web/src/app/templates/client.tsx
+++ b/src/web/src/app/templates/client.tsx
@@ -1,5 +1,9 @@
"use client";
+/* eslint-disable @next/next/no-html-link-for-pages -- Product entrances require a new document to unload public tracking. */
+
+import { trackLandingCtaClicked } from "@/lib/analytics"
+
import { useAtom, useCreateAtom } from "@tanstack/react-store";
import { useEffect, useRef } from "react";
import Link from "next/link";
@@ -55,19 +59,21 @@ export function TemplatesClient({
Blog
</a>
{isLoggedIn ? (
- <Link
+ <a
href="/c/me"
+ onClick={() => trackLandingCtaClicked({ cta_name: "templates_open_app" })}
className="inline-flex items-center gap-2 px-4 py-2 text-xs uppercase tracking-widest font-mono border border-current transition-opacity hover:opacity-70"
>
App
- </Link>
+ </a>
) : (
- <Link
+ <a
href="/sign-in"
+ onClick={() => trackLandingCtaClicked({ cta_name: "templates_get_started" })}
className="inline-flex items-center gap-2 px-4 py-2 text-xs uppercase tracking-widest font-mono bg-foreground text-background transition-opacity hover:opacity-70"
>
Get Started
- </Link>
+ </a>
)}
</>
}
diff --git a/src/web/src/components/analytics-consent.dom.test.tsx b/src/web/src/components/analytics-consent.dom.test.tsx
index 341c0c635..9eb471048 100644
--- a/src/web/src/components/analytics-consent.dom.test.tsx
+++ b/src/web/src/components/analytics-consent.dom.test.tsx
@@ -1,4 +1,5 @@
import { act, fireEvent, render, screen, waitFor, within } from "@/test/react-dom-harness"
+import { StrictMode } from "react"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
const platform = vi.hoisted(() => ({
@@ -6,6 +7,8 @@ const platform = vi.hoisted(() => ({
isMobile: vi.fn(() => false),
}))
+const navigation = vi.hoisted(() => ({ reload: vi.fn() }))
+
const route = vi.hoisted(() => ({ pathname: "/" }))
vi.mock("next/navigation", () => ({ usePathname: () => route.pathname }))
@@ -43,14 +46,12 @@ function successfulFetch(decision: "granted" | "denied") {
function installCookieStore() {
const store = new EventTarget()
vi.stubGlobal("cookieStore", store)
- const added = vi.spyOn(store, "addEventListener")
- const removed = vi.spyOn(store, "removeEventListener")
- const change = (changed: Array<{ name: string; value?: string }> = [], deleted: Array<{ name: string }> = []) => {
+ const change = () => {
const event = new Event("change")
- Object.assign(event, { changed, deleted })
- act(() => { store.dispatchEvent(event) })
+ Object.assign(event, { changed: [{ name: "alook_analytics_consent" }], deleted: [] })
+ act(() => store.dispatchEvent(event))
}
- return { store, added, removed, change }
+ return { change }
}
function consentCommands() {
@@ -58,6 +59,13 @@ function consentCommands() {
}
beforeEach(() => {
+ const originalWindow = window
+ navigation.reload.mockReset()
+ vi.stubGlobal("window", new Proxy(originalWindow, {
+ get: (target, key) => key === "location" ? new Proxy({}, {
+ get: (_location, field) => field === "reload" ? navigation.reload : Reflect.get(originalWindow.location, field, originalWindow.location),
+ }) : Reflect.get(target, key, target),
+ }))
route.pathname = "/"
window.history.replaceState({}, "", "/")
clearCookies()
@@ -66,6 +74,7 @@ beforeEach(() => {
window.dataLayer = []
vi.stubGlobal("cookieStore", undefined)
bootstrapGoogleAnalytics()
+ vi.stubGlobal("fetch", vi.fn(async () => new Response("{}", { status: 503 })))
})
afterEach(() => {
@@ -76,331 +85,175 @@ afterEach(() => {
})
describe("AnalyticsConsent", () => {
- it("preserves page layout while the floating banner is open and dismissed", async () => {
- vi.stubGlobal("fetch", successfulFetch("denied"))
- const layoutStyle = document.createElement("style")
- layoutStyle.textContent = `
- body { padding-bottom: 0px; }
- .hero-section, .workspace-shell { height: 100dvh; }
- `
- document.head.appendChild(layoutStyle)
- try {
- render(
- <>
- <main className="hero-section" data-testid="consent-hero" />
- <main className="workspace-shell" data-testid="consent-workspace" />
- <AnalyticsConsent />
- </>,
- )
- const banner = await screen.findByTestId(tid.analyticsConsentBanner)
- const expectPageLayout = () => {
- expect(getComputedStyle(document.body).paddingBottom).toBe("0px")
- expect(getComputedStyle(screen.getByTestId("consent-hero")).height).toBe("100dvh")
- expect(getComputedStyle(screen.getByTestId("consent-workspace")).height).toBe("100dvh")
- }
- expectPageLayout()
- fireEvent(window, new Event("resize"))
- expectPageLayout()
- fireEvent.click(within(banner).getByRole("button", { name: "Only necessary" }))
- await waitFor(() => {
- expect(screen.queryByTestId(tid.analyticsConsentBanner)).not.toBeInTheDocument()
- })
- expectPageLayout()
- } finally {
- layoutStyle.remove()
- }
- })
-
- it("loads public GTM with denied cookies and retains the first-visit banner", async () => {
- render(<AnalyticsConsent />)
- const banner = await screen.findByTestId(tid.analyticsConsentBanner)
- expect(within(banner).getByText("Cookies are your choice")).toBeVisible()
- expect(banner).toHaveTextContent("Google receives page and feature signals on our public website, even without analytics cookies. Allow analytics enables analytics cookies and other optional analytics. No ad tracking. Read our privacy details.")
- expect(within(banner).getByRole("button", { name: "Only necessary" })).toBeVisible()
- expect(within(banner).getByRole("button", { name: "Allow analytics" })).toBeVisible()
- expect(within(banner).getByTestId(tid.analyticsConsentAvatarCluster).querySelectorAll("svg"))
- .toHaveLength(3)
- expect(screen.getByTestId("google-tag-manager")).toBeInTheDocument()
- expect(screen.queryByTestId(tid.ahrefsAnalyticsFrame)).not.toBeInTheDocument()
- })
-
- it.each(["/sign-in", "/pricing"])("retains the original Native desktop banner on %s without requiring a choice", async pathname => {
- platform.isTauri.mockReturnValue(true)
+ it.each(["/", "/privacy", "/blog/public-article"])("waits for default persistence before loading GTM on public %s without a choice UI", async pathname => {
route.pathname = pathname
window.history.replaceState({}, "", pathname)
- const fetcher = vi.fn()
+ let finish!: (response: Response) => void
+ const fetcher = vi.fn(() => new Promise<Response>(resolve => { finish = resolve }))
vi.stubGlobal("fetch", fetcher)
-
- render(<AnalyticsConsent />)
-
- const banner = await screen.findByTestId(tid.analyticsConsentBanner)
- expect(within(banner).getByText("Analytics, only if you want")).toBeVisible()
- expect(banner).toHaveTextContent("Optional analytics help us understand which parts of Alook are useful. No ad tracking. Read our privacy details.")
- expect(banner).not.toHaveTextContent("Google receives page and feature signals")
- expect(screen.queryByTestId("google-tag-manager")).not.toBeInTheDocument()
- expect(document.cookie).toBe("")
- expect(fetcher).not.toHaveBeenCalled()
- })
-
- it("hides the first-visit banner in native mobile clients", async () => {
- platform.isTauri.mockReturnValue(true)
- platform.isMobile.mockReturnValue(true)
-
- render(<AnalyticsConsent />)
-
- await waitFor(() => {
- expect(platform.isMobile).toHaveBeenCalled()
- })
+ render(<StrictMode><AnalyticsConsent /></StrictMode>)
+ await waitFor(() => expect(fetcher).toHaveBeenCalledOnce())
expect(screen.queryByTestId(tid.analyticsConsentBanner)).not.toBeInTheDocument()
+ expect(screen.queryByTestId(tid.analyticsPreferenceControl)).not.toBeInTheDocument()
expect(screen.queryByTestId("google-tag-manager")).not.toBeInTheDocument()
+ expect(screen.getByTestId(tid.ahrefsAnalyticsFrame)).toHaveAttribute("sandbox", "allow-scripts")
+ expect(consentCommands().at(-1)?.[2]).toEqual(expect.objectContaining({ analytics_storage: "granted", ad_storage: "denied" }))
+ await act(async () => {
+ document.cookie = "alook_analytics_consent=v1.granted; Path=/"
+ finish(new Response(JSON.stringify({ decision: "granted" })))
+ })
+ await screen.findByTestId("google-tag-manager")
})
- it("keeps public GTM and enables Ahrefs after the API confirms a grant", async () => {
- const fetcher = successfulFetch("granted")
- vi.stubGlobal("fetch", fetcher)
- render(<AnalyticsConsent />)
- const banner = await screen.findByTestId(tid.analyticsConsentBanner)
-
- fireEvent.click(within(banner).getByRole("button", { name: "Allow analytics" }))
-
- expect(await screen.findByTestId("google-tag-manager")).toHaveAttribute(
- "data-gtm-id",
- "GTM-56VHCCQZ",
- )
- expect(await screen.findByTestId(tid.ahrefsAnalyticsFrame)).toHaveAttribute("sandbox", "allow-scripts")
- expect(screen.queryByTestId(tid.analyticsConsentBanner)).not.toBeInTheDocument()
- expect(Array.from(window.dataLayer!.at(-1) as IArguments)).toEqual([
- "consent",
- "update",
- expect.objectContaining({ analytics_storage: "granted", ad_storage: "denied" }),
- ])
- expect(fetcher).toHaveBeenCalledWith(
- "/api/privacy/analytics-consent",
- expect.objectContaining({
- method: "POST",
- credentials: "same-origin",
- body: JSON.stringify({ decision: "granted" }),
- }),
- )
- })
-
- it("stores a denial while retaining public GTM and excluding Ahrefs", async () => {
- vi.stubGlobal("fetch", successfulFetch("denied"))
+ it("honors a previous Privacy denial without resaving it", async () => {
+ document.cookie = "alook_analytics_consent=v1.denied; Path=/"
render(<AnalyticsConsent />)
- const banner = await screen.findByTestId(tid.analyticsConsentBanner)
-
- fireEvent.click(within(banner).getByRole("button", { name: "Only necessary" }))
-
- await waitFor(() => {
- expect(screen.queryByTestId(tid.analyticsConsentBanner)).not.toBeInTheDocument()
- })
expect(screen.getByTestId("google-tag-manager")).toBeInTheDocument()
expect(screen.queryByTestId(tid.ahrefsAnalyticsFrame)).not.toBeInTheDocument()
+ expect(fetch).not.toHaveBeenCalled()
+ expect(consentCommands().at(-1)?.[2]).toEqual(expect.objectContaining({ analytics_storage: "denied" }))
})
- it("honors stored grant and denial choices on mount", async () => {
- document.cookie = "alook_analytics_consent=v1.granted; Path=/"
- const granted = render(<AnalyticsConsent />)
- expect(await screen.findByTestId("google-tag-manager")).toBeInTheDocument()
+ it("keeps public tracking and page layout when grant persistence fails", async () => {
+ render(<><main style={{ height: "100dvh" }} data-testid="consent-page" /><AnalyticsConsent /></>)
+ await waitFor(() => expect(fetch).toHaveBeenCalledOnce())
expect(screen.queryByTestId(tid.analyticsConsentBanner)).not.toBeInTheDocument()
- const home = screen.getByTestId(tid.ahrefsAnalyticsFrame)
- for (const pathname of ["/c", "/c/me", "/c/channels/private/channel", "/sign-in", "/auth/callback"]) {
- route.pathname = pathname
- granted.rerender(<AnalyticsConsent />)
- expect(screen.queryByTestId(tid.ahrefsAnalyticsFrame)).not.toBeInTheDocument()
- expect(screen.queryByTestId("google-tag-manager")).not.toBeInTheDocument()
- }
- route.pathname = "/pricing"
- granted.rerender(<AnalyticsConsent />)
- expect(screen.getByTestId(tid.ahrefsAnalyticsFrame)).not.toBe(home)
- expect(screen.getByTestId(tid.ahrefsAnalyticsFrame).getAttribute("srcdoc"))
- .toContain(`data-page-location="${window.location.origin}/pricing"`)
- document.cookie = "alook_analytics_consent=v1.denied; Path=/"
- fireEvent(window, new CustomEvent("alook:analytics-consent-change", { detail: "denied" }))
- await waitFor(() => expect(screen.queryByTestId(tid.ahrefsAnalyticsFrame)).not.toBeInTheDocument())
- granted.unmount()
+ expect(screen.queryByRole("alert")).not.toBeInTheDocument()
+ expect(await screen.findByTestId("google-tag-manager")).toBeInTheDocument()
+ 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)
+ })
- clearCookies()
- document.cookie = "alook_analytics_consent=v1.denied; Path=/"
+ it("does not resave an existing grant", async () => {
+ document.cookie = "alook_analytics_consent=v1.granted; Path=/"
render(<AnalyticsConsent />)
- await waitFor(() => {
- expect(screen.queryByTestId(tid.analyticsConsentBanner)).not.toBeInTheDocument()
- })
- expect(screen.getByTestId("google-tag-manager")).toBeInTheDocument()
+ expect(await screen.findByTestId(tid.ahrefsAnalyticsFrame)).toBeInTheDocument()
+ expect(fetch).not.toHaveBeenCalled()
})
- it("keeps the banner open and explains a save failure", async () => {
- vi.stubGlobal("fetch", vi.fn(async () => new Response(
- JSON.stringify({ error: "unavailable" }),
- { status: 503, headers: { "Content-Type": "application/json" } },
- )))
+ it.each(["/c", "/c/me", "/c/channels/private/channel", "/sign-in"])("does not grant or load analytics directly on %s", async pathname => {
+ route.pathname = pathname
+ window.history.replaceState({}, "", pathname)
+ clearCookies()
+ bootstrapGoogleAnalytics()
render(<AnalyticsConsent />)
- const banner = await screen.findByTestId(tid.analyticsConsentBanner)
- fireEvent.click(within(banner).getByRole("button", { name: "Allow analytics" }))
- expect(await within(banner).findByRole("alert")).toHaveTextContent("Couldn’t save this choice")
- expect(screen.getByTestId("google-tag-manager")).toBeInTheDocument()
+ expect(screen.queryByTestId(tid.analyticsConsentBanner)).not.toBeInTheDocument()
+ expect(screen.queryByTestId("google-tag-manager")).not.toBeInTheDocument()
expect(screen.queryByTestId(tid.ahrefsAnalyticsFrame)).not.toBeInTheDocument()
+ expect(fetch).not.toHaveBeenCalled()
+ expect(document.cookie).toBe("")
})
- it("changes a stored preference from the Privacy control", async () => {
- document.cookie = "alook_analytics_consent=v1.denied; Path=/"
- vi.stubGlobal("fetch", successfulFetch("granted"))
- render(
- <>
- <AnalyticsConsent />
- <AnalyticsPreferenceControl />
- </>,
- )
- const control = await screen.findByTestId(tid.analyticsPreferenceControl)
- expect(within(control).getByText(/Analytics cookies denied/u)).toBeVisible()
-
- fireEvent.click(within(control).getByRole("button", { name: "Allow analytics" }))
-
- expect(await within(control).findByText(/Analytics cookies allowed/u)).toBeVisible()
- expect(await screen.findByTestId("google-tag-manager")).toBeInTheDocument()
- expect(Array.from(window.dataLayer!.at(-1) as IArguments)).toEqual([
- "consent",
- "update",
- expect.objectContaining({ analytics_storage: "granted", ad_storage: "denied" }),
- ])
- })
-
- it("blocks already-loaded GA4 immediately on private history changes", async () => {
+ it("removes public analytics and blocks Google synchronously when entering the product", async () => {
document.cookie = "alook_analytics_consent=v1.granted; Path=/"
const view = render(<AnalyticsConsent />)
- await screen.findByTestId("google-tag-manager")
- expect(Reflect.get(window, "ga-disable-G-STBCL8F4ZY")).toBe(false)
+ await screen.findByTestId(tid.ahrefsAnalyticsFrame)
window.history.pushState({}, "", "/c/me?private=canary")
expect(Reflect.get(window, "ga-disable-G-STBCL8F4ZY")).toBe(true)
- window.history.replaceState({}, "", "/pricing")
- expect(Reflect.get(window, "ga-disable-G-STBCL8F4ZY")).toBe(false)
- document.cookie = "alook_analytics_consent=v1.denied; Path=/"
- expect(Reflect.get(window, "ga-disable-G-STBCL8F4ZY")).toBe(false)
- view.unmount()
- window.history.replaceState({}, "", "/")
+ route.pathname = "/c/me"
+ view.rerender(<AnalyticsConsent />)
+ expect(screen.queryByTestId("google-tag-manager")).not.toBeInTheDocument()
+ expect(screen.queryByTestId(tid.ahrefsAnalyticsFrame)).not.toBeInTheDocument()
+ expect(fetch).not.toHaveBeenCalled()
})
- it.each(["/blog", "/blog/public-article", "/pricing", "/contact"])("keeps %s measured", async pathname => {
- route.pathname = pathname
- window.history.replaceState({}, "", `${pathname}?private=canary`)
+ it.each(["focus", "pageshow", "visibilitychange"])("rereads an explicit denial on %s and disables optional public tracking", async type => {
document.cookie = "alook_analytics_consent=v1.granted; Path=/"
- render(<AnalyticsConsent />)
- expect(await screen.findByTestId("google-tag-manager")).toBeInTheDocument()
- expect(screen.getByTestId(tid.ahrefsAnalyticsFrame).getAttribute("srcdoc"))
- .toContain(`data-page-location="${window.location.origin}${pathname}"`)
- })
-
- it("registers the root CookieStore listener before the mount reread and keeps one Google update owner", async () => {
+ const view = render(<AnalyticsConsent />)
+ await screen.findByTestId(tid.ahrefsAnalyticsFrame)
document.cookie = "alook_analytics_consent=v1.denied; Path=/"
- const cookie = installCookieStore()
- cookie.added.mockImplementation((type, listener, options) => {
- document.cookie = "alook_analytics_consent=v1.granted; Path=/"
- EventTarget.prototype.addEventListener.call(cookie.store, type, listener, options)
- })
- render(<><AnalyticsConsent /><AnalyticsPreferenceControl /></>)
- expect(await screen.findByTestId(tid.ahrefsAnalyticsFrame)).toBeInTheDocument()
- expect(cookie.added).toHaveBeenCalledOnce()
- expect(consentCommands()).toEqual([
- ["consent", "default", expect.objectContaining({ analytics_storage: "denied" })],
- ["consent", "update", expect.objectContaining({ analytics_storage: "granted" })],
- ])
+ if (type === "visibilitychange") {
+ vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible")
+ fireEvent(document, new Event(type))
+ } else fireEvent(window, new Event(type))
+ expect(screen.queryByTestId(tid.ahrefsAnalyticsFrame)).not.toBeInTheDocument()
+ expect(consentCommands().at(-1)?.[2]).toEqual(expect.objectContaining({ analytics_storage: "denied" }))
+ expect(fetch).not.toHaveBeenCalled()
+ view.unmount()
+ vi.restoreAllMocks()
})
- it("rereads changed and deleted Cookies, rejects late values and deduplicates the original API event", async () => {
- const cookie = installCookieStore()
- const wake = vi.fn()
- window.addEventListener("alook:analytics-consent-change", wake)
- const view = render(<><AnalyticsConsent /><AnalyticsPreferenceControl /></>)
- await screen.findByTestId(tid.analyticsConsentBanner)
- wake.mockClear()
- const initial = consentCommands().length
- cookie.change([{ name: "alook_analytics_consent_proof", value: "ignored" }])
- expect(consentCommands()).toHaveLength(initial)
+ it("keeps the existing Privacy choices usable and preserves denial on reload", async () => {
+ route.pathname = "/privacy"
+ window.history.replaceState({}, "", "/privacy")
document.cookie = "alook_analytics_consent=v1.granted; Path=/"
- cookie.change([{ name: "alook_analytics_consent", value: "v1.denied" }])
- await screen.findByTestId(tid.ahrefsAnalyticsFrame)
- expect(screen.getByTestId(tid.analyticsPreferenceControl)).toHaveTextContent("Analytics cookies allowed")
- expect(wake).toHaveBeenCalledOnce()
- fireEvent(window, new CustomEvent("alook:analytics-consent-change", { detail: "granted" }))
- cookie.change([{ name: "alook_analytics_consent", value: "v1.granted" }])
- expect(consentCommands()).toHaveLength(initial + 1)
- document.cookie = "alook_analytics_consent=v1.denied; Path=/"
- cookie.change([{ name: "alook_analytics_consent", value: "v1.granted" }])
+ vi.stubGlobal("fetch", successfulFetch("denied"))
+ const view = render(<><AnalyticsConsent /><AnalyticsPreferenceControl /></>)
+ const control = screen.getByTestId(tid.analyticsPreferenceControl)
+ expect(within(control).getByTestId(tid.analyticsConsentAvatarCluster).querySelectorAll("svg")).toHaveLength(3)
+ fireEvent.click(within(control).getByRole("button", { name: "Only necessary" }))
+ await within(control).findByText(/Analytics cookies denied/u)
+ expect(navigation.reload).toHaveBeenCalledOnce()
expect(screen.queryByTestId(tid.ahrefsAnalyticsFrame)).not.toBeInTheDocument()
- expect(screen.getByTestId("google-tag-manager")).toBeInTheDocument()
- document.cookie = "alook_analytics_consent=; Max-Age=0; Path=/"
- cookie.change([], [{ name: "alook_analytics_consent" }])
- expect(screen.getByTestId(tid.analyticsConsentBanner)).toBeInTheDocument()
- expect(screen.getByTestId(tid.analyticsPreferenceControl)).toHaveTextContent("No choice saved — analytics cookies denied")
- document.cookie = "alook_analytics_consent=v0.granted; Path=/"
- cookie.change([{ name: "alook_analytics_consent", value: "v1.granted" }])
- expect(consentCommands()).toHaveLength(initial + 3)
- expect(consentCommands().slice(initial).map(command => (command[2] as { analytics_storage: string }).analytics_storage)).toEqual(["granted", "denied", "denied"])
view.unmount()
- expect(cookie.removed).toHaveBeenCalledWith("change", cookie.added.mock.calls[0][1])
- const prior = consentCommands().length
- cookie.change([{ name: "alook_analytics_consent", value: "v1.granted" }])
- expect(consentCommands()).toHaveLength(prior)
- window.removeEventListener("alook:analytics-consent-change", wake)
+ const reload = render(<><AnalyticsConsent /><AnalyticsPreferenceControl /></>)
+ expect(screen.getByTestId(tid.analyticsPreferenceControl)).toHaveTextContent("Analytics cookies denied")
+ expect(fetch).toHaveBeenCalledOnce()
+ vi.stubGlobal("fetch", successfulFetch("granted"))
+ fireEvent.click(screen.getByRole("button", { name: "Allow analytics" }))
+ await screen.findByText(/Analytics cookies allowed/u)
+ await screen.findByTestId(tid.ahrefsAnalyticsFrame)
+ reload.unmount()
})
- it("uses the committed Cookie while JSON remains pending and preserves an eventual response error", async () => {
- const cookie = installCookieStore()
- let rejectJson!: (error: Error) => void
- const json = new Promise((_resolve, reject) => { rejectJson = reject })
- vi.stubGlobal("fetch", vi.fn(async () => {
+ it("saves an immediate Privacy denial after the pending automatic grant", async () => {
+ route.pathname = "/privacy"
+ let finish!: (response: Response) => void
+ const fetcher = vi.fn()
+ .mockImplementationOnce(() => new Promise<Response>(resolve => { finish = resolve }))
+ .mockImplementationOnce(successfulFetch("denied"))
+ vi.stubGlobal("fetch", fetcher)
+ render(<><AnalyticsConsent /><AnalyticsPreferenceControl /></>)
+ await waitFor(() => expect(fetcher).toHaveBeenCalledOnce())
+ fireEvent.click(screen.getByRole("button", { name: "Only necessary" }))
+ expect(fetcher).toHaveBeenCalledOnce()
+ await act(async () => {
document.cookie = "alook_analytics_consent=v1.granted; Path=/"
- cookie.change([{ name: "alook_analytics_consent", value: "v1.granted" }])
- return { ok: true, json: () => json }
- }))
+ finish(new Response(JSON.stringify({ decision: "granted" })))
+ })
+ await screen.findByText(/Analytics cookies denied/u)
+ expect(fetcher.mock.calls.map(call => JSON.parse(call[1].body).decision)).toEqual(["granted", "denied"])
+ expect(document.cookie).toContain("v1.denied")
+ expect(screen.queryByTestId(tid.ahrefsAnalyticsFrame)).not.toBeInTheDocument()
+ })
+
+ it("shows a Privacy save error and can retry after automatic saving fails", async () => {
+ route.pathname = "/privacy"
render(<><AnalyticsConsent /><AnalyticsPreferenceControl /></>)
- await screen.findByTestId(tid.analyticsConsentBanner)
- const control = screen.getByTestId(tid.analyticsPreferenceControl)
- fireEvent.click(within(control).getByRole("button", { name: "Allow analytics" }))
- await screen.findByTestId(tid.ahrefsAnalyticsFrame)
- expect(control).toHaveTextContent("Analytics cookies allowed")
- expect(consentCommands().at(-1)).toEqual(["consent", "update", expect.objectContaining({ analytics_storage: "granted" })])
- await act(async () => rejectJson(new Error("response unavailable")))
+ await waitFor(() => expect(fetch).toHaveBeenCalledOnce())
+ fireEvent.click(screen.getByRole("button", { name: "Only necessary" }))
expect(await screen.findByRole("alert")).toHaveTextContent("Couldn’t save this choice")
- expect(control).toHaveTextContent("Analytics cookies allowed")
- expect(screen.getByTestId(tid.ahrefsAnalyticsFrame)).toBeInTheDocument()
+ expect(navigation.reload).not.toHaveBeenCalled()
+ vi.stubGlobal("fetch", successfulFetch("denied"))
+ fireEvent.click(screen.getByRole("button", { name: "Only necessary" }))
+ await screen.findByText(/Analytics cookies denied/u)
+ expect(screen.queryByTestId(tid.ahrefsAnalyticsFrame)).not.toBeInTheDocument()
})
- it.each(["focus", "pageshow", "visibilitychange"])("rereads on %s without promising unsupported cross-page notification", async type => {
- const view = render(<AnalyticsConsent />)
- await screen.findByTestId(tid.analyticsConsentBanner)
+ it.each(["/privacy", "/blog", "/c/me"])("synchronizes another tab's denial on %s without disrupting product drafts", pathname => {
+ route.pathname = pathname
+ window.history.replaceState({}, "", pathname)
document.cookie = "alook_analytics_consent=v1.granted; Path=/"
- expect(screen.queryByTestId(tid.ahrefsAnalyticsFrame)).not.toBeInTheDocument()
- if (type === "visibilitychange") {
- vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible")
- fireEvent(document, new Event(type))
- } else fireEvent(window, new Event(type))
- await screen.findByTestId(tid.ahrefsAnalyticsFrame)
- view.unmount()
- const count = consentCommands().length
+ const cookie = installCookieStore()
+ render(<AnalyticsConsent />)
+ cookie.change()
+ expect(navigation.reload).not.toHaveBeenCalled()
document.cookie = "alook_analytics_consent=v1.denied; Path=/"
+ cookie.change()
fireEvent(window, new Event("focus"))
- fireEvent(window, new Event("pageshow"))
- fireEvent(document, new Event("visibilitychange"))
- expect(consentCommands()).toHaveLength(count)
- vi.restoreAllMocks()
+ fireEvent(window, new CustomEvent("alook:analytics-consent-change", { detail: "granted" }))
+ expect(navigation.reload).toHaveBeenCalledTimes(pathname.startsWith("/c") ? 0 : 1)
+ expect(screen.queryByTestId(tid.ahrefsAnalyticsFrame)).not.toBeInTheDocument()
})
- it("retains Native defaults, detail updates, optional gates and immediate Cookie-based disabling", async () => {
+ it("keeps the native mobile exclusion", async () => {
platform.isTauri.mockReturnValue(true)
- document.cookie = "alook_analytics_consent=v1.granted; Path=/"
- window.dataLayer = []
- const cookie = installCookieStore()
+ platform.isMobile.mockReturnValue(true)
render(<AnalyticsConsent />)
- await screen.findByTestId("google-tag-manager")
- expect(cookie.added).not.toHaveBeenCalled()
- expect(consentCommands()[0]).toEqual(["consent", "default", expect.objectContaining({ analytics_storage: "granted" })])
- document.cookie = "alook_analytics_consent=v1.denied; Path=/"
- fireEvent(window, new CustomEvent("alook:analytics-consent-change", { detail: "denied" }))
expect(screen.queryByTestId("google-tag-manager")).not.toBeInTheDocument()
expect(screen.queryByTestId(tid.ahrefsAnalyticsFrame)).not.toBeInTheDocument()
- expect(Reflect.get(window, "ga-disable-G-STBCL8F4ZY")).toBe(true)
- expect(consentCommands().at(-1)).toEqual(["consent", "update", expect.objectContaining({ analytics_storage: "denied" })])
+ expect(fetch).not.toHaveBeenCalled()
})
-
})
diff --git a/src/web/src/components/analytics-consent.tsx b/src/web/src/components/analytics-consent.tsx
index 1a9249ac1..26cb71f78 100644
--- a/src/web/src/components/analytics-consent.tsx
+++ b/src/web/src/components/analytics-consent.tsx
@@ -5,7 +5,6 @@ import { GoogleTagManager } from "@next/third-parties/google"
import { isMobile, isTauri } from "@alook/shared"
import { usePathname } from "next/navigation"
import { useCallback, useEffect, useRef } from "react"
-import { GeneratedAvatar } from "@/components/avatar"
import {
ANALYTICS_CONSENT_CHANGE_EVENT,
ANALYTICS_CONSENT_COOKIE,
@@ -16,12 +15,21 @@ import {
readAnalyticsConsent,
type AnalyticsConsentDecision,
} from "@/lib/analytics-consent"
-import { tid } from "@/lib/community/testids"
+import { GeneratedAvatar } from "@/components/avatar"
import styles from "./analytics-consent.module.css"
+import { tid } from "@/lib/community/testids"
const GTM_ID = "GTM-56VHCCQZ"
const GA_DISABLE = "ga-disable-G-STBCL8F4ZY"
+const reloadingDocuments = new WeakSet<object>()
+
+function reloadAnalyticsDocument() {
+ if (reloadingDocuments.has(window)) return
+ reloadingDocuments.add(window)
+ window.location.reload()
+}
+
function useStoredAnalyticsConsent(syncGoogleConsent = false) {
const [ready, setReady] = useAtom(useCreateAtom(false))
const [decision, setDecision] = useAtom(useCreateAtom<AnalyticsConsentDecision | null>(null))
@@ -34,9 +42,13 @@ function useStoredAnalyticsConsent(syncGoogleConsent = false) {
const next = readAnalyticsConsent()
const changed = next !== decisionRef.current
if (syncGoogleConsent && (changed || initial)) {
- if (!native) applyGoogleConsent(next ?? "denied")
+ if (!native) applyGoogleConsent(isPublicAnalyticsPath(window.location.pathname) ? next ?? "granted" : "denied")
else if (initial && next === "granted") applyGoogleConsent(next, "default")
}
+ if (syncGoogleConsent && !native && !initial && next === "denied"
+ && decisionRef.current === "granted" && isPublicAnalyticsPath(window.location.pathname)) {
+ reloadAnalyticsDocument()
+ }
decisionRef.current = next
setDecision(next)
if (syncGoogleConsent && announce && changed) announceAnalyticsConsent(next ?? "denied")
@@ -103,6 +115,7 @@ function useAnalyticsConsentChoice() {
try {
await persistAnalyticsConsent(decision)
announceAnalyticsConsent(decision)
+ if (!isTauri()) reloadAnalyticsDocument()
} catch {
setError(true)
} finally {
@@ -172,9 +185,18 @@ function ConsentButtons({
export function AnalyticsConsent() {
const pathname = usePathname()
const { ready, decision, nativeMobile } = useStoredAnalyticsConsent(true)
- const { choose, saving, error } = useAnalyticsConsentChoice()
- const allowed = ready && decision === "granted" && !!pathname && isPublicAnalyticsPath(pathname)
+ const defaultStarted = useRef(false)
+ const [defaultSettled, setDefaultSettled] = useAtom(useCreateAtom(false))
+
+ useEffect(() => {
+ if (!ready || nativeMobile || decision !== null || defaultStarted.current) return
+ if (!pathname || !isPublicAnalyticsPath(pathname)) return
+ defaultStarted.current = true
+ void persistAnalyticsConsent("granted").then(() => announceAnalyticsConsent("granted")).catch(() => {}).finally(() => setDefaultSettled(true))
+ }, [ready, nativeMobile, decision, pathname, setDefaultSettled])
+
const googleAllowed = ready && !!pathname && isPublicAnalyticsPath(pathname) && (!isTauri() || decision === "granted")
+ const allowed = googleAllowed && (isTauri() ? decision === "granted" : decision !== "denied")
useEffect(() => {
if (!isTauri()) return
@@ -194,7 +216,7 @@ export function AnalyticsConsent() {
return (
<>
- {googleAllowed ? <GoogleTagManager gtmId={GTM_ID} /> : null}
+ {googleAllowed && (decision !== null || defaultSettled) ? <GoogleTagManager gtmId={GTM_ID} /> : null}
{allowed ? (
<iframe
key={pathname}
@@ -206,44 +228,9 @@ export function AnalyticsConsent() {
srcDoc={`<title>Alook</title><script async src="https://analytics.ahrefs.com/analytics.js" data-key="Td2Wr/poHD0pDEV30W9xMw" data-page-location="${new URL(pathname!, window.location.origin).href.replace(/"/g, "%22")}"></script>`}
/>
) : null}
- {ready && !nativeMobile && decision === null ? (
- <section
- aria-label="Analytics choices"
- className={styles.banner}
- data-testid={tid.analyticsConsentBanner}
- >
- <div className={styles.bannerContent}>
- <div className={styles.copy}>
- <p className={styles.eyebrow}>PRIVACY · OPTIONAL SIGNAL</p>
- <h2 className={styles.headline}>
- {isTauri() ? "Analytics, only if you want" : "Cookies are your choice"}
- </h2>
- <p className={styles.description}>
- {isTauri()
- ? "Optional analytics help us understand which parts of Alook are useful. "
- : "Google receives page and feature signals on our public website, even without analytics cookies. Allow analytics enables analytics cookies and other optional analytics. "}
- No ad tracking. Read our{" "}
- <a
- href="/privacy#analytics-choices"
- className={styles.privacyLink}
- >
- privacy details
- </a>{"."}
- </p>
- {error ? (
- <p className={styles.error} role="alert">
- Couldn’t save this choice. Try again.
- </p>
- ) : null}
- </div>
- <ConsentButtons saving={saving} onChoose={choose} />
- </div>
- </section>
- ) : null}
</>
)
}
-
export function AnalyticsPreferenceControl() {
const { ready, decision } = useStoredAnalyticsConsent()
const { choose, saving, error } = useAnalyticsConsentChoice()
@@ -251,7 +238,7 @@ export function AnalyticsPreferenceControl() {
? "Analytics cookies allowed"
: decision === "denied"
? "Analytics cookies denied"
- : "No choice saved — analytics cookies denied"
+ : "Analytics cookies allowed by default"
return (
<section
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.ts
index 90b951982..2b464d9b1 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
@@ -15,6 +15,7 @@ function render(node: React.ReactNode) {
const mocks = vi.hoisted(() => ({
pathname: "/c/me/machines",
complete: vi.fn(),
+ capture: vi.fn(async () => {}),
navigate: vi.fn(),
initialize: vi.fn(),
recoverHarness: vi.fn(),
@@ -27,6 +28,7 @@ const mocks = vi.hoisted(() => ({
} as Record<string, unknown>,
}))
+vi.mock("@/lib/product-analytics", () => ({ captureProductAnalytics: mocks.capture }))
vi.mock("next/navigation", () => ({
usePathname: () => mocks.pathname,
}))
@@ -95,6 +97,7 @@ describe("CommunityOnboardingForm room navigation", () => {
harness: "codex",
identity: "work",
}
+ mocks.capture.mockReset().mockResolvedValue(undefined)
mocks.complete.mockClear()
mocks.navigate.mockClear()
mocks.recoverHarness.mockClear()
@@ -121,7 +124,8 @@ describe("CommunityOnboardingForm room navigation", () => {
}))
fireEvent.click(screen.getByTestId("onboarding-status-dialog"))
- expect(mocks.navigate).toHaveBeenCalledWith("server-1", "channel-1")
+ await waitFor(() => expect(mocks.navigate).toHaveBeenCalledWith("server-1", "channel-1"))
+ expect(mocks.capture).toHaveBeenCalledWith({ event: "onboarding_enter_clicked", serverId: "server-1" })
expect(mocks.complete).not.toHaveBeenCalled()
mocks.pathname = "/c/channels/server-1/channel-1"
@@ -129,6 +133,16 @@ describe("CommunityOnboardingForm room navigation", () => {
expect(mocks.complete).toHaveBeenCalledTimes(1)
})
+ it("counts Enter even when the shell cannot navigate to the room", async () => {
+ render(createElement(CommunityOnboardingForm))
+ await waitFor(() => expect(screen.getByTestId("onboarding-status-dialog")).toHaveAttribute("data-status", "success"))
+ owner.runtime.ui.setState(state => ({ ...state, uiHandlers: { ...state.uiHandlers, navigate: undefined } }))
+ fireEvent.click(screen.getByTestId("onboarding-status-dialog"))
+ await waitFor(() => expect(mocks.capture).toHaveBeenCalledWith({ event: "onboarding_enter_clicked", serverId: "server-1" }))
+ expect(mocks.navigate).not.toHaveBeenCalled()
+ expect(mocks.complete).not.toHaveBeenCalled()
+ })
+
it("clears the local harness choice when recovering from the machine limit", async () => {
mocks.state = { status: "active", stage: "harness" }
const rendered = render(createElement(CommunityOnboardingForm))
diff --git a/src/web/src/components/community/onboarding/community-onboarding-form.tsx b/src/web/src/components/community/onboarding/community-onboarding-form.tsx
index 67f3000f3..4007f0afa 100644
--- a/src/web/src/components/community/onboarding/community-onboarding-form.tsx
+++ b/src/web/src/components/community/onboarding/community-onboarding-form.tsx
@@ -19,6 +19,7 @@ import {
ONBOARDING_HARNESSES,
ONBOARDING_IDENTITIES,
} from "./onboarding-form-options"
+import { captureProductAnalytics } from "@/lib/product-analytics"
import { initializeCommunityOnboarding } from "./initialize-community-onboarding"
import { tid } from "@/lib/community/testids"
import { useCurrentUser } from "@/contexts/community/current-user"
@@ -238,13 +239,16 @@ export function CommunityOnboardingForm() {
: "Follow along as your room comes together."
}
onRetry={() => void runInitialization()}
- onContinue={() => {
+ onContinue={async () => {
if (!initializationResult) return
const destination = `/c/channels/${initializationResult.serverId}/${initializationResult.publicChannelId}`
- const navigate = communityRuntime.ui.get().uiHandlers.navigate
- if (!navigate) return
const assert = source.capture()
assert()
+ await captureProductAnalytics({ event: "onboarding_enter_clicked", serverId: initializationResult.serverId })
+ if (!communityRuntime.lifecycle.get().active) return
+ try { assert() } catch { return }
+ const navigate = communityRuntime.ui.get().uiHandlers.navigate
+ if (!navigate) return
updateCommunityOnboardingInitialization(communityRuntime, (current) => ({ ...current, pendingDestination: destination }))
navigate(initializationResult.serverId, initializationResult.publicChannelId)
}}
diff --git a/src/web/src/components/community/onboarding/onboarding-preview-flow.test.ts b/src/web/src/components/community/onboarding/onboarding-preview-flow.test.ts
index b86214c49..450048e43 100644
--- a/src/web/src/components/community/onboarding/onboarding-preview-flow.test.ts
+++ b/src/web/src/components/community/onboarding/onboarding-preview-flow.test.ts
@@ -92,7 +92,7 @@ describe("onboarding preview flow", () => {
it("keeps onboarding mounted until shell navigation commits the new room", () => {
expect(onboardingFormSource).toMatch(
- /onContinue=\{\(\) => \{[\s\S]*?pendingDestination: destination[\s\S]*?navigate\(initializationResult\.serverId, initializationResult\.publicChannelId\)/,
+ /onContinue=\{async \(\) => \{[\s\S]*?pendingDestination: destination[\s\S]*?navigate\(initializationResult\.serverId, initializationResult\.publicChannelId\)/,
)
expect(onboardingFormSource).toMatch(
/const pendingDestination = protocol\?\.pendingDestination[\s\S]*?pathname !== pendingDestination[\s\S]*?completeCommunityOnboarding\(communityRuntime\)/,
diff --git a/src/web/src/components/home/hero-section.tsx b/src/web/src/components/home/hero-section.tsx
index 64550091e..9c175082a 100644
--- a/src/web/src/components/home/hero-section.tsx
+++ b/src/web/src/components/home/hero-section.tsx
@@ -1,5 +1,7 @@
"use client";
+/* eslint-disable @next/next/no-html-link-for-pages -- Product entrances require a new document to unload public tracking. */
+
import { useAtom, useCreateAtom } from "@tanstack/react-store";
import { type CSSProperties, type ReactNode } from "react";
import Link from "next/link";
@@ -268,7 +270,7 @@ export function HeroSection({
OPEN SOURCE
</a> */}
{isLoggedIn ? (
- <Link
+ <a
href="/c/me"
onClick={() => trackLandingCtaClicked({ cta_name: "open_app" })}
className={`inline-flex items-center gap-2 transition-all duration-200 hover:opacity-80 ${ctaSizingClassName}`}
@@ -285,7 +287,7 @@ export function HeroSection({
<line x1="15" y1="12" x2="3" y2="12" />
</svg>
{primaryCtaLabel ?? "OPEN APP"}
- </Link>
+ </a>
) : (
<a
href="/sign-in"
diff --git a/src/web/src/components/home/landing-page-funnel.dom.test.ts b/src/web/src/components/home/landing-page-funnel.dom.test.ts
new file mode 100644
index 000000000..0427291bc
--- /dev/null
+++ b/src/web/src/components/home/landing-page-funnel.dom.test.ts
@@ -0,0 +1,32 @@
+import { createElement, type ReactNode } from "react"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { fireEvent, render, screen } from "@/test/react-dom-harness"
+const mocks = vi.hoisted(() => ({ capture: vi.fn() }))
+vi.mock("@/lib/analytics", () => ({ trackLandingCtaClicked: mocks.capture }))
+vi.mock("./landing-page.module.css", () => ({ default: new Proxy({}, { get: (_target, key) => String(key) }) }))
+vi.mock("./hero-section", () => ({ HeroSection: () => null }))
+vi.mock("./hero-avatar-swarm", () => ({ HeroAvatarSwarm: () => null }))
+vi.mock("./homepage-faq", () => ({ HomepageFaq: () => null }))
+vi.mock("./landing-reach-motion", () => ({ LandingReachMotion: () => null }))
+vi.mock("./marketing-nav", () => ({ MarketingNav: () => null }))
+vi.mock("./landing-shell-motion", () => ({ LandingShellMotion: () => null }))
+vi.mock("./landing-footer", () => ({ LandingFooter: () => null }))
+vi.mock("@/components/community/social/profile-card", () => ({ ProfileCard: () => null }))
+vi.mock("@/stores/community/profile-preview", () => ({ CommunityPreviewProfileOwner: ({ children }: { children: ReactNode }) => children }))
+import { LandingPage } from "./landing-page"
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ vi.stubGlobal("ResizeObserver", class { observe() {} unobserve() {} disconnect() {} })
+})
+afterEach(() => vi.unstubAllGlobals())
+describe("landing closing funnel entrance", () => {
+ it.each([false, true])("captures the actual closing click for signed-in=%s before document navigation", isLoggedIn => {
+ render(createElement(LandingPage, { isLoggedIn }))
+ const anchor = screen.getByTestId("landing-closing-open")
+ expect(anchor).toHaveAttribute("href", isLoggedIn ? "/c/me" : "/sign-in")
+ anchor.addEventListener("click", event => event.preventDefault())
+ fireEvent.click(anchor)
+ expect(mocks.capture).toHaveBeenCalledWith({ cta_name: isLoggedIn ? "closing_open_app" : "closing_get_started" })
+ })
+})
diff --git a/src/web/src/components/home/landing-page.tsx b/src/web/src/components/home/landing-page.tsx
index 357c2de1e..7e0fe872c 100644
--- a/src/web/src/components/home/landing-page.tsx
+++ b/src/web/src/components/home/landing-page.tsx
@@ -1,7 +1,6 @@
"use client"
import Image from "next/image"
-import Link from "next/link"
import { useEffect, useRef, type PointerEvent as ReactPointerEvent } from "react"
import { LANDING_HUMAN_AVATARS } from "./landing-human-avatars"
import { GeneratedAvatar } from "@/components/avatar"
@@ -33,14 +32,14 @@ function SectionCta({ isLoggedIn, section, children }: {
children: React.ReactNode
}) {
return (
- <Link
+ <a
href={isLoggedIn ? "/c/me" : "/sign-in"}
className={styles.sectionCta}
data-testid={`landing-section-cta-${section}`}
onClick={() => trackLandingCtaClicked({ cta_name: `${section}_${isLoggedIn ? "open_app" : "get_started"}` })}
>
{children}
- </Link>
+ </a>
)
}
@@ -387,14 +386,15 @@ export function LandingPage({ isLoggedIn }: { isLoggedIn: boolean }) {
)}
</span>
))}
- <Link
+ <a
href={isLoggedIn ? "/c/me" : "/sign-in"}
className={styles.closingAction}
data-testid="landing-closing-open"
+ onClick={() => trackLandingCtaClicked({ cta_name: isLoggedIn ? "closing_open_app" : "closing_get_started" })}
>
{isLoggedIn ? LANDING_HERO.loggedInCta : LANDING_HERO.loggedOutCta}{" "}
<span aria-hidden>↗</span>
- </Link>
+ </a>
</div>
</div>
</section>
diff --git a/src/web/src/components/home/marketing-nav.tsx b/src/web/src/components/home/marketing-nav.tsx
index 1d315f3a4..f36f4b8e3 100644
--- a/src/web/src/components/home/marketing-nav.tsx
+++ b/src/web/src/components/home/marketing-nav.tsx
@@ -1,5 +1,9 @@
"use client";
+/* eslint-disable @next/next/no-html-link-for-pages -- Product entrances require a new document to unload public tracking. */
+
+import { trackLandingCtaClicked } from "@/lib/analytics"
+
import { useAtom, useCreateAtom } from "@tanstack/react-store";
import Image from "next/image";
import Link from "next/link";
@@ -165,8 +169,9 @@ export function MarketingNav({
</details>
)}
{isLoggedIn ? (
- <Link
+ <a
href="/c/me"
+ onClick={() => trackLandingCtaClicked({ cta_name: "public_nav_open_app" })}
className="inline-flex items-center gap-2 px-4 py-2 text-xs uppercase tracking-widest transition-opacity duration-150 hover:opacity-70"
style={{
fontFamily: "var(--font-mono)",
@@ -188,10 +193,11 @@ export function MarketingNav({
>
<path d="M5 12h14M12 5l7 7-7 7" />
</svg>
- </Link>
+ </a>
) : (
<a
href="/sign-in"
+ onClick={() => trackLandingCtaClicked({ cta_name: "public_nav_get_started" })}
className="inline-flex items-center gap-2 px-4 py-2 text-xs uppercase tracking-widest transition-opacity duration-150 hover:opacity-70"
style={{
fontFamily: "var(--font-mono)",
diff --git a/src/web/src/components/privacy/privacy-policy-content.test.ts b/src/web/src/components/privacy/privacy-policy-content.test.ts
index 4c3b1e735..61f50f9b3 100644
--- a/src/web/src/components/privacy/privacy-policy-content.test.ts
+++ b/src/web/src/components/privacy/privacy-policy-content.test.ts
@@ -22,17 +22,21 @@ describe("shared Privacy policy", () => {
expect(html).toContain("even without analytics cookies")
expect(html).toContain("other optional analytics")
expect(html).toContain("180 days")
+ expect(html).toContain("optional analytics cookies by default")
expect(html).toContain("Google still receives signals without analytics cookies")
expect(html).not.toContain("keeps Google Tag Manager and")
expect(html).not.toContain("collected only after")
})
- it("places analytics preferences after the policy content", () => {
- const html = renderToStaticMarkup(createElement(PrivacyPolicyContent))
+ it("places analytics preferences after the policy content only when enabled", () => {
+ const html = renderToStaticMarkup(createElement(PrivacyPolicyContent, { showAnalyticsChoices: true }))
expect(html.indexOf("Analytics choices")).toBeGreaterThan(html.indexOf("Contact Us"))
expect(html).toContain('<div class="mt-12"><section id="analytics-choices"')
- expect(html).toContain("using the preference control below at any time")
+ expect(html).toContain("using the preference control on the")
+ expect(html).toContain('href="/privacy#analytics-choices"')
+ expect(html).toContain("Other optional analytics follow the same choice")
+ expect(renderToStaticMarkup(createElement(PrivacyPolicyContent))).not.toContain("Analytics choices")
})
it("is the body source for both public and Settings entry points", () => {
diff --git a/src/web/src/components/privacy/privacy-policy-content.tsx b/src/web/src/components/privacy/privacy-policy-content.tsx
index e6e34d54b..27611c181 100644
--- a/src/web/src/components/privacy/privacy-policy-content.tsx
+++ b/src/web/src/components/privacy/privacy-policy-content.tsx
@@ -10,7 +10,7 @@ export const PRIVACY_POLICY = {
const linkClass =
"underline decoration-foreground/30 underline-offset-3 transition-colors hover:decoration-foreground/60"
-export function PrivacyPolicyContent({ className }: { className?: string }) {
+export function PrivacyPolicyContent({ className, showAnalyticsChoices = false }: { className?: string; showAnalyticsChoices?: boolean }) {
return (
<div className={cn(className)} data-privacy-policy={PRIVACY_POLICY.lastUpdated}>
<p className="mb-12 text-sm text-muted-foreground">
@@ -71,11 +71,11 @@ export function PrivacyPolicyContent({ className }: { className?: string }) {
<h4 className="mt-6 mb-2 text-base font-medium">Tracking Technologies and Cookies</h4>
<p className="text-foreground/80">
We use necessary cookies to provide sign-in, security, and saved preferences. We use
- optional analytics cookies only after You allow them. Your analytics choice is saved
- in a first-party cookie for 180 days and can be changed using the preference control
- below at any time. Choosing only necessary cookies denies analytics cookies;
+ optional analytics cookies by default. Your analytics choice is saved in a first-party
+ cookie for 180 days and can be changed using the preference control on the{" "}
+ <a href="/privacy#analytics-choices" className={linkClass}>Privacy page</a> at any time. Choosing only necessary cookies denies analytics cookies;
Google still receives signals without analytics cookies on our public website and
- Blog. Other optional analytics require Your permission.
+ Blog. Other optional analytics follow the same choice.
</p>
</section>
@@ -206,9 +206,7 @@ export function PrivacyPolicyContent({ className }: { className?: string }) {
</section>
</div>
- <div className="mt-12">
- <AnalyticsPreferenceControl />
- </div>
+ {showAnalyticsChoices ? <div className="mt-12"><AnalyticsPreferenceControl /></div> : null}
</div>
)
}
diff --git a/src/web/src/components/signup-tracker.dom.test.tsx b/src/web/src/components/signup-tracker.dom.test.tsx
index 7f0758c2b..d78fff247 100644
--- a/src/web/src/components/signup-tracker.dom.test.tsx
+++ b/src/web/src/components/signup-tracker.dom.test.tsx
@@ -42,7 +42,7 @@ describe("SignupTracker account-owned initiation", () => {
const { registry, rerender } = mount("/c/me/machines")
mocks.breakpoint = "mobile"; rerender()
mocks.breakpoint = "desktop"; rerender()
- expect(mocks.track).toHaveBeenCalledOnce()
+ expect(mocks.track).not.toHaveBeenCalled()
expect(registry.runtime.ui.get().onboardingState).toBeNull()
expect(mocks.replace).not.toHaveBeenCalled()
})
@@ -53,7 +53,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).toHaveBeenCalledWith("email")
+ expect(mocks.track).not.toHaveBeenCalled()
expect(registry.runtime.ui.get().onboardingState).toMatchObject({ stage: "harness" })
expect(mocks.replace).toHaveBeenCalledWith("/c/me/machines")
})
@@ -62,7 +62,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).toHaveBeenCalledWith("email")
+ expect(mocks.track).not.toHaveBeenCalled()
expect(registry.runtime.ui.get().onboardingState).toBeNull()
expect(mocks.replace).not.toHaveBeenCalled()
})
@@ -71,14 +71,14 @@ describe("SignupTracker account-owned initiation", () => {
document.cookie = "is_new_signup=email; path=/"
const { rerender } = mount("/c/me/machines")
rerender()
- expect(mocks.track).toHaveBeenCalledOnce()
+ expect(mocks.track).not.toHaveBeenCalled()
expect(mocks.replace).toHaveBeenCalledOnce()
})
- it("keeps signup method tracking intact on a public entry without an owner", () => {
+ it("does not duplicate server signup tracking on a public entry without an owner", () => {
document.cookie = "is_new_signup=github; path=/"
render(<SignupTracker />)
- expect(mocks.track).toHaveBeenCalledWith("github")
+ expect(mocks.track).not.toHaveBeenCalled()
expect(mocks.replace).not.toHaveBeenCalled()
})
diff --git a/src/web/src/components/signup-tracker.tsx b/src/web/src/components/signup-tracker.tsx
index cb476d75d..dd3c4bb10 100644
--- a/src/web/src/components/signup-tracker.tsx
+++ b/src/web/src/components/signup-tracker.tsx
@@ -3,7 +3,6 @@
import { useEffect } from "react"
import { useRouter } from "next/navigation"
import { useBreakpoint } from "@/hooks/use-mobile"
-import { trackSignUp } from "@/lib/analytics"
import { startCommunityOnboarding } from "@/lib/community-onboarding"
import { useOptionalCommunityDbRegistry } from "@/lib/community-db/projections"
@@ -16,8 +15,6 @@ export function SignupTracker({ redirectTo }: { redirectTo?: string } = {}) {
if (breakpoint === "unknown") return
const match = document.cookie.match(/(?:^|; )is_new_signup=([^;]*)/)
if (!match) return
- const method = decodeURIComponent(match[1])
- trackSignUp(method)
document.cookie = "is_new_signup=; max-age=0; path=/"
if (breakpoint === "mobile") return
if (redirectTo) {
diff --git a/src/web/src/env.d.ts b/src/web/src/env.d.ts
index 5b664ba4f..691e6de9b 100644
--- a/src/web/src/env.d.ts
+++ b/src/web/src/env.d.ts
@@ -4,11 +4,14 @@ interface RuntimeEnv {
STRIPE_PORTAL_CONFIGURATION_ID?: string
STRIPE_RETURN_ORIGIN?: string
GA4_API_SECRET?: string
+ DEV_PRODUCT_ANALYTICS_COLLECTOR?: string
+ DEV_PRODUCT_ANALYTICS_MEASUREMENT_ID?: string
ENCRYPTION_KEY: string
APP_REVIEW_EMAIL?: string
APP_REVIEW_OTP?: string
AUTH_OTP_RATE_LIMIT_MAX?: string
AUTH_OTP_RATE_LIMIT_WINDOW_SEC?: string
+ DEV_AUTH_OTP?: string
DEVICE_CLIENT_IDS?: string
NODE_ENV?: string
DEV_WS_DO_URL?: string
diff --git a/src/web/src/instrumentation-client.test.ts b/src/web/src/instrumentation-client.test.ts
index c3ed05098..3d256dbf1 100644
--- a/src/web/src/instrumentation-client.test.ts
+++ b/src/web/src/instrumentation-client.test.ts
@@ -40,7 +40,7 @@ it.each(["", "v1.denied", "v0.granted", "v1.granted"])("initializes the real Web
bootstrapObservabilityMock.mockImplementation(() => {
expect(Reflect.get(browser, "ga-disable-G-STBCL8F4ZY")).toBe(false)
expect(browser.dataLayer.map(command => Array.from(command as IArguments))).toEqual([
- ["consent", "default", { analytics_storage: cookie === "v1.granted" ? "granted" : "denied", ad_storage: "denied", ad_user_data: "denied", ad_personalization: "denied" }],
+ ["consent", "default", { analytics_storage: cookie === "v1.denied" ? "denied" : "granted", ad_storage: "denied", ad_user_data: "denied", ad_personalization: "denied" }],
["set", { page_location: "https://alook.ai/", page_referrer: "" }],
])
browser.dataLayer.push({ event: "existing-consumer" })
diff --git a/src/web/src/lib/analytics-consent.test.ts b/src/web/src/lib/analytics-consent.test.ts
index 9a726db53..379e6cf2c 100644
--- a/src/web/src/lib/analytics-consent.test.ts
+++ b/src/web/src/lib/analytics-consent.test.ts
@@ -74,7 +74,7 @@ describe("analytics consent browser contract", () => {
bootstrapGoogleAnalytics()
expect(Reflect.get(browser, "ga-disable-G-STBCL8F4ZY")).toBe(false)
expect(browser.dataLayer.map(command => Array.from(command as IArguments))).toEqual([
- ["consent", "default", { analytics_storage: value === "v1.granted" ? "granted" : "denied", ad_storage: "denied", ad_user_data: "denied", ad_personalization: "denied" }],
+ ["consent", "default", { analytics_storage: value === "v1.denied" ? "denied" : "granted", ad_storage: "denied", ad_user_data: "denied", ad_personalization: "denied" }],
["set", { page_location: "https://alook.ai/pricing", page_referrer: "" }],
])
browser.location = new URL("https://alook.ai/c/me")
@@ -104,6 +104,17 @@ describe("analytics consent browser contract", () => {
expect(JSON.stringify(browser.dataLayer)).not.toMatch(/secret|fragment|page_view/)
})
+ it.each(["/c", "/c/me"])("keeps Google disabled at private startup on %s even with a grant", path => {
+ const browser = { location: new URL(`https://alook.ai${path}`), dataLayer: [] as unknown[] }
+ vi.stubGlobal("window", browser)
+ vi.stubGlobal("document", { cookie: "alook_analytics_consent=v1.granted" })
+ bootstrapGoogleAnalytics()
+ expect(Reflect.get(browser, "ga-disable-G-STBCL8F4ZY")).toBe(true)
+ expect(browser.dataLayer.map(command => Array.from(command as IArguments))).toEqual([
+ ["consent", "default", expect.objectContaining({ analytics_storage: "denied" })],
+ ])
+ })
+
it("does not initialize browser measurement on the server", () => {
vi.stubGlobal("window", undefined)
expect(() => bootstrapGoogleAnalytics()).not.toThrow()
diff --git a/src/web/src/lib/analytics-consent.ts b/src/web/src/lib/analytics-consent.ts
index b99a5f4ac..0b0eca02a 100644
--- a/src/web/src/lib/analytics-consent.ts
+++ b/src/web/src/lib/analytics-consent.ts
@@ -1,3 +1,5 @@
+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"
@@ -39,7 +41,8 @@ export function bootstrapGoogleAnalytics(): void {
configurable: true,
get: () => !isPublicAnalyticsPath(window.location.pathname),
})
- applyGoogleConsent(readAnalyticsConsent() ?? "denied", "default")
+ if (isPublicAnalyticsPath(window.location.pathname) && readAnalyticsConsent() !== "denied") ensureBrowserAnalyticsIdentity()
+ applyGoogleConsent(isPublicAnalyticsPath(window.location.pathname) ? readAnalyticsConsent() ?? "granted" : "denied", "default")
updateGooglePageFields(window.location.href)
}
@@ -87,15 +90,22 @@ export function applyGoogleConsent(
})
}
-export async function persistAnalyticsConsent(decision: AnalyticsConsentDecision): Promise<void> {
- const response = await fetch("/api/privacy/analytics-consent", {
- method: "POST",
- credentials: "same-origin",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ decision }),
+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",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ decision }),
+ })
+ const body = await response.json().catch(() => null) as { decision?: unknown } | null
+ if (!response.ok || body?.decision !== decision) throw new Error("analytics consent was not saved")
})
- const body = await response.json().catch(() => null) as { decision?: unknown } | null
- if (!response.ok || body?.decision !== decision) throw new Error("analytics consent was not saved")
+ pendingConsentSave = save.catch(() => {})
+ return save
}
export function announceAnalyticsConsent(decision: AnalyticsConsentDecision): void {
diff --git a/src/web/src/lib/analytics.test.ts b/src/web/src/lib/analytics.test.ts
index 209a41573..f40df1c22 100644
--- a/src/web/src/lib/analytics.test.ts
+++ b/src/web/src/lib/analytics.test.ts
@@ -1,9 +1,11 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
const mocks = vi.hoisted(() => ({
+ product: vi.fn(),
hasAnalyticsConsent: vi.fn(() => true),
sendGTMEvent: vi.fn(),
}))
+vi.mock("@/lib/product-analytics", () => ({ captureProductAnalytics: mocks.product }))
vi.mock("@next/third-parties/google", () => ({
sendGTMEvent: (...args: unknown[]) => mocks.sendGTMEvent(...args),
}))
@@ -42,7 +44,6 @@ describe("analytics utility", () => {
trackGithubOutboundClicked("blog")
expect(mockSendGTMEvent.mock.calls).toEqual([
[{ event: "pricing_view", auth_state: "guest", current_plan: "none" }],
- [{ event: "landing_cta_clicked", cta_name: "get_started" }],
[{ event: "templates_browsed", category_filter: "engineering" }],
[{ event: "github_outbound_clicked", surface: "blog", destination: "alook_repo" }],
])
@@ -60,6 +61,25 @@ describe("analytics utility", () => {
expect(mockSendGTMEvent.mock.calls).toEqual([[{ event: "pricing_view", auth_state: "guest", current_plan: "none" }]])
})
+ it.each(["/c", "/c/me", "/c/channels/private/channel"])("blocks granted product events on %s after public tracking", path => {
+ const browser = { location: new URL("https://alook.ai/pricing") }
+ vi.stubGlobal("window", browser)
+ trackPricingView({ auth_state: "guest", current_plan: "none" })
+ mockSendGTMEvent.mockClear()
+ browser.location = new URL(`https://alook.ai${path}`)
+ trackSignUp("github")
+ trackCommunityOnboardingStarted()
+ trackHumanInvitationCopied()
+ trackCommunityRuntimeConnected()
+ trackFirstAgentReplyPersisted("thread")
+ trackHumanInvitationSent()
+ trackInvitedHumanJoined()
+ trackCommunityOnboardingCompleted()
+ trackCommunityOnboardingSkipped("complete")
+ trackCommunityWsFrameDropped({ type: "message.new", reason: "invalid-json" })
+ expect(mockSendGTMEvent).not.toHaveBeenCalled()
+ })
+
it("preserves the Native Allow gate on public paths", () => {
vi.stubGlobal("window", { __TAURI__: {}, location: new URL("https://alook.ai/") })
mocks.hasAnalyticsConsent.mockReturnValue(false)
@@ -143,11 +163,10 @@ describe("analytics utility", () => {
describe("P3 — Page-Level Behavior", () => {
it("trackLandingCtaClicked sends landing_cta_clicked event", () => {
+ vi.stubGlobal("window", { location: new URL("https://alook.ai/") })
trackLandingCtaClicked({ cta_name: "get_started" })
- expect(mockSendGTMEvent).toHaveBeenCalledWith({
- event: "landing_cta_clicked",
- cta_name: "get_started",
- })
+ expect(mocks.product).toHaveBeenCalledWith({ event: "landing_cta_clicked", ctaName: "get_started" })
+ expect(mockSendGTMEvent).not.toHaveBeenCalled()
})
it("trackTemplatesBrowsed sends templates_browsed event", () => {
diff --git a/src/web/src/lib/analytics.ts b/src/web/src/lib/analytics.ts
index 740f62a69..9f20908ef 100644
--- a/src/web/src/lib/analytics.ts
+++ b/src/web/src/lib/analytics.ts
@@ -4,6 +4,9 @@ import { sendGTMEvent } from "@next/third-parties/google";
import { isTauri } from "@alook/shared"
import { hasAnalyticsConsent, isPublicAnalyticsPath } from "@/lib/analytics-consent"
+import { captureProductAnalytics } from "@/lib/product-analytics"
+import { LANDING_CTA_NAMES } from "@/lib/product-analytics-contract"
+
const analyticsPlanIds = ["free", "studio", "house"] as const
export type AnalyticsAuthState = "guest" | "signed_in"
@@ -34,6 +37,7 @@ const pricingCtaIdByEntryPoint: Record<BillingEntryPoint, Partial<Record<Analyti
const analyticsPlanIdSet = new Set<string>(analyticsPlanIds)
function sendConsentAwareGTMEvent(payload: Record<string, unknown>) {
+ if (typeof window !== "undefined" && /^\/c(?:\/|$)/u.test(window.location.pathname)) return
const publicWeb = typeof window !== "undefined" && !isTauri() && isPublicAnalyticsPath(window.location.pathname)
if (!publicWeb && !hasAnalyticsConsent()) return
try {
@@ -405,7 +409,9 @@ export function trackCommunityWsRetryScheduled(params: {
// ─── P3 — Page-Level Behavior ───────────────────────────────────────────────
export function trackLandingCtaClicked(params: { cta_name: string }) {
- sendConsentAwareGTMEvent({ event: "landing_cta_clicked", ...params });
+ if (typeof window === "undefined" || !isPublicAnalyticsPath(window.location.pathname)
+ || !LANDING_CTA_NAMES.includes(params.cta_name)) return
+ void captureProductAnalytics({ event: "landing_cta_clicked", ctaName: params.cta_name })
}
export function trackTemplatesBrowsed(params: { category_filter: string }) {
diff --git a/src/web/src/lib/auth.test.ts b/src/web/src/lib/auth.test.ts
index 46bf129ca..e933a113e 100644
--- a/src/web/src/lib/auth.test.ts
+++ b/src/web/src/lib/auth.test.ts
@@ -1,5 +1,9 @@
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"),
}))
@@ -153,6 +157,7 @@ type AuthOptions = {
maxAge?: number
}
}
+ hooks?: { before: (ctx: unknown) => Promise<void>; after: (ctx: unknown) => Promise<void> }
databaseHooks?: {
user?: {
create?: {
@@ -934,3 +939,116 @@ describe("createAuth databaseHooks — user.create.before", () => {
expect(result.data.discriminator).toMatch(/^\d{4}$/)
})
})
+
+
+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())
+ })
+ 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
+ expect(options.plugins).toContainEqual(expect.objectContaining({ __plugin: "emailOTP" }))
+ const defaultOptions = (createAuth(makeEnv({ NODE_ENV: "development" }) as never) as { __options: AuthOptions }).__options
+ 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.ts
index 390cfc1fe..734ee4bd3 100644
--- a/src/web/src/lib/auth.ts
+++ b/src/web/src/lib/auth.ts
@@ -1,5 +1,6 @@
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"
@@ -24,6 +25,8 @@ 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" })
const DEFAULT_OTP_RATE_LIMIT_MAX = RATE_LIMITS["auth:otpSend"].max
@@ -108,6 +111,13 @@ 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"
@@ -213,6 +223,36 @@ 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: {
@@ -248,6 +288,13 @@ 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"
@@ -300,6 +347,13 @@ 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) return
const path = ctx.request?.url ? new URL(ctx.request.url).pathname : ""
@@ -319,7 +373,7 @@ export function createAuth(env: Env) {
},
},
},
- plugins: isProd
+ plugins: (isProd || (mode === "dev" && env.DEV_AUTH_OTP === "1"))
? [
...applePlugins,
deviceAuthorization({ verificationUri: "/device", validateClient, expiresIn: "5m", schema: {} }),
@@ -422,6 +476,10 @@ function authConfiguration(env: Env): readonly (string | undefined)[] {
env.DEVICE_CLIENT_IDS,
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/community-onboarding.test.ts b/src/web/src/lib/community-onboarding.test.ts
index cff40a872..d2f22d1ab 100644
--- a/src/web/src/lib/community-onboarding.test.ts
+++ b/src/web/src/lib/community-onboarding.test.ts
@@ -132,7 +132,7 @@ describe("community onboarding journey", () => {
completeCommunityOnboarding(runtime());
expect(readCommunityOnboardingState(runtime())).toBeNull();
expect(analytics.stageCompleted).toHaveBeenLastCalledWith("initializing");
- expect(analytics.completed).toHaveBeenCalledOnce();
+ expect(analytics.completed).not.toHaveBeenCalled();
});
it("does not complete before initialization finishes", () => {
diff --git a/src/web/src/lib/community-onboarding.ts b/src/web/src/lib/community-onboarding.ts
index 2f22d2522..73e6939f1 100644
--- a/src/web/src/lib/community-onboarding.ts
+++ b/src/web/src/lib/community-onboarding.ts
@@ -5,7 +5,6 @@ import { useCommunityRuntime, type CommunityRuntime } from "@/stores/community/r
import type { OnboardingInitializationProtocol } from "./community/models/onboarding";
import {
- trackCommunityOnboardingCompleted,
trackCommunityOnboardingSkipped,
trackCommunityOnboardingStageCompleted,
trackCommunityOnboardingStarted,
@@ -111,7 +110,6 @@ export function completeCommunityOnboarding(runtime: CommunityRuntime) {
}
publish(runtime, null);
trackCommunityOnboardingStageCompleted("initializing");
- trackCommunityOnboardingCompleted();
return null;
}
diff --git a/src/web/src/lib/product-analytics-contract.ts b/src/web/src/lib/product-analytics-contract.ts
new file mode 100644
index 000000000..8bfd648db
--- /dev/null
+++ b/src/web/src/lib/product-analytics-contract.ts
@@ -0,0 +1,5 @@
+export const LANDING_CTA_NAMES = [
+ "open_app", "get_started", "templates", "public_nav_open_app", "public_nav_get_started",
+ "pricing_open_app", "pricing_get_started", "templates_open_app", "templates_get_started", "closing_open_app", "closing_get_started",
+ ...["product", "identity", "continuity", "reach", "ownership"].flatMap(section => [`${section}_open_app`, `${section}_get_started`]),
+] as const
diff --git a/src/web/src/lib/product-analytics-identity.ts b/src/web/src/lib/product-analytics-identity.ts
new file mode 100644
index 000000000..e51b4409b
--- /dev/null
+++ b/src/web/src/lib/product-analytics-identity.ts
@@ -0,0 +1,10 @@
+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.ts
new file mode 100644
index 000000000..726101b8f
--- /dev/null
+++ b/src/web/src/lib/product-analytics-server.test.ts
@@ -0,0 +1,202 @@
+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.ts
new file mode 100644
index 000000000..6846f8c48
--- /dev/null
+++ b/src/web/src/lib/product-analytics-server.ts
@@ -0,0 +1,216 @@
+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"
+
+export const PRODUCT_SESSION_COOKIE = "alook_product_analytics_session"
+const log = createLogger({ service: "product-analytics" })
+const idleSeconds = 30 * 60
+
+export 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.ts
new file mode 100644
index 000000000..e2585da03
--- /dev/null
+++ b/src/web/src/lib/product-analytics.dom.test.ts
@@ -0,0 +1,38 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { waitFor } 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"
+
+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 }))) })
+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 () => {
+ mocks.native = true; await captureProductAnalytics({ event: "login_page_view" })
+ mocks.native = false; mocks.consent = "denied"; await captureProductAnalytics({ event: "login_page_view" })
+ expect(fetch).not.toHaveBeenCalled()
+ })
+ it("isolates a rejected analytics request from product navigation", async () => {
+ vi.mocked(fetch).mockRejectedValueOnce(new Error("offline"))
+ await expect(captureProductAnalytics({ event: "onboarding_enter_clicked", serverId: "server" })).resolves.toBeUndefined()
+ })
+})
diff --git a/src/web/src/lib/product-analytics.ts b/src/web/src/lib/product-analytics.ts
new file mode 100644
index 000000000..7054e548a
--- /dev/null
+++ b/src/web/src/lib/product-analytics.ts
@@ -0,0 +1,24 @@
+"use client"
+
+import { ensureBrowserAnalyticsIdentity } from "@/lib/product-analytics-identity"
+import { isTauri } from "@alook/shared"
+import { readAnalyticsConsent } from "@/lib/analytics-consent"
+
+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: "onboarding_enter_clicked"; serverId: string }
+ | { 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()
+ 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),
+ })
+ } catch {}
+}
diff --git a/src/web/src/test/e2e-ui/54-blog-multizone.spec.ts b/src/web/src/test/e2e-ui/54-blog-multizone.spec.ts
index 0d006d95d..c4a057459 100644
--- a/src/web/src/test/e2e-ui/54-blog-multizone.spec.ts
+++ b/src/web/src/test/e2e-ui/54-blog-multizone.spec.ts
@@ -11,8 +11,6 @@ test("main and Blog navigate across Workers through one public origin", async ({
await page.goto("/")
const consentBanner = page.getByTestId(tid.analyticsConsentBanner)
- await expect(consentBanner).toBeVisible()
- await consentBanner.getByRole("button", { name: "Only necessary", exact: true }).click()
await expect(consentBanner).toHaveCount(0)
await expect(consentBanner).toBeHidden()
const publicOrigin = new URL(page.url()).origin