Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. π₯
TypeScript aiai-agentsai-crawlerai-scrapingai-searchcrawlerdata-extractionhtml-to-markdownllmmarkdownscraperscrapingweb-crawlerweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
feat(api): emit keyless_prompt_shown for keyless signup prompts (#4893)
claude[bot]034293a4cd09
diff --git a/apps/api/src/controllers/__tests__/auth.test.ts b/apps/api/src/controllers/__tests__/auth.test.tsindex 775e93ca7..9ede0f9f8 100644--- a/apps/api/src/controllers/__tests__/auth.test.ts+++ b/apps/api/src/controllers/__tests__/auth.test.ts@@ -22,6 +22,7 @@ import {import { decryptKeylessSignupToken } from "../../lib/keyless-signup-link";import { logger } from "../../lib/logger";import { isKeylessIpSuspicious } from "../../lib/spur";+import { trackKeylessPromptShown } from "../../lib/keyless-prompt-analytics";import { db } from "../../db/connection";import { autumnService } from "../../services/autumn/autumn.service";@@ -31,7 +32,9 @@ vi.mock("../../services/queue-service", () => ({})),}));-vi.mock("uuid", () => ({+vi.mock("uuid", async importOriginal => ({+ // keyless prompts derive their analytics team id with the real v5.+ ...(await importOriginal<typeof import("uuid")>()),validate: vi.fn(() => true),}));@@ -84,6 +87,10 @@ vi.mock("../../lib/keyless", async importOriginal => {};});+vi.mock("../../lib/keyless-prompt-analytics", () => ({+ trackKeylessPromptShown: vi.fn(),+}));+vi.mock("../../lib/spur", () => ({isKeylessIpSuspicious: vi.fn().mockResolvedValue(false),}));@@ -285,7 +292,16 @@ describe("authenticateUser", () => {// Nothing about the surface or the identity is visible in the link.expect(signupUrl).not.toContain("utm_");expect((auth as { error: string }).error).not.toContain("203.0.113.8");+ // Each prompt is reported for the funnel, keyed on the web's team id.+ expect(trackKeylessPromptShown).toHaveBeenCalledWith({+ keylessTeamId: "abd15a03-d147-557e-801b-005da8c69bbf",+ surface: "api",+ reason,+ httpStatus: status,+ tokenLink: true,+ });}+ expect(trackKeylessPromptShown).toHaveBeenCalledTimes(3);for (const [message, auth] of [["Keyless request blocked", limited],["Keyless request blocked: suspicious IP", suspicious],diff --git a/apps/api/src/controllers/auth.ts b/apps/api/src/controllers/auth.tsindex f9be80525..17bf0b078 100644--- a/apps/api/src/controllers/auth.ts+++ b/apps/api/src/controllers/auth.ts@@ -21,6 +21,7 @@ import {keylessSignupUrlForIp,keylessTeamId,normalizeKeylessIpv4,+ reportKeylessPromptShown,} from "../lib/keyless";import { keylessSignupSurface } from "../lib/keyless-signup-link";import { isKeylessIpSuspicious } from "../lib/spur";@@ -524,10 +525,19 @@ async function handleKeylessAuth(// Configured, but this endpoint isn't part of the keyless tier: tell the user// they need a key (with the signup nudge) rather than a bare "Unauthorized".if (!allowKeyless) {- const { url } = keylessSignupUrlForIp(- keylessClientIp(req),- keylessSignupSurface(req),+ const ip = keylessClientIp(req);+ const surface = keylessSignupSurface(req);+ const { url, signupRef } = keylessSignupUrlForIp(+ ip,+ surface,+ "unsupported_endpoint",+ );+ reportKeylessPromptShown(+ ip,+ surface,"unsupported_endpoint",+ 401,+ signupRef,);return {success: false,@@ -567,6 +577,13 @@ async function handleKeylessAuth(signupSurface,"suspicious_ip",);+ reportKeylessPromptShown(+ ip,+ signupSurface,+ "suspicious_ip",+ 403,+ signupRef,+ );logger.warn("Keyless request blocked: suspicious IP", {canonicalLog: "keyless/consume",ip,diff --git a/apps/api/src/controllers/v2/keyless-eligibility.ts b/apps/api/src/controllers/v2/keyless-eligibility.tsindex 49f5f7f0b..c4df9eb2f 100644--- a/apps/api/src/controllers/v2/keyless-eligibility.ts+++ b/apps/api/src/controllers/v2/keyless-eligibility.ts@@ -3,6 +3,7 @@ import { config } from "../../config";import {checkKeylessEligibility,keylessSignupUrlForIp,+ reportKeylessPromptShown,} from "../../lib/keyless";import {type KeylessPromptReason,@@ -52,8 +53,12 @@ export async function keylessEligibilityController(: undefined;// A tier that is off or a limiter that is down is not a prompt about this// identity, so it gets the regular signup link.- const signupUrl = reason- ? keylessSignupUrlForIp(ip, surface, reason).url- : keylessFallbackSignupUrl(surface);+ let signupUrl = keylessFallbackSignupUrl(surface);+ if (reason) {+ const link = keylessSignupUrlForIp(ip, surface, reason);+ signupUrl = link.url;+ // The hosted MCP relays this link as the prompt; this check answers 200.+ reportKeylessPromptShown(ip, surface, reason, 200, link.signupRef);+ }res.status(200).json({ ...result, signupUrl });}diff --git a/apps/api/src/lib/__tests__/keyless-prompt-analytics.test.ts b/apps/api/src/lib/__tests__/keyless-prompt-analytics.test.tsnew file mode 100644index 000000000..30fc46b67--- /dev/null+++ b/apps/api/src/lib/__tests__/keyless-prompt-analytics.test.ts@@ -0,0 +1,195 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ /** Redis keys the SET NX / DEL mocks hold, so a test sees the marker lifecycle. */+ markers: new Set<string>(),+ set: vi.fn(),+ del: vi.fn(),+ capturePostHog: vi.fn(),+ enabled: vi.fn(),+}));++vi.mock("../../services/rate-limiter", () => ({+ redisRateLimitClient: { set: mocks.set, del: mocks.del },+}));+vi.mock("../../services/posthog-capture", () => ({+ capturePostHog: mocks.capturePostHog,+ isPostHogCaptureEnabled: mocks.enabled,+}));++import {+ KEYLESS_PROMPT_SHOWN_EVENT,+ keylessPromptDedupeKey,+ trackKeylessPromptShown,+} from "../keyless-prompt-analytics";++const TEAM_UUID = "abd15a03-d147-557e-801b-005da8c69bbf";+const PROMPT = {+ keylessTeamId: TEAM_UUID,+ surface: "mcp" as const,+ reason: "limit" as const,+ httpStatus: 429,+ tokenLink: true,+};++/** Let the fire-and-forget task run. */+const settle = () => new Promise(resolve => setImmediate(resolve));++beforeEach(() => {+ mocks.enabled.mockReturnValue(true);+ mocks.markers.clear();+ mocks.set.mockImplementation(async (key: string) => {+ if (mocks.markers.has(key)) return null;+ mocks.markers.add(key);+ return "OK";+ });+ mocks.del.mockImplementation(async (key: string) =>+ mocks.markers.delete(key) ? 1 : 0,+ );+ mocks.capturePostHog.mockResolvedValue(true);+ vi.useFakeTimers({+ now: new Date("2026-10-01T23:59:30.000Z"),+ toFake: ["Date"],+ });+});++afterEach(() => {+ vi.useRealTimers();+ vi.clearAllMocks();+});++describe("keylessPromptDedupeKey", () => {+ it("keys on the UTC day, team, surface and reason", () => {+ expect(keylessPromptDedupeKey(PROMPT)).toBe(+ `keyless_prompt_shown:2026-10-01:${TEAM_UUID}:mcp:limit`,+ );+ expect(+ keylessPromptDedupeKey(PROMPT, new Date("2026-10-02T00:00:01.000Z")),+ ).toBe(`keyless_prompt_shown:2026-10-02:${TEAM_UUID}:mcp:limit`);+ expect(+ keylessPromptDedupeKey({ ...PROMPT, reason: "suspicious_ip" }),+ ).not.toBe(keylessPromptDedupeKey(PROMPT));+ expect(keylessPromptDedupeKey({ ...PROMPT, surface: "cli" })).not.toBe(+ keylessPromptDedupeKey(PROMPT),+ );+ });+});++describe("trackKeylessPromptShown", () => {+ it("claims the day's marker with SET NX and a 25h TTL, then captures", async () => {+ trackKeylessPromptShown(PROMPT);+ await settle();++ expect(mocks.set).toHaveBeenCalledExactlyOnceWith(+ `keyless_prompt_shown:2026-10-01:${TEAM_UUID}:mcp:limit`,+ "1",+ "EX",+ 90000,+ "NX",+ );+ expect(mocks.capturePostHog).toHaveBeenCalledExactlyOnceWith(+ KEYLESS_PROMPT_SHOWN_EVENT,+ TEAM_UUID,+ {+ keyless_team_id: TEAM_UUID,+ surface: "mcp",+ reason: "limit",+ http_status: 429,+ link_type: "token",+ $process_person_profile: false,+ },+ );+ });++ it("keeps the marker once PostHog accepts the event", async () => {+ trackKeylessPromptShown(PROMPT);+ await settle();++ expect(mocks.del).not.toHaveBeenCalled();+ expect(mocks.markers.has(keylessPromptDedupeKey(PROMPT))).toBe(true);+ });++ it("releases the marker when PostHog rejects the event, so the next prompt retries", async () => {+ mocks.capturePostHog.mockResolvedValueOnce(false);++ trackKeylessPromptShown(PROMPT);+ await settle();++ expect(mocks.del).toHaveBeenCalledExactlyOnceWith(+ `keyless_prompt_shown:2026-10-01:${TEAM_UUID}:mcp:limit`,+ );+ expect(mocks.markers.size).toBe(0);++ // The retry captures only because the release cleared the SET NX marker.+ trackKeylessPromptShown(PROMPT);+ await settle();+ expect(mocks.capturePostHog).toHaveBeenCalledTimes(2);+ expect(mocks.markers.has(keylessPromptDedupeKey(PROMPT))).toBe(true);+ });++ it("swallows a failed marker release", async () => {+ mocks.capturePostHog.mockResolvedValueOnce(false);+ mocks.del.mockRejectedValueOnce(new Error("redis down"));++ expect(() => trackKeylessPromptShown(PROMPT)).not.toThrow();+ await settle();++ expect(mocks.del).toHaveBeenCalledTimes(1);+ });++ it("labels a prompt without a token as the fallback link", async () => {+ trackKeylessPromptShown({+ ...PROMPT,+ reason: "unsupported_endpoint",+ httpStatus: 401,+ tokenLink: false,+ });+ await settle();++ expect(mocks.capturePostHog).toHaveBeenCalledWith(+ KEYLESS_PROMPT_SHOWN_EVENT,+ TEAM_UUID,+ expect.objectContaining({+ reason: "unsupported_endpoint",+ http_status: 401,+ link_type: "fallback",+ }),+ );+ });++ it("does not capture again once the day's marker exists", async () => {+ trackKeylessPromptShown(PROMPT);+ trackKeylessPromptShown(PROMPT);+ await settle();++ expect(mocks.set).toHaveBeenCalledTimes(2);+ await expect(mocks.set.mock.results[1].value).resolves.toBeNull();+ expect(mocks.capturePostHog).toHaveBeenCalledTimes(1);+ });++ it("spends no marker while capture is off", async () => {+ mocks.enabled.mockReturnValue(false);++ trackKeylessPromptShown(PROMPT);+ await settle();++ expect(mocks.set).not.toHaveBeenCalled();+ expect(mocks.capturePostHog).not.toHaveBeenCalled();+ });++ it("returns before Redis answers and swallows a Redis failure", async () => {+ let fail!: (error: Error) => void;+ mocks.set.mockReturnValueOnce(+ new Promise((_, reject) => {+ fail = reject;+ }),+ );++ expect(trackKeylessPromptShown(PROMPT)).toBeUndefined();+ expect(mocks.capturePostHog).not.toHaveBeenCalled();+ fail(new Error("redis down"));+ await settle();++ expect(mocks.capturePostHog).not.toHaveBeenCalled();+ });+});diff --git a/apps/api/src/lib/keyless-prompt-analytics.ts b/apps/api/src/lib/keyless-prompt-analytics.tsnew file mode 100644index 000000000..7248409ec--- /dev/null+++ b/apps/api/src/lib/keyless-prompt-analytics.ts@@ -0,0 +1,79 @@+import { redisRateLimitClient } from "../services/rate-limiter";+import {+ capturePostHog,+ isPostHogCaptureEnabled,+} from "../services/posthog-capture";+import { logger } from "./logger";+import type {+ KeylessPromptReason,+ KeylessSignupSurface,+} from "./keyless-signup-link";++export const KEYLESS_PROMPT_SHOWN_EVENT = "keyless_prompt_shown";++// One UTC day plus an hour, so a marker outlives the day it is keyed on.+const DEDUPE_TTL_SECONDS = 25 * 60 * 60;++type KeylessPromptShown = {+ /** keylessTeamUuid of the caller: the user_onboarding.keyless_team_id join key. */+ keylessTeamId: string;+ surface: KeylessSignupSurface;+ reason: KeylessPromptReason;+ httpStatus: number;+ /** True when the prompt carried a /k/<token> link, false for the fallback link. */+ tokenLink: boolean;+};++export function keylessPromptDedupeKey(+ prompt: Pick<KeylessPromptShown, "keylessTeamId" | "surface" | "reason">,+ now: Date = new Date(),+): string {+ const day = now.toISOString().slice(0, 10);+ return `keyless_prompt_shown:${day}:${prompt.keylessTeamId}:${prompt.surface}:${prompt.reason}`;+}++/**+ * Emit `keyless_prompt_shown` at most once per (keyless team, surface, reason)+ * per UTC day. The dedup marker is a Redis SET NX, released when the capture+ * fails so a later prompt retries. Fire-and-forget: never+ * awaited in the request path, never throws.+ */+export function trackKeylessPromptShown(prompt: KeylessPromptShown): void {+ // Bail before the SET NX so a marker is not spent while capture is off.+ if (!isPostHogCaptureEnabled()) return;++ void (async () => {+ try {+ const key = keylessPromptDedupeKey(prompt);+ const first = await redisRateLimitClient.set(+ key,+ "1",+ "EX",+ DEDUPE_TTL_SECONDS,+ "NX",+ );+ if (first !== "OK") return;++ const sent = await capturePostHog(+ KEYLESS_PROMPT_SHOWN_EVENT,+ prompt.keylessTeamId,+ {+ keyless_team_id: prompt.keylessTeamId,+ surface: prompt.surface,+ reason: prompt.reason,+ http_status: prompt.httpStatus,+ link_type: prompt.tokenLink ? "token" : "fallback",+ // Keyless identities are per IP: do not create a person for each one.+ $process_person_profile: false,+ },+ );+ // Release the marker so the next prompt today retries the event.+ if (!sent) await redisRateLimitClient.del(key);+ } catch (error) {+ logger.debug("trackKeylessPromptShown failed", {+ module: "keyless-prompt-analytics",+ error,+ });+ }+ })();+}diff --git a/apps/api/src/lib/keyless.signup-prompt.test.ts b/apps/api/src/lib/keyless.signup-prompt.test.tsindex a373e80bd..8fb6ccee1 100644--- a/apps/api/src/lib/keyless.signup-prompt.test.ts+++ b/apps/api/src/lib/keyless.signup-prompt.test.ts@@ -11,6 +11,9 @@ vi.mock("ioredis", () => ({vi.mock("../services/rate-limiter", () => ({redisRateLimitClient: { ttl: vi.fn().mockResolvedValue(-1), on: vi.fn() },}));+vi.mock("./keyless-prompt-analytics", () => ({+ trackKeylessPromptShown: vi.fn(),+}));vi.mock("./keyless", async importOriginal => {const actual = await importOriginal<typeof import("./keyless")>();return { ...actual, checkKeylessEligibility: vi.fn() };@@ -27,12 +30,24 @@ import {keylessSignupUrlForIp,keylessTeamId,keylessTeamUuid,+ reportKeylessPromptShown,} from "./keyless";+import { trackKeylessPromptShown } from "./keyless-prompt-analytics";import { decryptKeylessSignupToken } from "./keyless-signup-link";import { logger } from "./logger";const TEST_KEY = "AAECAwQFBgcICQoLDA0ODw==";const IP = "203.0.113.8";+const TEAM_UUID = "abd15a03-d147-557e-801b-005da8c69bbf";++/** The prompt reported to analytics, with its defaults for IP. */+function shown(fields: Partial<Parameters<typeof trackKeylessPromptShown>[0]>) {+ return {+ keylessTeamId: TEAM_UUID,+ tokenLink: true,+ ...fields,+ };+}/** The prompt a /k link carries, or null for any other link. */function decoded(url: unknown) {@@ -96,6 +111,9 @@ describe("keyless limit prompt", () => {signupRef: body.signup_url.split("/k/")[1],}),);+ expect(trackKeylessPromptShown).toHaveBeenCalledExactlyOnceWith(+ shown({ surface: "cli", reason: "limit", httpStatus: 429 }),+ );});it("uses the api surface when no request is given", async () => {@@ -117,6 +135,14 @@ describe("keyless limit prompt", () => {"https://www.firecrawl.dev/signin?utm_source=keyless&utm_medium=mcp",);expect(body.error).toContain(`${body.signup_url}\n`);+ expect(trackKeylessPromptShown).toHaveBeenCalledExactlyOnceWith(+ shown({+ surface: "mcp",+ reason: "limit",+ httpStatus: 429,+ tokenLink: false,+ }),+ );});it("keys IPv4-mapped IPv6 on the IPv4 identity and gives other IPs the regular link", () => {@@ -132,6 +158,23 @@ describe("keyless limit prompt", () => {});});+describe("reportKeylessPromptShown", () => {+ it("reports an IPv4-mapped IPv6 caller under the IPv4 team id", () => {+ reportKeylessPromptShown("::ffff:203.0.113.8", "api", "limit", 429, "ref");+ expect(trackKeylessPromptShown).toHaveBeenCalledExactlyOnceWith(+ shown({ surface: "api", reason: "limit", httpStatus: 429 }),+ );+ });++ it.each([null, undefined, "", "unknown", "2001:db8::1"])(+ "does not report a caller without a keyless identity (%j)",+ ip => {+ reportKeylessPromptShown(ip, "api", "limit", 429);+ expect(trackKeylessPromptShown).not.toHaveBeenCalled();+ },+ );+});+describe("browserError", () => {it("replaces the keyless browser limit text with the caller's own link", () => {const res = fakeRes();@@ -153,6 +196,9 @@ describe("browserError", () => {error: expect.stringContaining(`${body.signup_url}\n`),signup_url: body.signup_url,});+ expect(trackKeylessPromptShown).toHaveBeenCalledExactlyOnceWith(+ shown({ surface: "cli", reason: "limit", httpStatus: 429 }),+ );});it("leaves other browser errors unchanged", () => {@@ -166,6 +212,7 @@ describe("browserError", () => {success: false,error: "Session closed.",});+ expect(trackKeylessPromptShown).not.toHaveBeenCalled();});});@@ -218,6 +265,10 @@ describe("keyless eligibility signup link", () => {surface: "mcp",reason,});+ // The MCP relays the link as the prompt, so the check reports it.+ expect(trackKeylessPromptShown).toHaveBeenCalledExactlyOnceWith(+ shown({ surface: "mcp", reason, httpStatus: 200 }),+ );},);@@ -255,6 +306,7 @@ describe("keyless eligibility signup link", () => {reason,signupUrl: MCP_FALLBACK,});+ expect(trackKeylessPromptShown).not.toHaveBeenCalled();},);@@ -275,6 +327,8 @@ describe("keyless eligibility signup link", () => {reason: "ineligible_ip",signupUrl: MCP_FALLBACK,});+ // An IPv6 caller is not a keyless identity, so nothing is reported.+ expect(trackKeylessPromptShown).not.toHaveBeenCalled();});it("omits the link for an eligible IP unless asked", async () => {@@ -289,6 +343,10 @@ describe("keyless eligibility signup link", () => {expect(res.status.mock.calls).toEqual([[200], [200]]);expect(res.json.mock.calls[0]).toEqual([{ eligible: true }]);+ // Only the asked-for account-only link is a prompt.+ expect(trackKeylessPromptShown).toHaveBeenCalledExactlyOnceWith(+ shown({ surface: "mcp", reason: "account_only_tool", httpStatus: 200 }),+ );const asked = res.json.mock.calls[1][0];expect(asked).toEqual({ eligible: true, signupUrl: expect.any(String) });expect(decoded(asked.signupUrl)).toEqual({diff --git a/apps/api/src/lib/keyless.ts b/apps/api/src/lib/keyless.tsindex 8c79df4f4..1e9167f1d 100644--- a/apps/api/src/lib/keyless.ts+++ b/apps/api/src/lib/keyless.ts@@ -18,6 +18,7 @@ import {keylessSignupLink,keylessSignupSurface,} from "./keyless-signup-link";+import { trackKeylessPromptShown } from "./keyless-prompt-analytics";// Keyless free tier: scrape, search, and interact can be used without an API key// from the official MCP server, CLI, or SDKs. It's gated per-IP/day by TWO@@ -183,12 +184,47 @@ export function keylessSignupUrlForIp();}-/** The caller's own signup link and the limit message that carries it. */+/**+ * Report a keyless prompt shown to the caller, for the prompt to signup+ * funnel. Deduplicated per identity, surface and reason per UTC day; never+ * blocks or throws. Only a keyless identity (IPv4) is reported: no other+ * caller can hold a token link or a keyless ledger row to join on.+ */+export function reportKeylessPromptShown(+ ip: string | null | undefined,+ surface: KeylessSignupSurface,+ reason: KeylessPromptReason,+ httpStatus: number,+ signupRef?: string,+): void {+ try {+ const teamUuid =+ ip && isKeylessIpEligible(ip)+ ? keylessTeamUuid(keylessTeamId(normalizeKeylessIpv4(ip)))+ : null;+ if (!teamUuid) return;+ trackKeylessPromptShown({+ keylessTeamId: teamUuid,+ surface,+ reason,+ httpStatus,+ tokenLink: Boolean(signupRef),+ });+ } catch {+ // Analytics only: the prompt itself must still go out.+ }+}++/**+ * The caller's own signup link and the limit message that carries it. Every+ * caller answers 429 with it, so the prompt is reported here.+ */export function keylessLimitPrompt(ip: string | null | undefined,surface: KeylessSignupSurface,): { error: string; signup_url: string; signupRef?: string } {const { url, signupRef } = keylessSignupUrlForIp(ip, surface, "limit");+ reportKeylessPromptShown(ip, surface, "limit", 429, signupRef);return {error: keylessFreeTierLimitMessage(url),signup_url: url,diff --git a/apps/api/src/services/posthog-capture.test.ts b/apps/api/src/services/posthog-capture.test.tsnew file mode 100644index 000000000..5f02ac2be--- /dev/null+++ b/apps/api/src/services/posthog-capture.test.ts@@ -0,0 +1,66 @@+import { afterEach, describe, expect, it, vi } from "vitest";++/** A fresh module, so it reads the stubbed POSTHOG_API_KEY at import. */+async function load(apiKey: string) {+ vi.resetModules();+ vi.stubEnv("POSTHOG_API_KEY", apiKey);+ vi.stubEnv("POSTHOG_HOST", "https://ph.example.com/");+ return await import("./posthog-capture.js");+}++afterEach(() => {+ vi.unstubAllEnvs();+ vi.unstubAllGlobals();+});++describe("capturePostHog", () => {+ it("resolves true when PostHog accepts the event", async () => {+ const fetchMock = vi.fn().mockResolvedValue(new Response("{}"));+ vi.stubGlobal("fetch", fetchMock);+ const { capturePostHog } = await load("phc_test");++ await expect(capturePostHog("e", "d", { a: 1 })).resolves.toBe(true);+ expect(fetchMock).toHaveBeenCalledWith(+ "https://ph.example.com/capture/",+ expect.objectContaining({+ method: "POST",+ body: JSON.stringify({+ api_key: "phc_test",+ event: "e",+ distinct_id: "d",+ properties: { a: 1 },+ }),+ }),+ );+ });++ it.each([400, 401, 500, 503])(+ "resolves false on a %i answer",+ async status => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue(new Response("no", { status })),+ );+ const { capturePostHog } = await load("phc_test");++ await expect(capturePostHog("e", "d")).resolves.toBe(false);+ },+ );++ it("resolves false, without rejecting, on a network error", async () => {+ vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error("reset")));+ const { capturePostHog } = await load("phc_test");++ await expect(capturePostHog("e", "d")).resolves.toBe(false);+ });++ it("sends nothing and resolves false with no key", async () => {+ const fetchMock = vi.fn();+ vi.stubGlobal("fetch", fetchMock);+ const { capturePostHog, isPostHogCaptureEnabled } = await load("");++ expect(isPostHogCaptureEnabled()).toBe(false);+ await expect(capturePostHog("e", "d")).resolves.toBe(false);+ expect(fetchMock).not.toHaveBeenCalled();+ });+});diff --git a/apps/api/src/services/posthog-capture.ts b/apps/api/src/services/posthog-capture.tsnew file mode 100644index 000000000..7a8dd6c39--- /dev/null+++ b/apps/api/src/services/posthog-capture.ts@@ -0,0 +1,65 @@+import { logger as _logger } from "../lib/logger";++/**+ * Lightweight, dependency-free PostHog capture for the API.+ *+ * The API has no PostHog SDK wired up, so we POST directly to the capture+ * endpoint. Everything here is best-effort and fire-and-forget: a missing key+ * or a network error must never affect request handling.+ *+ * Configure via env:+ * POSTHOG_API_KEY β project API key (if unset, capture is a no-op)+ * POSTHOG_HOST β ingestion host (defaults to https://us.i.posthog.com)+ */+const POSTHOG_API_KEY = process.env.POSTHOG_API_KEY;+const POSTHOG_HOST = process.env.POSTHOG_HOST || "https://us.i.posthog.com";++/**+ * False when capture is a no-op. Callers that spend a dedup marker check this+ * first, so the marker is not burned while PostHog is off.+ */+export function isPostHogCaptureEnabled(): boolean {+ return Boolean(POSTHOG_API_KEY);+}++/**+ * Send one event. Resolves true when PostHog accepted it, false on a non-2xx+ * answer, a network error, or no key; never rejects. Callers that hold a dedup+ * marker release it on false. Do not await it in the request path.+ */+export async function capturePostHog(+ event: string,+ distinctId: string,+ properties: Record<string, unknown> = {},+): Promise<boolean> {+ if (!POSTHOG_API_KEY) return false;++ try {+ const response = await fetch(+ `${POSTHOG_HOST.replace(/\/$/, "")}/capture/`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ api_key: POSTHOG_API_KEY,+ event,+ distinct_id: distinctId,+ properties,+ }),+ },+ );+ if (response.ok) return true;+ _logger.debug("PostHog capture rejected", {+ module: "posthog",+ event,+ status: response.status,+ });+ } catch (error) {+ _logger.debug("PostHog capture failed", {+ module: "posthog",+ event,+ error,+ });+ }+ return false;+}diff --git a/apps/api/src/services/posthog.ts b/apps/api/src/services/posthog.tsindex dd9dc93f5..eb50e9bff 100644--- a/apps/api/src/services/posthog.ts+++ b/apps/api/src/services/posthog.ts@@ -3,50 +3,7 @@ import { redisEvictConnection } from "./redis";import { dbRr } from "../db/connection";import * as schema from "../db/schema";import { logger as _logger } from "../lib/logger";--/**- * Lightweight, dependency-free PostHog capture for the API.- *- * The API has no PostHog SDK wired up, so we POST directly to the capture- * endpoint. Everything here is best-effort and fire-and-forget: a missing key- * or a network error must never affect request handling.- *- * Configure via env:- * POSTHOG_API_KEY β project API key (if unset, capture is a no-op)- * POSTHOG_HOST β ingestion host (defaults to https://us.i.posthog.com)- */-const POSTHOG_API_KEY = process.env.POSTHOG_API_KEY;-const POSTHOG_HOST = process.env.POSTHOG_HOST || "https://us.i.posthog.com";--function capturePostHog(- event: string,- distinctId: string,- properties: Record<string, unknown> = {},-): void {- if (!POSTHOG_API_KEY) return;-- // Fire-and-forget β do not await in the request path, never throw.- void (async () => {- try {- await fetch(`${POSTHOG_HOST.replace(/\/$/, "")}/capture/`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- api_key: POSTHOG_API_KEY,- event,- distinct_id: distinctId,- properties,- }),- });- } catch (error) {- _logger.debug("PostHog capture failed", {- module: "posthog",- event,- error,- });- }- })();-}+import { capturePostHog, isPostHogCaptureEnabled } from "./posthog-capture";/** Normalized request surface, derived from the `origin` + `integration` fields. */type RequestSurface =@@ -161,7 +118,7 @@ export function trackFirstSurfaceUse(args: {// No PostHog key β capture is a no-op. Bail BEFORE the Redis SETNX so we don't// burn the dedup marker without emitting (which would lose the milestone for// good once PostHog is enabled).- if (!POSTHOG_API_KEY) return;+ if (!isPostHogCaptureEnabled()) return;// Skip anonymous / preview traffic β not a real team milestone.if (!teamId || teamId === "preview" || teamId.startsWith("preview_")) return;@@ -181,7 +138,7 @@ export function trackFirstSurfaceUse(args: {resolveOrgId(teamId),]);- capturePostHog("api_surface_first_used", distinctId, {+ const sent = await capturePostHog("api_surface_first_used", distinctId, {surface,raw_origin: origin ?? null,raw_integration: integration ?? null,@@ -192,6 +149,8 @@ export function trackFirstSurfaceUse(args: {// `company` ($group_0) groups for group-level analysis.$groups: { team: teamId, ...(orgId ? { company: orgId } : {}) },});+ // A rejected capture must not use up the one-time milestone.+ if (!sent) await redisEvictConnection.del(key);} catch (error) {_logger.debug("trackFirstSurfaceUse failed", {module: "posthog",