Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat: add server-side GA4 purchase tracking (#846)

Gener4bc24a1e7443
diff --git a/src/shared/src/db/billing-schema.ts b/src/shared/src/db/billing-schema.ts
index f05ca7fc8..1f605c21d 100644
--- a/src/shared/src/db/billing-schema.ts
+++ b/src/shared/src/db/billing-schema.ts
@@ -1,4 +1,4 @@
-import { integer, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
+import { index, integer, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
import { user } from "./schema";
import { productPlan } from "./product-plan-schema";
import type { BillingSubscription } from "../billing";
@@ -11,8 +11,18 @@ export type CheckoutAttempt = {
startedAt: number;
sessionId: string | null;
founderAcknowledged?: boolean;
+ analytics?: {
+ clientId: string;
+ sessionId: string;
+ consentRevision: number;
+ };
+ analyticsSkipReason?: "stale_consent_proof";
};
+export type BillingAnalyticsConsentDecision = "granted" | "denied";
+export type BillingPurchaseDeliveryStatus = "claimed" | "sent" | "failed" | "skipped";
+export type BillingPurchaseType = "initial_subscription" | "renewal" | "upgrade" | "other";
+
export const billingPrice = sqliteTable("billing_price", {
priceId: text("price_id").primaryKey(),
planId: text("plan_id").notNull().references(() => productPlan.id, { onDelete: "restrict" }),
@@ -33,3 +43,27 @@ export const userBilling = sqliteTable("user_billing", {
uniqueIndex("uq_user_billing_customer").on(t.customerId),
uniqueIndex("uq_user_billing_subscription").on(t.subscriptionId),
]);
+
+export const billingAnalyticsConsent = sqliteTable("billing_analytics_consent", {
+ userId: text("user_id").primaryKey().references(() => user.id, { onDelete: "cascade" }),
+ decision: text("decision").$type<BillingAnalyticsConsentDecision>().notNull(),
+ sourceVersion: integer("source_version").notNull(),
+ revision: integer("revision").notNull().default(1),
+ updatedAt: text("updated_at").notNull().$defaultFn(() => new Date().toISOString()),
+});
+
+export const billingPurchaseDelivery = sqliteTable("billing_purchase_delivery", {
+ invoiceId: text("invoice_id").primaryKey(),
+ userId: text("user_id").notNull().references(() => user.id, { onDelete: "cascade" }),
+ status: text("status").$type<BillingPurchaseDeliveryStatus>().notNull(),
+ reason: text("reason").notNull(),
+ purchaseType: text("purchase_type").$type<BillingPurchaseType>(),
+ currency: text("currency"),
+ valueMinor: integer("value_minor"),
+ planId: text("plan_id"),
+ validationJson: text("validation_json"),
+ claimedAt: text("claimed_at").notNull().$defaultFn(() => new Date().toISOString()),
+ finalizedAt: text("finalized_at"),
+}, (t) => [
+ index("idx_billing_purchase_delivery_user_claimed").on(t.userId, t.claimedAt),
+]);
diff --git a/src/shared/src/db/queries/billing.ts b/src/shared/src/db/queries/billing.ts
index d7149e513..2b5dbb20f 100644
--- a/src/shared/src/db/queries/billing.ts
+++ b/src/shared/src/db/queries/billing.ts
@@ -1,7 +1,15 @@
-import { and, eq, exists, isNull, sql } from "drizzle-orm";
+import { and, eq, exists, isNull, lt, or, sql } from "drizzle-orm";
import { alias } from "drizzle-orm/sqlite-core";
import type { Database } from "../index";
-import { userBilling, billingPrice } from "../billing-schema";
+import {
+ billingAnalyticsConsent,
+ billingPrice,
+ billingPurchaseDelivery,
+ userBilling,
+ type BillingAnalyticsConsentDecision,
+ type BillingPurchaseDeliveryStatus,
+ type BillingPurchaseType,
+} from "../billing-schema";
import { productPlan, productPlanEntitlement, userProductPlan } from "../product-plan-schema";
import { user } from "../schema";
import {
@@ -31,6 +39,88 @@ export async function getBillingByCustomer(db: Database, customerId: string) {
return rows[0] ?? null;
}
+export async function recordAnalyticsConsent(
+ db: Database,
+ userId: string,
+ decision: BillingAnalyticsConsentDecision,
+ sourceVersion: number,
+) {
+ if (!Number.isSafeInteger(sourceVersion) || sourceVersion <= 0) {
+ throw new Error("ANALYTICS_CONSENT_SOURCE_VERSION_INVALID");
+ }
+ const now = new Date().toISOString();
+ const rows = await db.insert(billingAnalyticsConsent).values({
+ userId,
+ decision,
+ sourceVersion,
+ revision: 1,
+ updatedAt: now,
+ }).onConflictDoUpdate({
+ target: billingAnalyticsConsent.userId,
+ set: {
+ decision,
+ sourceVersion,
+ revision: sql`CASE
+ WHEN ${billingAnalyticsConsent.decision} = ${decision} THEN ${billingAnalyticsConsent.revision}
+ ELSE ${billingAnalyticsConsent.revision} + 1
+ END`,
+ updatedAt: now,
+ },
+ setWhere: decision === "denied"
+ ? or(
+ lt(billingAnalyticsConsent.sourceVersion, sourceVersion),
+ and(
+ eq(billingAnalyticsConsent.sourceVersion, sourceVersion),
+ eq(billingAnalyticsConsent.decision, "granted"),
+ ),
+ )
+ : lt(billingAnalyticsConsent.sourceVersion, sourceVersion),
+ }).returning();
+ if (rows[0]) return rows[0];
+ const current = await getAnalyticsConsent(db, userId);
+ if (!current) throw new Error("ANALYTICS_CONSENT_WRITE_LOST");
+ return current;
+}
+
+export async function getAnalyticsConsent(db: Database, userId: string) {
+ const rows = await db.select().from(billingAnalyticsConsent)
+ .where(eq(billingAnalyticsConsent.userId, userId)).limit(1);
+ return rows[0] ?? null;
+}
+
+export async function claimPurchaseDelivery(db: Database, invoiceId: string, userId: string) {
+ const rows = await db.insert(billingPurchaseDelivery).values({
+ invoiceId,
+ userId,
+ status: "claimed",
+ reason: "delivery_in_progress",
+ }).onConflictDoNothing().returning({ invoiceId: billingPurchaseDelivery.invoiceId });
+ return rows.length === 1;
+}
+
+export async function finalizePurchaseDelivery(
+ db: Database,
+ invoiceId: string,
+ result: {
+ status: Exclude<BillingPurchaseDeliveryStatus, "claimed">;
+ reason: string;
+ purchaseType?: BillingPurchaseType;
+ currency?: string;
+ valueMinor?: number;
+ planId?: string;
+ validationJson?: string;
+ },
+) {
+ const rows = await db.update(billingPurchaseDelivery).set({
+ ...result,
+ finalizedAt: new Date().toISOString(),
+ }).where(and(
+ eq(billingPurchaseDelivery.invoiceId, invoiceId),
+ eq(billingPurchaseDelivery.status, "claimed"),
+ )).returning({ invoiceId: billingPurchaseDelivery.invoiceId });
+ return rows.length === 1;
+}
+
export async function ensureBilling(db: Database, userId: string, founderAcknowledged = false) {
const now = new Date().toISOString();
await db.insert(userBilling).select(db.select({
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index b91dfd8af..2df8ee1f9 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -191,6 +191,7 @@ export type { NotifLevel, NotificationLevelValue, ParticipantSource, MentionKind
export * from "./provider-telemetry";
export * from "./product-entitlements";
export * from "./billing";
+export type { CheckoutAttempt } from "./db/billing-schema";
export type {
CommunityFunnelAnalyticsEvent,
CommunityFunnelConversationType,
diff --git a/src/shared/test/queries/billing.test.ts b/src/shared/test/queries/billing.test.ts
index 3edf94cf8..41c222566 100644
--- a/src/shared/test/queries/billing.test.ts
+++ b/src/shared/test/queries/billing.test.ts
@@ -1,8 +1,8 @@
-import { beforeEach, afterEach, describe, expect, it } from "vitest";
+import { beforeEach, afterEach, describe, expect, it, vi } from "vitest";
import { createMachinePlanTables } from "./machine-plan-fixture";
import Sqlite from "better-sqlite3";
import { getTableConfig } from "drizzle-orm/sqlite-core";
-import { userBilling, billingPrice } from "../../src/db/billing-schema";
+import { billingAnalyticsConsent, billingPurchaseDelivery, userBilling, billingPrice } from "../../src/db/billing-schema";
import { drizzle } from "drizzle-orm/better-sqlite3";
import { readFileSync } from "node:fs";
import type { Database } from "../../src/db";
@@ -27,6 +27,7 @@ beforeEach(() => {
sqlite.exec(readFileSync(new URL("../../../web/migrations/0099_billing_founder.sql", import.meta.url), "utf8"));
createMachinePlanTables(sqlite);
sqlite.exec(readFileSync(new URL("../../../web/migrations/0101_machine_plan_limits.sql", import.meta.url), "utf8"));
+ sqlite.exec(readFileSync(new URL("../../../web/migrations/0104_server_ga4_purchase.sql", import.meta.url), "utf8"));
db = drizzle(sqlite) as unknown as Database;
db.batch = (async (statements: Statement[]) => sqlite.transaction(() => statements.map((s) =>
/^select\b|\breturning\b/i.test(s.toSQL().sql.trim()) ? s.all() : s.run(),
@@ -189,15 +190,125 @@ describe("billing catalog persistence", () => {
it("declares required foreign keys and unique Stripe identities, with a generated update timestamp", async () => {
const prices = getTableConfig(billingPrice);
const billingTable = getTableConfig(userBilling);
+ const consentTable = getTableConfig(billingAnalyticsConsent);
+ const deliveryTable = getTableConfig(billingPurchaseDelivery);
expect(prices.foreignKeys.map((key) => ({ column: key.reference().columns[0].name, target: key.reference().foreignColumns[0].name, onDelete: key.onDelete })))
.toEqual([{ column: "plan_id", target: "id", onDelete: "restrict" }]);
expect(billingTable.foreignKeys.map((key) => ({ column: key.reference().columns[0].name, onDelete: key.onDelete })))
.toEqual([{ column: "user_id", onDelete: "cascade" }]);
expect(billingTable.indexes.map((index) => ({ name: index.config.name, unique: index.config.unique })))
.toEqual([{ name: "uq_user_billing_customer", unique: true }, { name: "uq_user_billing_subscription", unique: true }]);
+ expect(consentTable.foreignKeys.map((key) => ({ column: key.reference().columns[0].name, onDelete: key.onDelete })))
+ .toEqual([{ column: "user_id", onDelete: "cascade" }]);
+ expect(deliveryTable.foreignKeys.map((key) => ({ column: key.reference().columns[0].name, onDelete: key.onDelete })))
+ .toEqual([{ column: "user_id", onDelete: "cascade" }]);
+ expect(deliveryTable.indexes.map((index) => index.config.name))
+ .toEqual(["idx_billing_purchase_delivery_user_claimed"]);
const inserted = await db.insert(userBilling).values({ userId: "new-user" }).returning();
expect(inserted[0]).toMatchObject({ userId: "new-user", revision: 0, customerId: null, subscriptionId: null });
expect(Number.isFinite(Date.parse(inserted[0].updatedAt))).toBe(true);
+ const consent = await db.insert(billingAnalyticsConsent)
+ .values({ userId: "new-user", decision: "granted", sourceVersion: 1 }).returning();
+ expect(Number.isFinite(Date.parse(consent[0].updatedAt))).toBe(true);
+ const delivery = await db.insert(billingPurchaseDelivery)
+ .values({ invoiceId: "in_schema", userId: "new-user", status: "claimed", reason: "test" }).returning();
+ expect(Number.isFinite(Date.parse(delivery[0].claimedAt))).toBe(true);
await expect(db.insert(billingPrice).values({ priceId: "bad", planId: "missing" })).rejects.toThrow();
});
});
+
+describe("purchase analytics persistence", () => {
+ const recordAnalyticsConsentAt = billing.recordAnalyticsConsent as unknown as (
+ database: Database,
+ userId: string,
+ decision: "granted" | "denied",
+ sourceVersion: number,
+ ) => ReturnType<typeof billing.recordAnalyticsConsent>;
+
+ it("keeps a monotonic current consent revision", async () => {
+ await expect(billing.recordAnalyticsConsent(db, "new-user", "granted", 100)).resolves.toMatchObject({ revision: 1, decision: "granted", sourceVersion: 100 });
+ await expect(billing.recordAnalyticsConsent(db, "new-user", "denied", 200)).resolves.toMatchObject({ revision: 2, decision: "denied", sourceVersion: 200 });
+ await expect(billing.getAnalyticsConsent(db, "new-user")).resolves.toMatchObject({ revision: 2, decision: "denied", sourceVersion: 200 });
+ });
+
+ it("rejects a non-positive or fractional consent source version", async () => {
+ await expect(billing.recordAnalyticsConsent(db, "new-user", "granted", 0))
+ .rejects.toThrow("ANALYTICS_CONSENT_SOURCE_VERSION_INVALID");
+ await expect(billing.recordAnalyticsConsent(db, "new-user", "granted", 1.5))
+ .rejects.toThrow("ANALYTICS_CONSENT_SOURCE_VERSION_INVALID");
+ });
+
+ it("fails closed when a consent write returns no row and no current record", async () => {
+ const returning = vi.fn().mockResolvedValue([]);
+ const writeDb = {
+ insert: vi.fn(() => ({
+ values: vi.fn(() => ({
+ onConflictDoUpdate: vi.fn(() => ({ returning })),
+ })),
+ })),
+ select: vi.fn(() => ({
+ from: vi.fn(() => ({
+ where: vi.fn(() => ({ limit: vi.fn().mockResolvedValue([]) })),
+ })),
+ })),
+ } as unknown as Database;
+
+ await expect(billing.recordAnalyticsConsent(writeDb, "new-user", "granted", 100))
+ .rejects.toThrow("ANALYTICS_CONSENT_WRITE_LOST");
+ expect(returning).toHaveBeenCalledOnce();
+ });
+
+ it("rejects an older signed grant after a newer denial", async () => {
+ await recordAnalyticsConsentAt(db, "new-user", "granted", 100);
+ await recordAnalyticsConsentAt(db, "new-user", "denied", 200);
+ await recordAnalyticsConsentAt(db, "new-user", "granted", 100);
+ await expect(billing.getAnalyticsConsent(db, "new-user")).resolves.toMatchObject({
+ decision: "denied",
+ revision: 2,
+ sourceVersion: 200,
+ });
+ });
+
+ it("is idempotent at one source version and resolves equal conflicts to denial", async () => {
+ await recordAnalyticsConsentAt(db, "new-user", "granted", 300);
+ await recordAnalyticsConsentAt(db, "new-user", "granted", 300);
+ await recordAnalyticsConsentAt(db, "new-user", "denied", 300);
+ await recordAnalyticsConsentAt(db, "new-user", "granted", 300);
+ await expect(billing.getAnalyticsConsent(db, "new-user")).resolves.toMatchObject({
+ decision: "denied",
+ revision: 2,
+ sourceVersion: 300,
+ });
+ });
+
+ it("converges to the newer decision regardless of arrival order", async () => {
+ sqlite.exec("INSERT INTO user(id) VALUES('arrival-a'),('arrival-b')");
+ await recordAnalyticsConsentAt(db, "arrival-a", "denied", 500);
+ await recordAnalyticsConsentAt(db, "arrival-a", "granted", 400);
+ await recordAnalyticsConsentAt(db, "arrival-b", "granted", 400);
+ await recordAnalyticsConsentAt(db, "arrival-b", "denied", 500);
+ await expect(billing.getAnalyticsConsent(db, "arrival-a")).resolves.toMatchObject({ decision: "denied", sourceVersion: 500 });
+ await expect(billing.getAnalyticsConsent(db, "arrival-b")).resolves.toMatchObject({ decision: "denied", sourceVersion: 500 });
+ });
+
+ it("claims an invoice once and finalizes only the winning claim", async () => {
+ expect(await billing.claimPurchaseDelivery(db, "in_once", "new-user")).toBe(true);
+ expect(await billing.claimPurchaseDelivery(db, "in_once", "new-user")).toBe(false);
+ expect(await billing.finalizePurchaseDelivery(db, "in_once", {
+ status: "sent", reason: "delivered", purchaseType: "renewal", currency: "USD",
+ valueMinor: 2000, planId: "studio", validationJson: '{"validationMessages":[]}',
+ })).toBe(true);
+ expect(await billing.finalizePurchaseDelivery(db, "in_once", { status: "failed", reason: "late" })).toBe(false);
+ await expect(db.select().from(billingPurchaseDelivery)).resolves.toEqual([expect.objectContaining({
+ invoiceId: "in_once", status: "sent", reason: "delivered", purchaseType: "renewal",
+ })]);
+ });
+
+ it("cascades user-scoped consent and delivery evidence", async () => {
+ await billing.recordAnalyticsConsent(db, "new-user", "granted", 100);
+ await billing.claimPurchaseDelivery(db, "in_delete", "new-user");
+ sqlite.exec("DELETE FROM user WHERE id='new-user'");
+ await expect(db.select().from(billingAnalyticsConsent)).resolves.toEqual([]);
+ await expect(db.select().from(billingPurchaseDelivery)).resolves.toEqual([]);
+ });
+});
diff --git a/src/web/migrations/0104_server_ga4_purchase.sql b/src/web/migrations/0104_server_ga4_purchase.sql
new file mode 100644
index 000000000..9e37da5a6
--- /dev/null
+++ b/src/web/migrations/0104_server_ga4_purchase.sql
@@ -0,0 +1,35 @@
+CREATE TABLE billing_analytics_consent (
+ user_id TEXT PRIMARY KEY NOT NULL REFERENCES user(id) ON DELETE CASCADE,
+ decision TEXT NOT NULL CONSTRAINT ck_billing_analytics_consent_decision
+ CHECK (decision IN ('granted', 'denied')),
+ source_version INTEGER NOT NULL CONSTRAINT ck_billing_analytics_consent_source_version
+ CHECK (source_version > 0),
+ revision INTEGER NOT NULL DEFAULT 1 CONSTRAINT ck_billing_analytics_consent_revision
+ CHECK (revision > 0),
+ updated_at TEXT NOT NULL
+);
+
+CREATE TABLE billing_purchase_delivery (
+ invoice_id TEXT PRIMARY KEY NOT NULL,
+ user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,
+ status TEXT NOT NULL CONSTRAINT ck_billing_purchase_delivery_status
+ CHECK (status IN ('claimed', 'sent', 'failed', 'skipped')),
+ reason TEXT NOT NULL CONSTRAINT ck_billing_purchase_delivery_reason
+ CHECK (length(reason) BETWEEN 1 AND 64),
+ purchase_type TEXT CONSTRAINT ck_billing_purchase_delivery_type
+ CHECK (purchase_type IS NULL OR purchase_type IN ('initial_subscription', 'renewal', 'upgrade', 'other')),
+ currency TEXT,
+ value_minor INTEGER,
+ plan_id TEXT,
+ validation_json TEXT CONSTRAINT ck_billing_purchase_delivery_validation
+ CHECK (validation_json IS NULL OR length(validation_json) <= 10000),
+ claimed_at TEXT NOT NULL,
+ finalized_at TEXT,
+ CONSTRAINT ck_billing_purchase_delivery_finalization CHECK (
+ (status = 'claimed' AND finalized_at IS NULL)
+ OR (status != 'claimed' AND finalized_at IS NOT NULL)
+ )
+);
+
+CREATE INDEX idx_billing_purchase_delivery_user_claimed
+ ON billing_purchase_delivery(user_id, claimed_at);
diff --git a/src/web/src/app/api/community/billing/checkout/route.ts b/src/web/src/app/api/community/billing/checkout/route.ts
index 1bb7663ad..434b2e2ee 100644
--- a/src/web/src/app/api/community/billing/checkout/route.ts
+++ b/src/web/src/app/api/community/billing/checkout/route.ts
@@ -1,14 +1,36 @@
-import { BillingCheckoutRequestSchema, BillingRedirectResponseSchema } from "@alook/shared"
+import { BillingCheckoutRequestSchema, BillingRedirectResponseSchema, queries } from "@alook/shared"
import { withCookieHumanAuth } from "@/lib/middleware/auth"
import { getPrimaryDb } from "@/lib/db"
import { billingClient, billingFailure, billingResponse } from "@/lib/billing/client"
import { createCheckout } from "@/lib/billing/service"
+import { readCheckoutAnalyticsConsent } from "@/lib/analytics-consent-server"
export const POST = withCookieHumanAuth(async (req, ctx) => {
const parsed = BillingCheckoutRequestSchema.safeParse(await req.json().catch(() => null))
if (!parsed.success) return billingResponse({ error: "BILLING_REQUEST_INVALID" }, 400)
try {
- const result = await createCheckout(getPrimaryDb(ctx.env.DB), billingClient(ctx.env), ctx.env, ctx.userId, ctx.email, parsed.data.priceId, parsed.data.founderAcknowledged)
+ const db = getPrimaryDb(ctx.env.DB)
+ const consent = await readCheckoutAnalyticsConsent(req.headers.get("cookie") ?? "", ctx.env.BETTER_AUTH_SECRET)
+ const persistedConsent = consent.decision && consent.sourceVersion
+ ? await queries.billing.recordAnalyticsConsent(db, ctx.userId, consent.decision, consent.sourceVersion)
+ : null
+ const analytics = consent.identity && persistedConsent?.decision === "granted"
+ ? { ...consent.identity, consentRevision: persistedConsent.revision }
+ : undefined
+ const analyticsSkipReason = consent.decision === "granted" && persistedConsent?.decision === "denied"
+ ? "stale_consent_proof" as const
+ : undefined
+ const result = await createCheckout(
+ db,
+ billingClient(ctx.env),
+ ctx.env,
+ ctx.userId,
+ ctx.email,
+ parsed.data.priceId,
+ parsed.data.founderAcknowledged,
+ analytics,
+ analyticsSkipReason,
+ )
return billingResponse(BillingRedirectResponseSchema.parse(result))
} catch (error) {
return billingFailure(error, "checkout")
diff --git a/src/web/src/app/api/community/billing/routes.test.ts b/src/web/src/app/api/community/billing/routes.test.ts
index e577a6911..1201e1c9f 100644
--- a/src/web/src/app/api/community/billing/routes.test.ts
+++ b/src/web/src/app/api/community/billing/routes.test.ts
@@ -1,10 +1,12 @@
import { beforeEach, afterEach, describe, expect, it, vi } from "vitest"
import { NextRequest } from "next/server"
+import { createAnalyticsConsentProof } from "@/lib/analytics-consent-server"
const mocks = vi.hoisted(() => ({
session: vi.fn(), owner: vi.fn(), summary: vi.fn(), checkout: vi.fn(),
portal: vi.fn(), cancel: vi.fn(), webhook: vi.fn(),
- db: { primary: true }, env: { DB: {}, STRIPE_SECRET_KEY: "sk_test_route_fixture" },
+ recordConsent: vi.fn(),
+ db: { primary: true }, env: { DB: {}, STRIPE_SECRET_KEY: "sk_test_route_fixture", BETTER_AUTH_SECRET: "consent-secret" },
}))
vi.mock("@opennextjs/cloudflare", () => ({
getCloudflareContext: vi.fn(() => ({ env: mocks.env, ctx: { waitUntil: vi.fn() } })),
@@ -16,7 +18,7 @@ vi.mock("@/lib/auth", () => ({
}))
vi.mock("@alook/shared", async (original) => ({
...await original<typeof import("@alook/shared")>(),
- queries: { user: { getUserInternal: mocks.owner } },
+ queries: { user: { getUserInternal: mocks.owner }, billing: { recordAnalyticsConsent: mocks.recordConsent } },
}))
vi.mock("@/lib/billing/service", () => ({
getBillingSummary: mocks.summary, createCheckout: mocks.checkout,
@@ -47,6 +49,7 @@ beforeEach(() => {
mocks.checkout.mockResolvedValue(redirect)
mocks.portal.mockResolvedValue(redirect)
mocks.cancel.mockResolvedValue(summary)
+ mocks.recordConsent.mockResolvedValue({ decision: "granted", revision: 4, sourceVersion: 1 })
vi.spyOn(console, "error").mockImplementation(() => {})
})
afterEach(() => vi.restoreAllMocks())
@@ -78,7 +81,59 @@ describe("billing HTTP route boundaries", () => {
const response = await checkout(request(JSON.stringify({ priceId: "price_studio", founderAcknowledged })))
expect(response.status).toBe(200)
expect(await response.json()).toEqual(redirect)
- expect(mocks.checkout).toHaveBeenCalledWith(mocks.db, expect.any(Object), mocks.env, owner.id, owner.email, "price_studio", founderAcknowledged)
+ expect(mocks.checkout).toHaveBeenCalledWith(mocks.db, expect.any(Object), mocks.env, owner.id, owner.email, "price_studio", founderAcknowledged, undefined, undefined)
+ })
+
+ it("hands a valid signed GA identity to checkout after persisting consent", async () => {
+ const proof = await createAnalyticsConsentProof("granted", mocks.env.BETTER_AUTH_SECRET)
+ const cookie = [
+ `alook_analytics_consent_proof=${encodeURIComponent(proof)}`,
+ "_ga=GA1.1.123.456",
+ "_ga_STBCL8F4ZY=GS1.1.1700000000.1",
+ ].join("; ")
+ const response = await checkout(request(JSON.stringify({ priceId: "price_studio" }), { cookie }))
+ expect(response.status).toBe(200)
+ expect(mocks.recordConsent).toHaveBeenCalledWith(mocks.db, owner.id, "granted", Number(proof.split(".")[2]))
+ expect(mocks.checkout).toHaveBeenCalledWith(
+ mocks.db, expect.any(Object), mocks.env, owner.id, owner.email, "price_studio", undefined,
+ { clientId: "123.456", sessionId: "1700000000", consentRevision: 4 }, undefined,
+ )
+ })
+
+ it("does not revive consent when an older browser replays a signed grant", async () => {
+ const issuedAt = Date.UTC(2026, 8, 29, 9, 0, 0)
+ const sourceVersion = Math.floor(issuedAt / 1000)
+ const proof = await createAnalyticsConsentProof("granted", mocks.env.BETTER_AUTH_SECRET, issuedAt)
+ const cookie = [
+ `alook_analytics_consent_proof=${encodeURIComponent(proof)}`,
+ "_ga=GA1.1.123.456",
+ "_ga_STBCL8F4ZY=GS1.1.1700000000.1",
+ ].join("; ")
+ mocks.recordConsent.mockResolvedValueOnce({ decision: "denied", revision: 2, sourceVersion: sourceVersion + 60 })
+
+ const response = await checkout(request(JSON.stringify({ priceId: "price_studio" }), { cookie }))
+
+ expect(response.status).toBe(200)
+ expect(mocks.recordConsent).toHaveBeenCalledWith(mocks.db, owner.id, "granted", sourceVersion)
+ expect(mocks.checkout).toHaveBeenCalledWith(
+ mocks.db, expect.any(Object), mocks.env, owner.id, owner.email, "price_studio", undefined,
+ undefined, "stale_consent_proof",
+ )
+ })
+
+ it("freezes no GA identity when the stream session cookie is invalid", async () => {
+ const proof = await createAnalyticsConsentProof("granted", mocks.env.BETTER_AUTH_SECRET)
+ const cookie = [
+ `alook_analytics_consent_proof=${encodeURIComponent(proof)}`,
+ "_ga=GA1.1.123.456",
+ "_ga_STBCL8F4ZY=invalid",
+ ].join("; ")
+ const response = await checkout(request(JSON.stringify({ priceId: "price_studio" }), { cookie }))
+ expect(response.status).toBe(200)
+ expect(mocks.recordConsent).toHaveBeenCalledWith(mocks.db, owner.id, "granted", Number(proof.split(".")[2]))
+ expect(mocks.checkout).toHaveBeenCalledWith(
+ mocks.db, expect.any(Object), mocks.env, owner.id, owner.email, "price_studio", undefined, undefined, undefined,
+ )
})
it.each(["{", "null", "{}", '{"priceId":""}', '{"priceId":"p","founderAcknowledged":"true"}', '{"priceId":"p","ownerId":"other"}'])("rejects malformed Checkout body %s before creating a Session", async (body) => {
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 b86723292..e77bfdd66 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
@@ -3,13 +3,17 @@ import { beforeEach, describe, expect, it, vi } from "vitest"
import { verifyAnalyticsConsentProof } from "@/lib/analytics-consent-server"
const mocks = vi.hoisted(() => ({
- env: { BETTER_AUTH_SECRET: "route-consent-signing-secret" },
+ env: { BETTER_AUTH_SECRET: "route-consent-signing-secret", DB: {} },
+ userId: undefined as string | undefined,
+ recordAnalyticsConsent: vi.fn(),
}))
-vi.mock("@/lib/middleware/env", () => ({
- withEnv: (handler: (request: NextRequest, context: { env: typeof mocks.env }) => Promise<Response>) =>
- (request: NextRequest) => handler(request, { env: mocks.env }),
+vi.mock("@/lib/middleware/auth", () => ({
+ withOptionalAuth: (handler: (request: NextRequest, context: { env: typeof mocks.env; userId?: string }) => Promise<Response>) =>
+ (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 } } }))
import { POST } from "./route"
@@ -26,7 +30,10 @@ function request(
}
beforeEach(() => {
+ vi.resetAllMocks()
mocks.env.BETTER_AUTH_SECRET = "route-consent-signing-secret"
+ mocks.userId = undefined
+ mocks.recordAnalyticsConsent.mockResolvedValue({ decision: "granted", revision: 1, sourceVersion: 1 })
})
describe("POST /api/privacy/analytics-consent", () => {
@@ -52,7 +59,7 @@ describe("POST /api/privacy/analytics-consent", () => {
await expect(verifyAnalyticsConsentProof(
proof,
mocks.env.BETTER_AUTH_SECRET,
- )).resolves.toBe(decision)
+ )).resolves.toEqual({ decision, sourceVersion: expect.any(Number) })
})
it("allows local HTTP while omitting Secure", async () => {
@@ -65,6 +72,35 @@ describe("POST /api/privacy/analytics-consent", () => {
expect(response.headers.getSetCookie().every((cookie) => !cookie.includes("Secure"))).toBe(true)
})
+ it("persists an authenticated decision before issuing its proof", async () => {
+ mocks.userId = "owner"
+ const response = await POST(request({ decision: "denied" }))
+ expect(response.status).toBe(200)
+ const proof = response.headers.getSetCookie()[1]?.match(/^[^=]+=([^;]+)/u)?.[1]
+ const verified = await verifyAnalyticsConsentProof(proof, mocks.env.BETTER_AUTH_SECRET)
+ expect(mocks.recordAnalyticsConsent).toHaveBeenCalledWith(
+ mocks.env.DB,
+ "owner",
+ "denied",
+ verified?.sourceVersion,
+ )
+ })
+
+ it("does not accept a revocation when an apparent signed-in session cannot be resolved", async () => {
+ const input = new NextRequest("https://alook.ai/api/privacy/analytics-consent", {
+ method: "POST",
+ headers: {
+ Origin: "https://alook.ai",
+ "Content-Type": "application/json",
+ cookie: "better-auth.session_token=unresolved",
+ },
+ body: JSON.stringify({ decision: "denied" }),
+ })
+ const response = await POST(input)
+ expect(response.status).toBe(503)
+ expect(response.headers.getSetCookie()).toEqual([])
+ })
+
it("uses the browser origin behind a local reverse proxy", async () => {
const response = await POST(new NextRequest(
"https://localhost:3001/api/privacy/analytics-consent",
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 68bf68161..16c3160bd 100644
--- a/src/web/src/app/api/privacy/analytics-consent/route.ts
+++ b/src/web/src/app/api/privacy/analytics-consent/route.ts
@@ -1,5 +1,7 @@
import { NextResponse, type NextRequest } from "next/server"
-import { withEnv } from "@/lib/middleware/env"
+import { queries } from "@alook/shared"
+import { withOptionalAuth } from "@/lib/middleware/auth"
+import { getPrimaryDb } from "@/lib/db"
import {
ANALYTICS_CONSENT_COOKIE,
ANALYTICS_CONSENT_MAX_AGE_SECONDS,
@@ -34,7 +36,7 @@ function parseDecision(value: unknown): AnalyticsConsentDecision | null {
return decision === "granted" || decision === "denied" ? decision : null
}
-export const POST = withEnv(async (request, ctx) => {
+export const POST = withOptionalAuth(async (request, ctx) => {
const origin = sameOriginUrl(request)
if (!origin) {
return NextResponse.json({ error: "forbidden" }, { status: 403 })
@@ -46,6 +48,16 @@ export const POST = withEnv(async (request, ctx) => {
if (!ctx.env.BETTER_AUTH_SECRET) {
return NextResponse.json({ error: "temporarily unavailable" }, { status: 503 })
}
+ const hasSessionCookie = request.cookies.has("better-auth.session_token")
+ || request.cookies.has("__Secure-better-auth.session_token")
+ if (hasSessionCookie && !ctx.userId) {
+ return NextResponse.json({ error: "temporarily unavailable" }, { status: 503 })
+ }
+ const issuedAtMs = Date.now()
+ const sourceVersion = Math.floor(issuedAtMs / 1000)
+ if (ctx.userId) {
+ await queries.billing.recordAnalyticsConsent(getPrimaryDb(ctx.env.DB), ctx.userId, decision, sourceVersion)
+ }
const response = NextResponse.json({ decision })
const secure = origin.protocol === "https:"
@@ -62,7 +74,7 @@ export const POST = withEnv(async (request, ctx) => {
)
response.cookies.set(
ANALYTICS_CONSENT_PROOF_COOKIE,
- await createAnalyticsConsentProof(decision, ctx.env.BETTER_AUTH_SECRET),
+ await createAnalyticsConsentProof(decision, ctx.env.BETTER_AUTH_SECRET, issuedAtMs),
{ ...shared, httpOnly: true },
)
response.headers.set("Cache-Control", "no-store, max-age=0")
diff --git a/src/web/src/env.d.ts b/src/web/src/env.d.ts
index b9fd4dce3..5b664ba4f 100644
--- a/src/web/src/env.d.ts
+++ b/src/web/src/env.d.ts
@@ -3,6 +3,7 @@ interface RuntimeEnv {
STRIPE_WEBHOOK_SECRET?: string
STRIPE_PORTAL_CONFIGURATION_ID?: string
STRIPE_RETURN_ORIGIN?: string
+ GA4_API_SECRET?: string
ENCRYPTION_KEY: string
APP_REVIEW_EMAIL?: string
APP_REVIEW_OTP?: string
diff --git a/src/web/src/lib/analytics-consent-server.test.ts b/src/web/src/lib/analytics-consent-server.test.ts
index 4e127b065..d844dae68 100644
--- a/src/web/src/lib/analytics-consent-server.test.ts
+++ b/src/web/src/lib/analytics-consent-server.test.ts
@@ -4,6 +4,9 @@ import {
} from "./analytics-consent"
import {
createAnalyticsConsentProof,
+ parseGaClientId,
+ parseGaSessionId,
+ readCheckoutAnalyticsConsent,
verifyAnalyticsConsentProof,
} from "./analytics-consent-server"
@@ -13,7 +16,18 @@ const NOW = Date.UTC(2026, 8, 17, 4, 0, 0)
describe("analytics consent proof", () => {
it.each(["granted", "denied"] as const)("round-trips %s", async (decision) => {
const proof = await createAnalyticsConsentProof(decision, SECRET, NOW)
- await expect(verifyAnalyticsConsentProof(proof, SECRET, NOW)).resolves.toBe(decision)
+ await expect(verifyAnalyticsConsentProof(proof, SECRET, NOW)).resolves.toEqual({
+ decision,
+ sourceVersion: Math.floor(NOW / 1000),
+ })
+ })
+
+ it("returns the signed decision time as the consent source version", async () => {
+ const proof = await createAnalyticsConsentProof("granted", SECRET, NOW)
+ await expect(verifyAnalyticsConsentProof(proof, SECRET, NOW)).resolves.toEqual({
+ decision: "granted",
+ sourceVersion: Math.floor(NOW / 1000),
+ })
})
it("rejects a changed decision or signature", async () => {
@@ -46,3 +60,62 @@ describe("analytics consent proof", () => {
await expect(verifyAnalyticsConsentProof(current, "other-secret", NOW)).resolves.toBeNull()
})
})
+
+describe("GA checkout identity", () => {
+ it.each([
+ ["GA1.1.123456789.1700000000", "123456789.1700000000"],
+ ["GA2.2.1.2", "1.2"],
+ ["bad", null],
+ ["GA1.1.a.2", null],
+ ])("parses client cookie %s", (value, expected) => {
+ expect(parseGaClientId(value)).toBe(expected)
+ })
+
+ it.each([
+ ["GS1.1.1700000000.3.0.0", "1700000000"],
+ ["GS2.1.s1700000000$o3$g0", "1700000000"],
+ ["GS2.1.o3$s1700000000", null],
+ ["bad", null],
+ ])("parses session cookie %s", (value, expected) => {
+ expect(parseGaSessionId(value)).toBe(expected)
+ })
+
+ it("returns identity only with a valid signed grant and valid client cookie", async () => {
+ const proof = await createAnalyticsConsentProof("granted", SECRET)
+ const cookies = [
+ `alook_analytics_consent_proof=${encodeURIComponent(proof)}`,
+ "_ga=GA1.1.123456789.1700000000",
+ "_ga_STBCL8F4ZY=GS2.1.s1700000000$o1",
+ ].join("; ")
+ await expect(readCheckoutAnalyticsConsent(cookies, SECRET)).resolves.toEqual({
+ decision: "granted",
+ sourceVersion: Number(proof.split(".")[2]),
+ identity: { clientId: "123456789.1700000000", sessionId: "1700000000" },
+ })
+ await expect(readCheckoutAnalyticsConsent(cookies, "wrong-secret")).resolves.toEqual({ decision: null, sourceVersion: null, identity: null })
+ })
+
+ it("treats a malformed percent-encoded identity cookie as unavailable", async () => {
+ const proof = await createAnalyticsConsentProof("granted", SECRET)
+ const cookies = [
+ `alook_analytics_consent_proof=${encodeURIComponent(proof)}`,
+ "_ga=%",
+ "_ga_STBCL8F4ZY=GS2.1.s1700000000$o1",
+ ].join("; ")
+ await expect(readCheckoutAnalyticsConsent(cookies, SECRET)).resolves.toEqual({
+ decision: "granted",
+ sourceVersion: Number(proof.split(".")[2]),
+ identity: null,
+ })
+ })
+
+ it.each(["", "; _ga_STBCL8F4ZY=bad"])("rejects checkout identity without a valid stream session cookie (%s)", async (sessionCookie) => {
+ const proof = await createAnalyticsConsentProof("granted", SECRET)
+ const cookies = `alook_analytics_consent_proof=${encodeURIComponent(proof)}; _ga=GA1.1.123456789.1700000000${sessionCookie}`
+ await expect(readCheckoutAnalyticsConsent(cookies, SECRET)).resolves.toEqual({
+ decision: "granted",
+ sourceVersion: Number(proof.split(".")[2]),
+ identity: null,
+ })
+ })
+})
diff --git a/src/web/src/lib/analytics-consent-server.ts b/src/web/src/lib/analytics-consent-server.ts
index 3b17bb2fc..900b3ba9c 100644
--- a/src/web/src/lib/analytics-consent-server.ts
+++ b/src/web/src/lib/analytics-consent-server.ts
@@ -1,9 +1,18 @@
import {
+ ANALYTICS_CONSENT_PROOF_COOKIE,
ANALYTICS_CONSENT_MAX_AGE_SECONDS,
ANALYTICS_CONSENT_VERSION,
type AnalyticsConsentDecision,
} from "@/lib/analytics-consent"
+export const GA4_MEASUREMENT_ID = "G-STBCL8F4ZY"
+export const GA4_CLIENT_ID_METADATA = "alook_ga_client_id"
+export const GA4_SESSION_ID_METADATA = "alook_ga_session_id"
+export const GA4_CONSENT_REVISION_METADATA = "alook_ga_consent_revision"
+export const GA4_CONSENT_STATUS_METADATA = "alook_ga_consent_status"
+
+const GA4_SESSION_COOKIE = `_ga_${GA4_MEASUREMENT_ID.slice(2).replaceAll("-", "_")}`
+
const encoder = new TextEncoder()
async function consentSigningKey(secret: string): Promise<CryptoKey> {
@@ -55,7 +64,7 @@ export async function verifyAnalyticsConsentProof(
proof: string | null | undefined,
secret: string,
nowMs = Date.now(),
-): Promise<AnalyticsConsentDecision | null> {
+): Promise<{ decision: AnalyticsConsentDecision; sourceVersion: number } | null> {
const parts = proof?.split(".") ?? []
if (parts.length !== 4) return null
const [version, decision, issuedAtRaw, signatureRaw] = parts
@@ -76,5 +85,57 @@ export async function verifyAnalyticsConsentProof(
signature,
encoder.encode(payload),
)
- return valid ? decision : null
+ return valid ? { decision, sourceVersion: issuedAtSeconds } : null
+}
+
+function cookieValue(cookieHeader: string, name: string): string | null {
+ for (const part of cookieHeader.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 function parseGaClientId(value: string | null | undefined): string | null {
+ const parts = value?.split(".") ?? []
+ if (parts.length < 4 || !/^GA\d+$/u.test(parts[0]!)) return null
+ const clientId = parts.slice(-2).join(".")
+ return /^\d{1,20}\.\d{1,20}$/u.test(clientId) ? clientId : null
+}
+
+export function parseGaSessionId(value: string | null | undefined): string | null {
+ if (!value) return null
+ const gs2 = /^GS2\.\d+\.s(\d{1,20})(?:\$|$)/u.exec(value)?.[1]
+ if (gs2 && Number.isSafeInteger(Number(gs2)) && Number(gs2) > 0) return gs2
+ const gs1 = /^GS1\.\d+\.(\d{1,20})(?:\.|$)/u.exec(value)?.[1]
+ return gs1 && Number.isSafeInteger(Number(gs1)) && Number(gs1) > 0 ? gs1 : null
+}
+
+export async function readCheckoutAnalyticsConsent(cookieHeader: string, secret: string) {
+ const proof = await verifyAnalyticsConsentProof(
+ cookieValue(cookieHeader, ANALYTICS_CONSENT_PROOF_COOKIE),
+ secret,
+ )
+ if (proof?.decision !== "granted") {
+ return {
+ decision: proof?.decision ?? null,
+ sourceVersion: proof?.sourceVersion ?? null,
+ identity: null,
+ }
+ }
+ const clientId = parseGaClientId(cookieValue(cookieHeader, "_ga"))
+ const sessionId = parseGaSessionId(cookieValue(cookieHeader, GA4_SESSION_COOKIE))
+ if (!clientId || !sessionId) return { ...proof, identity: null }
+ return {
+ ...proof,
+ identity: {
+ clientId,
+ sessionId,
+ },
+ }
}
diff --git a/src/web/src/lib/billing/purchase-analytics.test.ts b/src/web/src/lib/billing/purchase-analytics.test.ts
new file mode 100644
index 000000000..d2367a877
--- /dev/null
+++ b/src/web/src/lib/billing/purchase-analytics.test.ts
@@ -0,0 +1,367 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import type Stripe from "stripe"
+import type { Database } from "@alook/shared"
+
+const mocked = vi.hoisted(() => ({
+ claimPurchaseDelivery: vi.fn(),
+ finalizePurchaseDelivery: vi.fn(),
+ getAnalyticsConsent: vi.fn(),
+ listPrices: vi.fn(),
+}))
+vi.mock("@alook/shared", () => ({ queries: { billing: mocked } }))
+import { deliverInvoicePurchase, validatePurchasePayloadForAcceptance } from "./purchase-analytics"
+
+const db = {} as Database
+const env = { STRIPE_SECRET_KEY: "sk_test_fixture", GA4_API_SECRET: "ga-secret" } as Env
+const catalog = [
+ { priceId: "price_studio", planId: "studio", displayName: "Studio", sortOrder: 1 },
+ { priceId: "price_house", planId: "house", displayName: "House", sortOrder: 2 },
+]
+
+function invoice(overrides: Record<string, unknown> = {}) {
+ return {
+ id: "in_current", livemode: false, status: "paid", amount_paid: 2400,
+ currency: "usd", created: 200, customer: "cus_owner", billing_reason: "subscription_create",
+ parent: { subscription_details: { subscription: "sub_owner" } },
+ ...overrides,
+ } as unknown as Stripe.Invoice
+}
+
+function line(price: string, amount: number, subscription = "sub_owner") {
+ return {
+ amount,
+ parent: { subscription_item_details: { subscription } },
+ pricing: { price_details: { price } },
+ } as unknown as Stripe.InvoiceLineItem
+}
+
+function iterable<T>(values: T[]) {
+ return { async *[Symbol.asyncIterator]() { yield* values } }
+}
+
+let currentInvoice: Stripe.Invoice
+let lines: Stripe.InvoiceLineItem[]
+let priorInvoices: Stripe.Invoice[]
+let stripe: Stripe
+let fetcher: ReturnType<typeof vi.fn>
+
+beforeEach(() => {
+ vi.resetAllMocks()
+ currentInvoice = invoice()
+ lines = [line("price_studio", 2000), { amount: 400 } as Stripe.InvoiceLineItem]
+ priorInvoices = [currentInvoice]
+ mocked.claimPurchaseDelivery.mockResolvedValue(true)
+ mocked.finalizePurchaseDelivery.mockResolvedValue(true)
+ mocked.getAnalyticsConsent.mockResolvedValue({ decision: "granted", revision: 2 })
+ mocked.listPrices.mockResolvedValue(catalog)
+ stripe = {
+ invoices: {
+ retrieve: vi.fn(async () => currentInvoice),
+ listLineItems: vi.fn(() => iterable(lines)),
+ list: vi.fn(() => iterable(priorInvoices)),
+ },
+ subscriptions: {
+ retrieve: vi.fn(async () => ({
+ id: "sub_owner", livemode: false, customer: "cus_owner",
+ metadata: {
+ alook_user_id: "owner",
+ alook_ga_client_id: "123456789.1700000000",
+ alook_ga_session_id: "1700000000",
+ alook_ga_consent_revision: "2",
+ },
+ })),
+ },
+ } as unknown as Stripe
+ fetcher = vi.fn().mockResolvedValue(new Response(null, { status: 204 }))
+ vi.stubGlobal("fetch", fetcher)
+})
+
+describe("server GA4 purchase delivery", () => {
+ it("sends an initial tax-exclusive purchase with checkout session attribution", async () => {
+ await deliverInvoicePurchase(db, stripe, env, currentInvoice, "owner")
+ expect(fetcher).toHaveBeenCalledOnce()
+ expect(fetcher.mock.calls[0][0]).toContain("/mp/collect?")
+ expect(fetcher.mock.calls[0][0]).not.toContain("/debug/")
+ const payload = JSON.parse(fetcher.mock.calls[0][1].body as string)
+ expect(payload).toMatchObject({
+ client_id: "123456789.1700000000",
+ events: [{ name: "purchase", params: {
+ transaction_id: "in_current", currency: "USD", value: 20,
+ purchase_type: "initial_subscription", session_id: 1700000000,
+ items: [{ item_id: "studio", item_name: "Studio", price: 20, quantity: 1 }],
+ } }],
+ })
+ expect(payload).not.toHaveProperty("validation_behavior")
+ expect(mocked.finalizePurchaseDelivery).toHaveBeenLastCalledWith(db, "in_current", expect.objectContaining({
+ status: "sent", purchaseType: "initial_subscription", valueMinor: 2000,
+ }))
+ })
+
+ it("sends exactly once when Stripe provides only the legacy invoice subscription", async () => {
+ currentInvoice = invoice({ parent: null, subscription: "sub_owner" })
+
+ await deliverInvoicePurchase(db, stripe, env, currentInvoice, "owner")
+
+ expect(stripe.subscriptions.retrieve).toHaveBeenCalledOnce()
+ expect(stripe.subscriptions.retrieve).toHaveBeenCalledWith("sub_owner")
+ expect(fetcher).toHaveBeenCalledOnce()
+ expect(mocked.finalizePurchaseDelivery).toHaveBeenLastCalledWith(db, "in_current", expect.objectContaining({
+ status: "sent", reason: "delivered", purchaseType: "initial_subscription",
+ }))
+ })
+
+ it.each([
+ ["missing", undefined],
+ ["invalid", "not-a-session"],
+ ])("skips an initial purchase with %s session identity", async (_name, sessionId) => {
+ const metadata: Record<string, string> = {
+ alook_user_id: "owner",
+ alook_ga_client_id: "123456789.1700000000",
+ alook_ga_consent_revision: "2",
+ }
+ if (sessionId) metadata.alook_ga_session_id = sessionId
+ vi.mocked(stripe.subscriptions.retrieve).mockResolvedValue({
+ id: "sub_owner", livemode: false, customer: "cus_owner", metadata,
+ } as unknown as Stripe.Subscription)
+
+ await deliverInvoicePurchase(db, stripe, env, currentInvoice, "owner")
+
+ expect(fetcher).not.toHaveBeenCalled()
+ expect(mocked.finalizePurchaseDelivery).toHaveBeenLastCalledWith(db, "in_current", expect.objectContaining({
+ status: "skipped", reason: "session_identity_invalid",
+ }))
+ })
+
+ it.each([
+ ["renewal", "subscription_cycle", [line("price_studio", 2000)], "renewal"],
+ ["upgrade", "subscription_update", [line("price_studio", -1000), line("price_house", 3000)], "upgrade"],
+ ["ambiguous update", "subscription_update", [line("price_house", 2000)], "other"],
+ ["resubscription", "subscription_create", [line("price_studio", 2000)], "other"],
+ ])("classifies %s and never reuses the old session", async (_name, reason, invoiceLines, expected) => {
+ currentInvoice = invoice({ billing_reason: reason })
+ lines = invoiceLines
+ priorInvoices = [invoice({ id: "in_prior", created: 100 }), currentInvoice]
+ await deliverInvoicePurchase(db, stripe, env, currentInvoice, "owner")
+ const payload = JSON.parse(fetcher.mock.calls[0][1].body as string)
+ expect(payload.events[0].params.purchase_type).toBe(expected)
+ expect(payload.events[0].params).not.toHaveProperty("session_id")
+ })
+
+ it("records later consent withdrawal as revoked without network delivery", async () => {
+ mocked.getAnalyticsConsent.mockResolvedValue({ decision: "denied", revision: 3 })
+ await deliverInvoicePurchase(db, stripe, env, currentInvoice, "owner")
+ expect(fetcher).not.toHaveBeenCalled()
+ expect(mocked.finalizePurchaseDelivery).toHaveBeenLastCalledWith(db, "in_current", expect.objectContaining({
+ status: "skipped", reason: "consent_revoked",
+ }))
+ })
+
+ it("does not revive checkout identity after consent is denied and granted again", async () => {
+ mocked.getAnalyticsConsent.mockResolvedValue({ decision: "granted", revision: 4 })
+ await deliverInvoicePurchase(db, stripe, env, currentInvoice, "owner")
+ expect(fetcher).not.toHaveBeenCalled()
+ expect(mocked.finalizePurchaseDelivery).toHaveBeenLastCalledWith(db, "in_current", expect.objectContaining({
+ status: "skipped", reason: "consent_revision_changed",
+ }))
+ })
+
+ it("keeps a replayed stale grant auditable and suppresses duplicate webhook attempts", async () => {
+ mocked.getAnalyticsConsent.mockResolvedValue({ decision: "denied", revision: 2, sourceVersion: 200 })
+ vi.mocked(stripe.subscriptions.retrieve).mockResolvedValue({
+ id: "sub_owner", livemode: false, customer: "cus_owner",
+ metadata: { alook_user_id: "owner", alook_ga_consent_status: "stale_consent_proof" },
+ } as unknown as Stripe.Subscription)
+ mocked.claimPurchaseDelivery.mockResolvedValueOnce(true).mockResolvedValueOnce(false)
+
+ await deliverInvoicePurchase(db, stripe, env, currentInvoice, "owner")
+ await deliverInvoicePurchase(db, stripe, env, currentInvoice, "owner")
+
+ expect(fetcher).not.toHaveBeenCalled()
+ expect(mocked.claimPurchaseDelivery).toHaveBeenCalledTimes(2)
+ expect(mocked.finalizePurchaseDelivery).toHaveBeenCalledOnce()
+ expect(mocked.finalizePurchaseDelivery).toHaveBeenLastCalledWith(db, "in_current", expect.objectContaining({
+ status: "skipped", reason: "stale_consent_proof",
+ }))
+ })
+
+ it("records zero-value and credit-covered invoices as skipped", async () => {
+ currentInvoice = invoice({ amount_paid: 0 })
+ await deliverInvoicePurchase(db, stripe, env, currentInvoice, "owner")
+ expect(fetcher).not.toHaveBeenCalled()
+ expect(mocked.finalizePurchaseDelivery).toHaveBeenLastCalledWith(db, "in_current", expect.objectContaining({
+ status: "skipped", reason: "invoice_ineligible",
+ }))
+ })
+
+ it("records invoice retrieval failure", async () => {
+ vi.mocked(stripe.invoices.retrieve).mockRejectedValue(new Error("offline"))
+ await deliverInvoicePurchase(db, stripe, env, currentInvoice, "owner")
+ expect(mocked.finalizePurchaseDelivery).toHaveBeenLastCalledWith(db, "in_current", {
+ status: "failed", reason: "invoice_retrieval_failed",
+ })
+ })
+
+ it("rejects a webhook invoice whose customer differs from the retrieved invoice", async () => {
+ await deliverInvoicePurchase(db, stripe, env, invoice({ customer: "cus_other" }), "owner")
+ expect(mocked.finalizePurchaseDelivery).toHaveBeenLastCalledWith(db, "in_current", {
+ status: "failed", reason: "invoice_customer_mismatch",
+ })
+ })
+
+ it("records purchase context retrieval failure", async () => {
+ mocked.listPrices.mockRejectedValue(new Error("offline"))
+ await deliverInvoicePurchase(db, stripe, env, currentInvoice, "owner")
+ expect(mocked.finalizePurchaseDelivery).toHaveBeenLastCalledWith(db, "in_current", {
+ status: "failed", reason: "purchase_context_failed",
+ })
+ })
+
+ it("rejects a subscription owned by a different customer or user", async () => {
+ vi.mocked(stripe.subscriptions.retrieve).mockResolvedValue({
+ id: "sub_owner", livemode: false, customer: "cus_other", metadata: { alook_user_id: "owner" },
+ } as unknown as Stripe.Subscription)
+ await deliverInvoicePurchase(db, stripe, env, currentInvoice, "owner")
+ expect(mocked.finalizePurchaseDelivery).toHaveBeenLastCalledWith(db, "in_current", {
+ status: "failed", reason: "subscription_mismatch",
+ })
+ })
+
+ it("skips invoice lines that do not map to an eligible paid plan", async () => {
+ lines = [line("price_unknown", 2000)]
+ await deliverInvoicePurchase(db, stripe, env, currentInvoice, "owner")
+ expect(mocked.finalizePurchaseDelivery).toHaveBeenLastCalledWith(db, "in_current", {
+ status: "skipped", reason: "invoice_items_ineligible", currency: "USD", valueMinor: 2000,
+ })
+ })
+
+ it("records purchase classification failure", async () => {
+ stripe.invoices.list = vi.fn(() => ({ async *[Symbol.asyncIterator]() { throw new Error("offline") } })) as unknown as typeof stripe.invoices.list
+ await deliverInvoicePurchase(db, stripe, env, currentInvoice, "owner")
+ expect(mocked.finalizePurchaseDelivery).toHaveBeenLastCalledWith(db, "in_current", expect.objectContaining({
+ status: "failed", reason: "purchase_classification_failed",
+ }))
+ })
+
+ it("records consent lookup failure", async () => {
+ mocked.getAnalyticsConsent.mockRejectedValue(new Error("offline"))
+ await deliverInvoicePurchase(db, stripe, env, currentInvoice, "owner")
+ expect(mocked.finalizePurchaseDelivery).toHaveBeenLastCalledWith(db, "in_current", expect.objectContaining({
+ status: "failed", reason: "consent_lookup_failed",
+ }))
+ })
+
+ it("skips when current consent or checkout identity is unavailable", async () => {
+ mocked.getAnalyticsConsent.mockResolvedValue(null)
+ await deliverInvoicePurchase(db, stripe, env, currentInvoice, "owner")
+ expect(mocked.finalizePurchaseDelivery).toHaveBeenLastCalledWith(db, "in_current", expect.objectContaining({
+ status: "skipped", reason: "consent_or_identity_unavailable",
+ }))
+ })
+
+ it("does not send when configuration is missing", async () => {
+ await deliverInvoicePurchase(db, stripe, { ...env, GA4_API_SECRET: undefined }, currentInvoice, "owner")
+ expect(fetcher).not.toHaveBeenCalled()
+ expect(mocked.finalizePurchaseDelivery).toHaveBeenLastCalledWith(db, "in_current", expect.objectContaining({
+ status: "failed", reason: "ga_configuration_missing",
+ }))
+ })
+
+ it("keeps debug validation in an explicit acceptance-only helper", async () => {
+ fetcher.mockReset().mockResolvedValueOnce(new Response(JSON.stringify({ validationMessages: [{
+ fieldPath: "events[0]", description: "invalid", validationCode: "VALUE_INVALID",
+ }] }), { status: 200 }))
+ const result = await validatePurchasePayloadForAcceptance(env, {
+ client_id: "123456789.1700000000",
+ events: [{ name: "purchase", params: { transaction_id: "in_acceptance" } }],
+ })
+ expect(fetcher).toHaveBeenCalledOnce()
+ expect(fetcher.mock.calls[0][0]).toContain("/debug/mp/collect?")
+ expect(JSON.parse(fetcher.mock.calls[0][1].body as string)).toMatchObject({
+ validation_behavior: "ENFORCE_RECOMMENDATIONS",
+ events: [{ name: "purchase", params: { transaction_id: "in_acceptance" } }],
+ })
+ expect(result).toMatchObject({ ok: false, reason: "validation_rejected", validationJson: expect.not.stringContaining("ga-secret") })
+ })
+
+ it("acceptance validation reports missing configuration, transport, HTTP, and success", async () => {
+ const payload = { client_id: "fixture", events: [] }
+ await expect(validatePurchasePayloadForAcceptance({ ...env, GA4_API_SECRET: undefined }, payload))
+ .resolves.toEqual({ ok: false, reason: "ga_configuration_missing" })
+ expect(fetcher).not.toHaveBeenCalled()
+
+ fetcher.mockRejectedValueOnce(new Error("offline"))
+ await expect(validatePurchasePayloadForAcceptance(env, payload))
+ .resolves.toEqual({ ok: false, reason: "validation_transport_failed" })
+
+ fetcher.mockResolvedValueOnce(new Response(null, { status: 429 }))
+ await expect(validatePurchasePayloadForAcceptance(env, payload))
+ .resolves.toEqual({ ok: false, reason: "validation_http_429" })
+
+ fetcher.mockResolvedValueOnce(new Response(JSON.stringify({ validationMessages: [] }), { status: 200 }))
+ await expect(validatePurchasePayloadForAcceptance(env, payload)).resolves.toEqual({
+ ok: true, reason: "accepted", validationJson: '{"validationMessages":[]}',
+ })
+ })
+
+ it("fails closed when the debug endpoint returns malformed evidence", async () => {
+ fetcher.mockReset().mockResolvedValueOnce(new Response("not-json", { status: 200 }))
+ const result = await validatePurchasePayloadForAcceptance(env, { client_id: "fixture", events: [] })
+ expect(fetcher).toHaveBeenCalledOnce()
+ expect(result).toEqual({ ok: false, reason: "validation_response_invalid" })
+ })
+
+ it("rejects a debug response without a validation message array", async () => {
+ fetcher.mockReset().mockResolvedValueOnce(new Response("{}", { status: 200 }))
+ await expect(validatePurchasePayloadForAcceptance(env, { client_id: "fixture", events: [] }))
+ .resolves.toEqual({ ok: false, reason: "validation_response_invalid" })
+ })
+
+ it("rejects a null debug response as malformed evidence", async () => {
+ fetcher.mockReset().mockResolvedValueOnce(new Response("null", { status: 200 }))
+ await expect(validatePurchasePayloadForAcceptance(env, { client_id: "fixture", events: [] }))
+ .resolves.toEqual({ ok: false, reason: "validation_response_invalid" })
+ })
+
+ it("sanitizes a malformed validation message item", async () => {
+ fetcher.mockReset().mockResolvedValueOnce(new Response(JSON.stringify({ validationMessages: [null] }), { status: 200 }))
+ await expect(validatePurchasePayloadForAcceptance(env, { client_id: "fixture", events: [] })).resolves.toEqual({
+ ok: false,
+ reason: "validation_rejected",
+ validationJson: '{"validationMessages":[{}]}',
+ })
+ })
+
+ it("aborts acceptance validation at the bounded timeout", async () => {
+ vi.useFakeTimers()
+ try {
+ fetcher.mockReset().mockImplementationOnce((_url, init: RequestInit) => new Promise((_resolve, reject) => {
+ init.signal?.addEventListener("abort", () => reject(new DOMException("aborted", "AbortError")))
+ }))
+ const pending = validatePurchasePayloadForAcceptance(env, { client_id: "fixture", events: [] })
+ await vi.advanceTimersByTimeAsync(2_500)
+ await expect(pending).resolves.toEqual({ ok: false, reason: "validation_transport_failed" })
+ expect(fetcher.mock.calls[0][1].signal).toMatchObject({ aborted: true })
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it("keeps an ambiguous collection failure auditable and suppresses duplicate attempts", async () => {
+ fetcher.mockReset().mockRejectedValueOnce(new Error("timeout"))
+ await deliverInvoicePurchase(db, stripe, env, currentInvoice, "owner")
+ expect(mocked.finalizePurchaseDelivery).toHaveBeenLastCalledWith(db, "in_current", expect.objectContaining({
+ status: "failed", reason: "collection_transport_ambiguous",
+ }))
+ mocked.claimPurchaseDelivery.mockResolvedValue(false)
+ await deliverInvoicePurchase(db, stripe, env, currentInvoice, "owner")
+ expect(fetcher).toHaveBeenCalledOnce()
+ })
+
+ it("records a non-success collection response", async () => {
+ fetcher.mockResolvedValueOnce(new Response(null, { status: 503 }))
+ await deliverInvoicePurchase(db, stripe, env, currentInvoice, "owner")
+ expect(mocked.finalizePurchaseDelivery).toHaveBeenLastCalledWith(db, "in_current", expect.objectContaining({
+ status: "failed", reason: "collection_http_503",
+ }))
+ })
+})
diff --git a/src/web/src/lib/billing/purchase-analytics.ts b/src/web/src/lib/billing/purchase-analytics.ts
new file mode 100644
index 000000000..e0bce87d2
--- /dev/null
+++ b/src/web/src/lib/billing/purchase-analytics.ts
@@ -0,0 +1,308 @@
+import { queries, type Database } from "@alook/shared"
+import type Stripe from "stripe"
+import { assertStripeMode, stripeId } from "./client"
+import { stripeAmountToMajorUnit } from "./currency"
+import {
+ GA4_CLIENT_ID_METADATA,
+ GA4_CONSENT_REVISION_METADATA,
+ GA4_CONSENT_STATUS_METADATA,
+ GA4_MEASUREMENT_ID,
+ GA4_SESSION_ID_METADATA,
+ parseGaClientId,
+ parseGaSessionId,
+} from "@/lib/analytics-consent-server"
+
+const GA_TIMEOUT_MS = 2_500
+const MAX_VALIDATION_MESSAGES = 10
+const MAX_VALIDATION_TEXT = 300
+const PLAN_NAMES = { studio: "Studio", house: "House" } as const
+
+type CatalogEntry = Awaited<ReturnType<typeof queries.billing.listPrices>>[number]
+type PurchaseType = "initial_subscription" | "renewal" | "upgrade" | "other"
+type InvoiceWithLegacySubscription = Stripe.Invoice & { subscription?: string | Stripe.Subscription | null }
+
+type ValidationMessage = {
+ fieldPath?: string
+ description?: string
+ validationCode?: string
+}
+
+function invoiceSubscriptionId(invoice: Stripe.Invoice): string | null {
+ return stripeId(invoice.parent?.subscription_details?.subscription
+ ?? (invoice as InvoiceWithLegacySubscription).subscription)
+}
+
+function lineSubscriptionId(line: Stripe.InvoiceLineItem): string | null {
+ return stripeId(line.parent?.subscription_item_details?.subscription ?? line.subscription)
+}
+
+function linePriceId(line: Stripe.InvoiceLineItem): string | null {
+ return stripeId(line.pricing?.price_details?.price)
+}
+
+function boundedText(value: unknown): string | undefined {
+ return typeof value === "string" ? value.slice(0, MAX_VALIDATION_TEXT) : undefined
+}
+
+function validationEvidence(value: unknown): { json: string; hasErrors: boolean } | null {
+ const source = value && typeof value === "object" && !Array.isArray(value)
+ ? (value as { validationMessages?: unknown }).validationMessages
+ : null
+ if (!Array.isArray(source)) return null
+ const messages = source.slice(0, MAX_VALIDATION_MESSAGES).map((item): ValidationMessage => {
+ if (!item || typeof item !== "object" || Array.isArray(item)) return {}
+ const message = item as Record<string, unknown>
+ return {
+ fieldPath: boundedText(message.fieldPath),
+ description: boundedText(message.description),
+ validationCode: boundedText(message.validationCode),
+ }
+ })
+ return { json: JSON.stringify({ validationMessages: messages }), hasErrors: messages.length > 0 }
+}
+
+export async function validatePurchasePayloadForAcceptance(
+ env: Env,
+ payload: Record<string, unknown>,
+): Promise<{ ok: boolean; reason: string; validationJson?: string }> {
+ if (!env.GA4_API_SECRET) return { ok: false, reason: "ga_configuration_missing" }
+ const query = new URLSearchParams({ measurement_id: GA4_MEASUREMENT_ID, api_secret: env.GA4_API_SECRET })
+ let response: Response
+ try {
+ response = await fetchWithTimeout(`https://www.google-analytics.com/debug/mp/collect?${query}`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ ...payload, validation_behavior: "ENFORCE_RECOMMENDATIONS" }),
+ })
+ } catch {
+ return { ok: false, reason: "validation_transport_failed" }
+ }
+ if (!response.ok) return { ok: false, reason: `validation_http_${response.status}` }
+ let evidence: ReturnType<typeof validationEvidence>
+ try {
+ evidence = validationEvidence(await response.json())
+ } catch {
+ evidence = null
+ }
+ if (!evidence) return { ok: false, reason: "validation_response_invalid" }
+ if (evidence.hasErrors) return { ok: false, reason: "validation_rejected", validationJson: evidence.json }
+ return { ok: true, reason: "accepted", validationJson: evidence.json }
+}
+
+async function fetchWithTimeout(url: string, init: RequestInit): Promise<Response> {
+ const controller = new AbortController()
+ const timer = setTimeout(() => controller.abort(), GA_TIMEOUT_MS)
+ try {
+ return await fetch(url, { ...init, signal: controller.signal })
+ } finally {
+ clearTimeout(timer)
+ }
+}
+
+async function invoiceLines(stripe: Stripe, invoiceId: string) {
+ const lines: Stripe.InvoiceLineItem[] = []
+ for await (const line of stripe.invoices.listLineItems(invoiceId, { limit: 100 })) lines.push(line)
+ return lines
+}
+
+function positivePaidSubscriptionInvoice(invoice: Stripe.Invoice): boolean {
+ return invoice.status === "paid" && invoice.amount_paid > 0 && invoiceSubscriptionId(invoice) !== null
+}
+
+async function hasEarlierPositiveInvoice(
+ stripe: Stripe,
+ invoice: Stripe.Invoice,
+ customerId: string,
+): Promise<boolean> {
+ for await (const candidate of stripe.invoices.list({ customer: customerId, status: "paid", limit: 100 })) {
+ if (candidate.id === invoice.id || candidate.created > invoice.created) continue
+ if (positivePaidSubscriptionInvoice(candidate)) return true
+ }
+ return false
+}
+
+function mappedPlan(lines: Stripe.InvoiceLineItem[], subscriptionId: string, catalog: CatalogEntry[]) {
+ const byPrice = new Map(catalog.map((entry) => [entry.priceId, entry]))
+ const relevant = lines.filter((line) => lineSubscriptionId(line) === subscriptionId)
+ const valueMinor = relevant.reduce((sum, line) => sum + line.amount, 0)
+ const positivePlans = new Map<string, CatalogEntry>()
+ const negativePlans = new Map<string, CatalogEntry>()
+ for (const line of relevant) {
+ const mapping = byPrice.get(linePriceId(line) ?? "")
+ if (!mapping) continue
+ if (line.amount > 0) positivePlans.set(mapping.planId, mapping)
+ if (line.amount < 0) negativePlans.set(mapping.planId, mapping)
+ }
+ const target = positivePlans.size === 1 ? [...positivePlans.values()][0]! : null
+ return { valueMinor, target, previous: [...negativePlans.values()] }
+}
+
+async function purchaseType(
+ stripe: Stripe,
+ invoice: Stripe.Invoice,
+ customerId: string,
+ target: CatalogEntry,
+ previous: CatalogEntry[],
+): Promise<PurchaseType> {
+ if (!await hasEarlierPositiveInvoice(stripe, invoice, customerId)) return "initial_subscription"
+ if (invoice.billing_reason === "subscription_cycle") return "renewal"
+ if (invoice.billing_reason === "subscription_update" && previous.length === 1
+ && previous[0]!.planId !== target.planId && previous[0]!.sortOrder < target.sortOrder) return "upgrade"
+ return "other"
+}
+
+function finalizedFields(input: {
+ purchaseType?: PurchaseType
+ currency?: string
+ valueMinor?: number
+ planId?: string
+ validationJson?: string
+}) {
+ return input
+}
+
+export async function deliverInvoicePurchase(
+ db: Database,
+ stripe: Stripe,
+ env: Env,
+ webhookInvoice: Stripe.Invoice,
+ userId: string,
+) {
+ if (!await queries.billing.claimPurchaseDelivery(db, webhookInvoice.id, userId)) return
+
+ const skip = async (reason: string, fields = finalizedFields({})) => {
+ await queries.billing.finalizePurchaseDelivery(db, webhookInvoice.id, { status: "skipped", reason, ...fields })
+ }
+ const fail = async (reason: string, fields = finalizedFields({})) => {
+ await queries.billing.finalizePurchaseDelivery(db, webhookInvoice.id, { status: "failed", reason, ...fields })
+ }
+
+ let invoice: Stripe.Invoice
+ try {
+ invoice = await stripe.invoices.retrieve(webhookInvoice.id)
+ assertStripeMode(env, invoice)
+ } catch {
+ await fail("invoice_retrieval_failed")
+ return
+ }
+ if (!positivePaidSubscriptionInvoice(invoice)) {
+ await skip("invoice_ineligible")
+ return
+ }
+ const subscriptionId = invoiceSubscriptionId(invoice)!
+ const customerId = stripeId(invoice.customer)
+ if (!customerId || customerId !== stripeId(webhookInvoice.customer)) {
+ await fail("invoice_customer_mismatch")
+ return
+ }
+
+ let lines: Stripe.InvoiceLineItem[]
+ let subscription: Stripe.Subscription
+ let catalog: CatalogEntry[]
+ try {
+ [lines, subscription, catalog] = await Promise.all([
+ invoiceLines(stripe, invoice.id),
+ stripe.subscriptions.retrieve(subscriptionId),
+ queries.billing.listPrices(db, true),
+ ])
+ assertStripeMode(env, subscription)
+ } catch {
+ await fail("purchase_context_failed")
+ return
+ }
+ if (stripeId(subscription.customer) !== customerId || subscription.metadata.alook_user_id !== userId) {
+ await fail("subscription_mismatch")
+ return
+ }
+ const { valueMinor, target, previous } = mappedPlan(lines, subscriptionId, catalog)
+ const currency = invoice.currency.toUpperCase()
+ const value = stripeAmountToMajorUnit(valueMinor, currency)
+ if (!target || !["studio", "house"].includes(target.planId) || value === null || value <= 0) {
+ await skip("invoice_items_ineligible", { currency, valueMinor })
+ return
+ }
+
+ let type: PurchaseType
+ try {
+ type = await purchaseType(stripe, invoice, customerId, target, previous)
+ } catch {
+ await fail("purchase_classification_failed", { currency, valueMinor, planId: target.planId })
+ return
+ }
+ const fields = { purchaseType: type, currency, valueMinor, planId: target.planId }
+ let consent: Awaited<ReturnType<typeof queries.billing.getAnalyticsConsent>>
+ try {
+ consent = await queries.billing.getAnalyticsConsent(db, userId)
+ } catch {
+ await fail("consent_lookup_failed", fields)
+ return
+ }
+ const consentRevision = Number(subscription.metadata[GA4_CONSENT_REVISION_METADATA])
+ const clientId = parseGaClientId(`GA1.1.${subscription.metadata[GA4_CLIENT_ID_METADATA] ?? ""}`)
+ if (subscription.metadata[GA4_CONSENT_STATUS_METADATA] === "stale_consent_proof") {
+ await skip("stale_consent_proof", fields)
+ return
+ }
+ if (consent?.decision === "denied") {
+ await skip("consent_revoked", fields)
+ return
+ }
+ if (consent?.decision !== "granted" || !Number.isSafeInteger(consentRevision)
+ || consentRevision < 1 || !clientId) {
+ await skip("consent_or_identity_unavailable", fields)
+ return
+ }
+ if (consent.revision !== consentRevision) {
+ await skip("consent_revision_changed", fields)
+ return
+ }
+ const sessionId = type === "initial_subscription"
+ ? parseGaSessionId(`GS1.1.${subscription.metadata[GA4_SESSION_ID_METADATA] ?? ""}`)
+ : null
+ if (type === "initial_subscription" && !sessionId) {
+ await skip("session_identity_invalid", fields)
+ return
+ }
+ if (!env.GA4_API_SECRET) {
+ await fail("ga_configuration_missing", fields)
+ return
+ }
+
+ const params = {
+ transaction_id: invoice.id,
+ currency,
+ value,
+ purchase_type: type,
+ engagement_time_msec: 1,
+ ...(sessionId ? { session_id: Number(sessionId) } : {}),
+ items: [{
+ item_id: target.planId,
+ item_name: PLAN_NAMES[target.planId as keyof typeof PLAN_NAMES],
+ price: value,
+ quantity: 1,
+ }],
+ }
+ const payload = {
+ client_id: clientId,
+ consent: { ad_user_data: "DENIED", ad_personalization: "DENIED" },
+ events: [{ name: "purchase", params }],
+ }
+ const query = new URLSearchParams({ measurement_id: GA4_MEASUREMENT_ID, api_secret: env.GA4_API_SECRET })
+ const request = { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) }
+
+ try {
+ const response = await fetchWithTimeout(`https://www.google-analytics.com/mp/collect?${query}`, request)
+ if (!response.ok) {
+ await fail(`collection_http_${response.status}`, fields)
+ return
+ }
+ } catch {
+ await fail("collection_transport_ambiguous", fields)
+ return
+ }
+ await queries.billing.finalizePurchaseDelivery(db, invoice.id, {
+ status: "sent",
+ reason: "delivered",
+ ...fields,
+ })
+}
diff --git a/src/web/src/lib/billing/reconcile-races.test.ts b/src/web/src/lib/billing/reconcile-races.test.ts
index 34f9200a4..f0927a58a 100644
--- a/src/web/src/lib/billing/reconcile-races.test.ts
+++ b/src/web/src/lib/billing/reconcile-races.test.ts
@@ -40,11 +40,47 @@ describe("reconciliation freshness and post-commit effects", () => {
it("passes the committed machine epochs into automatic disconnection", async () => {
mocked.applyBillingPlan.mockResolvedValue({ applied: true, deactivatedBotIds: [], disconnectedMachines: [{ machineId: "m", userId: "owner", doName: "captured-old-epoch" }] })
const warning = vi.spyOn(console, "warn").mockImplementation(() => {})
- await reconcileBilling(db, stripe, env, "owner")
+ await expect(reconcileBilling(db, stripe, env, "owner")).resolves.toBe("applied")
expect(forceCloseCommunityMachinesByDoNames).toHaveBeenCalledExactlyOnceWith(env, ["captured-old-epoch"])
warning.mockRestore()
})
+ it("verifies an already committed billing projection without writing again", async () => {
+ const subscription = sub("sub_new", "house")
+ retrieve.mockResolvedValue(subscription)
+ mocked.getBilling.mockResolvedValue({
+ ...row,
+ subscriptionId: subscription.id,
+ subscription: {
+ plan: { id: "house", displayName: "House" },
+ status: "active",
+ currentPeriodEnd: new Date(1791604427 * 1000).toISOString(),
+ cancelAt: null,
+ scheduledChange: null,
+ },
+ })
+ mocked.getEffectivePlan.mockResolvedValue({ isFounder: false, plan: { id: "house", displayName: "House" } })
+
+ await expect(reconcileBilling(db, stripe, env, "owner")).resolves.toBe("verified_already_applied")
+ expect(mocked.applyBillingPlan).not.toHaveBeenCalled()
+ })
+
+ it("verifies an already committed null Free projection without writing again", async () => {
+ mocked.getBilling.mockResolvedValue({ ...row, customerId: null, subscriptionId: null, subscription: null })
+ mocked.getEffectivePlan.mockResolvedValue({ isFounder: false, plan: { id: "free", displayName: "Free" } })
+
+ await expect(reconcileBilling(db, stripe, env, "owner")).resolves.toBe("verified_already_applied")
+ expect(stripe.customers.retrieve).not.toHaveBeenCalled()
+ expect(mocked.applyBillingPlan).not.toHaveBeenCalled()
+ })
+
+ it("returns ignored when the billing owner is no longer eligible", async () => {
+ mocked.getUserInternal.mockResolvedValue({ isBot: false, deletedAt: "2026-09-29" })
+ await expect(reconcileBilling(db, stripe, env, "owner")).resolves.toBe("ignored")
+ expect(stripe.customers.retrieve).not.toHaveBeenCalled()
+ expect(mocked.applyBillingPlan).not.toHaveBeenCalled()
+ })
+
function confirmedFounder() {
const attempt = { id: "attempt-founder", priceId: "studio", founderAcknowledged: true, sessionId: "cs-founder" }
mocked.getBilling.mockResolvedValue({ ...row, checkoutAttempt: attempt })
@@ -167,7 +203,7 @@ describe("reconciliation freshness and post-commit effects", () => {
})
it("does not call Stripe or apply a projection for a Founder", async () => {
mocked.getEffectivePlan.mockResolvedValue({ isFounder: true })
- await reconcileBilling(db, stripe, env, "owner")
+ await expect(reconcileBilling(db, stripe, env, "owner")).resolves.toBe("ignored")
expect(stripe.customers.retrieve).not.toHaveBeenCalled()
expect(mocked.applyBillingPlan).not.toHaveBeenCalled()
})
@@ -187,7 +223,7 @@ describe("reconciliation freshness and post-commit effects", () => {
mocked.applyBillingPlan.mockResolvedValue({ applied: true, deactivatedBotIds: ["bot1"] })
mocked.getBotOwnedBy.mockResolvedValue({ isActive: false, machineId: "m1" })
mocked.push.mockRejectedValue(new Error("offline"))
- await expect(reconcileBilling(db, stripe, env, "owner")).resolves.toBeUndefined()
+ await expect(reconcileBilling(db, stripe, env, "owner")).resolves.toBe("applied")
expect(mocked.applyBillingPlan).toHaveBeenCalledOnce()
})
})
diff --git a/src/web/src/lib/billing/reconcile.ts b/src/web/src/lib/billing/reconcile.ts
index c1a44c01b..208e28ca3 100644
--- a/src/web/src/lib/billing/reconcile.ts
+++ b/src/web/src/lib/billing/reconcile.ts
@@ -9,6 +9,7 @@ import { broadcastToUser } from "@/lib/broadcast"
type Catalog = Awaited<ReturnType<typeof getCatalog>>
type BillingRow = NonNullable<Awaited<ReturnType<typeof queries.billing.getBilling>>>
+export type BillingReconcileResult = "applied" | "verified_already_applied" | "ignored"
const terminal = new Set(["canceled", "unpaid", "incomplete_expired"])
@@ -162,17 +163,32 @@ export async function notifyDisconnectedMachines(env: Env, db: Database, machine
}
}
-export async function reconcileBilling(db: Database, stripe: Stripe, env: Env, userId: string) {
+function sameSubscription(left: BillingSubscription | null, right: BillingSubscription | null) {
+ if (!left || !right) return left === right
+ return left.plan.id === right.plan.id && left.plan.displayName === right.plan.displayName
+ && left.status === right.status && left.currentPeriodEnd === right.currentPeriodEnd
+ && left.cancelAt === right.cancelAt
+ && left.scheduledChange?.plan.id === right.scheduledChange?.plan.id
+ && left.scheduledChange?.plan.displayName === right.scheduledChange?.plan.displayName
+ && left.scheduledChange?.effectiveAt === right.scheduledChange?.effectiveAt
+}
+
+export async function reconcileBilling(
+ db: Database,
+ stripe: Stripe,
+ env: Env,
+ userId: string,
+): Promise<BillingReconcileResult> {
for (let attempt = 0; attempt < 4; attempt++) {
const row = await queries.billing.getBilling(db, userId)
const effective = await queries.billing.getEffectivePlan(db, userId)
- if (!row || (effective.isFounder && !row.checkoutAttempt?.founderAcknowledged)) return
+ if (!row || (effective.isFounder && !row.checkoutAttempt?.founderAcknowledged)) return "ignored"
const owner = await queries.user.getUserInternal(db, userId)
- if (!owner || owner.deletedAt !== null || owner.isBot) return
+ if (!owner || owner.deletedAt !== null || owner.isBot) return "ignored"
const subscription = await currentSubscription(stripe, env, row)
if (effective.isFounder && (!subscription || !["active", "past_due"].includes(subscription.status)
|| subscription.pending_update || subscription.metadata.alook_attempt_id !== row.checkoutAttempt!.id
- || subscription.items.data[0]?.price.id !== row.checkoutAttempt!.priceId)) return
+ || subscription.items.data[0]?.price.id !== row.checkoutAttempt!.priceId)) return "ignored"
const [catalog, free, paidInvoice] = await Promise.all([
getCatalog(db), queries.billing.getDefaultPlan(db),
subscription ? paidInvoiceFor(stripe, subscription) : Promise.resolve(null),
@@ -186,20 +202,25 @@ export async function reconcileBilling(db: Database, stripe: Stripe, env: Env, u
if (effective.isFounder && (paidInvoice?.status !== "paid"
|| stripeId(paidLineFor(subscription!, paidInvoice, catalog)?.pricing?.price_details?.price) !== row.checkoutAttempt!.priceId
|| projection.plan.id !== catalog.find((entry) => entry.priceId === row.checkoutAttempt!.priceId)?.planId
- || !await acknowledgedFounderSession(stripe, env, row, subscription!))) return
+ || !await acknowledgedFounderSession(stripe, env, row, subscription!))) return "ignored"
const patch = {
subscriptionId: subscription?.id ?? null,
subscription: projection.subscription,
...(subscription && row.checkoutAttempt && subscription.metadata.alook_attempt_id === row.checkoutAttempt.id
? { checkoutAttempt: null } : {}),
}
+ const checkoutMatches = !("checkoutAttempt" in patch) || row.checkoutAttempt === patch.checkoutAttempt
+ if (effective.plan?.id === projection.plan.id && row.subscriptionId === patch.subscriptionId
+ && sameSubscription(row.subscription, patch.subscription) && checkoutMatches) {
+ return "verified_already_applied"
+ }
const result = effective.isFounder
? await queries.billing.applyBillingPlan(db, row, patch, projection.plan.id, row.checkoutAttempt!.id)
: await queries.billing.applyBillingPlan(db, row, patch, projection.plan.id)
if (result.applied) {
await notifyDeactivated(env, db, userId, result.deactivatedBotIds)
await notifyDisconnectedMachines(env, db, result.disconnectedMachines ?? [])
- return
+ return "applied"
}
}
throw new BillingError("BILLING_RETRY_REQUIRED", 503)
diff --git a/src/web/src/lib/billing/service.test.ts b/src/web/src/lib/billing/service.test.ts
index 3243315f4..54a713c02 100644
--- a/src/web/src/lib/billing/service.test.ts
+++ b/src/web/src/lib/billing/service.test.ts
@@ -14,7 +14,7 @@ import { BillingError } from "./client"
type Row = {
userId: string; customerId: string | null; subscriptionId: string | null; subscription: null; revision: number;
- checkoutAttempt: null | { id: string; priceId: string; email: string; origin: string; startedAt: number; sessionId: string | null; founderAcknowledged?: boolean };
+ checkoutAttempt: null | { id: string; priceId: string; email: string; origin: string; startedAt: number; sessionId: string | null; founderAcknowledged?: boolean; analytics?: { clientId: string; sessionId: string; consentRevision: number }; analyticsSkipReason?: "stale_consent_proof" };
}
let row: Row
let founder: boolean
@@ -166,6 +166,32 @@ describe("one unresolved Checkout per owner", () => {
expect(sessionCreates.mock.calls[0][0]).toMatchObject({ success_url: "http://localhost:3000/c/me/bots?billing=checkout", cancel_url: "http://localhost:3000/c/me/bots?billing=cancel", mode: "subscription", managed_payments: { enabled: false } })
expect(sessionCreates.mock.calls[0][1].idempotencyKey).toBe(`alook:checkout:${row.checkoutAttempt!.id}`)
})
+ it("freezes consented GA identity and copies it only to subscription metadata", async () => {
+ await createCheckout(db, stripe, env, "owner", "[email protected]", "studio", false, {
+ clientId: "123.456",
+ sessionId: "1700000000",
+ consentRevision: 3,
+ })
+ expect(row.checkoutAttempt?.analytics).toEqual({ clientId: "123.456", sessionId: "1700000000", consentRevision: 3 })
+ expect(sessionCreates.mock.calls[0][0].subscription_data.metadata).toMatchObject({
+ alook_ga_client_id: "123.456",
+ alook_ga_session_id: "1700000000",
+ alook_ga_consent_revision: "3",
+ })
+ expect(sessionCreates.mock.calls[0][0].metadata).not.toHaveProperty("alook_ga_client_id")
+ })
+ it("freezes a stale-proof audit marker without any GA identity", async () => {
+ const createCheckoutWithSkipReason = createCheckout as unknown as (...args: unknown[]) => ReturnType<typeof createCheckout>
+ await createCheckoutWithSkipReason(
+ db, stripe, env, "owner", "[email protected]", "studio", false, undefined, "stale_consent_proof",
+ )
+ expect(row.checkoutAttempt).toMatchObject({ analyticsSkipReason: "stale_consent_proof" })
+ expect(row.checkoutAttempt?.analytics).toBeUndefined()
+ expect(sessionCreates.mock.calls[0][0].subscription_data.metadata).toMatchObject({
+ alook_ga_consent_status: "stale_consent_proof",
+ })
+ expect(sessionCreates.mock.calls[0][0].subscription_data.metadata).not.toHaveProperty("alook_ga_client_id")
+ })
it("requires Founder acknowledgment before purchase and returns normal offers", async () => {
founder = true
await expect(checkout()).rejects.toMatchObject({ code: "BILLING_FOUNDER_PROTECTED" })
diff --git a/src/web/src/lib/billing/service.ts b/src/web/src/lib/billing/service.ts
index 6bc8bd297..5532d033a 100644
--- a/src/web/src/lib/billing/service.ts
+++ b/src/web/src/lib/billing/service.ts
@@ -1,8 +1,14 @@
-import { queries, type Database, type BillingSummary } from "@alook/shared"
+import { queries, type CheckoutAttempt, type Database, type BillingSummary } from "@alook/shared"
import type Stripe from "stripe"
import { assertStripeMode, billingOrigin, BillingError, stripeId } from "./client"
import { getOffers, requireOffer } from "./catalog"
import { currentSubscription, reconcileBilling } from "./reconcile"
+import {
+ GA4_CLIENT_ID_METADATA,
+ GA4_CONSENT_REVISION_METADATA,
+ GA4_CONSENT_STATUS_METADATA,
+ GA4_SESSION_ID_METADATA,
+} from "@/lib/analytics-consent-server"
type BillingRow = NonNullable<Awaited<ReturnType<typeof queries.billing.getBilling>>>
@@ -40,7 +46,17 @@ async function sessionForAttempt(stripe: Stripe, env: Env, row: BillingRow) {
return null
}
-export async function createCheckout(db: Database, stripe: Stripe, env: Env, userId: string, email: string, priceId: string, founderAcknowledged = false) {
+export async function createCheckout(
+ db: Database,
+ stripe: Stripe,
+ env: Env,
+ userId: string,
+ email: string,
+ priceId: string,
+ founderAcknowledged = false,
+ analytics?: NonNullable<CheckoutAttempt["analytics"]>,
+ analyticsSkipReason?: CheckoutAttempt["analyticsSkipReason"],
+) {
const effective = await requireBillingOwner(db, userId, founderAcknowledged)
await requireOffer(db, stripe, env, priceId)
for (let retry = 0; retry < 5; retry++) {
@@ -55,6 +71,8 @@ export async function createCheckout(db: Database, stripe: Stripe, env: Env, use
id: crypto.randomUUID(), priceId, email, origin: billingOrigin(env),
startedAt: Math.floor(Date.now() / 1000), sessionId: null,
...(founderAcknowledged ? { founderAcknowledged: true } : {}),
+ ...(analytics ? { analytics } : {}),
+ ...(analyticsSkipReason ? { analyticsSkipReason } : {}),
} }, founderAcknowledged)
if (!reserved) continue
row = reserved
@@ -102,6 +120,18 @@ export async function createCheckout(db: Database, stripe: Stripe, env: Env, use
row = saved
}
await requireBillingOwner(db, userId, founderAcknowledged)
+ const subscriptionMetadata = {
+ alook_user_id: userId,
+ alook_attempt_id: attempt.id,
+ ...(attempt.analytics ? {
+ [GA4_CLIENT_ID_METADATA]: attempt.analytics.clientId,
+ [GA4_SESSION_ID_METADATA]: attempt.analytics.sessionId,
+ [GA4_CONSENT_REVISION_METADATA]: String(attempt.analytics.consentRevision),
+ } : {}),
+ ...(attempt.analyticsSkipReason ? {
+ [GA4_CONSENT_STATUS_METADATA]: attempt.analyticsSkipReason,
+ } : {}),
+ }
session = await stripe.checkout.sessions.create({
mode: "subscription",
managed_payments: { enabled: false },
@@ -109,7 +139,7 @@ export async function createCheckout(db: Database, stripe: Stripe, env: Env, use
client_reference_id: userId,
line_items: [{ price: attempt.priceId, quantity: 1 }],
metadata: { alook_user_id: userId, alook_attempt_id: attempt.id },
- subscription_data: { metadata: { alook_user_id: userId, alook_attempt_id: attempt.id } },
+ subscription_data: { metadata: subscriptionMetadata },
expires_at: attempt.startedAt + 24 * 3600 - 60,
success_url: `${attempt.origin}/c/me/bots?billing=checkout`,
cancel_url: `${attempt.origin}/c/me/bots?billing=cancel`,
diff --git a/src/web/src/lib/billing/webhook.test.ts b/src/web/src/lib/billing/webhook.test.ts
index 8e5d4a1a8..dc2a4a33a 100644
--- a/src/web/src/lib/billing/webhook.test.ts
+++ b/src/web/src/lib/billing/webhook.test.ts
@@ -1,15 +1,16 @@
import { beforeEach, describe, expect, it, vi } from "vitest"
import Stripe from "stripe"
import type { Database } from "@alook/shared"
-const mocked = vi.hoisted(() => ({ getBillingByCustomer: vi.fn(), getBilling: vi.fn(), getEffectivePlan: vi.fn(), updateBilling: vi.fn(), reconcileBilling: vi.fn() }))
+const mocked = vi.hoisted(() => ({ getBillingByCustomer: vi.fn(), getBilling: vi.fn(), getEffectivePlan: vi.fn(), updateBilling: vi.fn(), reconcileBilling: vi.fn(), deliverInvoicePurchase: vi.fn() }))
vi.mock("@alook/shared", () => ({ queries: { billing: mocked } }))
vi.mock("./reconcile", () => ({ reconcileBilling: mocked.reconcileBilling }))
+vi.mock("./purchase-analytics", () => ({ deliverInvoicePurchase: mocked.deliverInvoicePurchase }))
import { handleBillingWebhook } from "./webhook"
const db = {} as Database
const stripe = new Stripe("sk_test_fixture")
const env = { STRIPE_SECRET_KEY: "sk_test_fixture", STRIPE_WEBHOOK_SECRET: "whsec_fixture" } as Env
-const body = (object: Record<string, unknown> = { customer: "cus_owner" }, livemode = false) => JSON.stringify({
+const body = (object: Record<string, unknown> = { id: "in_fixture", customer: "cus_owner" }, livemode = false) => JSON.stringify({
id: "evt_fixture", object: "event", type: "invoice.paid", livemode, data: { object },
}, null, 2)
const signature = (raw: string) => stripe.webhooks.generateTestHeaderString({ payload: raw, secret: env.STRIPE_WEBHOOK_SECRET! })
@@ -17,6 +18,7 @@ const signature = (raw: string) => stripe.webhooks.generateTestHeaderString({ pa
beforeEach(() => {
vi.resetAllMocks()
mocked.getBillingByCustomer.mockResolvedValue({ userId: "owner", customerId: "cus_owner", revision: 2 })
+ mocked.reconcileBilling.mockResolvedValue("applied")
})
describe("Stripe signed ingress", () => {
@@ -24,6 +26,8 @@ describe("Stripe signed ingress", () => {
const raw = body()
await handleBillingWebhook(db, stripe, env, raw, signature(raw))
expect(mocked.reconcileBilling).toHaveBeenCalledWith(db, stripe, env, "owner")
+ expect(mocked.deliverInvoicePurchase).toHaveBeenCalledWith(db, stripe, env, expect.objectContaining({ customer: "cus_owner" }), "owner")
+ expect(mocked.reconcileBilling.mock.invocationCallOrder[0]).toBeLessThan(mocked.deliverInvoicePurchase.mock.invocationCallOrder[0])
})
it.each([null, "invalid"])("rejects missing or invalid signatures before database access", async (header) => {
await expect(handleBillingWebhook(db, stripe, env, body(), header)).rejects.toMatchObject({ code: "BILLING_SIGNATURE_INVALID", status: 400 })
@@ -43,6 +47,26 @@ describe("Stripe signed ingress", () => {
const raw = body()
await expect(handleBillingWebhook(db, stripe, env, raw, signature(raw))).rejects.toThrow("D1 unavailable")
})
+ it("acknowledges reconciled billing when purchase analytics fails", async () => {
+ mocked.deliverInvoicePurchase.mockRejectedValue(new Error("analytics unavailable"))
+ const warning = vi.spyOn(console, "warn").mockImplementation(() => {})
+ const raw = body()
+ await expect(handleBillingWebhook(db, stripe, env, raw, signature(raw))).resolves.toBeUndefined()
+ expect(warning).toHaveBeenCalledWith("billing_purchase_analytics_failed", { invoiceId: "in_fixture" })
+ warning.mockRestore()
+ })
+ it("does not claim or deliver analytics when reconciliation is ignored", async () => {
+ mocked.reconcileBilling.mockResolvedValue("ignored")
+ const raw = body()
+ await handleBillingWebhook(db, stripe, env, raw, signature(raw))
+ expect(mocked.deliverInvoicePurchase).not.toHaveBeenCalled()
+ })
+ it("delivers analytics after verifying that the projection was already applied", async () => {
+ mocked.reconcileBilling.mockResolvedValue("verified_already_applied")
+ const raw = body()
+ await handleBillingWebhook(db, stripe, env, raw, signature(raw))
+ expect(mocked.deliverInvoicePurchase).toHaveBeenCalledOnce()
+ })
it("reconciles duplicates again instead of treating event receipt as completed work", async () => {
const raw = body()
await handleBillingWebhook(db, stripe, env, raw, signature(raw))
diff --git a/src/web/src/lib/billing/webhook.ts b/src/web/src/lib/billing/webhook.ts
index ccbe617b2..b13bcadea 100644
--- a/src/web/src/lib/billing/webhook.ts
+++ b/src/web/src/lib/billing/webhook.ts
@@ -2,6 +2,7 @@ import { queries, type Database } from "@alook/shared"
import Stripe from "stripe"
import { assertStripeMode, BillingError, stripeId } from "./client"
import { reconcileBilling } from "./reconcile"
+import { deliverInvoicePurchase } from "./purchase-analytics"
export async function handleBillingWebhook(db: Database, stripe: Stripe, env: Env, raw: string, signature: string | null) {
if (!env.STRIPE_WEBHOOK_SECRET) throw new BillingError("BILLING_UNAVAILABLE", 503)
@@ -32,5 +33,13 @@ export async function handleBillingWebhook(db: Database, stripe: Stripe, env: En
row = await queries.billing.updateBilling(db, candidate, { customerId })
if (!row) throw new BillingError("BILLING_RETRY_REQUIRED", 503)
}
- await reconcileBilling(db, stripe, env, row.userId)
+ const reconciliation = await reconcileBilling(db, stripe, env, row.userId)
+ if (event.type === "invoice.paid"
+ && (reconciliation === "applied" || reconciliation === "verified_already_applied")) {
+ try {
+ await deliverInvoicePurchase(db, stripe, env, event.data.object, row.userId)
+ } catch {
+ console.warn("billing_purchase_analytics_failed", { invoiceId: event.data.object.id })
+ }
+ }
}