diff --git a/doc/cloud-browser-analytics.md b/doc/cloud-browser-analytics.md new file mode 100644 index 00000000000..27bb253688e --- /dev/null +++ b/doc/cloud-browser-analytics.md @@ -0,0 +1,122 @@ +# Cloud Browser Product Analytics + +On Paperclip Cloud, the board UI can send page views, sessions, autocapture +clicks, heatmaps, Web Vitals and session replays to PostHog. Self-hosted +installs never do this: they do not download `posthog-js` and do not serve the +PostHog proxy. + +## Who gets it + +The server decides, in `server/src/services/cloud-posthog-browser.ts`. The +authenticated `GET /api/auth/get-session` response carries a +`browserAnalytics` object only when all of these hold: + +1. The instance is cloud managed (`isCloudManagedInstance`). +2. `PAPERCLIP_POSTHOG_PROJECT_TOKEN` and `PAPERCLIP_CLOUD_STACK_ID` are set. +3. `PAPERCLIP_POSTHOG_BROWSER_ENABLED=1`. + +Otherwise the field is `null`, and the browser loads nothing. When it is set, +the browser loads PostHog's browser script (`/_ph/static/array.js`, through the +proxy) only after the page settles (first paint, page reads finished, browser +idle), so cold loads do not wait for it. posthog-js is not an npm dependency +of the board and is in no bundle chunk; PostHog serves it, as it serves the +extensions posthog-js loads at run time (recorder, web vitals). + +## Configuration + +| Variable | Default | Meaning | +| --- | --- | --- | +| `PAPERCLIP_POSTHOG_PROJECT_TOKEN` | — | PostHog project token. It is public by design: it can send events but cannot read data. | +| `PAPERCLIP_POSTHOG_HOST` | `https://us.i.posthog.com` | PostHog ingest host. The proxy forwards to it. | +| `PAPERCLIP_POSTHOG_ENVIRONMENT` | — | `staging` or `production`. Added to every event as `environment`. | +| `PAPERCLIP_POSTHOG_BROWSER_ENABLED` | off | `1` turns browser analytics on for this stack. Leave it unset to keep it off. | +| `PAPERCLIP_POSTHOG_REPLAY_ENABLED` | on (when browser analytics is on) | `0` turns session replay off for this stack and keeps the other browser analytics. | + +### Per-stack opt-out + +For a customer whose contract forbids recording, set +`PAPERCLIP_POSTHOG_REPLAY_ENABLED=0` on that stack. To turn off all browser +analytics for a stack, unset `PAPERCLIP_POSTHOG_BROWSER_ENABLED`. Both take +effect on the next server restart. + +## Reverse proxy + +The browser sends to `/_ph` on its own origin, so ad blockers do not drop +events. `server/src/routes/posthog-proxy.ts` is not a generic proxy. It +forwards only the requests posthog-js makes: + +| Method | Path | Upstream | +| --- | --- | --- | +| `POST` | `/e/`, `/i/v0/e/`, `/batch/` | ingest host | +| `POST` | `/s/` (session replay) | ingest host | +| `POST` | `/flags/`, `/decide/` | ingest host | +| `GET` | `/array//config`, `/array//config.js` | assets host | +| `GET` | `/static/.js` | assets host | + +The ingest host is `PAPERCLIP_POSTHOG_HOST`. The assets host is derived from it +(`us.i.posthog.com` → `us-assets.i.posthog.com`). Every other method or path +answers 404 without contacting PostHog. The proxy streams bodies, builds a new +header set from an allowlist plus `X-Forwarded-For`, and never forwards the +inbound Host, Cookie or Authorization headers. It drops `Set-Cookie` from +responses. It refuses bodies over 64 MiB (413) and limits requests in +flight to 16 per client address and 256 in total (429). It is mounted only when +browser analytics is on. It does not require a session: posthog-js sends some +events while a page unloads, and the proxy can only reach the two PostHog hosts +with the public project token, like PostHog's own ingest endpoint. + +## Identity + +- After sign-in: `identify(session.userId, { email, name })`. `session.userId` + is the authenticated actor's user id verbatim (`req.actor.userId`, for + example `paperclip-id:...`), the same id server events use as `distinct_id`. Email and name are person + properties only, never event properties. +- `group("workspace", stackId)`. +- Every event carries `deployment_source: "cloud"` and `environment`. Without + `PAPERCLIP_POSTHOG_ENVIRONMENT`, `environment` is `staging` on a + `*.staging.paperclip.app` host and `production` otherwise. +- Sign-out: `reset()`, called by `useSignOut` before it leaves the page. +- API requests to our own host carry PostHog tracing headers, so server events + link to the browser session. + +## Privacy + +Masking is deny by default. A surface that nobody marked stays masked. + +- Session replay masks every input value and every text node. + `maskReplayText` in `ui/src/lib/analytics/privacy.ts` shows text only inside + elements with `ANALYTICS_UNMASK_PROPS`: sidebar items whose label is a fixed + string, and a shared `Button`, `Label`, `TabsTrigger` or `EmptyState` only + when its caller passes `analyticsChrome`. None of them opts in by default, + because they also render customer text such as agent names and titles. +- Replay also masks attribute values (`maskReplayAttribute`): only layout + attributes (`class`, `style`, `role`, `data-state`, SVG geometry and similar), + rrweb metadata and stylesheet links keep their values. `title`, + `aria-label`, `alt`, `placeholder`, `src`, `href`, `data-*` values and + element references (`id`, `for`, `aria-labelledby`) are always masked, even on unmasked chrome, so images record as empty boxes and + link targets (for example download links with file paths) never leave. +- `ANALYTICS_MASK_CLASS` keeps customer content masked even inside unmasked + chrome: rendered markdown (task bodies, comments, chat messages, documents), + task and issue chat threads, the comment timeline, the rich editor and the + file viewer. Text in a `contenteditable` editor is always masked. +- `ANALYTICS_NO_CAPTURE_CLASS` replaces secrets with a blank box in replays: + every password-type `Input`, environment variable values and new secret + values. +- Every event and replay meta event goes through `scrubCapturedEvent` + (`before_send`). Every URL keeps only its origin and path: query and hash + values never leave, because they can hold credentials, file paths or search + text. The token segment of `/board-claim/` and `/invite/` is + redacted (`redactAnalyticsUrl`). Other strings only have secret + `key=value` pairs redacted. +- Events never carry the page title (`before_send` drops `title`), because + Paperclip page titles name the task and the organization. +- Autocapture never records element text or attribute values + (`mask_all_text`, `mask_all_element_attributes`). It keeps the click, the + element tree and the page. +- Connected-account content (Gmail bodies, Calendar events, Slack messages + in tasks, chat, tool results and previews) is Google user data or Slack + data. No human may read it in a replay (Google API Limited Use). It is never + inside the unmask allowlist, and autocapture records no element text at all. + `ui/src/lib/analytics/unmask-allowlist.test.ts` pins the allowlist: a new + unmask needs a reviewed entry there. +- The UI never captures an event that the server already sends + (`PAPERCLIP_EVENTS`); `product-analytics-events.test.ts` enforces this. diff --git a/doc/observability.md b/doc/observability.md index 77a0b1d8e66..f9aaac0700f 100644 --- a/doc/observability.md +++ b/doc/observability.md @@ -154,6 +154,9 @@ for this workload; everything else from - **Browser page-load tracing** on hosted instances needs `PAPERCLIP_BROWSER_TRACES_ENDPOINT`. See [browser performance tracing](browser-performance-tracing.md). +- **Browser product analytics** (PostHog) on Paperclip Cloud needs + `PAPERCLIP_POSTHOG_PROJECT_TOKEN` and `PAPERCLIP_POSTHOG_BROWSER_ENABLED=1`. + See [Cloud browser product analytics](cloud-browser-analytics.md). ## Sentry Error Monitoring diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index e17ff48b580..793b9067f01 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -2451,6 +2451,7 @@ export { currentUserProfileSchema, authSessionSchema, browserTracingConfigSchema, + browserAnalyticsConfigSchema, updateCurrentUserProfileSchema, updateCompanyMemberSchema, updateCompanyMemberWithPermissionsSchema, @@ -2477,6 +2478,7 @@ export { type CurrentUserProfile, type AuthSession, type BrowserTracingConfig, + type BrowserAnalyticsConfig, type UpdateCurrentUserProfile, type UpdateCompanyMember, type UpdateCompanyMemberWithPermissions, diff --git a/packages/shared/src/validators/access.ts b/packages/shared/src/validators/access.ts index eb1c2ab3cc6..110a49f427a 100644 --- a/packages/shared/src/validators/access.ts +++ b/packages/shared/src/validators/access.ts @@ -216,6 +216,27 @@ export const browserTracingConfigSchema = z.object({ export type BrowserTracingConfig = z.infer; +/** + * Browser product analytics (PostHog) settings for a hosted Paperclip Cloud + * instance. The server sends a value only when the instance is cloud managed, + * `PAPERCLIP_POSTHOG_PROJECT_TOKEN` and `PAPERCLIP_CLOUD_STACK_ID` are set, and + * `PAPERCLIP_POSTHOG_BROWSER_ENABLED=1`. `token` is a PostHog project token, + * which is public by design (it can only send events). `apiHost` is the + * same-origin reverse proxy path, and `uiHost` is the PostHog app host for + * links, or null when it is not a PostHog Cloud host. `environment` is + * always set, so every browser event carries it. + */ +export const browserAnalyticsConfigSchema = z.object({ + token: z.string().min(1), + apiHost: z.string().min(1), + uiHost: z.string().url().nullable(), + environment: z.string().min(1), + stackId: z.string().min(1), + replayEnabled: z.boolean(), +}); + +export type BrowserAnalyticsConfig = z.infer; + export const authSessionSchema = z.object({ session: z.object({ id: z.string().min(1), @@ -234,6 +255,9 @@ export const authSessionSchema = z.object({ // Null or absent leaves browser performance tracing off. Optional for // browser/server version skew. browserTracing: browserTracingConfigSchema.nullable().optional(), + // Null or absent leaves browser product analytics off; the browser then never + // downloads posthog-js. Optional for browser/server version skew. + browserAnalytics: browserAnalyticsConfigSchema.nullable().optional(), }); export type AuthSession = z.infer; diff --git a/packages/shared/src/validators/index.ts b/packages/shared/src/validators/index.ts index b0bc5449eb5..c8cbf1aea75 100644 --- a/packages/shared/src/validators/index.ts +++ b/packages/shared/src/validators/index.ts @@ -775,6 +775,7 @@ export { currentUserProfileSchema, authSessionSchema, browserTracingConfigSchema, + browserAnalyticsConfigSchema, updateCurrentUserProfileSchema, updateCompanyMemberSchema, updateCompanyMemberWithPermissionsSchema, @@ -797,6 +798,7 @@ export { type CurrentUserProfile, type AuthSession, type BrowserTracingConfig, + type BrowserAnalyticsConfig, type UpdateCurrentUserProfile, type UpdateCompanyMember, type UpdateCompanyMemberWithPermissions, diff --git a/server/src/__tests__/auth-routes.test.ts b/server/src/__tests__/auth-routes.test.ts index 381c99b517a..8098f990864 100644 --- a/server/src/__tests__/auth-routes.test.ts +++ b/server/src/__tests__/auth-routes.test.ts @@ -96,6 +96,41 @@ describe("auth routes", () => { sentryDsn: null, sentryEnvironment: null, browserTracing: null, + browserAnalytics: null, + }); + }); + + it("returns the authenticated actor's user id verbatim, the id browser analytics identifies with", async () => { + const actorId = "paperclip-id:uf2X8Ha4H9hNdAMnc1rOy91VIRos5pch"; + const actor = { type: "board", userId: actorId, source: "cloud_tenant" } as Express.Request["actor"]; + const res = await request(createApp(actor, { ...baseUser, id: actorId })).get("/api/auth/get-session"); + expect(res.status).toBe(200); + // ProductAnalyticsGate calls identify(session.userId); server events use the actor id as distinct_id. + expect(res.body.session.userId).toBe(actorId); + }); + + it("sends browserAnalytics only on Cloud with a PostHog token and the browser switch", async () => { + const actor = { type: "board", userId: "user-1", source: "session" } as Express.Request["actor"]; + vi.stubEnv("PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN", "tenant-token"); + vi.stubEnv("PAPERCLIP_CLOUD_STACK_ID", "stack-1"); + vi.stubEnv("PAPERCLIP_POSTHOG_PROJECT_TOKEN", "phc_test"); + vi.stubEnv("PAPERCLIP_POSTHOG_BROWSER_ENABLED", undefined); + + const off = await request(createApp(actor, baseUser)).get("/api/auth/get-session"); + expect(off.status).toBe(200); + expect(off.body.browserAnalytics).toBeNull(); + + vi.stubEnv("PAPERCLIP_POSTHOG_BROWSER_ENABLED", "1"); + vi.stubEnv("PAPERCLIP_POSTHOG_ENVIRONMENT", "staging"); + const on = await request(createApp(actor, baseUser)).get("/api/auth/get-session"); + expect(on.status).toBe(200); + expect(on.body.browserAnalytics).toEqual({ + token: "phc_test", + apiHost: "/_ph", + uiHost: "https://us.posthog.com", + environment: "staging", + stackId: "stack-1", + replayEnabled: true, }); }); diff --git a/server/src/__tests__/board-skill-ui-guidance.test.ts b/server/src/__tests__/board-skill-ui-guidance.test.ts index 877c7271f87..d177137832d 100644 --- a/server/src/__tests__/board-skill-ui-guidance.test.ts +++ b/server/src/__tests__/board-skill-ui-guidance.test.ts @@ -31,7 +31,7 @@ describe("paperclip-board skill web UI guidance", () => { it("keeps the overlay promise to the shortcut and describes the sidebar Search item as full search", () => { // The classic sidebar Search item is a link to the full search page, not the overlay. - expect(read("ui/src/components/Sidebar.tsx")).toMatch(/]*\bto="\/search" label="Search"/); expect(section).toMatch(/sidebar \*\*Search\*\* item[^\n]*opens the full search page/); expect(section).not.toMatch(/search icon[^\n]*opens over the current page/i); }); diff --git a/server/src/__tests__/cloud-posthog-browser.test.ts b/server/src/__tests__/cloud-posthog-browser.test.ts new file mode 100644 index 00000000000..8cf1863a8ce --- /dev/null +++ b/server/src/__tests__/cloud-posthog-browser.test.ts @@ -0,0 +1,295 @@ +import http from "node:http"; +import type { AddressInfo } from "node:net"; +import express from "express"; +import request from "supertest"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { + posthogAssetsOrigin, + posthogUiHost, + resolveBrowserAnalyticsConfig, +} from "../services/cloud-posthog-browser.js"; +import { resolveCloudPostHogConfig } from "../services/cloud-posthog-config.js"; +import { + posthogProxyRoutes, + posthogUpstreamUrl, + resolvePostHogProxyMount, +} from "../routes/posthog-proxy.js"; + +const CLOUD = { PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN: "tenant-token", PAPERCLIP_CLOUD_STACK_ID: "stack-1" }; +const TOKEN = { PAPERCLIP_POSTHOG_PROJECT_TOKEN: "phc_test" }; +const BROWSER = { PAPERCLIP_POSTHOG_BROWSER_ENABLED: "1" }; + +describe("browser analytics config exposure", () => { + const cases: Array<[string, Record, boolean, boolean | null]> = [ + ["self-hosted, even with every PostHog switch set", { ...TOKEN, ...BROWSER, PAPERCLIP_CLOUD_STACK_ID: "stack-1" }, false, null], + ["Cloud without a token", { ...CLOUD, ...BROWSER }, false, null], + ["Cloud without a stack ID", { PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN: "t", ...TOKEN, ...BROWSER }, false, null], + ["Cloud with a token but no browser switch", { ...CLOUD, ...TOKEN }, false, null], + ["Cloud with the browser switch set to something other than 1", { ...CLOUD, ...TOKEN, PAPERCLIP_POSTHOG_BROWSER_ENABLED: "true" }, false, null], + ["Cloud with browser analytics on", { ...CLOUD, ...TOKEN, ...BROWSER }, true, true], + ["Cloud with browser analytics on and replay off", { ...CLOUD, ...TOKEN, ...BROWSER, PAPERCLIP_POSTHOG_REPLAY_ENABLED: "0" }, true, false], + ]; + + it.each(cases)("%s", (_name, env, exposed, replayEnabled) => { + const config = resolveBrowserAnalyticsConfig(env); + if (!exposed) { + expect(config).toBeNull(); + return; + } + expect(config).toEqual({ + token: "phc_test", + apiHost: "/_ph", + uiHost: "https://us.posthog.com", + environment: "production", + stackId: "stack-1", + replayEnabled, + }); + }); + + it("always sends an environment: the explicit variable, else staging or production from the host", () => { + const on = { ...CLOUD, ...TOKEN, ...BROWSER }; + expect(resolveBrowserAnalyticsConfig({ ...on, PAPERCLIP_POSTHOG_ENVIRONMENT: "qa" })?.environment).toBe("qa"); + expect(resolveBrowserAnalyticsConfig({ ...on, PAPERCLIP_PRIMARY_HOST: "acme.staging.paperclip.app" })?.environment).toBe("staging"); + expect(resolveBrowserAnalyticsConfig({ ...on, PAPERCLIP_PRIMARY_HOST: "acme.paperclip.app" })?.environment).toBe("production"); + }); + + it("never turns replay on without the browser switch", () => { + expect(resolveCloudPostHogConfig({ ...CLOUD, ...TOKEN, PAPERCLIP_POSTHOG_REPLAY_ENABLED: "1" })?.replayEnabled).toBe(false); + }); + + it("keeps browser analytics off for an invalid host", () => { + expect(resolveBrowserAnalyticsConfig({ ...CLOUD, ...TOKEN, ...BROWSER, PAPERCLIP_POSTHOG_HOST: "not a url" })).toBeNull(); + }); + + it("maps PostHog Cloud hosts to their assets and app hosts", () => { + expect(posthogAssetsOrigin("https://us.i.posthog.com")).toBe("https://us-assets.i.posthog.com"); + expect(posthogAssetsOrigin("https://eu.i.posthog.com")).toBe("https://eu-assets.i.posthog.com"); + expect(posthogAssetsOrigin("http://127.0.0.1:9999")).toBe("http://127.0.0.1:9999"); + expect(posthogUiHost("https://eu.i.posthog.com")).toBe("https://eu.posthog.com"); + expect(posthogUiHost("http://127.0.0.1:9999")).toBeNull(); + }); +}); + +describe("PostHog proxy mount", () => { + it("is not mounted unless browser analytics is on", () => { + expect(resolvePostHogProxyMount({})).toBeNull(); + expect(resolvePostHogProxyMount({ ...TOKEN, ...BROWSER, PAPERCLIP_CLOUD_STACK_ID: "s" })).toBeNull(); + expect(resolvePostHogProxyMount({ ...CLOUD, ...TOKEN })).toBeNull(); + expect(resolvePostHogProxyMount({ ...CLOUD, ...TOKEN, ...BROWSER })?.path).toBe("/_ph"); + }); + + it("routes static assets to the assets host and events to the ingest host", () => { + const host = "https://us.i.posthog.com"; + expect(posthogUpstreamUrl(host, "GET", "/static/recorder.js?v=1")?.href) + .toBe("https://us-assets.i.posthog.com/static/recorder.js?v=1"); + expect(posthogUpstreamUrl(host, "GET", "/array/phc_x/config.js")?.origin).toBe("https://us-assets.i.posthog.com"); + expect(posthogUpstreamUrl(host, "GET", "/array/phc_x/config")?.origin).toBe("https://us-assets.i.posthog.com"); + expect(posthogUpstreamUrl(host, "GET", "/static/1.442.1/lazy-recorder.js")?.href) + .toBe("https://us-assets.i.posthog.com/static/1.442.1/lazy-recorder.js"); + expect(posthogUpstreamUrl(host, "POST", "/e/?ip=0")?.href).toBe("https://us.i.posthog.com/e/?ip=0"); + expect(posthogUpstreamUrl(host, "POST", "/i/v0/e/")?.origin).toBe("https://us.i.posthog.com"); + expect(posthogUpstreamUrl(host, "POST", "/s/?compression=gzip-js")?.pathname).toBe("/s/"); + expect(posthogUpstreamUrl(host, "POST", "/flags/?v=2")?.pathname).toBe("/flags/"); + }); + + it.each([ + ["GET", "/e/"], + ["PUT", "/e/"], + ["DELETE", "/s/"], + ["OPTIONS", "/flags/"], + ["POST", "/static/recorder.js"], + ["GET", "/api/projects/"], + ["POST", "/api/surveys/"], + ["GET", "/static/../api/x.js"], + ["GET", "/static/recorder.css"], + ["GET", "/static/v1/../x.js"], + ["GET", "/static/a/b/c.js"], + ["GET", "//evil.example/static/x.js"], + ["POST", "//evil.example/e/"], + ["GET", "/array/phc_x/../../api"], + ["GET", "/"], + ])("refuses %s %s", (method, path) => { + expect(posthogUpstreamUrl("https://us.i.posthog.com", method, path)).toBeNull(); + }); +}); + +describe("PostHog proxy forwarding", () => { + let upstream: http.Server; + let upstreamUrl: string; + let seen: Array<{ method?: string; url?: string; headers: http.IncomingHttpHeaders; body: string }>; + + beforeEach(async () => { + seen = []; + upstream = http.createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (chunk: Buffer) => chunks.push(chunk)); + req.on("end", () => { + seen.push({ method: req.method, url: req.url, headers: req.headers, body: Buffer.concat(chunks).toString() }); + res.writeHead(200, { "content-type": "application/json", "set-cookie": "upstream=1" }); + res.end(JSON.stringify({ status: 1 })); + }); + }); + await new Promise((resolve) => upstream.listen(0, "127.0.0.1", resolve)); + upstreamUrl = `http://127.0.0.1:${(upstream.address() as AddressInfo).port}`; + }); + + afterEach(async () => { + await new Promise((resolve) => upstream.close(() => resolve())); + }); + + function proxyApp() { + const mount = resolvePostHogProxyMount({ ...CLOUD, ...TOKEN, ...BROWSER, PAPERCLIP_POSTHOG_HOST: upstreamUrl }); + expect(mount).not.toBeNull(); + const app = express(); + app.use(mount!.path, mount!.router); + // A body parser after the proxy, as in app.ts, must never see proxied bodies. + app.use(express.json()); + return app; + } + + it("streams the request body and strips Host, Cookie, Authorization and set-cookie", async () => { + const res = await request(proxyApp()) + .post("/_ph/e/?compression=gzip-js") + .set("Host", "acme.paperclip.app") + .set("Content-Type", "application/json") + .set("Cookie", "paperclip.session=secret") + .set("Authorization", "Bearer secret") + .set("X-POSTHOG-SESSION-ID", "s1") + .send(JSON.stringify({ event: "$pageview" })); + + expect(res.status).toBe(200); + expect(res.body).toEqual({ status: 1 }); + expect(res.headers["set-cookie"]).toBeUndefined(); + expect(seen).toHaveLength(1); + expect(seen[0]!.method).toBe("POST"); + expect(seen[0]!.url).toBe("/e/?compression=gzip-js"); + expect(seen[0]!.body).toBe(JSON.stringify({ event: "$pageview" })); + expect(seen[0]!.headers.host).toBe(new URL(upstreamUrl).host); + expect(seen[0]!.headers.cookie).toBeUndefined(); + expect(seen[0]!.headers.authorization).toBeUndefined(); + expect(seen[0]!.headers["x-posthog-session-id"]).toBeUndefined(); + expect(seen[0]!.headers["x-forwarded-for"]).toBeTruthy(); + }); + + it.each([ + ["GET", "/_ph/api/projects/@current"], + ["PUT", "/_ph/e/"], + ["DELETE", "/_ph/e/"], + ["GET", "/_ph/e/"], + ["POST", "/_ph/static/recorder.js"], + ])("answers 404 to %s %s without contacting PostHog", async (method, path) => { + const res = await request(proxyApp())[method.toLowerCase() as "get"](path); + expect(res.status).toBe(404); + expect(seen).toHaveLength(0); + }); + + it("refuses a declared body over the limit without contacting PostHog", async () => { + const app = express(); + app.use("/_ph", posthogProxyRoutes(upstreamUrl, { maxBodyBytes: 10, maxInFlightPerClient: 16, maxInFlight: 256 })); + const res = await request(app).post("/_ph/e/").set("Content-Type", "text/plain").send("x".repeat(11)); + expect(res.status).toBe(413); + expect(seen).toHaveLength(0); + }); + + it("cuts off a streamed body that grows past the limit", async () => { + const app = express(); + app.use("/_ph", posthogProxyRoutes(upstreamUrl, { maxBodyBytes: 10, maxInFlightPerClient: 16, maxInFlight: 256 })); + const server = app.listen(0, "127.0.0.1"); + await new Promise((resolve) => server.once("listening", () => resolve())); + const port = (server.address() as AddressInfo).port; + try { + const status = await new Promise((resolve) => { + const req = http.request({ host: "127.0.0.1", port, path: "/_ph/e/", method: "POST", headers: { "content-type": "text/plain", "transfer-encoding": "chunked" } }, (res) => { + res.resume(); + resolve(res.statusCode ?? 0); + }); + req.on("error", () => resolve("error")); + req.write("x".repeat(8)); + req.write("x".repeat(8)); + req.end(); + }); + expect([413, "error"]).toContain(status); + expect(seen.every((entry) => entry.body.length <= 10)).toBe(true); + } finally { + await new Promise((resolve) => server.close(() => resolve())); + } + }); + + it("limits requests in flight from one client", async () => { + let release: () => void = () => {}; + const held = new Promise((resolve) => { release = resolve; }); + const slow = http.createServer(async (_req, res) => { await held; res.end("ok"); }); + await new Promise((resolve) => slow.listen(0, "127.0.0.1", resolve)); + const app = express(); + app.use("/_ph", posthogProxyRoutes(`http://127.0.0.1:${(slow.address() as AddressInfo).port}`, { maxBodyBytes: 1024, maxInFlightPerClient: 1, maxInFlight: 256 })); + const server = app.listen(0, "127.0.0.1"); + await new Promise((resolve) => server.once("listening", () => resolve())); + try { + const first = request(server).get("/_ph/static/array.js").then((res) => res.status); + await new Promise((resolve) => setTimeout(resolve, 50)); + const second = await request(server).get("/_ph/static/array.js"); + expect(second.status).toBe(429); + release(); + expect(await first).toBe(200); + // The slot frees up once the first request finishes. + expect((await request(server).get("/_ph/static/array.js")).status).toBe(200); + } finally { + release(); + await new Promise((resolve) => server.close(() => resolve())); + await new Promise((resolve) => slow.close(() => resolve())); + } + }); + + it("never forwards the inbound Host header", async () => { + await request(proxyApp()).get("/_ph/static/recorder.js").set("Host", "acme.paperclip.app"); + expect(seen[0]!.headers.host).toBe(new URL(upstreamUrl).host); + }); + + it("answers 502 when PostHog cannot be reached", async () => { + const mount = resolvePostHogProxyMount({ ...CLOUD, ...TOKEN, ...BROWSER, PAPERCLIP_POSTHOG_HOST: "http://127.0.0.1:1" }); + const app = express(); + app.use(mount!.path, mount!.router); + const res = await request(app).get("/_ph/static/array.js"); + expect(res.status).toBe(502); + }); + + it("survives PostHog closing the connection partway through a response", async () => { + const broken = http.createServer((_req, res) => { + res.writeHead(200, { "content-type": "application/javascript", "content-length": "100000" }); + res.write("partial"); + setTimeout(() => res.socket?.destroy(), 20); + }); + await new Promise((resolve) => broken.listen(0, "127.0.0.1", resolve)); + const brokenUrl = `http://127.0.0.1:${(broken.address() as AddressInfo).port}`; + const errors: unknown[] = []; + const onUncaught = (err: unknown) => errors.push(err); + process.on("uncaughtException", onUncaught); + try { + const mount = resolvePostHogProxyMount({ ...CLOUD, ...TOKEN, ...BROWSER, PAPERCLIP_POSTHOG_HOST: brokenUrl }); + const app = express(); + app.use(mount!.path, mount!.router); + const server = app.listen(0, "127.0.0.1"); + await new Promise((resolve) => server.once("listening", () => resolve())); + const port = (server.address() as AddressInfo).port; + const outcome = await new Promise((resolve) => { + http.get(`http://127.0.0.1:${port}/_ph/static/recorder.js`, (res) => { + res.on("data", () => {}); + res.on("end", () => resolve("end")); + res.on("error", () => resolve("error")); + res.on("aborted", () => resolve("aborted")); + }).on("error", () => resolve("error")); + }); + // The browser sees a cut-off response, not a complete one. + expect(outcome).not.toBe("end"); + await new Promise((resolve) => setTimeout(resolve, 50)); + // The proxy keeps serving after the broken response. + const health = await request(server).put("/_ph/e/"); + expect(health.status).toBe(404); + await new Promise((resolve) => server.close(() => resolve())); + } finally { + process.off("uncaughtException", onUncaught); + await new Promise((resolve) => broken.close(() => resolve())); + } + expect(errors).toEqual([]); + }); +}); diff --git a/server/src/app.ts b/server/src/app.ts index 2715922012e..4be9c420154 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -179,6 +179,7 @@ import { } from "./routes/instance-database-backups.js"; import { llmRoutes } from "./routes/llms.js"; import { authRoutes } from "./routes/auth.js"; +import { resolvePostHogProxyMount } from "./routes/posthog-proxy.js"; import { assetRoutes } from "./routes/assets.js"; import { accessRoutes } from "./routes/access.js"; import { pluginRoutes } from "./routes/plugins.js"; @@ -535,6 +536,10 @@ export async function createApp( // Default is unset → Express trusts nothing, which is the only safe choice // when the server may be reachable without a known reverse proxy in front. applyTrustProxy(app, parseTrustProxyEnv(process.env.TRUST_PROXY)); + // Browser analytics on Paperclip Cloud only. Mounted before every body + // parser so PostHog payloads stream through unread; see routes/posthog-proxy.ts. + const posthogProxy = resolvePostHogProxyMount(process.env); + if (posthogProxy) app.use(posthogProxy.path, posthogProxy.router); app.use( COMPANY_IMPORT_API_PATH, diff --git a/server/src/routes/auth.ts b/server/src/routes/auth.ts index 602287aa1d5..0da917b6bcf 100644 --- a/server/src/routes/auth.ts +++ b/server/src/routes/auth.ts @@ -13,6 +13,7 @@ import { resolveSentryDsns } from "../sentry-dsn.js"; import { resolveBrowserTracingConfig, warnOnce } from "../browser-tracing-config.js"; import { logger } from "../middleware/logger.js"; import { loadBoardBootstrap } from "../services/board-bootstrap.js"; +import { resolveBrowserAnalyticsConfig } from "../services/cloud-posthog-browser.js"; async function loadCurrentUserProfile(db: Db, userId: string) { const user = await db @@ -73,6 +74,9 @@ export function authRoutes(db: Db) { // Hosted Paperclip Cloud only; null everywhere else. The ingest key is // ingest-only by construction — see `server/src/browser-tracing-config.ts`. browserTracing: resolveBrowserTracingConfig(process.env, warnBrowserTracing), + // Hosted Paperclip Cloud with PAPERCLIP_POSTHOG_BROWSER_ENABLED=1 only; + // null everywhere else. See `server/src/services/cloud-posthog-browser.ts`. + browserAnalytics: resolveBrowserAnalyticsConfig(process.env), }); res.json({ ...session, ...(boardBootstrap ? { boardBootstrap } : {}) }); }); diff --git a/server/src/routes/posthog-proxy.ts b/server/src/routes/posthog-proxy.ts new file mode 100644 index 00000000000..f1964ffbf91 --- /dev/null +++ b/server/src/routes/posthog-proxy.ts @@ -0,0 +1,238 @@ +// Same-origin reverse proxy for browser PostHog traffic on Paperclip Cloud. +// +// Ad blockers drop requests to PostHog's own hosts, so the board UI sends to +// `/_ph` on its own origin and this proxy forwards them. +// +// It is not a generic proxy. It forwards only the requests posthog-js makes: +// the method and path must match `POSTHOG_PROXY_ROUTES`, and the upstream is +// always the configured ingest host or its static assets host. Everything +// else answers 404 without contacting PostHog. +// +// `app.ts` mounts it only when browser analytics is on (see +// `services/cloud-posthog-browser.ts`), before any body parser, so request and +// response bodies stream through without buffering. It carries no Paperclip +// data and grants nothing: it builds a fresh header set from an allowlist, so +// the browser's Host, Cookie and Authorization headers never leave. + +import http from "node:http"; +import https from "node:https"; +import { pipeline, Transform } from "node:stream"; +import type { IncomingHttpHeaders, OutgoingHttpHeaders } from "node:http"; +import { Router, type Request, type Response } from "express"; +import { logger } from "../middleware/logger.js"; +import type { CloudInstanceEnv } from "../services/cloud-instance.js"; +import { + POSTHOG_PROXY_PATH, + posthogAssetsOrigin, + resolveBrowserPostHogConfig, +} from "../services/cloud-posthog-browser.js"; + +const UPSTREAM_TIMEOUT_MS = 30_000; + +export type PostHogProxyLimits = { + /** Largest request body forwarded (PostHog's own proxy guide uses 64 MiB). */ + maxBodyBytes: number; + /** Requests in flight from one client address. */ + maxInFlightPerClient: number; + /** Requests in flight for the whole proxy. */ + maxInFlight: number; +}; + +export const DEFAULT_POSTHOG_PROXY_LIMITS: PostHogProxyLimits = { + maxBodyBytes: 64 * 1024 * 1024, + maxInFlightPerClient: 16, + maxInFlight: 256, +}; + +const BODY_TOO_LARGE = "posthog_proxy_body_too_large"; + +type PostHogUpstream = "ingest" | "assets"; + +/** + * Every request posthog-js makes with surveys, product tours, web experiments + * and conversations turned off (see `ui/src/lib/analytics/product-analytics.ts`). + */ +const POSTHOG_PROXY_ROUTES: ReadonlyArray<{ method: "GET" | "POST"; path: RegExp; upstream: PostHogUpstream }> = [ + // Event batches, including the newer `/i/v0/e/` endpoint. + { method: "POST", path: /^\/(?:i\/v0\/)?e\/?$/, upstream: "ingest" }, + { method: "POST", path: /^\/batch\/?$/, upstream: "ingest" }, + // Session replay snapshots. + { method: "POST", path: /^\/s\/?$/, upstream: "ingest" }, + // Remote settings (they carry the project's replay and autocapture switches). + { method: "POST", path: /^\/(?:flags|decide)\/?$/, upstream: "ingest" }, + // Project config and lazily loaded extensions (recorder, web vitals, ...). + { method: "GET", path: /^\/array\/[A-Za-z0-9_-]+\/config(?:\.js)?$/, upstream: "assets" }, + // posthog-js first asks for a versioned path (`/static/1.442.1/x.js`). + { method: "GET", path: /^\/static\/(?:\d+\.\d+\.\d+\/)?[A-Za-z0-9_-][A-Za-z0-9._-]*\.js$/, upstream: "assets" }, +]; + +/** Request headers PostHog needs. Host, cookies, auth and tracing headers never leave. */ +const FORWARDED_REQUEST_HEADERS = [ + "accept", + "accept-encoding", + "accept-language", + "content-encoding", + "content-length", + "content-type", + "user-agent", +] as const; + +/** Response headers that describe the connection or set state on our origin. */ +const DROPPED_RESPONSE_HEADERS = new Set([ + "connection", + "keep-alive", + "proxy-authenticate", + "proxy-connection", + "set-cookie", + "strict-transport-security", + "transfer-encoding", + "upgrade", +]); + +/** + * The upstream URL for an allowed request, or null. `requestUrl` is the path + * and query below the proxy mount. + */ +export function posthogUpstreamUrl(ingestHost: string, method: string, requestUrl: string): URL | null { + const queryAt = requestUrl.indexOf("?"); + const path = queryAt === -1 ? requestUrl : requestUrl.slice(0, queryAt); + const query = queryAt === -1 ? "" : requestUrl.slice(queryAt); + const route = POSTHOG_PROXY_ROUTES.find((candidate) => candidate.method === method && candidate.path.test(path)); + if (!route) return null; + const origin = route.upstream === "assets" ? posthogAssetsOrigin(ingestHost) : new URL(ingestHost).origin; + // The path matched a fixed pattern, so it cannot name another host. + return new URL(`${origin}${path}${query}`); +} + +export function posthogForwardRequestHeaders( + headers: IncomingHttpHeaders, + clientIp: string | undefined, + upstreamHost: string, +): OutgoingHttpHeaders { + const forwarded: OutgoingHttpHeaders = { host: upstreamHost }; + for (const name of FORWARDED_REQUEST_HEADERS) { + const value = headers[name]; + if (value !== undefined) forwarded[name] = value; + } + // PostHog derives the visitor's location from this header behind a proxy. + if (clientIp) forwarded["x-forwarded-for"] = clientIp; + return forwarded; +} + +export function posthogProxyRoutes(ingestHost: string, limits: PostHogProxyLimits = DEFAULT_POSTHOG_PROXY_LIMITS) { + const router = Router(); + let inFlight = 0; + const inFlightByClient = new Map(); + + router.use((req: Request, res: Response) => { + let upstream: URL | null; + try { + upstream = posthogUpstreamUrl(ingestHost, req.method, req.url); + } catch { + upstream = null; + } + if (!upstream) { + res.status(404).json({ error: "not_found" }); + return; + } + const target = upstream; + let received = 0; + let bodyTooLarge = false; + + const declaredLength = Number(req.headers["content-length"] ?? 0); + if (Number.isFinite(declaredLength) && declaredLength > limits.maxBodyBytes) { + res.status(413).json({ error: "payload_too_large" }); + return; + } + + // Bound the work one browser, or all of them, can put on this process. + const client = req.ip ?? "unknown"; + const clientInFlight = inFlightByClient.get(client) ?? 0; + if (inFlight >= limits.maxInFlight || clientInFlight >= limits.maxInFlightPerClient) { + res.setHeader("Retry-After", "1"); + res.status(429).json({ error: "too_many_requests" }); + return; + } + inFlight += 1; + inFlightByClient.set(client, clientInFlight + 1); + res.once("close", () => { + inFlight -= 1; + const remaining = (inFlightByClient.get(client) ?? 1) - 1; + if (remaining > 0) inFlightByClient.set(client, remaining); + else inFlightByClient.delete(client); + }); + + const transport = target.protocol === "https:" ? https : http; + const upstreamReq = transport.request(target, { + method: req.method, + headers: posthogForwardRequestHeaders(req.headers, req.ip, target.host), + timeout: UPSTREAM_TIMEOUT_MS, + }); + + upstreamReq.on("response", (upstreamRes) => { + const headers: OutgoingHttpHeaders = {}; + for (const [name, value] of Object.entries(upstreamRes.headers)) { + if (value !== undefined && !DROPPED_RESPONSE_HEADERS.has(name)) headers[name] = value; + } + res.writeHead(upstreamRes.statusCode ?? 502, headers); + // pipeline() handles an error on either side (PostHog closing the + // connection mid-response, the browser going away) by destroying both + // streams, so no stream error goes unhandled. + pipeline(upstreamRes, res, (err) => { + if (err) logger.debug({ err, path: target.pathname }, "PostHog proxy response ended early"); + }); + }); + upstreamReq.on("timeout", () => { + upstreamReq.destroy(new Error("posthog_proxy_timeout")); + }); + upstreamReq.on("error", (err) => { + logger.debug({ err, path: target.pathname }, "PostHog proxy request failed"); + if (!res.headersSent && bodyTooLarge) { + res.status(413).json({ error: "payload_too_large" }); + } else if (!res.headersSent) { + res.status(502).json({ error: "analytics_upstream_unavailable" }); + } else { + res.destroy(); + } + }); + // The browser went away: stop the upstream request too. + res.on("close", () => { + if (!res.writableFinished) upstreamReq.destroy(); + }); + + // A body without (or with a false) Content-Length is counted as it + // streams and cut off at the limit. + const sizeLimit = new Transform({ + transform(chunk: Buffer, _encoding, callback) { + received += chunk.length; + if (received > limits.maxBodyBytes) { + bodyTooLarge = true; + callback(new Error(BODY_TOO_LARGE)); + } else { + callback(null, chunk); + } + }, + }); + // An aborted or oversized browser upload destroys the upstream request, + // whose error listener above answers or closes the browser response. + pipeline(req, sizeLimit, upstreamReq, () => {}); + }); + + return router; +} + +/** + * The proxy mount for this instance, or null when browser analytics is off. + * Self-hosted installs always get null, so `/_ph` falls through to the UI. + */ +export function resolvePostHogProxyMount(env: CloudInstanceEnv = process.env) { + const config = resolveBrowserPostHogConfig(env); + if (!config) return null; + try { + posthogAssetsOrigin(config.host); + } catch { + logger.warn("PAPERCLIP_POSTHOG_HOST is not a valid URL; the PostHog proxy is off"); + return null; + } + return { path: POSTHOG_PROXY_PATH, router: posthogProxyRoutes(config.host) }; +} diff --git a/server/src/services/cloud-posthog-browser.ts b/server/src/services/cloud-posthog-browser.ts new file mode 100644 index 00000000000..a0331033f1b --- /dev/null +++ b/server/src/services/cloud-posthog-browser.ts @@ -0,0 +1,65 @@ +// Browser product analytics (PostHog) for hosted Paperclip Cloud instances. +// +// The signed-in session hands the board UI a `browserAnalytics` config only +// when `resolveCloudPostHogConfig` returns a config (cloud managed, project +// token and stack ID set) and `PAPERCLIP_POSTHOG_BROWSER_ENABLED=1`. Every +// other instance gets `null`, so self-hosted installs, local development and +// tests never download posthog-js and never mount the PostHog proxy. +// +// The browser sends to `POSTHOG_PROXY_PATH` on its own origin, not to PostHog, +// so ad blockers do not drop the events. See `routes/posthog-proxy.ts`. + +import type { BrowserAnalyticsConfig } from "@paperclipai/shared"; +import { isCloudStagingInstance, type CloudInstanceEnv } from "./cloud-instance.js"; +import { resolveCloudPostHogConfig, type CloudPostHogConfig } from "./cloud-posthog-config.js"; + +/** Same-origin path that the PostHog reverse proxy serves. */ +export const POSTHOG_PROXY_PATH = "/_ph"; + +const POSTHOG_CLOUD_INGEST_HOST = /^(us|eu)\.i\.posthog\.com$/i; + +/** The browser analytics part of the Cloud PostHog config, or null when it is off. */ +export function resolveBrowserPostHogConfig(env: CloudInstanceEnv = process.env): CloudPostHogConfig | null { + const config = resolveCloudPostHogConfig(env); + return config?.browserEnabled ? config : null; +} + +/** + * PostHog serves its static scripts (`/static/*`, `/array/*`) from a separate + * assets host. A self-run or test host serves both from one origin. + */ +export function posthogAssetsOrigin(ingestHost: string): string { + const url = new URL(ingestHost); + const match = POSTHOG_CLOUD_INGEST_HOST.exec(url.hostname); + if (match) url.hostname = `${match[1]!.toLowerCase()}-assets.i.posthog.com`; + return url.origin; +} + +/** The PostHog app host (for toolbar and replay links), or null for a non-PostHog host. */ +export function posthogUiHost(ingestHost: string): string | null { + const url = new URL(ingestHost); + const match = POSTHOG_CLOUD_INGEST_HOST.exec(url.hostname); + return match ? `https://${match[1]!.toLowerCase()}.posthog.com` : null; +} + +export function resolveBrowserAnalyticsConfig(env: CloudInstanceEnv = process.env): BrowserAnalyticsConfig | null { + const config = resolveBrowserPostHogConfig(env); + if (!config) return null; + let uiHost: string | null; + try { + uiHost = posthogUiHost(config.host); + } catch { + // An invalid host cannot be proxied either; keep browser analytics off. + return null; + } + return { + token: config.token, + apiHost: POSTHOG_PROXY_PATH, + uiHost, + // Every browser event carries an environment. Without the explicit + // variable, a staging host name means staging; anything else production. + environment: config.environment ?? (isCloudStagingInstance(env) ? "staging" : "production"), + stackId: config.stackId, + replayEnabled: config.replayEnabled, + }; +} diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index c1d8b7c91ec..dfa279c54b1 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -268,7 +268,7 @@ "packages/shared/src/home-paths.ts": "fa4f1c440653b76b3dbb7a51026d557287deb45d", "packages/shared/src/humanize-connection.test.ts": "ba9e90a44c63452b0bf9f733adb90241921e8eca", "packages/shared/src/humanize-connection.ts": "fbd414476a0ef7106a7c80d8572208781b091699", - "packages/shared/src/index.ts": "e17ff48b5807bf070dcacec86c2edcab48b341f9", + "packages/shared/src/index.ts": "793b9067f01fd57e8e33e4abea87f828d90d861a", "packages/shared/src/issue-activity-identity.test.ts": "3dc294640f54c2be67943e3e0149cf4eff2c95ca", "packages/shared/src/issue-activity-identity.ts": "1b0f07ec3fe0506aaaf80a4fa9893f3baf8f0075", "packages/shared/src/issue-attribution.test.ts": "84563685e7f3c48029243cf1cc24a3a09ee3cde9", @@ -444,7 +444,7 @@ "packages/shared/src/types/workspace-runtime.ts": "00ab237577d3ea3a1fa946ce6ab6ef8b389b1739", "packages/shared/src/types/workspace-source-verification.ts": "647f5c8817590629439813df5dc63750b316206d", "packages/shared/src/validators/access.test.ts": "0df0e096658a31c4f21462a992e38cf8bd7082b1", - "packages/shared/src/validators/access.ts": "eb1c2ab3cc6616477f6cf68d2745a1d1de16640e", + "packages/shared/src/validators/access.ts": "110a49f427a9deb194b51d671c6007120c2af0a6", "packages/shared/src/validators/adapter-auth-session.ts": "14cffbd7281265bf3f059bcf1b97739ebe0e1f81", "packages/shared/src/validators/adapter-registry.test.ts": "567c113e50dd0c0d259b095375f8f8f403ffa893", "packages/shared/src/validators/adapter-registry.ts": "6fb9f655d49f774ef7f082bf842f388f1187e545", @@ -487,7 +487,7 @@ "packages/shared/src/validators/folder.ts": "b486444ab09ec3d5a9afec7dbd2e71c1bc2beb67", "packages/shared/src/validators/goal.ts": "602724134915e1e83c50115abba36b288c0abd3d", "packages/shared/src/validators/inbox-agent-policy.ts": "29cef157f4d9b564fd813868038aa8c813df4a7b", - "packages/shared/src/validators/index.ts": "b0bc5449eb5c21fc89064d9d5243223ab33cf5e0", + "packages/shared/src/validators/index.ts": "c8cbf1aea7577e7f7a07b4ca733dabb9b23b0458", "packages/shared/src/validators/instance.test.ts": "3faa9593a9a05f74429d9b1d2251906a03e9a903", "packages/shared/src/validators/instance.ts": "d801db219659707f0c9a8c1fbad06e862be4892d", "packages/shared/src/validators/issue-chat-bootstrap.test.ts": "e1ebb9aa94da22c825bc3ddd32ce2cfc98bfe645", diff --git a/ui/src/components/AppsSidebar.production.tsx b/ui/src/components/AppsSidebar.production.tsx index bf50e5d4b2c..cc5153b7f85 100644 --- a/ui/src/components/AppsSidebar.production.tsx +++ b/ui/src/components/AppsSidebar.production.tsx @@ -66,8 +66,8 @@ export function AppsSidebar() { Connectors
- - +
- + {developerTabs.map((tab) => (
- - + +

Timeline ({timeline.length + queuedComments.length})

- + {showPage("instance.profile") && ( - )} {showPage("company.members") && ( - ))} {showPage("company.invites") && ( - + )} {showPage("company.secrets") && ( - + )} {showPage("instance.environments") && ( - )} - + {showPage("instance.access") && ( - )} {showPage("instance.heartbeats") && ( - )} {showPage("company.export") && ( - + )} {!isCloud && showPage("company.import") && ( - + )} {showPage("instance.experimental") && ( - )} {showPlugins && ( - ) : null} {showPage("instance.adapters") && ( -
- +