Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(pricing): preserve free offers and verify consent boundaries (#938)

Gener0526f6b212d5
diff --git a/scripts/ci/e2e-shards.mjs b/scripts/ci/e2e-shards.mjs
index b4e923b3f..7883b002b 100644
--- a/scripts/ci/e2e-shards.mjs
+++ b/scripts/ci/e2e-shards.mjs
@@ -84,6 +84,7 @@ export const SPEC_SECONDS = {
"60-desktop-default-user-bar-width.spec.ts": 83.700,
"63-mobile-notification-chat-route.spec.ts": DEFAULT_SPEC_SECONDS,
"64-billing-contact.spec.ts": 6,
+ "65-analytics-document-boundary.spec.ts": DEFAULT_SPEC_SECONDS,
}
function walk(directory) {
diff --git a/scripts/ci/e2e-shards.test.ts b/scripts/ci/e2e-shards.test.ts
index 2493b9fcf..14042f9f1 100644
--- a/scripts/ci/e2e-shards.test.ts
+++ b/scripts/ci/e2e-shards.test.ts
@@ -75,16 +75,16 @@ describe("planE2eShards", () => {
expect(first).toEqual(second)
expect(Object.keys(SPEC_SECONDS).sort()).toEqual(specs)
- expect(first).toHaveLength(13)
+ expect(first).toHaveLength(14)
expect([...assigned].sort()).toEqual(specs)
expect(new Set(assigned).size).toBe(specs.length)
expect(SPEC_SECONDS["55-message-scroll-characterization.spec.ts"]).toBe(109.548)
expect(specSeconds).toEqual([
- 165, 165, 151.379, 152.389, 150.76, 151.219, 151.183,
+ 165, 165, 165, 151.379, 152.389, 150.76, 151.219, 151.183,
153.805, 154.219, 151.127, 150.794, 154.182, 153.225,
])
expect(predictedSeconds).toEqual([
- 240, 240, 226.379, 227.389, 225.76, 226.219, 226.183,
+ 240, 240, 240, 226.379, 227.389, 225.76, 226.219, 226.183,
228.805, 229.219, 226.127, 225.794, 229.182, 228.225,
])
expect(first.every((shard) => (
diff --git a/src/web/src/app/api/pricing/route.test.ts b/src/web/src/app/api/pricing/route.test.ts
index 38cb92155..642fcb867 100644
--- a/src/web/src/app/api/pricing/route.test.ts
+++ b/src/web/src/app/api/pricing/route.test.ts
@@ -1,14 +1,18 @@
import { beforeEach, describe, expect, it, vi } from "vitest"
import { NextRequest } from "next/server"
-const mocked = vi.hoisted(() => ({ listPrices: vi.fn(), getDefaultPlanOffer: vi.fn(), retrieve: vi.fn() }))
-vi.mock("@opennextjs/cloudflare", () => ({ getCloudflareContext: vi.fn(() => ({ env: { DB: {}, STRIPE_SECRET_KEY: "sk_test_fake" } })) }))
+const mocked = vi.hoisted(() => ({
+ listPrices: vi.fn(), getDefaultPlanOffer: vi.fn(), retrieve: vi.fn(), clientCreated: vi.fn(),
+ env: { DB: {}, STRIPE_SECRET_KEY: "sk_test_fake" as string | undefined },
+}))
+vi.mock("@opennextjs/cloudflare", () => ({ getCloudflareContext: vi.fn(() => ({ env: mocked.env })) }))
vi.mock("@/lib/db", () => ({ getPrimaryDb: vi.fn(() => ({})) }))
vi.mock("@alook/shared", async (original) => ({
...await original<typeof import("@alook/shared")>(),
queries: { billing: mocked },
}))
vi.mock("stripe", () => ({ default: class {
+ constructor() { mocked.clientCreated() }
static createFetchHttpClient() { return {} }
prices = { retrieve: mocked.retrieve }
} }))
@@ -20,6 +24,7 @@ const request = () => GET(new NextRequest("http://localhost/api/pricing"))
beforeEach(() => {
vi.resetAllMocks()
+ mocked.env.STRIPE_SECRET_KEY = "sk_test_fake"
mocked.listPrices.mockResolvedValue([mapping])
mocked.getDefaultPlanOffer.mockResolvedValue({ plan: { id: "free", displayName: "Free" }, botLimit: 3, machineLimit: 1 })
mocked.retrieve.mockResolvedValue(price)
@@ -55,12 +60,45 @@ describe("public pricing", () => {
expect(await (await request()).json()).toMatchObject({ offers: [] })
})
- it("returns an empty paid catalog without inventing prices", async () => {
+ it("returns the actual free catalog without Stripe configuration when no paid prices exist", async () => {
+ mocked.env.STRIPE_SECRET_KEY = undefined
mocked.listPrices.mockResolvedValue([])
- expect(await (await request()).json()).toMatchObject({ offers: [] })
+ mocked.getDefaultPlanOffer.mockResolvedValue({ plan: { id: "starter", displayName: "Starter" }, botLimit: 5, machineLimit: 2 })
+ const response = await request()
+ expect(response.status).toBe(200)
+ expect(response.headers.get("cache-control")).toBe("no-store")
+ expect(response.headers.get("set-cookie")).toBeNull()
+ expect(await response.json()).toEqual({
+ free: { plan: { id: "starter", displayName: "Starter" }, botLimit: 5, machineLimit: 2 },
+ offers: [],
+ })
+ expect(mocked.clientCreated).not.toHaveBeenCalled()
expect(mocked.retrieve).not.toHaveBeenCalled()
})
+ it("keeps mapped paid prices unavailable without Stripe configuration", async () => {
+ mocked.env.STRIPE_SECRET_KEY = undefined
+ const response = await request()
+ expect(response.status).toBe(503)
+ expect(await response.json()).toEqual({ error: "BILLING_UNAVAILABLE" })
+ expect(mocked.listPrices).toHaveBeenCalledOnce()
+ expect(mocked.clientCreated).not.toHaveBeenCalled()
+ })
+
+ it.each(["mapping", "default", "invalid quota"])("does not manufacture an empty free catalog after %s failure", async (failure) => {
+ const log = vi.spyOn(console, "error").mockImplementation(() => {})
+ mocked.env.STRIPE_SECRET_KEY = undefined
+ mocked.listPrices.mockResolvedValue([])
+ if (failure === "mapping") mocked.listPrices.mockRejectedValue(new Error("database unavailable"))
+ if (failure === "default") mocked.getDefaultPlanOffer.mockRejectedValue(new Error("DEFAULT_PLAN_UNAVAILABLE"))
+ if (failure === "invalid quota") mocked.getDefaultPlanOffer.mockResolvedValue({ plan: { id: "free", displayName: "Free" }, botLimit: -1 })
+ const response = await request()
+ expect(response.status).toBe(503)
+ expect(await response.json()).toEqual({ error: "BILLING_UNAVAILABLE" })
+ expect(mocked.clientCreated).not.toHaveBeenCalled()
+ log.mockRestore()
+ })
+
it("fails closed on a Stripe environment mismatch", async () => {
mocked.retrieve.mockResolvedValue({ ...price, livemode: true })
const response = await request()
diff --git a/src/web/src/app/api/pricing/route.ts b/src/web/src/app/api/pricing/route.ts
index 7d657e494..11b097b65 100644
--- a/src/web/src/app/api/pricing/route.ts
+++ b/src/web/src/app/api/pricing/route.ts
@@ -5,7 +5,7 @@ import { getPublicPricing } from "@/lib/billing/catalog"
export const GET = withEnv(async (_req, ctx) => {
try {
- return billingResponse(await getPublicPricing(getPrimaryDb(ctx.env.DB), billingClient(ctx.env), ctx.env))
+ return billingResponse(await getPublicPricing(getPrimaryDb(ctx.env.DB), () => billingClient(ctx.env), ctx.env))
} catch (error) {
return billingFailure(error, "public_pricing")
}
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 133a078b5..4303dd527 100644
--- a/src/web/src/app/pricing/pricing-client.dom.test.tsx
+++ b/src/web/src/app/pricing/pricing-client.dom.test.tsx
@@ -134,6 +134,23 @@ it("does not invent purchasable offers when the catalog is empty", async () => {
expect(view.queryByText(/selected/)).not.toBeInTheDocument()
})
+it.each([false, true])("keeps free document navigation with a validated empty paid catalog, signed-in=%s", async signedIn => {
+ state.api.mockResolvedValue({ ...catalog, offers: [] })
+ if (signedIn) {
+ state.session.data = { user: { id: "buyer" } }
+ state.billing.data = { ...free, offers: [] }
+ }
+ const view = render(<PricingClient />)
+ const action = await view.findByRole("button", { name: signedIn ? "Open Alook" : "Start free" })
+ await waitFor(() => expect(action).toBeEnabled())
+ expect(view.getAllByRole("button", { name: "Unavailable" })).toHaveLength(2)
+ await setupUser().click(action)
+ expect(state.assign).toHaveBeenCalledExactlyOnceWith(signedIn ? "/c/me/bots" : "/sign-in?redirect=%2Fc%2Fme%2Fbots")
+ expect(state.checkout).not.toHaveBeenCalled()
+ expect(state.portal).not.toHaveBeenCalled()
+ expect(state.pricingCta).toHaveBeenCalledExactlyOnceWith({ plan_id: "free", cta_action: signedIn ? "open_app" : "start_free", auth_state: signedIn ? "signed_in" : "guest", current_plan: signedIn ? "free" : "none", entry_point: "pricing_page" })
+})
+
it("does not allow stale public prices to initiate purchase when account loading failed", async () => {
state.session.data = { user: { id: "buyer" } }
state.billing = { ...state.billing, isError: true }
diff --git a/src/web/src/lib/billing/catalog.test.ts b/src/web/src/lib/billing/catalog.test.ts
index 158363ff6..8c2a70c95 100644
--- a/src/web/src/lib/billing/catalog.test.ts
+++ b/src/web/src/lib/billing/catalog.test.ts
@@ -2,12 +2,13 @@ import { beforeEach, describe, expect, it, vi } from "vitest"
import type Stripe from "stripe"
import type { Database } from "@alook/shared"
-const mocked = vi.hoisted(() => ({ listPrices: vi.fn() }))
+const mocked = vi.hoisted(() => ({ listPrices: vi.fn(), getDefaultPlanOffer: vi.fn() }))
vi.mock("@alook/shared", async (original) => ({
...await original<typeof import("@alook/shared")>(),
queries: { billing: mocked },
}))
-import { getCatalog, requireOffer } from "./catalog"
+import { getCatalog, getOffers, getPublicPricing, requireOffer } from "./catalog"
+import { billingClient } from "./client"
const db = {} as Database
const env = { STRIPE_SECRET_KEY: "sk_test_fixture" } as Env
@@ -18,13 +19,52 @@ const stripe = { prices: { retrieve } } as unknown as Stripe
beforeEach(() => {
vi.resetAllMocks()
mocked.listPrices.mockResolvedValue([mapping])
- retrieve.mockResolvedValue({
- id: "studio", active: true, livemode: false, type: "recurring", unit_amount: 2000,
+ mocked.getDefaultPlanOffer.mockResolvedValue({ plan: { id: "starter", displayName: "Starter" }, botLimit: 7, machineLimit: 2 })
+ retrieve.mockImplementation(async (priceId: string) => ({
+ id: priceId, active: true, livemode: false, type: "recurring", unit_amount: 2000,
currency: "usd", recurring: { interval: "month", interval_count: 1 }, product: { active: true },
- })
+ }))
})
describe("billing catalog purchase boundary", () => {
+ it("returns the database free offer without a Stripe client for an empty paid catalog", async () => {
+ mocked.listPrices.mockResolvedValue([])
+ const client = vi.fn(() => billingClient({} as Env))
+ expect(await getPublicPricing(db, client, {} as Env)).toEqual({
+ free: { plan: { id: "starter", displayName: "Starter" }, botLimit: 7, machineLimit: 2 },
+ offers: [],
+ })
+ expect(client).not.toHaveBeenCalled()
+ expect(retrieve).not.toHaveBeenCalled()
+ })
+ it("uses one Stripe client to validate all actual paid mappings", async () => {
+ mocked.listPrices.mockResolvedValue([mapping, { ...mapping, priceId: "house", planId: "house", displayName: "House" }])
+ const client = vi.fn(() => stripe)
+ const offers = await getOffers(db, client, env)
+ expect(client).toHaveBeenCalledOnce()
+ expect(offers.map(offer => offer.plan.id)).toEqual(["studio", "house"])
+ expect(offers.map(offer => offer.priceId)).toEqual(["studio", "house"])
+ expect(retrieve.mock.calls).toEqual([
+ ["studio", { expand: ["product"] }],
+ ["house", { expand: ["product"] }],
+ ])
+ })
+ it("does not treat a failed mapping lookup as an empty paid catalog", async () => {
+ mocked.listPrices.mockRejectedValue(new Error("catalog database unavailable"))
+ const client = vi.fn(() => stripe)
+ await expect(getOffers(db, client, env)).rejects.toThrow("catalog database unavailable")
+ expect(client).not.toHaveBeenCalled()
+ })
+ it("still requires Stripe configuration for a mapped paid offer", async () => {
+ await expect(getOffers(db, () => billingClient({} as Env), {} as Env))
+ .rejects.toMatchObject({ code: "BILLING_UNAVAILABLE", status: 503 })
+ expect(retrieve).not.toHaveBeenCalled()
+ })
+ it("still rejects a mapped offer from the wrong Stripe mode", async () => {
+ retrieve.mockResolvedValue({ active: true, livemode: true })
+ await expect(getOffers(db, () => stripe, env))
+ .rejects.toMatchObject({ code: "BILLING_ENVIRONMENT_MISMATCH", status: 503 })
+ })
it("includes disabled mappings when reconciling historical purchases", async () => {
expect(await getCatalog(db)).toEqual([mapping])
expect(mocked.listPrices).toHaveBeenCalledWith(db, true)
diff --git a/src/web/src/lib/billing/catalog.ts b/src/web/src/lib/billing/catalog.ts
index a816c50cf..129391110 100644
--- a/src/web/src/lib/billing/catalog.ts
+++ b/src/web/src/lib/billing/catalog.ts
@@ -26,13 +26,15 @@ async function offerFor(stripe: Stripe, env: Env, mapping: Mapping) {
})
}
-export async function getOffers(db: Database, stripe: Stripe, env: Env) {
+export async function getOffers(db: Database, stripe: () => Stripe, env: Env) {
const mappings = await queries.billing.listPrices(db)
- const offers = await Promise.all(mappings.map((mapping) => offerFor(stripe, env, mapping)))
+ if (mappings.length === 0) return []
+ const client = stripe()
+ const offers = await Promise.all(mappings.map((mapping) => offerFor(client, env, mapping)))
return offers.filter((offer) => offer !== null)
}
-export async function getPublicPricing(db: Database, stripe: Stripe, env: Env) {
+export async function getPublicPricing(db: Database, stripe: () => Stripe, env: Env) {
const [free, offers] = await Promise.all([
queries.billing.getDefaultPlanOffer(db),
getOffers(db, stripe, env),
diff --git a/src/web/src/lib/billing/service.test.ts b/src/web/src/lib/billing/service.test.ts
index 54a713c02..ca9fa93af 100644
--- a/src/web/src/lib/billing/service.test.ts
+++ b/src/web/src/lib/billing/service.test.ts
@@ -69,6 +69,52 @@ beforeEach(() => {
})
const checkout = (price = "studio") => createCheckout(db, stripe, env, "owner", "[email protected]", price)
+describe("billing summary offer loading", () => {
+ it.each([false, true])("preserves the database plan without constructing Stripe for an empty catalog, Founder=%s", async (isFounder) => {
+ founder = isFounder
+ const client = vi.fn(() => { throw new BillingError("BILLING_UNAVAILABLE", 503) })
+ expect(await getBillingSummary(db, client, env, "owner")).toEqual({
+ plan: { id: isFounder ? "house" : "free", displayName: isFounder ? "House" : "Free" },
+ isFounder, offers: [], subscription: null,
+ })
+ expect(mocked.getOffers).toHaveBeenCalledExactlyOnceWith(db, client, env)
+ expect(client).not.toHaveBeenCalled()
+ expect(customerCreates).not.toHaveBeenCalled()
+ expect(sessionCreates).not.toHaveBeenCalled()
+ })
+ it("keeps the existing subscription and current plan when the paid catalog is empty", async () => {
+ const subscription = {
+ plan: { id: "studio", displayName: "Studio" }, status: "active", currentPeriodEnd: null,
+ cancelAt: null, scheduledChange: null,
+ }
+ mocked.getEffectivePlan.mockResolvedValue({ plan: subscription.plan, isFounder: false })
+ mocked.getBilling.mockResolvedValue({ ...row, subscription })
+ const client = vi.fn(() => { throw new BillingError("BILLING_UNAVAILABLE", 503) })
+ expect(await getBillingSummary(db, client, env, "owner")).toEqual({
+ plan: subscription.plan, isFounder: false, offers: [], subscription,
+ })
+ expect(client).not.toHaveBeenCalled()
+ expect(mocked.getBilling).toHaveBeenCalledExactlyOnceWith(db, "owner")
+ })
+ it("preserves Stripe configuration failures when the catalog requires the client", async () => {
+ mocked.getOffers.mockImplementation(async (_db: Database, client: () => Stripe) => {
+ client()
+ return []
+ })
+ const client = vi.fn(() => { throw new BillingError("BILLING_UNAVAILABLE", 503) })
+ await expect(getBillingSummary(db, client, env, "owner"))
+ .rejects.toMatchObject({ code: "BILLING_UNAVAILABLE", status: 503 })
+ expect(client).toHaveBeenCalledOnce()
+ })
+ it("does not turn a failed plan lookup into a free account", async () => {
+ mocked.getEffectivePlan.mockRejectedValue(new Error("plan lookup unavailable"))
+ const client = vi.fn(() => stripe)
+ await expect(getBillingSummary(db, client, env, "owner")).rejects.toThrow("plan lookup unavailable")
+ expect(mocked.getOffers).not.toHaveBeenCalled()
+ expect(client).not.toHaveBeenCalled()
+ })
+})
+
describe("one unresolved Checkout per owner", () => {
it("converges parallel same-offer requests to one customer and session", async () => {
const results = await Promise.all([checkout(), checkout(), checkout()])
@@ -198,7 +244,8 @@ describe("one unresolved Checkout per owner", () => {
await expect(createPortal(db, stripe, env, "owner")).rejects.toMatchObject({ code: "BILLING_FOUNDER_PROTECTED" })
const client = vi.fn(() => stripe)
expect(await getBillingSummary(db, client, env, "owner")).toMatchObject({ isFounder: true, offers: [], subscription: null })
- expect(client).toHaveBeenCalledOnce()
+ expect(mocked.getOffers).toHaveBeenCalledWith(db, client, env)
+ expect(client).not.toHaveBeenCalled()
expect(customerCreates).not.toHaveBeenCalled()
})
it("freezes Founder consent and reuses the session while keeping Founder until payment", async () => {
diff --git a/src/web/src/lib/billing/service.ts b/src/web/src/lib/billing/service.ts
index 5532d033a..50a51177a 100644
--- a/src/web/src/lib/billing/service.ts
+++ b/src/web/src/lib/billing/service.ts
@@ -22,8 +22,8 @@ async function requireBillingOwner(db: Database, userId: string, founderAcknowle
export async function getBillingSummary(db: Database, stripe: () => Stripe, env: Env, userId: string): Promise<BillingSummary> {
const effective = await queries.billing.getEffectivePlan(db, userId)
- if (effective.isFounder) return { plan: effective.plan, isFounder: true, offers: await getOffers(db, stripe(), env), subscription: null }
- const [row, offers] = await Promise.all([queries.billing.getBilling(db, userId), getOffers(db, stripe(), env)])
+ if (effective.isFounder) return { plan: effective.plan, isFounder: true, offers: await getOffers(db, stripe, env), subscription: null }
+ const [row, offers] = await Promise.all([queries.billing.getBilling(db, userId), getOffers(db, stripe, env)])
return { plan: effective.plan, isFounder: false, offers, subscription: row?.subscription ?? null }
}
diff --git a/src/web/src/test/e2e-ui/65-analytics-document-boundary.spec.ts b/src/web/src/test/e2e-ui/65-analytics-document-boundary.spec.ts
new file mode 100644
index 000000000..b6205a796
--- /dev/null
+++ b/src/web/src/test/e2e-ui/65-analytics-document-boundary.spec.ts
@@ -0,0 +1,191 @@
+import type { APIResponse, Locator, Page, Request, Route } from "@playwright/test"
+import { expect, test } from "./_fixtures/community-fixture"
+import { tid } from "./_fixtures/testids"
+
+async function expectDefaultAnalytics(page: Page) {
+ await expect(page.getByTestId(tid.analyticsConsentBanner)).toHaveCount(0)
+ await expect(page.getByTestId(tid.ahrefsAnalyticsFrame)).toHaveCount(1)
+ await expect.poll(async () => (await page.context().cookies()).find(cookie => cookie.name === "alook_analytics_consent")?.value).toBe("v1.granted")
+}
+
+async function savePrivacyChoice(page: Page, decision: "granted" | "denied", previousDecision: "granted" | "denied" = "granted") {
+ const control = page.getByTestId(tid.analyticsPreferenceControl)
+ await expect(control).toContainText(previousDecision === "granted" ? "Analytics cookies allowed" : "Analytics cookies denied")
+ expect((await page.context().cookies()).find(cookie => cookie.name === "alook_analytics_consent")?.value).toBe(`v1.${previousDecision}`)
+ await expect(page.getByTestId(tid.analyticsConsentBanner)).toHaveCount(0)
+ await expect(page.getByTestId(tid.ahrefsAnalyticsFrame)).toHaveCount(previousDecision === "granted" ? 1 : 0)
+ const before = await page.evaluate(() => ({
+ timeOrigin: performance.timeOrigin, url: location.href, historyLength: history.length,
+ }))
+ const documents: string[] = []
+ const consentUrl = new URL("/api/privacy/analytics-consent", before.url).href
+ let saves = 0
+ let forwards = 0
+ const recordRequest = (request: Request) => {
+ if (request.isNavigationRequest() && request.frame() === page.mainFrame() && request.resourceType() === "document") documents.push(request.url())
+ if (request.url() === consentUrl && request.method() === "POST") saves++
+ }
+ const originalResponses: APIResponse[] = []
+ let resolveConsent!: (response: { status: number; body: Buffer; headers: Record<string, string> }) => void
+ let rejectConsent!: (error: unknown) => void
+ const consentResponse = new Promise<{ status: number; body: Buffer; headers: Record<string, string> }>((resolve, reject) => {
+ resolveConsent = resolve
+ rejectConsent = reject
+ })
+ const captureConsent = async (route: Route) => {
+ if (route.request().method() !== "POST") { await route.fallback(); return }
+ expect(route.request().postDataJSON()).toEqual({ decision })
+ forwards++
+ try {
+ const originalResponse = await route.fetch({ maxRetries: 0, maxRedirects: 0 })
+ originalResponses.push(originalResponse)
+ const body = await originalResponse.body()
+ const status = originalResponse.status()
+ const headers = originalResponse.headers()
+ await route.fulfill({ response: originalResponse, body })
+ resolveConsent({ status, body, headers })
+ } catch (error) {
+ rejectConsent(error)
+ throw error
+ }
+ }
+ page.on("request", recordRequest)
+ await page.route(consentUrl, captureConsent)
+ try {
+ const [response, browserResponse, documentRequest] = await Promise.all([
+ consentResponse,
+ page.waitForResponse(response => response.url() === consentUrl && response.request().method() === "POST"),
+ page.waitForRequest(request => request.isNavigationRequest() && request.resourceType() === "document" && request.frame() === page.mainFrame()),
+ page.waitForEvent("framenavigated", { predicate: frame => frame === page.mainFrame() }),
+ control.getByTestId(decision === "granted" ? tid.analyticsConsentAllow : tid.analyticsConsentNecessary).click(),
+ ])
+ await page.waitForLoadState("domcontentloaded")
+ expect(response.status).toBe(200)
+ expect(browserResponse.status()).toBe(response.status)
+ expect(JSON.parse(response.body.toString("utf8"))).toMatchObject({ decision })
+ expect(response.headers["set-cookie"]).toContain(`alook_analytics_consent=v1.${decision}`)
+ expect(saves).toBe(1)
+ expect(forwards).toBe(1)
+ await expect(control).toContainText(decision === "granted" ? "Analytics cookies allowed" : "Analytics cookies denied")
+ expect((await page.context().cookies()).find(cookie => cookie.name === "alook_analytics_consent")?.value).toBe(`v1.${decision}`)
+ expect(await page.evaluate(() => performance.timeOrigin)).not.toBe(before.timeOrigin)
+ expect(await page.evaluate(() => history.length)).toBe(before.historyLength)
+ const requestedUrl = new URL(before.url)
+ requestedUrl.hash = ""
+ expect(documentRequest.url()).toBe(requestedUrl.href)
+ expect(documents).toHaveLength(1)
+ await expect(page).toHaveURL(before.url)
+ await expect(page.getByTestId(tid.ahrefsAnalyticsFrame)).toHaveCount(decision === "granted" ? 1 : 0)
+ } finally {
+ page.off("request", recordRequest)
+ await page.unroute(consentUrl, captureConsent)
+ await Promise.all(originalResponses.map(response => response.dispose()))
+ }
+}
+
+async function expectNativeEntry(page: Page, link: Locator, pathname: string, keyboard = false) {
+ const before = await page.evaluate(() => performance.timeOrigin)
+ const navigation = page.waitForEvent("framenavigated", { predicate: frame => frame === page.mainFrame() })
+ const documentRequest = page.waitForRequest(request => request.isNavigationRequest() && request.resourceType() === "document" && request.frame() === page.mainFrame())
+ if (keyboard) {
+ await link.focus()
+ await page.keyboard.press("Enter")
+ } else await link.click()
+ const [, request] = await Promise.all([navigation, documentRequest])
+ await page.waitForLoadState("domcontentloaded")
+ expect(new URL(request.url()).pathname).toBe(pathname)
+ await expect(page).toHaveURL(url => url.pathname === pathname || pathname === "/c/me" && url.pathname.startsWith("/c/me/"))
+ expect(await page.evaluate(() => performance.timeOrigin)).not.toBe(before)
+ await expect(page.getByTestId(tid.ahrefsAnalyticsFrame)).toHaveCount(0)
+}
+
+test("public default grant has no banner, Pricing stays client-side, and Privacy can save a grant", async ({ page }) => {
+ const [response] = await Promise.all([
+ page.waitForResponse(response => new URL(response.url()).pathname === "/api/privacy/analytics-consent" && response.request().method() === "POST"),
+ page.goto("/"),
+ ])
+ expect(response.status()).toBe(200)
+ expect(response.request().postDataJSON()).toEqual({ decision: "granted" })
+ expect(await response.json()).toMatchObject({ decision: "granted" })
+ await expectDefaultAnalytics(page)
+ const before = await page.evaluate(() => performance.timeOrigin)
+ await page.getByTestId(tid.landingFooterNavigation).getByRole("link", { name: "Pricing", exact: true }).click()
+ await expect(page).toHaveURL(url => url.pathname === "/pricing")
+ expect(await page.evaluate(() => performance.timeOrigin)).toBe(before)
+ await expect(page.getByTestId(tid.ahrefsAnalyticsFrame)).toHaveCount(1)
+ await page.goto("/privacy?qa=grant#analytics-choices")
+ await savePrivacyChoice(page, "granted")
+})
+
+test("a saved withdrawal replaces the public document once with the actual denied Cookie", async ({ page }) => {
+ await page.goto("/")
+ await expectDefaultAnalytics(page)
+ await page.goto("/privacy?qa=consent#analytics-choices")
+ await savePrivacyChoice(page, "denied")
+})
+
+for (const signedIn of [false, true]) {
+ test(`Home private entries replace the public document for signed-in=${signedIn}`, async ({ page: guest, asUser }) => {
+ test.slow()
+ const page = signedIn ? (await asUser("alice")).page : guest
+ if (signedIn) {
+ await page.goto("/privacy?qa=entry#analytics-choices")
+ await savePrivacyChoice(page, "granted", "denied")
+ }
+ await page.goto("/")
+ await expectDefaultAnalytics(page)
+ const destination = signedIn ? "/c/me" : "/sign-in"
+ for (const section of ["hero", "nav", "product", "identity", "continuity", "reach", "ownership", "closing"]) {
+ await page.goto("/")
+ let link: Locator
+ if (section === "hero") link = page.locator(`.hero-ctas a[href="${destination}"]`)
+ else if (section === "nav") {
+ await page.locator(".hero-section").evaluate(hero => window.scrollTo(0, hero.getBoundingClientRect().bottom + window.scrollY + 1))
+ link = page.locator(`.marketing-nav a[href="${destination}"]`)
+ } else link = page.getByTestId(section === "closing" ? "landing-closing-open" : `landing-section-cta-${section}`)
+ await expect(link).toHaveAttribute("href", destination)
+ await expectNativeEntry(page, link, destination, section === "closing")
+ }
+ })
+
+ test(`Templates and Pricing private entries use document navigation for signed-in=${signedIn}`, async ({ page: guest, asUser }) => {
+ test.slow()
+ const page = signedIn ? (await asUser("alice")).page : guest
+ const destination = signedIn ? "/c/me" : "/sign-in"
+ if (signedIn) {
+ await page.goto("/privacy?qa=entry#analytics-choices")
+ await savePrivacyChoice(page, "granted", "denied")
+ }
+ await page.goto("/")
+ await expectDefaultAnalytics(page)
+ await page.goto("/templates")
+ const templateHref = await page.locator('main a[href^="/templates/"]').first().getAttribute("href")
+ expect(templateHref).toBeTruthy()
+ for (const route of ["/templates", templateHref!]) {
+ await page.goto(route)
+ const entry = page.locator(`a[href="${destination}"]`)
+ await expect(entry).toHaveCount(1)
+ await expectNativeEntry(page, entry, destination)
+ }
+ await page.goto("/pricing")
+ const action = page.getByRole("button", { name: signedIn ? "Open Alook" : "Start free", exact: true })
+ await expect(action).toBeEnabled()
+ await expectNativeEntry(page, action, signedIn ? "/c/me/bots" : "/sign-in", true)
+ if (!signedIn) expect(new URL(page.url()).searchParams.get("redirect")).toBe("/c/me/bots")
+ })
+}
+
+test("a modified private link opens another document and leaves the public tab intact", async ({ page, context }) => {
+ await page.goto("/")
+ await expectDefaultAnalytics(page)
+ const before = await page.evaluate(() => performance.timeOrigin)
+ const opened = context.waitForEvent("page")
+ await page.locator('.hero-ctas a[href="/sign-in"]').click({ modifiers: ["ControlOrMeta"] })
+ const privatePage = await opened
+ await expect(privatePage).toHaveURL(url => url.pathname === "/sign-in")
+ await privatePage.waitForLoadState("domcontentloaded")
+ await expect(privatePage.getByTestId(tid.ahrefsAnalyticsFrame)).toHaveCount(0)
+ await expect(page).toHaveURL(url => url.pathname === "/")
+ expect(await page.evaluate(() => performance.timeOrigin)).toBe(before)
+ await privatePage.close()
+})