mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 11:47:42 +01:00
feat(analytics): move onboarding funnel telemetry server-side and add granular step instrumentation (#23403)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Hosted Paperclip Cloud tracks user onboarding conversion in PostHog
across server-side events and browser events
> - Onboarding funnel events (`onboarding_opened`,
`onboarding_step_viewed`, `onboarding_step_completed`,
`onboarding_step_failed`, `onboarding_dismissed`) currently fire only
from browser `posthog-js`
> - Browser `posthog-js` loads lazily after `whenPageSettles` (up to 15
seconds), drops events captured before `startProductAnalytics`
initializes, and can be blocked by privacy extensions, causing
artificial dropoff between server-side `workspace_entry` and
`onboarding_opened`
> - Step 1 (`name_org`) is unmapped in `WIZARD_STEPS`, and
`connect_model` lacks sub-step visibility (provider selection,
credential mode switch, OAuth progress, API key submission, Cloud trial
CTA, mobile handoff)
> - This pull request routes all onboarding funnel events through a
first-party `POST /api/onboarding/telemetry` endpoint backed by
`trackCloudPostHogEvent` (`posthog-node`), preserves every existing
event name verbatim, adds granular step and sub-step instrumentation,
and fixes the pre-start queue drop in `product-analytics.ts`
> - The benefit is adblocker-proof, race-free server-side onboarding
analytics in PostHog with complete step-by-step dropoff visibility and
zero breaking changes to existing insights
## Linked Issues or Issue Description
**What existing behavior does this improve?**
Cloud onboarding funnel analytics in
`ui/src/lib/analytics/onboarding-analytics.ts`,
`ui/src/lib/analytics/product-analytics.ts`,
`ui/src/components/OnboardingWizard.tsx`, and `server/src/telemetry.ts`.
**Subsystem affected**
Cross-cutting (multiple of the above)
**Current behavior**
Onboarding funnel events fire only from browser `posthog-js`. Events
captured before `ProductAnalyticsGate` calls `startProductAnalytics` are
silently dropped, queued events are lost if the user leaves before
`/_ph/static/array.js` loads, Step 1 (`name_org`) is unmapped, and
`connect_model` sub-steps (OAuth link open, code submit, retry, abandon,
provider tile click, Cloud trial CTA, mobile desktop handoff) are not
instrumented.
**Proposed behavior**
All onboarding funnel and interaction events are sent via
`fetch("/api/onboarding/telemetry", { method: "POST", keepalive: true
})` to a board-authenticated, strictly Zod-validated Express route that
forwards them server-side to PostHog via `trackCloudPostHogEvent`.
Existing event names are preserved verbatim and removed from
`posthog-js` to guarantee a single sender per event. Pre-start browser
events in `product-analytics.ts` are also buffered until
`startProductAnalytics` runs.
**Reason and benefit**
Adblockers and browser script lazy-load races can no longer drop
onboarding funnel events. Product analytics can now separate
`workspace_entry` -> `onboarding_workspace_loaded` ->
`onboarding_opened` and pinpoint exact dropoff points on every step and
`connect_model` sub-step.
**Breaking changes**
None. Existing PostHog event names (`onboarding_opened`,
`onboarding_step_viewed`, `onboarding_step_completed`,
`onboarding_step_failed`, `onboarding_dismissed`,
`agent_chat_message_sent`) are preserved verbatim. On self-hosted
installs, `trackCloudPostHogEvent` is a no-op and the endpoint returns
`204 No Content`.
## What Changed
- Added `packages/shared/src/onboarding-telemetry.ts` (exported from
`packages/shared/src/index.ts`) with strict Zod discriminated-union
schemas (`onboardingTelemetryEventSchema`), canonical event names
(`ONBOARDING_TELEMETRY_EVENTS`), and snake_case PostHog property mapping
(`onboardingTelemetryEventToPostHogProperties`).
- Added `server/src/routes/onboarding-telemetry.ts` (`POST
/api/onboarding/telemetry`), mounted in `server/src/app.ts`, enforcing
`assertBoard(req)`, `assertCompanyAccess(req, companyId)` when
`companyId` is present, strict schema validation, and server-side
delivery via `trackCloudPostHogEvent`.
- Updated `ui/src/lib/analytics/onboarding-analytics.ts` to send all
onboarding events to `/api/onboarding/telemetry` with `keepalive: true`
(removing duplicate browser `posthog-js` sends), mapped Step 1 to
`name_org`, fixed `1 -> 3` forward step completion ordering, and added
granular capture helpers.
- Instrumented `ui/src/hooks/useAgentlessOnboardingAutoOpen.ts`
(`onboarding_workspace_loaded`),
`ui/src/components/onboarding/MobileDesktopNudge.tsx`
(`onboarding_mobile_handoff_action`), and
`ui/src/components/OnboardingWizard.tsx` (all step submissions,
back/jump navigation, Cloud trial CTA, model source selection,
credential mode switching, OAuth progress stages, API key submission,
advanced toggle, and launch click). Note: `OnboardingWizard.tsx` is an
existing large file (>1,000 lines); all schema and transport logic lives
in `packages/shared/src/onboarding-telemetry.ts` and
`ui/src/lib/analytics/onboarding-analytics.ts`, with only call-site
wiring added to the wizard.
- Fixed `ui/src/lib/analytics/product-analytics.ts` to buffer events
captured before `startProductAnalytics` runs (still bounded to 50 events
and cleared on user change).
- Added server route tests in
`server/src/__tests__/onboarding-telemetry-routes.test.ts` and expanded
`ui/src/lib/analytics/onboarding-analytics.test.tsx`.
- Updated `tests/runner-e2e/source-sdk-public-inputs.json` for the new
`@paperclipai/shared` export.
## Verification
- `pnpm --filter @paperclipai/shared build` — passed.
- `pnpm --filter @paperclipai/ui typecheck` — passed.
- `pnpm --filter @paperclipai/server typecheck` — passed.
- `pnpm vitest run
server/src/__tests__/onboarding-telemetry-routes.test.ts
ui/src/lib/analytics/onboarding-analytics.test.tsx
ui/src/lib/analytics/product-analytics.test.ts
ui/src/lib/analytics/product-analytics-events.test.ts
ui/src/components/ProductAnalyticsGate.test.tsx
ui/src/hooks/useAgentlessOnboardingAutoOpen.test.tsx` — 6/6 test files
passed (41/41 tests).
- `pnpm verify` — exited with code 2 because
`tests/runner-e2e/source-sdk-public-inputs.json` requires broad CI
coverage; relying on required CI checks for the remaining broad suites.
## Risks
- Low risk: `POST /api/onboarding/telemetry` performs no database
writes, validates all fields against a strict allowlist (enums,
booleans, bounded integers, safe regex slugs), enforces board auth and
company access, and is a no-op returning `204` on self-hosted instances.
- Browser telemetry calls swallow network failures so analytics can
never block or break onboarding.
## Model Used
- Google Gemini (Gemini 4 Neon, Medium) via Antigravity agentic coding
environment with tool use and local command execution.
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
This commit is contained in:
1 parent
689bfd04ac
commit
c0edaa21a3
18 files changed
+1877
-182
No files matched your search
@@ -34,6 +34,7 @@ const ROUTES_DIR = join(dirname(fileURLToPath(import.meta.url)), "..", "routes")
|
||||
// when the value cannot reveal whether a cross-tenant resource exists.
|
||||
const REQUEST_INPUT_ALLOWLIST = new Set([
|
||||
"companies.ts:target", // import target chosen by the caller (req.body.target)
|
||||
"onboarding-telemetry.ts:body", // optional companyId supplied in request body
|
||||
"plugins.ts:runContext", // run context supplied in the request body
|
||||
]);
|
||||
|
||||
|
||||
@@ -0,0 +1,307 @@
|
||||
import express from "express";
|
||||
import request from "supertest";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { errorHandler } from "../middleware/index.js";
|
||||
|
||||
const mockTrackCloudPostHogEvent = vi.hoisted(() => vi.fn());
|
||||
const mockIsPostHogDirectTelemetryActive = vi.hoisted(() => vi.fn(() => true));
|
||||
|
||||
vi.mock("../telemetry.js", () => ({
|
||||
isPostHogDirectTelemetryActive: mockIsPostHogDirectTelemetryActive,
|
||||
trackCloudPostHogEvent: mockTrackCloudPostHogEvent,
|
||||
}));
|
||||
|
||||
import {
|
||||
onboardingTelemetryRoutes,
|
||||
TELEMETRY_DELIVERED_HEADER,
|
||||
type OnboardingTelemetryRouteOptions,
|
||||
} from "../routes/onboarding-telemetry.js";
|
||||
|
||||
const COMPANY_ID = "11111111-1111-4111-8111-111111111111";
|
||||
const OTHER_COMPANY_ID = "22222222-2222-4222-8222-222222222222";
|
||||
|
||||
function createTestApp(
|
||||
actor: Express.Request["actor"],
|
||||
options?: OnboardingTelemetryRouteOptions,
|
||||
) {
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use((req, _res, next) => {
|
||||
req.actor = actor;
|
||||
next();
|
||||
});
|
||||
app.use("/api", onboardingTelemetryRoutes(options));
|
||||
app.use(errorHandler);
|
||||
return app;
|
||||
}
|
||||
|
||||
describe("POST /api/onboarding/telemetry", () => {
|
||||
beforeEach(() => {
|
||||
mockTrackCloudPostHogEvent.mockReset();
|
||||
mockIsPostHogDirectTelemetryActive.mockReset();
|
||||
mockIsPostHogDirectTelemetryActive.mockReturnValue(true);
|
||||
});
|
||||
|
||||
it("forwards validated onboarding events to PostHog with board user and company context", async () => {
|
||||
const app = createTestApp({
|
||||
type: "board",
|
||||
userId: "paperclip-id:user-1",
|
||||
source: "cloud_tenant",
|
||||
isInstanceAdmin: false,
|
||||
companyIds: [COMPANY_ID],
|
||||
});
|
||||
|
||||
const res = await request(app)
|
||||
.post("/api/onboarding/telemetry")
|
||||
.send({
|
||||
event: "onboarding_step_completed",
|
||||
companyId: COMPANY_ID,
|
||||
step: "connect_model",
|
||||
outcome: "subscription",
|
||||
provider: "anthropic",
|
||||
adapterType: "claude_local",
|
||||
});
|
||||
|
||||
expect(res.status).toBe(204);
|
||||
expect(mockTrackCloudPostHogEvent).toHaveBeenCalledExactlyOnceWith(
|
||||
"onboarding_step_completed",
|
||||
{
|
||||
step: "connect_model",
|
||||
outcome: "subscription",
|
||||
provider: "anthropic",
|
||||
adapter_type: "claude_local",
|
||||
},
|
||||
{
|
||||
userId: "paperclip-id:user-1",
|
||||
companyId: COMPANY_ID,
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it("accepts pre-company Step 1 events without a companyId", async () => {
|
||||
const app = createTestApp({
|
||||
type: "board",
|
||||
userId: "paperclip-id:user-1",
|
||||
source: "cloud_tenant",
|
||||
isInstanceAdmin: false,
|
||||
companyIds: [],
|
||||
});
|
||||
|
||||
const res = await request(app)
|
||||
.post("/api/onboarding/telemetry")
|
||||
.send({
|
||||
event: "onboarding_opened",
|
||||
step: "name_org",
|
||||
source: "manual",
|
||||
isMobile: false,
|
||||
resumedDraft: false,
|
||||
hasExistingCompany: false,
|
||||
});
|
||||
|
||||
expect(res.status).toBe(204);
|
||||
expect(mockTrackCloudPostHogEvent).toHaveBeenCalledExactlyOnceWith(
|
||||
"onboarding_opened",
|
||||
{
|
||||
step: "name_org",
|
||||
source: "manual",
|
||||
is_mobile: false,
|
||||
resumed_draft: false,
|
||||
has_existing_company: false,
|
||||
},
|
||||
{
|
||||
userId: "paperclip-id:user-1",
|
||||
companyId: null,
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it("forwards granular connect-model and workspace-loaded events with snake_case properties", async () => {
|
||||
const app = createTestApp({
|
||||
type: "board",
|
||||
userId: "paperclip-id:user-2",
|
||||
source: "cloud_tenant",
|
||||
isInstanceAdmin: false,
|
||||
companyIds: [COMPANY_ID],
|
||||
});
|
||||
|
||||
const loaded = await request(app)
|
||||
.post("/api/onboarding/telemetry")
|
||||
.send({
|
||||
event: "onboarding_workspace_loaded",
|
||||
companyId: COMPANY_ID,
|
||||
hasCompany: true,
|
||||
hasAgent: false,
|
||||
willAutoOpen: true,
|
||||
isMobile: true,
|
||||
});
|
||||
expect(loaded.status).toBe(204);
|
||||
|
||||
const oauth = await request(app)
|
||||
.post("/api/onboarding/telemetry")
|
||||
.send({
|
||||
event: "onboarding_oauth_progress",
|
||||
companyId: COMPANY_ID,
|
||||
stage: "auth_link_opened",
|
||||
provider: "anthropic",
|
||||
adapterType: "claude_local",
|
||||
phase: "ready",
|
||||
});
|
||||
expect(oauth.status).toBe(204);
|
||||
|
||||
expect(mockTrackCloudPostHogEvent.mock.calls).toEqual([
|
||||
[
|
||||
"onboarding_workspace_loaded",
|
||||
{
|
||||
has_company: true,
|
||||
has_agent: false,
|
||||
will_auto_open: true,
|
||||
is_mobile: true,
|
||||
},
|
||||
{ userId: "paperclip-id:user-2", companyId: COMPANY_ID },
|
||||
],
|
||||
[
|
||||
"onboarding_oauth_progress",
|
||||
{
|
||||
stage: "auth_link_opened",
|
||||
provider: "anthropic",
|
||||
adapter_type: "claude_local",
|
||||
phase: "ready",
|
||||
},
|
||||
{ userId: "paperclip-id:user-2", companyId: COMPANY_ID },
|
||||
],
|
||||
]);
|
||||
});
|
||||
|
||||
it("rejects unauthenticated and agent actors", async () => {
|
||||
const unauthApp = createTestApp({ type: "none", source: "none" });
|
||||
const unauthRes = await request(unauthApp)
|
||||
.post("/api/onboarding/telemetry")
|
||||
.send({ event: "onboarding_opened", step: "create_agent" });
|
||||
expect(unauthRes.status).toBe(403);
|
||||
|
||||
const agentApp = createTestApp({
|
||||
type: "agent",
|
||||
agentId: "agent-1",
|
||||
companyId: COMPANY_ID,
|
||||
source: "agent_key",
|
||||
});
|
||||
const agentRes = await request(agentApp)
|
||||
.post("/api/onboarding/telemetry")
|
||||
.send({ event: "onboarding_opened", step: "create_agent" });
|
||||
expect(agentRes.status).toBe(403);
|
||||
expect(mockTrackCloudPostHogEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects cross-company telemetry when the user lacks access to companyId", async () => {
|
||||
const app = createTestApp({
|
||||
type: "board",
|
||||
userId: "paperclip-id:user-1",
|
||||
source: "cloud_tenant",
|
||||
isInstanceAdmin: false,
|
||||
companyIds: [COMPANY_ID],
|
||||
});
|
||||
|
||||
const res = await request(app)
|
||||
.post("/api/onboarding/telemetry")
|
||||
.send({
|
||||
event: "onboarding_opened",
|
||||
companyId: OTHER_COMPANY_ID,
|
||||
step: "create_agent",
|
||||
});
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
expect(mockTrackCloudPostHogEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects unknown events, extra properties, and unsafe slug strings", async () => {
|
||||
const app = createTestApp({
|
||||
type: "board",
|
||||
userId: "paperclip-id:user-1",
|
||||
source: "cloud_tenant",
|
||||
isInstanceAdmin: false,
|
||||
companyIds: [COMPANY_ID],
|
||||
});
|
||||
|
||||
const unknownEvent = await request(app)
|
||||
.post("/api/onboarding/telemetry")
|
||||
.send({ event: "arbitrary_event" });
|
||||
expect(unknownEvent.status).toBe(400);
|
||||
|
||||
const unsafeProvider = await request(app)
|
||||
.post("/api/onboarding/telemetry")
|
||||
.send({
|
||||
event: "onboarding_step_failed",
|
||||
step: "connect_model",
|
||||
reason: "api_key_save_failed",
|
||||
provider: "sk-secret-key with spaces",
|
||||
});
|
||||
expect(unsafeProvider.status).toBe(400);
|
||||
|
||||
const extraField = await request(app)
|
||||
.post("/api/onboarding/telemetry")
|
||||
.send({
|
||||
event: "onboarding_opened",
|
||||
step: "create_agent",
|
||||
email: "user@example.com",
|
||||
});
|
||||
expect(extraField.status).toBe(400);
|
||||
expect(mockTrackCloudPostHogEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("signals X-Paperclip-Telemetry-Delivered: 0 when direct delivery is inactive", async () => {
|
||||
mockIsPostHogDirectTelemetryActive.mockReturnValue(false);
|
||||
const app = createTestApp({
|
||||
type: "board",
|
||||
userId: "paperclip-id:user-1",
|
||||
source: "cloud_tenant",
|
||||
isInstanceAdmin: false,
|
||||
companyIds: [COMPANY_ID],
|
||||
});
|
||||
|
||||
const res = await request(app)
|
||||
.post("/api/onboarding/telemetry")
|
||||
.send({ event: "onboarding_opened", step: "create_agent" });
|
||||
|
||||
expect(res.status).toBe(204);
|
||||
expect(res.headers[TELEMETRY_DELIVERED_HEADER.toLowerCase()]).toBe("0");
|
||||
expect(mockTrackCloudPostHogEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rate limits excessive events per actor", async () => {
|
||||
let clock = 1_000;
|
||||
const app = createTestApp(
|
||||
{
|
||||
type: "board",
|
||||
userId: "paperclip-id:user-1",
|
||||
source: "cloud_tenant",
|
||||
isInstanceAdmin: false,
|
||||
companyIds: [COMPANY_ID],
|
||||
},
|
||||
{ maxEventsPerWindow: 2, windowMs: 60_000, now: () => clock },
|
||||
);
|
||||
|
||||
const first = await request(app)
|
||||
.post("/api/onboarding/telemetry")
|
||||
.send({ event: "onboarding_opened", step: "create_agent" });
|
||||
const second = await request(app)
|
||||
.post("/api/onboarding/telemetry")
|
||||
.send({ event: "onboarding_step_viewed", step: "create_agent" });
|
||||
const third = await request(app)
|
||||
.post("/api/onboarding/telemetry")
|
||||
.send({ event: "onboarding_step_viewed", step: "connect_model" });
|
||||
|
||||
expect(first.status).toBe(204);
|
||||
expect(first.headers[TELEMETRY_DELIVERED_HEADER.toLowerCase()]).toBe("1");
|
||||
expect(second.status).toBe(204);
|
||||
expect(third.status).toBe(429);
|
||||
expect(mockTrackCloudPostHogEvent).toHaveBeenCalledTimes(2);
|
||||
|
||||
// After the window advances, the actor can send again.
|
||||
clock += 60_001;
|
||||
const afterWindow = await request(app)
|
||||
.post("/api/onboarding/telemetry")
|
||||
.send({ event: "onboarding_step_viewed", step: "connect_model" });
|
||||
expect(afterWindow.status).toBe(204);
|
||||
expect(mockTrackCloudPostHogEvent).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
});
|
||||
@@ -49,6 +49,7 @@ const apiPrefixes: Record<string, string> = {
|
||||
"email.ts": "/api",
|
||||
"cloud.ts": "/api/cloud",
|
||||
"cloud-inference.ts": "/api",
|
||||
"onboarding-telemetry.ts": "/api",
|
||||
"customer-success.ts": "/api/customer-success/v1",
|
||||
"companies.ts": "/api/companies",
|
||||
"company-skills.ts": "/api",
|
||||
|
||||
@@ -102,6 +102,7 @@ import { cloudControlMiddleware } from "./middleware/cloud-control.js";
|
||||
import { runnerCallOutcomeMiddleware } from "./middleware/runner-call-outcome.js";
|
||||
import { cloudRoutes } from "./routes/cloud.js";
|
||||
import { cloudInferenceInternalProxyRoutes, cloudInferenceRoutes } from "./routes/cloud-inference.js";
|
||||
import { onboardingTelemetryRoutes } from "./routes/onboarding-telemetry.js";
|
||||
import {
|
||||
createCloudTrialInferenceController,
|
||||
setDefaultCloudTrialInferenceController,
|
||||
@@ -782,6 +783,7 @@ export async function createApp(
|
||||
api.use(openApiRoutes());
|
||||
api.use("/cloud", cloudRoutes());
|
||||
api.use(cloudInferenceRoutes(db, cloudTrialInferenceController));
|
||||
api.use(onboardingTelemetryRoutes());
|
||||
api.use(headlessIdentityRoutes(db, { deploymentMode: opts.deploymentMode }));
|
||||
api.use("/companies", companyRoutes(db, opts.storageService));
|
||||
api.use(llmRoutes(db));
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import { Router } from "express";
|
||||
import {
|
||||
onboardingTelemetryEventSchema,
|
||||
onboardingTelemetryEventToPostHogProperties,
|
||||
type OnboardingTelemetryEventInput,
|
||||
} from "@paperclipai/shared";
|
||||
import { validate } from "../middleware/validate.js";
|
||||
import { isPostHogDirectTelemetryActive, trackCloudPostHogEvent } from "../telemetry.js";
|
||||
import { assertBoard, assertCompanyAccess, getActorInfo } from "./authz.js";
|
||||
|
||||
const DEFAULT_RATE_LIMIT_WINDOW_MS = 60_000;
|
||||
const DEFAULT_MAX_EVENTS_PER_WINDOW = 120;
|
||||
const MAX_TRACKED_ACTORS = 2_000;
|
||||
|
||||
export const TELEMETRY_DELIVERED_HEADER = "X-Paperclip-Telemetry-Delivered";
|
||||
|
||||
export interface OnboardingTelemetryRouteOptions {
|
||||
windowMs?: number;
|
||||
maxEventsPerWindow?: number;
|
||||
now?: () => number;
|
||||
}
|
||||
|
||||
/**
|
||||
* First-party board endpoint for server-side onboarding funnel telemetry.
|
||||
*
|
||||
* Events are validated against a strict allowlist schema (enums, booleans,
|
||||
* bounded integers, and safe slugs only — never free-form text or secrets)
|
||||
* and forwarded straight to PostHog via `posthog-node` on Paperclip Cloud.
|
||||
* Routing onboarding funnel events through the server avoids adblockers and
|
||||
* browser `posthog-js` lazy-load races.
|
||||
*
|
||||
* The response sets `X-Paperclip-Telemetry-Delivered: 1` when direct PostHog
|
||||
* delivery is active and `0` when it is inactive (self-hosted installs,
|
||||
* `PAPERCLIP_POSTHOG_DIRECT=0`, or missing `PAPERCLIP_POSTHOG_ENVIRONMENT`).
|
||||
* Browser callers can fall back to `posthog-js` only when the header is `0`,
|
||||
* guaranteeing single-sender delivery with no silent loss in hybrid configs.
|
||||
*/
|
||||
export function onboardingTelemetryRoutes(options: OnboardingTelemetryRouteOptions = {}) {
|
||||
const router = Router();
|
||||
const windowMs = options.windowMs ?? DEFAULT_RATE_LIMIT_WINDOW_MS;
|
||||
const maxEventsPerWindow = options.maxEventsPerWindow ?? DEFAULT_MAX_EVENTS_PER_WINDOW;
|
||||
const now = options.now ?? Date.now;
|
||||
const actorBuckets = new Map<string, { windowStart: number; count: number }>();
|
||||
|
||||
function allowActor(actorKey: string): boolean {
|
||||
const current = now();
|
||||
const bucket = actorBuckets.get(actorKey);
|
||||
if (!bucket || current - bucket.windowStart >= windowMs) {
|
||||
if (actorBuckets.size >= MAX_TRACKED_ACTORS) {
|
||||
for (const [key, entry] of actorBuckets) {
|
||||
if (current - entry.windowStart >= windowMs) actorBuckets.delete(key);
|
||||
}
|
||||
if (actorBuckets.size >= MAX_TRACKED_ACTORS) {
|
||||
const oldestKey = actorBuckets.keys().next().value;
|
||||
if (oldestKey !== undefined) actorBuckets.delete(oldestKey);
|
||||
}
|
||||
}
|
||||
actorBuckets.set(actorKey, { windowStart: current, count: 1 });
|
||||
return true;
|
||||
}
|
||||
if (bucket.count >= maxEventsPerWindow) return false;
|
||||
bucket.count += 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
router.post(
|
||||
"/onboarding/telemetry",
|
||||
validate(onboardingTelemetryEventSchema),
|
||||
(req, res) => {
|
||||
assertBoard(req);
|
||||
const body = req.body as OnboardingTelemetryEventInput;
|
||||
if (body.companyId) {
|
||||
assertCompanyAccess(req, body.companyId);
|
||||
}
|
||||
const actor = getActorInfo(req);
|
||||
if (!allowActor(actor.actorId)) {
|
||||
res.status(429).json({ error: "Too many onboarding telemetry events" });
|
||||
return;
|
||||
}
|
||||
const delivered = isPostHogDirectTelemetryActive();
|
||||
if (delivered) {
|
||||
const properties = onboardingTelemetryEventToPostHogProperties(body);
|
||||
trackCloudPostHogEvent(body.event, properties, {
|
||||
userId: actor.actorId,
|
||||
companyId: body.companyId ?? null,
|
||||
});
|
||||
}
|
||||
res.setHeader(TELEMETRY_DELIVERED_HEADER, delivered ? "1" : "0");
|
||||
res.status(204).end();
|
||||
},
|
||||
);
|
||||
|
||||
return router;
|
||||
}
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
experimentalApiQueries,
|
||||
} from "./experimental-api-paths.js";
|
||||
import { Router } from "express";
|
||||
import { subscriptionPriceSchema, mergeSubscriptionsSchema, CLOUD_TRIAL_INFERENCE_STATUSES, cloudTrialTelemetryEventSchema, migrateCloudTrialAgentsSchema } from "@paperclipai/shared";
|
||||
import { subscriptionPriceSchema, mergeSubscriptionsSchema, CLOUD_TRIAL_INFERENCE_STATUSES, cloudTrialTelemetryEventSchema, migrateCloudTrialAgentsSchema, onboardingTelemetryEventSchema } from "@paperclipai/shared";
|
||||
import { z } from "zod";
|
||||
import { getHiddenSettings } from "../services/settings-visibility.js";
|
||||
import {
|
||||
@@ -1551,6 +1551,7 @@ const BOARD_ONLY_OPERATIONS = new Set([
|
||||
"GET /api/companies/{companyId}/cloud-inference/status",
|
||||
"POST /api/companies/{companyId}/cloud-inference/migrate",
|
||||
"POST /api/companies/{companyId}/cloud-inference/telemetry",
|
||||
"POST /api/onboarding/telemetry",
|
||||
"GET /api/companies",
|
||||
"POST /api/companies",
|
||||
"GET /api/companies/stats",
|
||||
@@ -2255,6 +2256,24 @@ registry.registerPath({
|
||||
},
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
method: "post",
|
||||
path: "/api/onboarding/telemetry",
|
||||
tags: ["cloud"],
|
||||
summary: "Record server-side onboarding funnel telemetry",
|
||||
description:
|
||||
"Requires an authenticated board session (and company access when companyId is supplied). Validates strict allowlisted event fields and forwards Cloud-only PostHog funnel events server-side. Sets X-Paperclip-Telemetry-Delivered to 1 when direct PostHog delivery is active, or 0 otherwise.",
|
||||
request: {
|
||||
body: jsonBody(onboardingTelemetryEventSchema),
|
||||
},
|
||||
responses: {
|
||||
204: { description: "Accepted" },
|
||||
400: r.badRequest,
|
||||
403: r.forbidden,
|
||||
429: { description: "Rate limit exceeded" },
|
||||
},
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
method: "get",
|
||||
path: "/api/companies",
|
||||
|
||||
Reference in new issue
Block a user