AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
feat(analytics): stamp marketing attribution on the PostHog person at sign-up (#15534)
moaaz12b1ff60ac29
diff --git a/brain/knowledge/connections-auth/ce-authentication.md b/brain/knowledge/connections-auth/ce-authentication.mdindex 0df4364eeb4..f186b7e90ff 100644--- a/brain/knowledge/connections-auth/ce-authentication.md+++ b/brain/knowledge/connections-auth/ce-authentication.md@@ -16,7 +16,7 @@ The core (all-editions) auth layer: user identity creation, sign-in, and JWT ses- Token is a short-lived JWT (7 days) signed with a shared secret. `PrincipalType`: USER, ENGINE, WORKER, SERVICE, UNKNOWN, ONBOARDING.- Endpoints (all rate-limited via `API_RATE_LIMIT_AUTHN_*`): `POST /v1/authentication/sign-up`, `/sign-in`, `/switch-platform`.- First sign-up side effects: creates identity → User (PlatformRole.ADMIN) → default PERSONAL project; sends OTP on Cloud prod, auto-verifies otherwise; fires `USER_CREATED` flag + `SIGNED_UP` telemetry.-- **`signUp` has two arms and only one of them can create a platform.** When `params.platformId` is set (self-hosted, or a custom domain) the member joins that existing platform through `getOrCreateWithProject` and no platform is ever created or named. When it is nil (Cloud only) the identity is created first, then `getPreferredPlatformId` looks for a platform the identity already belongs to; finding none it hands off to `authenticationUtils.provisionOrOnboard`, which creates the platform straight away when the identity already carries a name someone gave us, and only falls back to an ONBOARDING response (finished at `/create-platform`) when the name is the placeholder derived from the email. `getPreferredPlatformId` returns null on every non-Cloud edition. **The member never types a platform name; they type their own, and the platform name is derived from it.** `completeSignUp` takes a single `fullName` field (that is the whole of `CompleteSignUpRequest`) and calls `signupNames.platformNameFromSignup`, which prefers the company read off a work email domain (`"Activepieces"`) and falls back to the person (`"<FirstName>'s Platform"`, then the capitalised first token of the email local part, then `"My Platform"`). The project name follows from the platform name via `personalProjectName`.+- **`signUp` has two arms and only one of them can create a platform.** When `params.platformId` is set (self-hosted, or a custom domain) the member joins that existing platform through `getOrCreateWithProject` and no platform is ever created or named. When it is nil (Cloud only) the identity is created first, then `getPreferredPlatformId` looks for a platform the identity already belongs to; finding none it hands off to `authenticationUtils.provisionOrOnboard`, which creates the platform straight away only when the identity is **verified and** carries a name someone gave us, and falls back to an ONBOARDING response (finished at `/create-platform`) when `!identity.verified || isPlaceholderName(identity)`. On Cloud a password sign-up is created unverified, so it always takes the onboarding arm at `/sign-up`; its platform is created on the first `/sign-in` after the verification email, which is where the `SignUpMethod.PASSWORD` telemetry stamp lives. `getPreferredPlatformId` returns null on every non-Cloud edition. **The member never types a platform name; they type their own, and the platform name is derived from it.** `completeSignUp` takes a single `fullName` field (that is the whole of `CompleteSignUpRequest`) and calls `signupNames.platformNameFromSignup`, which prefers the company read off a work email domain (`"Activepieces"`) and falls back to the person (`"<FirstName>'s Platform"`, then the capitalised first token of the email local part, then `"My Platform"`). The project name follows from the platform name via `personalProjectName`.- **ONBOARDING** is the pre-platform principal: `authenticationUtils.getOnboardingResponse` mints it with `platformId: null, projectId: null` for a verified identity that belongs to no platform yet **and whose name we only guessed**, so the member can call `POST /v1/platforms` (`securityAccess.unscoped([ONBOARDING, USER])`) and land on `/create-platform`. It is Cloud-only in practice, because on self-hosted `platformUtils.getPlatformIdForRequest` falls back to `getOldestPlatform()` and there is always a platform to join. `accessTokenManager.assertUserSession` still revalidates it against `tokenVersion` + `verified`.- **Sign-up address validation** is one call to ZeroBounce (`zerobounce.maySignUp`), from `signUp` for the EMAIL provider and from `requestCode` for an address with no identity yet. It runs only when `AP_ZEROBOUNCE_API_KEY` is set, refuses the abuse half of `do_not_mail` plus `spamtrap`/`abuse`, and fails open on anything it cannot read. Both call sites refuse **silently**, and the lib throws nothing: `requestCode` returns the same `204` as a success (no identity, no code), and `signUp` throws `EMAIL_IS_NOT_VERIFIED`, the response a genuine unverified Cloud sign-up already produces. `DOMAIN_NOT_ALLOWED` is not used here at all. See [000032](../decisions/000032-a-signup-address-is-checked-against-zerobounce-not-a-bundled-blocklist.md).- **Passwordless sign-in** (`EMAIL_LOGIN`) is a typed 6-digit code on the same OTP primitive, with password as the fallback path. Its two unauthenticated routes, `/otp/request` and `/otp/verify`, live in `passwordlessAuthModule`, registered **only in the Cloud arm of `app.ts` and only when `turnstile.isConfigured()`** — everywhere else they do not exist, so a self-hosted instance answers 404. `/complete-sign-up` stays in `authenticationModule` on every edition, because it finishes any ONBOARDING principal and not just a code sign-up. The UI reads one flag, `ApFlagId.EMAIL_CODE_AUTH_ENABLED`, which carries that same pair of conditions. See [000027](../decisions/000027-email-sign-in-is-a-typed-code-on-the-existing-otp-primitive.md) for the code-not-link and anti-enumeration reasoning and [000032](../decisions/000032-emailed-sign-in-codes-are-served-on-cloud-only-and-only-behind-a-captcha.md) for why the reach narrowed.diff --git a/brain/knowledge/data-storage-observability/index.md b/brain/knowledge/data-storage-observability/index.mdindex a48826fb969..26e0360637a 100644--- a/brain/knowledge/data-storage-observability/index.md+++ b/brain/knowledge/data-storage-observability/index.md@@ -53,6 +53,14 @@ Gotchas:- **Names and emails only ever leave on Cloud, and one helper is the whole reason.** `pickTelemetryPii` returns `{}` unless `edition === ApEdition.CLOUD`, and both the `signed.up` payload and `identify` build their PII by spreading it — so on CE and EE those events carry a user id and nothing personal, while on Cloud they carry email, first name and last name. Reviewers reading the payload type see the fields and reasonably conclude they are always sent; the gate is one spread away in the call site, not in the type. Since [000034](../decisions/000034-account-and-sign-in-telemetry-is-cloud-only.md) the question is moot for account events, which never leave a self-hosted instance at all; `pickTelemetryPii` still governs what `identify` carries, and `identify` still runs there.- **Pre-login capture happens only on `cloud.activepieces.com`** — the browser cannot read a platform's row before a session exists, so that hostname is the whole of the exception (see the decision). `canary.activepieces.com` and the `*.preview.activepieces.dev` envs are therefore excluded, which means **the pre-login funnel cannot be exercised on canary or a preview environment** — verify it on `cloud.activepieces.com`, or add the host.+### Sign-up Attribution++The web stashes the marketing params a visitor arrived with (`utm_*`, `gclid`, `fbclid`, `ref`, `ap_cta`, `ap_landing`, `ap_referrer`, `ap_sid`; contract in `attribution.ts` in shared) in local storage at boot and sends them as `attribution` on `SignUpRequest`, `VerifyEmailCodeRequest`, `CompleteSignUpRequest` and `ClaimTokenRequest`. The auth services return `{ response, signedUp }`; `signedUp` comes from `createPlatformWithProject`'s `provisioned` flag and from `getOrCreateWithProject`'s `created` flag. Only when it is true does the controller call `telemetry(log).identifySignUp`, which writes `signup_method` (`SignUpMethod`) and the attribution as PostHog `$set_once` person properties, so later logins never overwrite them.++Gotchas:+- The Google `USER_SIGNED_UP` audit event is gated on `signedUp` too; before that it fired on every login.+- SAML users are never stamped: they are provisioned by their platform admin, not by a campaign link.+### Flow Failure Alerts (EE)Email on flow-run failure. First failure per flowVersion per 24h window sends; rest suppressed via Redis counter `flow_fail_count:<flowVersionId>` (1-day TTL). Personal projects: single owner-only receiver toggle; team projects: any number of receivers. Platform admins can bulk sub/unsub across projects (max 5 concurrent). Receivers stored/compared lowercase. Edition check (`paidEditions`) in service, no plan flag. No Issues feature — email links straight to the run page. EE/Cloud only.diff --git a/packages/core/shared/src/index.ts b/packages/core/shared/src/index.tsindex 6d78c750a12..43d6384a323 100755--- a/packages/core/shared/src/index.ts+++ b/packages/core/shared/src/index.ts@@ -1,5 +1,6 @@export * from './lib/core/common/telemetry'export * from './lib/core/common/telemetry-pii'+export * from './lib/core/common/attribution'export * from './lib/core/authentication/dto/authentication-response'export * from './lib/core/authentication/dto/sign-up-request'export * from './lib/core/authentication/dto/sign-in-request'diff --git a/packages/core/shared/src/lib/core/authentication/dto/passwordless-request.ts b/packages/core/shared/src/lib/core/authentication/dto/passwordless-request.tsindex 236a6919f86..ab32b855259 100644--- a/packages/core/shared/src/lib/core/authentication/dto/passwordless-request.ts+++ b/packages/core/shared/src/lib/core/authentication/dto/passwordless-request.ts@@ -1,4 +1,5 @@import { z } from 'zod'+import { AttributionParams } from '../../common/attribution'import { EmailType } from '../../user/user'export const MAX_FULL_NAME_LENGTH = 100@@ -14,12 +15,14 @@ export type RequestEmailCodeRequest = z.infer<typeof RequestEmailCodeRequest>export const VerifyEmailCodeRequest = z.object({email: EmailType,code: z.string().trim().min(1),+ attribution: AttributionParams.optional(),})export type VerifyEmailCodeRequest = z.infer<typeof VerifyEmailCodeRequest>export const CompleteSignUpRequest = z.object({fullName: z.string().trim().min(1).max(MAX_FULL_NAME_LENGTH),+ attribution: AttributionParams.optional(),})export type CompleteSignUpRequest = z.infer<typeof CompleteSignUpRequest>diff --git a/packages/core/shared/src/lib/core/authentication/dto/sign-in-request.ts b/packages/core/shared/src/lib/core/authentication/dto/sign-in-request.tsindex 544d150ca76..3f009a3ae89 100755--- a/packages/core/shared/src/lib/core/authentication/dto/sign-in-request.ts+++ b/packages/core/shared/src/lib/core/authentication/dto/sign-in-request.ts@@ -1,9 +1,11 @@import { z } from 'zod'+import { AttributionParams } from '../../common/attribution'import { EmailType, PasswordType } from '../../user/user'export const SignInRequest = z.object({email: EmailType,password: PasswordType,+ attribution: AttributionParams.optional(),})export type SignInRequest = z.infer<typeof SignInRequest>diff --git a/packages/core/shared/src/lib/core/authentication/dto/sign-up-request.ts b/packages/core/shared/src/lib/core/authentication/dto/sign-up-request.tsindex d46862de117..482e1fcd7c1 100755--- a/packages/core/shared/src/lib/core/authentication/dto/sign-up-request.ts+++ b/packages/core/shared/src/lib/core/authentication/dto/sign-up-request.ts@@ -1,5 +1,6 @@import { ApId, SAFE_STRING_PATTERN } from '@activepieces/core-utils'import { z } from 'zod'+import { AttributionParams } from '../../common/attribution'import { EmailType, PasswordType } from '../../user/user'import { MAX_CAPTCHA_TOKEN_LENGTH } from './passwordless-request'@@ -11,6 +12,7 @@ export const SignUpRequest = z.object({trackEvents: z.boolean(),newsLetter: z.boolean(),captchaToken: z.string().trim().min(1).max(MAX_CAPTCHA_TOKEN_LENGTH).optional(),+ attribution: AttributionParams.optional(),})export type SignUpRequest = z.infer<typeof SignUpRequest>diff --git a/packages/core/shared/src/lib/core/common/attribution.ts b/packages/core/shared/src/lib/core/common/attribution.tsnew file mode 100644index 00000000000..3474e5fdf72--- /dev/null+++ b/packages/core/shared/src/lib/core/common/attribution.ts@@ -0,0 +1,93 @@+import { z } from 'zod'+import { UserIdentityProvider } from '../authentication/user-identity'++function readAttributionFromSearch({ search }: { search: string }): AttributionParams {+ const params = new URLSearchParams(search)+ return ATTRIBUTION_PARAM_KEYS.reduce<AttributionParams>((acc, key) => {+ const value = params.get(key)+ if (value !== null && value.trim().length > 0) {+ acc[key] = value.trim().slice(0, ATTRIBUTION_VALUE_MAX_LENGTH)+ }+ return acc+ }, {})+}++function isEmptyAttribution({ attribution }: { attribution: AttributionParams | undefined | null }): boolean {+ if (attribution === undefined || attribution === null) {+ return true+ }+ return ATTRIBUTION_PARAM_KEYS.every((key) => attribution[key] === undefined)+}++export const attributionUtils = {+ readAttributionFromSearch,+ isEmptyAttribution,+ signUpMethodFromProvider,+}++export const ATTRIBUTION_VALUE_MAX_LENGTH = 300++export const ATTRIBUTION_PARAM_KEYS = [+ 'utm_source',+ 'utm_medium',+ 'utm_campaign',+ 'utm_term',+ 'utm_content',+ 'gclid',+ 'fbclid',+ 'ref',+ 'ap_cta',+ 'ap_landing',+ 'ap_referrer',+ 'ap_sid',+] as const++export type AttributionParamKey = (typeof ATTRIBUTION_PARAM_KEYS)[number]++const attributionValue = z.string().trim().min(1).max(ATTRIBUTION_VALUE_MAX_LENGTH).optional()++export const AttributionParams = z.object({+ utm_source: attributionValue,+ utm_medium: attributionValue,+ utm_campaign: attributionValue,+ utm_term: attributionValue,+ utm_content: attributionValue,+ gclid: attributionValue,+ fbclid: attributionValue,+ ref: attributionValue,+ ap_cta: attributionValue,+ ap_landing: attributionValue,+ ap_referrer: attributionValue,+ ap_sid: attributionValue,+})++export type AttributionParams = z.infer<typeof AttributionParams>++export const ATTRIBUTION_STORAGE_KEY = 'ap_acquisition_params'++export const ATTRIBUTION_STORAGE_TTL_MS = 30 * 24 * 60 * 60 * 1000++export enum SignUpMethod {+ PASSWORD = 'password',+ EMAIL_CODE = 'email_code',+ GOOGLE = 'google',+ SAML = 'saml',+ JWT = 'jwt',+}++// Any provider whose identity lands in onboarding finishes at /complete-sign-up,+// so the method there has to come from the identity, not from the route.+// EMAIL identities that reach onboarding came through the code flow; a password+// sign-up is provisioned at /sign-in instead and is stamped there.+function signUpMethodFromProvider({ provider }: { provider: UserIdentityProvider }): SignUpMethod {+ switch (provider) {+ case UserIdentityProvider.EMAIL:+ return SignUpMethod.EMAIL_CODE+ case UserIdentityProvider.GOOGLE:+ return SignUpMethod.GOOGLE+ case UserIdentityProvider.SAML:+ return SignUpMethod.SAML+ case UserIdentityProvider.JWT:+ return SignUpMethod.JWT+ }+}diff --git a/packages/core/shared/src/lib/core/common/telemetry.ts b/packages/core/shared/src/lib/core/common/telemetry.tsindex b58f9eebeef..7f0ca282d4e 100644--- a/packages/core/shared/src/lib/core/common/telemetry.ts+++ b/packages/core/shared/src/lib/core/common/telemetry.ts@@ -1,6 +1,7 @@import type { RunEnvironment } from '@activepieces/core-execution'import type { FlowId, ProjectId, UserId } from '@activepieces/core-utils'import type { McpId } from '../../automation/mcp/mcp'+import type { AttributionParams } from './attribution'type SignedUp = {userId: UserId@@ -16,17 +17,8 @@ type SignedIn = {}type SignUpSubmitted = {- method: 'email'- utm_source?: string- utm_medium?: string- utm_campaign?: string- utm_term?: string- utm_content?: string- gclid?: string- fbclid?: string- ref?: string- ap_cta?: string-}+ method: 'password' | 'email_code'+} & AttributionParamstype SignUpFailed = {errorCode: stringdiff --git a/packages/core/shared/src/lib/core/federated-authn/index.ts b/packages/core/shared/src/lib/core/federated-authn/index.tsindex 933bdeecdc8..ad8c035279f 100644--- a/packages/core/shared/src/lib/core/federated-authn/index.ts+++ b/packages/core/shared/src/lib/core/federated-authn/index.ts@@ -1,5 +1,6 @@import { Nullable } from '@activepieces/core-utils'import { z } from 'zod'+import { AttributionParams } from '../common/attribution'import { ThirdPartyAuthnProviderEnum } from './authn-provider-name'export * from './authn-provider-name'@@ -13,6 +14,7 @@ export type FederatedAuthnLoginResponse = z.infer<typeof federatedAuthnLoginRespexport const ClaimTokenRequest = z.object({providerName: z.nativeEnum(ThirdPartyAuthnProviderEnum),code: z.string(),+ attribution: AttributionParams.optional(),})export type ClaimTokenRequest = z.infer<typeof ClaimTokenRequest>diff --git a/packages/core/shared/test/core/common/attribution.test.ts b/packages/core/shared/test/core/common/attribution.test.tsnew file mode 100644index 00000000000..a7d7353e361--- /dev/null+++ b/packages/core/shared/test/core/common/attribution.test.ts@@ -0,0 +1,17 @@+import { describe, expect, it } from 'vitest'+import { attributionUtils, SignUpMethod, UserIdentityProvider } from '../../../src'++describe('attributionUtils.signUpMethodFromProvider', () => {+ it.each([+ [UserIdentityProvider.EMAIL, SignUpMethod.EMAIL_CODE],+ [UserIdentityProvider.GOOGLE, SignUpMethod.GOOGLE],+ [UserIdentityProvider.SAML, SignUpMethod.SAML],+ [UserIdentityProvider.JWT, SignUpMethod.JWT],+ ])('should map %s to %s', (provider, method) => {+ expect(attributionUtils.signUpMethodFromProvider({ provider })).toBe(method)+ })++ it('should never record a Google identity finishing onboarding as an email-code sign-up', () => {+ expect(attributionUtils.signUpMethodFromProvider({ provider: UserIdentityProvider.GOOGLE })).not.toBe(SignUpMethod.EMAIL_CODE)+ })+})diff --git a/packages/server/api/src/app/authentication/authentication-utils.ts b/packages/server/api/src/app/authentication/authentication-utils.tsindex fe632152465..b86b3d91b55 100644--- a/packages/server/api/src/app/authentication/authentication-utils.ts+++ b/packages/server/api/src/app/authentication/authentication-utils.ts@@ -113,19 +113,19 @@ export const authenticationUtils = (log: FastifyBaseLogger) => ({}},- async provisionOrOnboard({ identityId }: ProvisionOrOnboardParams): Promise<AuthenticationResponse> {+ async provisionOrOnboard({ identityId }: ProvisionOrOnboardParams): Promise<AuthenticationResult> {const identity = await userIdentityService(log).getOneOrFail({ id: identityId })if (!identity.verified || signupNames.isPlaceholderName(identity)) {- return this.getOnboardingResponse({ identityId })+ return { response: await this.getOnboardingResponse({ identityId }), signedUp: false }}- const { response } = await platformService(log).createPlatformWithProject({+ const { response, provisioned } = await platformService(log).createPlatformWithProject({identityId,name: signupNames.platformNameFromSignup({ firstName: identity.firstName, email: identity.email }),invalidatePreviousTokens: false,isFirstPlatform: true,callerTokenVersion: undefined,})- return response+ return { response, signedUp: provisioned }},async assertDomainIsAllowed({@@ -303,6 +303,11 @@ type ProvisionOrOnboardParams = {identityId: string}+export type AuthenticationResult = {+ response: AuthenticationResponse+ signedUp: boolean+}+type GetOnboardingResponseParams = {identityId: string}diff --git a/packages/server/api/src/app/authentication/authentication.controller.ts b/packages/server/api/src/app/authentication/authentication.controller.tsindex 92035e4b898..6d2d4340e78 100644--- a/packages/server/api/src/app/authentication/authentication.controller.ts+++ b/packages/server/api/src/app/authentication/authentication.controller.ts@@ -1,5 +1,5 @@import { isNil } from '@activepieces/core-utils'-import { ApplicationEventName, CompleteSignUpRequest, PrincipalType, SignInRequest, SignUpRequest, SwitchPlatformRequest, TelemetryEventName, UserIdentityProvider } from '@activepieces/shared'+import { ApplicationEventName, attributionUtils, CompleteSignUpRequest, PrincipalType, SignInRequest, SignUpMethod, SignUpRequest, SwitchPlatformRequest, TelemetryEventName, UserIdentityProvider } from '@activepieces/shared'import { FastifyRequest } from 'fastify'import { FastifyPluginAsyncZod } from 'fastify-type-provider-zod'import { securityAccess } from '../core/security/authorization/fastify-security'@@ -27,17 +27,18 @@ export const authenticationController: FastifyPluginAsyncZod = async (remoteIp: clientIp(request),log: request.log,})- const signUpResponse = await authenticationService(request.log).signUp({- ...request.body,+ const { attribution, ...signUpRequest } = request.body+ const { response, signedUp } = await authenticationService(request.log).signUp({+ ...signUpRequest,provider: UserIdentityProvider.EMAIL,platformId: platformId ?? null,})- if (!isNil(signUpResponse.platformId)) {+ if (signedUp && !isNil(response.platformId)) {applicationEvents(request.log).sendUserEvent({- platformId: signUpResponse.platformId,- userId: signUpResponse.id,- projectId: signUpResponse.projectId ?? undefined,+ platformId: response.platformId,+ userId: response.id,+ projectId: response.projectId ?? undefined,ip: networkUtils.extractClientRealIp(request, system.get(AppSystemProp.CLIENT_REAL_IP_HEADER)),}, {action: ApplicationEventName.USER_SIGNED_UP,@@ -45,20 +46,35 @@ export const authenticationController: FastifyPluginAsyncZod = async (source: 'credentials',},})+ rejectedPromiseHandler(telemetry(request.log).identifySignUp({+ userId: response.id,+ platformId: response.platformId,+ method: SignUpMethod.PASSWORD,+ attribution,+ }), request.log)}- return signUpResponse+ return response})app.post('/sign-in', SignInRequestOptions, async (request) => {const predefinedPlatformId = await platformUtils.getPlatformIdForRequest(request)- const response = await authenticationService(request.log).signInWithPassword({+ const { response, signedUp } = await authenticationService(request.log).signInWithPassword({email: request.body.email,password: request.body.password,predefinedPlatformId,})+ if (signedUp && !isNil(response.platformId)) {+ rejectedPromiseHandler(telemetry(request.log).identifySignUp({+ userId: response.id,+ platformId: response.platformId,+ method: SignUpMethod.PASSWORD,+ attribution: request.body.attribution,+ }), request.log)+ }+if (!isNil(response.platformId)) {applicationEvents(request.log).sendUserEvent({platformId: response.platformId,@@ -86,7 +102,7 @@ export const authenticationController: FastifyPluginAsyncZod = async (})app.post('/complete-sign-up', CompleteSignUpRequestOptions, async (request) => {- const { response, signedUp } = await passwordlessAuthService(request.log).completeSignUp({+ const { response, signedUp, provider } = await passwordlessAuthService(request.log).completeSignUp({identityId: request.principal.id,fullName: request.body.fullName,})@@ -101,6 +117,12 @@ export const authenticationController: FastifyPluginAsyncZod = async (action: ApplicationEventName.USER_SIGNED_UP,data: {},})+ rejectedPromiseHandler(telemetry(request.log).identifySignUp({+ userId: response.id,+ platformId: response.platformId,+ method: attributionUtils.signUpMethodFromProvider({ provider }),+ attribution: request.body.attribution,+ }), request.log)}return responsediff --git a/packages/server/api/src/app/authentication/authentication.service.ts b/packages/server/api/src/app/authentication/authentication.service.tsindex 136fc5f25a4..59ac880c814 100644--- a/packages/server/api/src/app/authentication/authentication.service.ts+++ b/packages/server/api/src/app/authentication/authentication.service.ts@@ -9,13 +9,13 @@ import { AppSystemProp } from '../helper/system/system-props'import { platformService } from '../platform/platform.service'import { userService } from '../user/user-service'import { userInvitationsService } from '../user-invitations/user-invitation.service'-import { authenticationUtils } from './authentication-utils'+import { AuthenticationResult, authenticationUtils } from './authentication-utils'import { zerobounce } from './lib/zerobounce'import { otpService } from './otp/otp-service'import { userIdentityService } from './user-identity/user-identity-service'export const authenticationService = (log: FastifyBaseLogger) => ({- async signUp(params: SignUpParams): Promise<AuthenticationResponse> {+ async signUp(params: SignUpParams): Promise<AuthenticationResult> {if (params.provider === UserIdentityProvider.EMAIL) {const maySignUp = await zerobounce.maySignUp({ email: params.email, log })if (!maySignUp) {@@ -48,18 +48,19 @@ export const authenticationService = (log: FastifyBaseLogger) => ({...params,verified: true,})- const user = await userService(log).getOrCreateWithProject({+ const { user } = await userService(log).getOrCreateWithProject({identity: userIdentity,platformId,})await userInvitationsService(log).provisionUserInvitation({ email: params.email })log.info({ email: params.email, platform: { id: platformId } }, 'User signed up to existing platform')- return authenticationUtils(log).getProjectAndToken({+ const response = await authenticationUtils(log).getProjectAndToken({userId: user.id,platformId,projectId: null,})+ return { response, signedUp: true }}const hasInvitations = await userInvitationsService(log).hasAnyAcceptedInvitationsForEmail({ email: params.email })@@ -75,7 +76,7 @@ export const authenticationService = (log: FastifyBaseLogger) => ({const preferredPlatformId = await authenticationService(log).selectCloudSignInPlatformId({ identityId: userIdentity.id })if (!isNil(preferredPlatformId)) {- const user = await userService(log).getOrCreateWithProject({+ const { user } = await userService(log).getOrCreateWithProject({identity: userIdentity,platformId: preferredPlatformId,})@@ -86,17 +87,20 @@ export const authenticationService = (log: FastifyBaseLogger) => ({projectId: null,})rejectedPromiseHandler(authenticationUtils(log).sendTelemetry({ identity: userIdentity, user, projectId: authResponse.projectId ?? '' }), log)- return authResponse+ return { response: authResponse, signedUp: true }}log.info({ email: params.email, provider: params.provider }, 'User signed up without a platform to join')return authenticationUtils(log).provisionOrOnboard({ identityId: userIdentity.id })},- async signInWithPassword(params: SignInWithPasswordParams): Promise<AuthenticationResponse> {+ async signInWithPassword(params: SignInWithPasswordParams): Promise<AuthenticationResult> {const identity = await userIdentityService(log).verifyIdentityPassword(params)const platformId = isNil(params.predefinedPlatformId) ? await authenticationService(log).selectCloudSignInPlatformId({ identityId: identity.id }) : params.predefinedPlatformIdif (isNil(platformId)) { // always cloud+ // A Cloud password sign-up is created unverified and only gets its+ // platform here, on the first sign-in after the verification email.+ // `signedUp` carries that moment out so the controller can stamp it.log.info({ email: params.email }, 'User signed in without an active platform on cloud')return authenticationUtils(log).provisionOrOnboard({ identityId: identity.id })}@@ -122,11 +126,12 @@ export const authenticationService = (log: FastifyBaseLogger) => ({})}log.info({ email: params.email, platform: { id: platformId } }, 'User signed in with password')- return authenticationUtils(log).getProjectAndToken({+ const response = await authenticationUtils(log).getProjectAndToken({userId: user.id,platformId,projectId: null,})+ return { response, signedUp: false }},async selectCloudSignInPlatformId({ identityId }: SelectCloudSignInPlatformIdParams): Promise<string | null> {if (system.getEdition() !== ApEdition.CLOUD) {@@ -138,7 +143,7 @@ export const authenticationService = (log: FastifyBaseLogger) => ({const licensed = platforms.find((p) => !isNil(p.plan.licenseKey))return lastUsed?.id ?? licensed?.id ?? platforms[0]?.id ?? null},- async federatedAuthn(params: FederatedAuthnParams): Promise<AuthenticationResponse> {+ async federatedAuthn(params: FederatedAuthnParams): Promise<AuthenticationResult> {const platformId = isNil(params.predefinedPlatformId) ? await selectCloudSignInPlatformIdByEmail({ email: params.email, log }) : params.predefinedPlatformIdconst userIdentity = await userIdentityService(log).getIdentityByEmail(params.email)@@ -179,16 +184,17 @@ export const authenticationService = (log: FastifyBaseLogger) => ({imageUrl: params.imageUrl,})}- const user = await userService(log).getOrCreateWithProject({+ const { user, created } = await userService(log).getOrCreateWithProject({identity: userIdentity,platformId,})await userInvitationsService(log).provisionUserInvitation({ email: params.email })- return authenticationUtils(log).getProjectAndToken({+ const response = await authenticationUtils(log).getProjectAndToken({userId: user.id,platformId,projectId: null,})+ return { response, signedUp: created }},async switchPlatform(params: SwitchPlatformParams): Promise<AuthenticationResponse> {const platforms = await platformService(log).listPlatformsForIdentityWithAtleastProject({ identityId: params.identityId })diff --git a/packages/server/api/src/app/authentication/passwordless-auth.controller.ts b/packages/server/api/src/app/authentication/passwordless-auth.controller.tsindex f340a27b0f6..26e1f0f981b 100644--- a/packages/server/api/src/app/authentication/passwordless-auth.controller.ts+++ b/packages/server/api/src/app/authentication/passwordless-auth.controller.ts@@ -1,5 +1,5 @@import { isNil } from '@activepieces/core-utils'-import { ApplicationEventName, RequestEmailCodeRequest, TelemetryEventName, VerifyEmailCodeRequest } from '@activepieces/shared'+import { ApplicationEventName, RequestEmailCodeRequest, SignUpMethod, TelemetryEventName, VerifyEmailCodeRequest } from '@activepieces/shared'import { FastifyPluginAsyncZod } from 'fastify-type-provider-zod'import { StatusCodes } from 'http-status-codes'import { securityAccess } from '../core/security/authorization/fastify-security'@@ -27,12 +27,21 @@ export const passwordlessAuthController: FastifyPluginAsyncZod = async (app.post('/otp/verify', VerifyEmailCodeRequestOptions, async (request) => {const platformId = await platformUtils.getPlatformIdForRequest(request)- const response = await passwordlessAuthService(request.log).verifyCode({+ const { response, signedUp } = await passwordlessAuthService(request.log).verifyCode({email: request.body.email,code: request.body.code,platformId: platformId ?? null,})+ if (signedUp && !isNil(response.platformId)) {+ rejectedPromiseHandler(telemetry(request.log).identifySignUp({+ userId: response.id,+ platformId: response.platformId,+ method: SignUpMethod.EMAIL_CODE,+ attribution: request.body.attribution,+ }), request.log)+ }+if (!isNil(response.platformId)) {applicationEvents(request.log).sendUserEvent({platformId: response.platformId,diff --git a/packages/server/api/src/app/authentication/passwordless-auth.service.ts b/packages/server/api/src/app/authentication/passwordless-auth.service.tsindex 3071c8a9ddf..18b536ea803 100644--- a/packages/server/api/src/app/authentication/passwordless-auth.service.ts+++ b/packages/server/api/src/app/authentication/passwordless-auth.service.ts@@ -1,6 +1,6 @@import { ActivepiecesError, ErrorCode, isNil } from '@activepieces/core-utils'import { cryptoUtils } from '@activepieces/server-utils'-import { ApFlagId, AuthenticationResponse, OtpType, TelemetryEventName, UserIdentity, UserIdentityProvider } from '@activepieces/shared'+import { ApFlagId, OtpType, TelemetryEventName, UserIdentity, UserIdentityProvider } from '@activepieces/shared'import { FastifyBaseLogger } from 'fastify'import { flagService } from '../flags/flag.service'import { rejectedPromiseHandler } from '../helper/promise-handler'@@ -10,7 +10,7 @@ import { telemetry } from '../helper/telemetry.utils'import { platformService } from '../platform/platform.service'import { userService } from '../user/user-service'import { userInvitationsService } from '../user-invitations/user-invitation.service'-import { authenticationUtils } from './authentication-utils'+import { AuthenticationResult, authenticationUtils } from './authentication-utils'import { authenticationService } from './authentication.service'import { signupNames } from './lib/signup-names'import { turnstile } from './lib/turnstile'@@ -63,7 +63,7 @@ export const passwordlessAuthService = (log: FastifyBaseLogger) => ({}},- async verifyCode({ email, code, platformId }: VerifyCodeParams): Promise<AuthenticationResponse> {+ async verifyCode({ email, code, platformId }: VerifyCodeParams): Promise<AuthenticationResult> {const identity = await userIdentityService(log).getIdentityByEmail(email)if (isNil(identity)) {throw new ActivepiecesError({ code: ErrorCode.INVALID_OTP, params: {} })@@ -102,34 +102,36 @@ export const passwordlessAuthService = (log: FastifyBaseLogger) => ({params: { message: 'User is not invited to the platform' },})}- const user = await userService(log).getOrCreateWithProject({+ const { user, created } = await userService(log).getOrCreateWithProject({identity: verifiedIdentity,platformId,})await userInvitationsService(log).provisionUserInvitation({ email })- return authenticationUtils(log).getProjectAndToken({+ const response = await authenticationUtils(log).getProjectAndToken({userId: user.id,platformId,projectId: null,})+ return { response, signedUp: created }}if (!isNil(preferredPlatformId)) {await assertPlatformAuthIsOpenTo({ email, platformId: preferredPlatformId, log })- const user = await userService(log).getOrCreateWithProject({+ const { user, created } = await userService(log).getOrCreateWithProject({identity: verifiedIdentity,platformId: preferredPlatformId,})- return authenticationUtils(log).getProjectAndToken({+ const response = await authenticationUtils(log).getProjectAndToken({userId: user.id,platformId: preferredPlatformId,projectId: null,})+ return { response, signedUp: created }}return authenticationUtils(log).provisionOrOnboard({ identityId: verifiedIdentity.id })},- async completeSignUp({ identityId, fullName }: CompleteSignUpParams): Promise<CompleteSignUpResult> {+ async completeSignUp({ identityId, fullName }: CompleteSignUpParams): Promise<AuthenticationResult & { provider: UserIdentityProvider }> {const identity = await userIdentityService(log).getOneOrFail({ id: identityId })const { firstName, lastName } = signupNames.splitFullName({ fullName, email: identity.email })const writeNames = async (): Promise<void> => {@@ -143,7 +145,7 @@ export const passwordlessAuthService = (log: FastifyBaseLogger) => ({callerTokenVersion: undefined,beforeProvision: writeNames,})- return { response, signedUp: provisioned }+ return { response, signedUp: provisioned, provider: identity.provider }},})@@ -195,11 +197,6 @@ type RequestCodeParams = {remoteIp: string | undefined}-type CompleteSignUpResult = {- response: AuthenticationResponse- signedUp: boolean-}-type CompleteSignUpParams = {identityId: stringfullName: stringdiff --git a/packages/server/api/src/app/ee/authentication/federated-authn/federated-authn-module.ts b/packages/server/api/src/app/ee/authentication/federated-authn/federated-authn-module.tsindex 4e64dab5dde..40471087639 100644--- a/packages/server/api/src/app/ee/authentication/federated-authn/federated-authn-module.ts+++ b/packages/server/api/src/app/ee/authentication/federated-authn/federated-authn-module.ts@@ -1,12 +1,14 @@import { isNil } from '@activepieces/core-utils'-import { ApplicationEventName, ClaimTokenRequest, ThirdPartyAuthnProviderEnum } from '@activepieces/shared'+import { ApplicationEventName, ClaimTokenRequest, SignUpMethod, ThirdPartyAuthnProviderEnum } from '@activepieces/shared'import { FastifyPluginAsyncZod } from 'fastify-type-provider-zod'import { z } from 'zod'import { securityAccess } from '../../../core/security/authorization/fastify-security'import { applicationEvents } from '../../../helper/application-events'import { networkUtils } from '../../../helper/network-utils'+import { rejectedPromiseHandler } from '../../../helper/promise-handler'import { system } from '../../../helper/system/system'import { AppSystemProp } from '../../../helper/system/system-props'+import { telemetry } from '../../../helper/telemetry.utils'import { platformUtils } from '../../../platform/platform.utils'import { federatedAuthnService } from './federated-authn-service'@@ -26,11 +28,11 @@ const federatedAuthnController: FastifyPluginAsyncZod = async (app) => {app.post('/claim', ClaimTokenRequestSchema, async (req) => {const platformId = await platformUtils.getPlatformIdForRequest(req)- const response = await federatedAuthnService(req.log).claim({+ const { response, signedUp } = await federatedAuthnService(req.log).claim({platformId: platformId ?? undefined,code: req.body.code,})- if (!isNil(response.platformId)) {+ if (signedUp && !isNil(response.platformId)) {applicationEvents(req.log).sendUserEvent({platformId: response.platformId,userId: response.id,@@ -42,6 +44,12 @@ const federatedAuthnController: FastifyPluginAsyncZod = async (app) => {source: 'sso',},})+ rejectedPromiseHandler(telemetry(req.log).identifySignUp({+ userId: response.id,+ platformId: response.platformId,+ method: SignUpMethod.GOOGLE,+ attribution: req.body.attribution,+ }), req.log)}return response})diff --git a/packages/server/api/src/app/ee/authentication/federated-authn/federated-authn-service.ts b/packages/server/api/src/app/ee/authentication/federated-authn/federated-authn-service.tsindex aeded7c0b9c..e5ee873bcdc 100644--- a/packages/server/api/src/app/ee/authentication/federated-authn/federated-authn-service.ts+++ b/packages/server/api/src/app/ee/authentication/federated-authn/federated-authn-service.ts@@ -1,9 +1,9 @@import {- AuthenticationResponse,FederatedAuthnLoginResponse,UserIdentityProvider,} from '@activepieces/shared'import { FastifyBaseLogger } from 'fastify'+import { AuthenticationResult } from '../../../authentication/authentication-utils'import { authenticationService } from '../../../authentication/authentication.service'import { domainHelper } from '../../../helper/domain-helper'import { system } from '../../../helper/system/system'@@ -28,7 +28,7 @@ export const federatedAuthnService = (log: FastifyBaseLogger) => ({async claim({platformId,code,- }: ClaimParams): Promise<AuthenticationResponse> {+ }: ClaimParams): Promise<AuthenticationResult> {const { clientId, clientSecret } = getClientIdAndSecret()const idToken = await googleAuthnProvider(log).authenticate({clientId,diff --git a/packages/server/api/src/app/ee/authentication/saml-authn/authn-sso-saml-service.ts b/packages/server/api/src/app/ee/authentication/saml-authn/authn-sso-saml-service.tsindex 78842834034..60aee73ccaa 100644--- a/packages/server/api/src/app/ee/authentication/saml-authn/authn-sso-saml-service.ts+++ b/packages/server/api/src/app/ee/authentication/saml-authn/authn-sso-saml-service.ts@@ -45,7 +45,7 @@ export const authnSsoSamlService = (log: FastifyBaseLogger) => {const acsUrl = await this.getAcsUrl(platformId)const client = await createSamlClient({ platformId, samlProvider, acsUrl })const attributes = await client.parseAndValidateLoginResponse(idpLoginResponse)- return authenticationService(log).federatedAuthn({+ const { response } = await authenticationService(log).federatedAuthn({email: attributes.email,firstName: attributes.firstName,lastName: attributes.lastName,@@ -54,6 +54,7 @@ export const authnSsoSamlService = (log: FastifyBaseLogger) => {provider: UserIdentityProvider.SAML,predefinedPlatformId: platformId,})+ return response},async discoverByDomain(domain: string): Promise<DiscoverResult> {const ssoDomain = domain.trim().toLowerCase()diff --git a/packages/server/api/src/app/ee/scim/scim-user-service.ts b/packages/server/api/src/app/ee/scim/scim-user-service.tsindex 4ce1fae9287..1408d34b612 100644--- a/packages/server/api/src/app/ee/scim/scim-user-service.ts+++ b/packages/server/api/src/app/ee/scim/scim-user-service.ts@@ -59,7 +59,7 @@ export const scimUserService = (log: FastifyBaseLogger) => ({)}- const user = await userService(log).getOrCreateWithProject({+ const { user } = await userService(log).getOrCreateWithProject({identity,platformId,})diff --git a/packages/server/api/src/app/helper/telemetry.utils.ts b/packages/server/api/src/app/helper/telemetry.utils.tsindex 7d57bf2ed37..b491aa3a6e7 100644--- a/packages/server/api/src/app/helper/telemetry.utils.ts+++ b/packages/server/api/src/app/helper/telemetry.utils.ts@@ -1,6 +1,6 @@import { AIProviderName, isNil, ProjectId, spreadIfDefined, UserId } from '@activepieces/core-utils'import { apVersionUtil } from '@activepieces/server-utils'-import { ApEdition, AppInstance, DeploymentConfig, FlowRunStatus, GetDiagnosticsResponse, GetSystemHealthChecksResponse, isCloudOnlyTelemetryEvent, MachineInformation, pickTelemetryPii, RunEnvironment, TelemetryEvent, User, UserIdentity } from '@activepieces/shared'+import { ApEdition, AppInstance, AttributionParams, attributionUtils, DeploymentConfig, FlowRunStatus, GetDiagnosticsResponse, GetSystemHealthChecksResponse, isCloudOnlyTelemetryEvent, MachineInformation, pickTelemetryPii, RunEnvironment, SignUpMethod, TelemetryEvent, User, UserIdentity } from '@activepieces/shared'import { FastifyBaseLogger } from 'fastify'import { PostHog } from 'posthog-node'import { platformConfigurationService } from '../platform/platform-configuration.service'@@ -43,6 +43,20 @@ export const telemetry = (log: FastifyBaseLogger) => ({},})},+ async identifySignUp({ userId, platformId, method, attribution }: IdentifySignUpParams): Promise<void> {+ if (!await platformConfigurationService(log).isProductTelemetryEnabled({ platformId })) {+ return+ }+ getPostHog().identify({+ distinctId: userId,+ properties: {+ $set_once: {+ signup_method: method,+ ...(attributionUtils.isEmptyAttribution({ attribution }) ? {} : attribution),+ },+ },+ })+ },async trackPlatform({ platformId, event }: TrackPlatformParams): Promise<void> {if (!await platformConfigurationService(log).isProductTelemetryEnabled({ platformId })) {return@@ -221,6 +235,13 @@ type IdentifyParams = {projectId?: ProjectId}+type IdentifySignUpParams = {+ userId: UserId+ platformId: string+ method: SignUpMethod+ attribution: AttributionParams | undefined+}+type TrackPlatformParams = {platformId: stringevent: TelemetryEventdiff --git a/packages/server/api/src/app/user-invitations/user-invitation.service.ts b/packages/server/api/src/app/user-invitations/user-invitation.service.tsindex d73dec5bfa4..71e345be23b 100644--- a/packages/server/api/src/app/user-invitations/user-invitation.service.ts+++ b/packages/server/api/src/app/user-invitations/user-invitation.service.ts@@ -58,7 +58,7 @@ export const userInvitationsService = (log: FastifyBaseLogger) => ({log.info({ count: invitations.length }, '[provisionUserInvitation] list invitations')for (const invitation of invitations) {log.info({ invitation }, '[provisionUserInvitation] provision')- const user = await userService(log).getOrCreateWithProject({+ const { user } = await userService(log).getOrCreateWithProject({identity,platformId: invitation.platformId,})diff --git a/packages/server/api/src/app/user/user-service.ts b/packages/server/api/src/app/user/user-service.tsindex 1fc051c0bfa..27bd1bcf4c5 100644--- a/packages/server/api/src/app/user/user-service.ts+++ b/packages/server/api/src/app/user/user-service.ts@@ -33,7 +33,7 @@ export const userService = (log: FastifyBaseLogger) => ({}return userRepo().save(user)},- async getOrCreateWithProject({ identity, platformId }: GetOrCreateWithProjectParams): Promise<User> {+ async getOrCreateWithProject({ identity, platformId }: GetOrCreateWithProjectParams): Promise<GetOrCreateWithProjectResult> {const user = await this.getOneByIdentityAndPlatform({identityId: identity.id,platformId,@@ -54,9 +54,9 @@ export const userService = (log: FastifyBaseLogger) => ({type: ProjectType.PERSONAL,})}- return newUser+ return { user: newUser, created: true }}- return user+ return { user, created: false }},async updateLastActiveDate({ id }: UpdateLastActiveDateParams): Promise<void> {await userRepo().update({ id }, { lastActiveDate: dayjs().toISOString() })@@ -394,3 +394,8 @@ type GetOrCreateWithProjectParams = {identity: UserIdentityplatformId: string}++type GetOrCreateWithProjectResult = {+ user: User+ created: boolean+}diff --git a/packages/server/api/test/integration/ee/projects/auto-create-personal-projects.test.ts b/packages/server/api/test/integration/ee/projects/auto-create-personal-projects.test.tsindex ad51aa3c322..822fe917651 100644--- a/packages/server/api/test/integration/ee/projects/auto-create-personal-projects.test.ts+++ b/packages/server/api/test/integration/ee/projects/auto-create-personal-projects.test.ts@@ -59,7 +59,7 @@ describe('Auto-create personal projects toggle', () => {const projectsBefore = await databaseConnection().getRepository('project').count({ where: { platformId: mockPlatform.id, type: ProjectType.PERSONAL } })- const user = await userService(mockLog).getOrCreateWithProject({+ const { user } = await userService(mockLog).getOrCreateWithProject({identity,platformId: mockPlatform.id,})diff --git a/packages/server/api/test/unit/app/helper/telemetry-identify-sign-up.test.ts b/packages/server/api/test/unit/app/helper/telemetry-identify-sign-up.test.tsnew file mode 100644index 00000000000..1277f002398--- /dev/null+++ b/packages/server/api/test/unit/app/helper/telemetry-identify-sign-up.test.ts@@ -0,0 +1,81 @@+import { SignUpMethod } from '@activepieces/shared'+import { beforeEach, describe, expect, it, vi } from 'vitest'++const { mockIdentify, mockIsProductTelemetryEnabled } = vi.hoisted(() => ({+ mockIdentify: vi.fn<(message: IdentifyMessage) => void>(),+ mockIsProductTelemetryEnabled: vi.fn().mockResolvedValue(true),+}))++vi.mock('posthog-node', () => ({+ PostHog: vi.fn(() => ({ identify: mockIdentify, capture: vi.fn(), flush: vi.fn(), shutdown: vi.fn() })),+}))++vi.mock('../../../../src/app/platform/platform-configuration.service', () => ({+ platformConfigurationService: vi.fn(() => ({+ isProductTelemetryEnabled: mockIsProductTelemetryEnabled,+ })),+}))++vi.mock('../../../../src/app/platform/platform.service', () => ({+ platformService: vi.fn(() => ({ getOneOrThrow: vi.fn() })),+}))++vi.mock('../../../../src/app/project/project-service', () => ({+ projectService: vi.fn(() => ({ getOne: vi.fn() })),+}))++vi.mock('../../../../src/app/helper/system/system', () => ({+ system: { getEdition: vi.fn(() => 'cloud'), get: vi.fn(() => 'prod') },+}))++import { telemetry } from '../../../../src/app/helper/telemetry.utils'++const mockLog = {+ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn(),+ child: vi.fn(), fatal: vi.fn(), trace: vi.fn(), silent: vi.fn(), level: 'info',+} as unknown as Parameters<typeof telemetry>[0]++const identifySignUp = (attribution: Record<string, string> | undefined): Promise<void> => telemetry(mockLog).identifySignUp({+ userId: 'user-1',+ platformId: 'platform-1',+ method: SignUpMethod.GOOGLE,+ attribution,+})++describe('identifySignUp', () => {+ beforeEach(() => {+ mockIdentify.mockClear()+ mockIsProductTelemetryEnabled.mockResolvedValue(true)+ })++ it('should stamp the sign-up method and attribution once on the user', async () => {+ await identifySignUp({ utm_source: 'google', gclid: 'abc', ap_sid: 'sid-1' })++ expect(mockIdentify).toHaveBeenCalledTimes(1)+ expect(mockIdentify.mock.calls[0][0]).toEqual({+ distinctId: 'user-1',+ properties: {+ $set_once: { signup_method: 'google', utm_source: 'google', gclid: 'abc', ap_sid: 'sid-1' },+ },+ })+ })++ it('should stamp only the method when no attribution was sent', async () => {+ await identifySignUp(undefined)++ expect(mockIdentify.mock.calls[0][0].properties.$set_once).toEqual({ signup_method: 'google' })+ })++ it('should stay silent when the platform turned product telemetry off', async () => {+ mockIsProductTelemetryEnabled.mockResolvedValue(false)++ await identifySignUp({ utm_source: 'google' })++ expect(mockIdentify).not.toHaveBeenCalled()+ })+})++type IdentifyMessage = {+ distinctId: string+ properties: { $set_once: Record<string, string> }+}diff --git a/packages/web/src/app/components/allow-logged-in-user-only-guard.tsx b/packages/web/src/app/components/allow-logged-in-user-only-guard.tsxindex 6b7fd5cd810..55a44a81aa2 100644--- a/packages/web/src/app/components/allow-logged-in-user-only-guard.tsx+++ b/packages/web/src/app/components/allow-logged-in-user-only-guard.tsx@@ -1,7 +1,6 @@import { Navigate, useLocation } from 'react-router-dom';import { SocketProvider } from '@/components/providers/socket-provider';-import { useTelemetry } from '@/components/providers/telemetry-provider';import { AutomaticTrialActivation } from '@/features/billing';import { projectCollectionUtils } from '@/features/projects';import { flagsHooks } from '@/hooks/flags-hooks';@@ -15,11 +14,9 @@ type AllowOnlyLoggedInUserOnlyGuardProps = {export const AllowOnlyLoggedInUserOnlyGuard = ({children,}: AllowOnlyLoggedInUserOnlyGuardProps) => {- const { reset } = useTelemetry();const location = useLocation();if (!authenticationSession.isLoggedIn()) {authenticationSession.logOut();- reset();const searchParams = new URLSearchParams();searchParams.set('from', location.pathname + location.search);return <Navigate to={`/sign-in?${searchParams.toString()}`} replace />;diff --git a/packages/web/src/app/components/primary-rail/index.tsx b/packages/web/src/app/components/primary-rail/index.tsxindex 4acc64b8a34..682726153bc 100644--- a/packages/web/src/app/components/primary-rail/index.tsx+++ b/packages/web/src/app/components/primary-rail/index.tsx@@ -33,7 +33,6 @@ import { Link, useLocation, useNavigate } from 'react-router-dom';import { UserAvatar } from '@/components/custom/user-avatar';import { useEmbedding } from '@/components/providers/embed-provider';-import { useTelemetry } from '@/components/providers/telemetry-provider';import { Button } from '@/components/ui/button';import {DropdownMenu,@@ -673,7 +672,6 @@ function RailAccountRow({ collapsed }: { collapsed: boolean }) {const [accountSettingsOpen, setAccountSettingsOpen] = useState(false);const { data: user } = userHooks.useCurrentUser();const queryClient = useQueryClient();- const { reset } = useTelemetry();const navigate = useNavigate();if (!user) {@@ -683,7 +681,6 @@ function RailAccountRow({ collapsed }: { collapsed: boolean }) {const handleLogout = () => {userHooks.invalidateCurrentUser(queryClient);authenticationSession.logOut();- reset();navigate('/sign-in');};diff --git a/packages/web/src/app/components/request-trial.tsx b/packages/web/src/app/components/request-trial.tsxindex 2da5b7975ce..1d3b2f49fb1 100644--- a/packages/web/src/app/components/request-trial.tsx+++ b/packages/web/src/app/components/request-trial.tsx@@ -1,9 +1,60 @@+import { isNil } from '@activepieces/core-utils';+import { UserWithMetaInformation } from '@activepieces/shared';import { t } from 'i18next';import { AnimatedIconButton } from '@/components/custom/animated-icon-button';import { SendIcon } from '@/components/icons/send';-import { flagsHooks } from '@/hooks/flags-hooks';import { userHooks } from '@/hooks/user-hooks';+import { telemetryUtils } from '@/lib/telemetry-utils';++export const RequestTrial = ({+ featureKey,+ buttonVariant = 'default',+ buttonSize = 'default',+}: RequestTrialProps) => {+ const { data: currentUser } = userHooks.useCurrentUser();++ const handleClick = () =>+ window.open(+ buildSalesUrl({ currentUser, featureKey }),+ '_blank',+ 'noopener noreferrer',+ );++ return (+ <AnimatedIconButton+ variant={buttonVariant}+ size={buttonSize}+ onClick={handleClick}+ icon={SendIcon}+ iconSize={14}+ >+ {t('Contact Sales')}+ </AnimatedIconButton>+ );+};++function buildSalesUrl({+ currentUser,+ featureKey,+}: {+ currentUser: UserWithMetaInformation | null | undefined;+ featureKey: FeatureKey;+}): string {+ const url = new URL(SALES_URL);+ url.searchParams.set('email', currentUser?.email ?? '');+ url.searchParams.set('firstName', currentUser?.firstName ?? '');+ url.searchParams.set('lastName', currentUser?.lastName ?? '');+ url.searchParams.set('featureKey', featureKey);+ url.searchParams.set('ap_cta', `app_${featureKey.toLowerCase()}`);+ const sessionId = telemetryUtils.getSessionId();+ if (!isNil(sessionId)) {+ url.searchParams.set('ap_sid', sessionId);+ }+ return url.toString();+}++const SALES_URL = 'https://www.activepieces.com/sales';export type FeatureKey =| 'PROJECTS'@@ -39,56 +90,3 @@ type RequestTrialProps = {buttonVariant?: 'default' | 'basic';buttonSize?: 'default' | 'sm' | 'xs';};--export const RequestTrial = ({- featureKey,- buttonVariant = 'default',- buttonSize = 'default',-}: RequestTrialProps) => {- const { data: currentUser } = userHooks.useCurrentUser();- const { data: flags } = flagsHooks.useFlags();-- const createQueryParams = () => {- const params = {- firstName: currentUser?.firstName || '',- lastName: currentUser?.lastName || '',- email: currentUser?.email || '',- featureKey,- flags: toLatin1SafeBase64(JSON.stringify(flags ?? {})),- };-- return Object.entries(params)- .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)- .join('&');- };-- const handleClick = () =>- window.open(- `https://www.activepieces.com/sales?${createQueryParams()}`,- '_blank',- 'noopener noreferrer',- );-- return (- <AnimatedIconButton- variant={buttonVariant}- size={buttonSize}- onClick={handleClick}- icon={SendIcon}- iconSize={14}- >- {t('Contact Sales')}- </AnimatedIconButton>- );-};--function toLatin1SafeBase64(value: string): string {- const latin1Safe = value- .split('')- .map((char) => {- const code = char.charCodeAt(0);- return code > 0xff ? `\\u${code.toString(16).padStart(4, '0')}` : char;- })- .join('');- return btoa(latin1Safe);-}diff --git a/packages/web/src/app/components/sidebar/sidebar-user.tsx b/packages/web/src/app/components/sidebar/sidebar-user.tsxindex 4fd03ffd78d..2163df2ec49 100644--- a/packages/web/src/app/components/sidebar/sidebar-user.tsx+++ b/packages/web/src/app/components/sidebar/sidebar-user.tsx@@ -6,7 +6,6 @@ import { useState } from 'react';import { UserAvatar } from '@/components/custom/user-avatar';import { useEmbedding } from '@/components/providers/embed-provider';-import { useTelemetry } from '@/components/providers/telemetry-provider';import {DropdownMenu,DropdownMenuContent,@@ -34,7 +33,6 @@ export function SidebarUser() {const { embedState } = useEmbedding();const { data: user } = userHooks.useCurrentUser();const queryClient = useQueryClient();- const { reset } = useTelemetry();const { state } = useSidebar();const isCollapsed = state === 'collapsed';if (!user || embedState.isEmbedded) {@@ -44,7 +42,6 @@ export function SidebarUser() {const handleLogout = () => {userHooks.invalidateCurrentUser(queryClient);authenticationSession.logOut();- reset();};return (diff --git a/packages/web/src/app/routes/redirect.tsx b/packages/web/src/app/routes/redirect.tsxindex 690bce12fe0..e0a26bb42a2 100644--- a/packages/web/src/app/routes/redirect.tsx+++ b/packages/web/src/app/routes/redirect.tsx@@ -7,6 +7,7 @@ import { toast } from 'sonner';import { authenticationApi } from '@/api/authentication-api';import { LoadingScreen } from '@/components/custom/loading-screen';import { internalErrorToast } from '@/components/ui/sonner';+import { acquisitionUtils } from '@/lib/acquisition-utils';import { api } from '@/lib/api';import { authenticationSession } from '@/lib/authentication-session';import {@@ -37,6 +38,7 @@ const RedirectPage: React.FC = React.memo(() => {const data = await authenticationApi.claimThirdPartyRequest({providerName,code,+ attribution: acquisitionUtils.getAcquisitionParams(),});authenticationSession.saveResponse(data, false);if (isNil(data.platformId)) {diff --git a/packages/web/src/components/providers/telemetry-provider.tsx b/packages/web/src/components/providers/telemetry-provider.tsxindex a0cb7b33653..e7416f675bd 100644--- a/packages/web/src/components/providers/telemetry-provider.tsx+++ b/packages/web/src/components/providers/telemetry-provider.tsx@@ -14,7 +14,6 @@ import { useEmbedding } from '@/components/providers/embed-provider';import { flagsHooks } from '@/hooks/flags-hooks';import { platformConfigurationHooks } from '@/hooks/platform-configuration-hooks';import { userHooks } from '@/hooks/user-hooks';-import { acquisitionUtils } from '@/lib/acquisition-utils';import { CLOUD_HOSTNAME, isRunningCloudInDevMode } from '@/lib/api';import { errorReporting } from '@/lib/error-reporting';@@ -99,8 +98,6 @@ const TelemetryProvider = ({ children }: TelemetryProviderProps) => {// Tag events so the shared project separates product from marketing traffic.posthog.register({ source_site: 'product' });- acquisitionUtils.stashAcquisitionParams();-if (isCloud && isInRecordingSample(posthog.get_distinct_id())) {posthog.startSessionRecording();}@@ -147,31 +144,22 @@ const TelemetryProvider = ({ children }: TelemetryProviderProps) => {const currentVersion = flagCurrentVersion || UNKNOWN_FLAG_VALUE;const environment = flagEnvironment || UNKNOWN_FLAG_VALUE;- posthog.identify(- currentUser.id,- {- ...pickTelemetryPii({- edition: edition ?? ApEdition.COMMUNITY,- email: currentUser.email,- firstName: currentUser.firstName,- lastName: currentUser.lastName,- }),- activepiecesVersion: currentVersion,- activepiecesEnvironment: environment,- },- acquisitionUtils.getAcquisitionParams(),- );+ posthog.identify(currentUser.id, {+ ...pickTelemetryPii({+ edition: edition ?? ApEdition.COMMUNITY,+ email: currentUser.email,+ firstName: currentUser.firstName,+ lastName: currentUser.lastName,+ }),+ activepiecesVersion: currentVersion,+ activepiecesEnvironment: environment,+ });if (currentUser.platformId) {posthog.group('platform', currentUser.platformId);}};- const reset = () => {- posthog.reset();- identifiedKey.current = null;- };-const capture = (event: TelemetryEvent) => {if (!telemetryEnabled ||@@ -183,7 +171,7 @@ const TelemetryProvider = ({ children }: TelemetryProviderProps) => {};return (- <TelemetryContext.Provider value={{ capture, reset }}>+ <TelemetryContext.Provider value={{ capture }}>{children}</TelemetryContext.Provider>);@@ -203,12 +191,10 @@ function isInRecordingSample(distinctId: string): boolean {interface TelemetryContextType {capture: (event: TelemetryEvent) => void;- reset: () => void;}const TelemetryContext = React.createContext<TelemetryContextType>({capture: () => {},- reset: () => {},});export const useTelemetry = () => React.useContext(TelemetryContext);diff --git a/packages/web/src/features/authentication/components/auth-landing/auth-drawer-body.tsx b/packages/web/src/features/authentication/components/auth-landing/auth-drawer-body.tsxindex 5d8cc04b088..9ee13ab59d6 100644--- a/packages/web/src/features/authentication/components/auth-landing/auth-drawer-body.tsx+++ b/packages/web/src/features/authentication/components/auth-landing/auth-drawer-body.tsx@@ -47,6 +47,7 @@ import { HorizontalSeparatorWithText } from '@/components/ui/separator';import { authMutations } from '@/features/authentication/hooks/auth-hooks';import { captchaUtils } from '@/features/authentication/utils/captcha-utils';import { flagsHooks } from '@/hooks/flags-hooks';+import { acquisitionUtils } from '@/lib/acquisition-utils';import { HttpError, api } from '@/lib/api';import { authenticationSession } from '@/lib/authentication-session';import { formatUtils } from '@/lib/format-utils';@@ -393,6 +394,7 @@ function AuthStep({</>)}<EmailStep+ mode={effectiveMode}invitedEmail={invitedEmail}captchaToken={captchaToken}captchaRequired={captchaRequired}@@ -490,6 +492,7 @@ function WorkEmailHint() {}function EmailStep({+ mode,invitedEmail,captchaToken,captchaRequired,@@ -513,6 +516,7 @@ function EmailStep({const showWorkEmailHint =formatUtils.emailRegex.test(email.trim()) && isPersonalEmail(email);+ const { capture } = useTelemetry();const { mutate, isPending } = authMutations.useRequestEmailCode({onSuccess: () => {onCaptchaSpent();@@ -528,6 +532,16 @@ function EmailStep({const onSubmit: SubmitHandler<EmailSchema> = (data) => {form.clearErrors('root.serverError');+ // The same box serves sign-in; only a sign-up attempt belongs in the funnel.+ if (mode === 'signup') {+ capture({+ name: TelemetryEventName.SIGN_UP_SUBMITTED,+ payload: {+ method: 'email_code',+ ...acquisitionUtils.getAcquisitionParams(),+ },+ });+ }mutate({ email: data.email.trim(), captchaToken });};@@ -734,7 +748,10 @@ function NameStep({ onSessionRejected }: NameStepProps) {const onSubmit: SubmitHandler<FullNameSchema> = (data) => {form.clearErrors('root.serverError');- mutate({ fullName: data.fullName.trim() });+ mutate({+ fullName: data.fullName.trim(),+ attribution: acquisitionUtils.getAcquisitionParams(),+ });};return (@@ -854,7 +871,11 @@ function CodeStep({setErrorMessage(null);setCode(value);if (value.length === CODE_LENGTH) {- verify({ email, code: value });+ verify({+ email,+ code: value,+ attribution: acquisitionUtils.getAcquisitionParams(),+ });}};@@ -1082,6 +1103,7 @@ type CodeStepProps = {};type EmailStepProps = {+ mode: AuthMode;invitedEmail: string;captchaToken: string | undefined;captchaRequired: boolean;diff --git a/packages/web/src/features/authentication/components/sign-in-form.tsx b/packages/web/src/features/authentication/components/sign-in-form.tsxindex f4d85677620..5d0fa5aecec 100644--- a/packages/web/src/features/authentication/components/sign-in-form.tsx+++ b/packages/web/src/features/authentication/components/sign-in-form.tsx@@ -23,6 +23,7 @@ import { Form, FormField, FormItem, FormMessage } from '@/components/ui/form';import { Input } from '@/components/ui/input';import { Label } from '@/components/ui/label';import { flagsHooks } from '@/hooks/flags-hooks';+import { acquisitionUtils } from '@/lib/acquisition-utils';import { HttpError, api } from '@/lib/api';import { authenticationSession } from '@/lib/authentication-session';import { formatUtils } from '@/lib/format-utils';@@ -140,7 +141,9 @@ const SignInForm = ({ onForgotPassword }: SignInFormProps) => {name: TelemetryEventName.SIGN_IN_SUBMITTED,payload: { method: 'email' },});- mutate(data);+ // On Cloud a password sign-up is only provisioned on this first sign-in+ // (after the verification email), so the stashed attribution rides along.+ mutate({ ...data, attribution: acquisitionUtils.getAcquisitionParams() });};return (diff --git a/packages/web/src/features/authentication/components/sign-up-form.tsx b/packages/web/src/features/authentication/components/sign-up-form.tsxindex 1dca7747528..4a3150e390c 100644--- a/packages/web/src/features/authentication/components/sign-up-form.tsx+++ b/packages/web/src/features/authentication/components/sign-up-form.tsx@@ -197,13 +197,17 @@ const SignUpForm = ({});capture({name: TelemetryEventName.SIGN_UP_SUBMITTED,- payload: { method: 'email', ...acquisitionUtils.getAcquisitionParams() },+ payload: {+ method: 'password',+ ...acquisitionUtils.getAcquisitionParams(),+ },});mutate({...data,email: data.email.trim().toLowerCase(),trackEvents: true,captchaToken,+ attribution: acquisitionUtils.getAcquisitionParams(),});};diff --git a/packages/web/src/lib/acquisition-utils.ts b/packages/web/src/lib/acquisition-utils.tsindex 3be1fa5220f..6f6bacfaaa6 100644--- a/packages/web/src/lib/acquisition-utils.ts+++ b/packages/web/src/lib/acquisition-utils.ts@@ -1,68 +1,83 @@import { tryCatchSync } from '@activepieces/core-utils';--const ACQUISITION_PARAM_KEYS = [- 'utm_source',- 'utm_medium',- 'utm_campaign',- 'utm_term',- 'utm_content',- 'gclid',- 'fbclid',- 'ref',- 'ap_cta',-] as const;--const STORAGE_KEY = 'ap_acquisition_params';+import {+ ATTRIBUTION_PARAM_KEYS,+ ATTRIBUTION_STORAGE_KEY,+ ATTRIBUTION_STORAGE_TTL_MS,+ ATTRIBUTION_VALUE_MAX_LENGTH,+ AttributionParams,+ attributionUtils,+} from '@activepieces/shared';function stashAcquisitionParams(): void {- const fromUrl = readFromSearch(window.location.search);- if (Object.keys(fromUrl).length === 0) {+ const fromUrl = attributionUtils.readAttributionFromSearch({+ search: window.location.search,+ });+ if (attributionUtils.isEmptyAttribution({ attribution: fromUrl })) {return;}tryCatchSync(() => {- if (sessionStorage.getItem(STORAGE_KEY) !== null) {+ if (readStash() !== null) {return;}- sessionStorage.setItem(STORAGE_KEY, JSON.stringify(fromUrl));+ const entry: StoredAttribution = {+ params: fromUrl,+ capturedAt: Date.now(),+ };+ localStorage.setItem(ATTRIBUTION_STORAGE_KEY, JSON.stringify(entry));});}-function getAcquisitionParams(): AcquisitionParams {+function getAcquisitionParams(): AttributionParams {const stashed = readStash();- if (stashed && Object.keys(stashed).length > 0) {+ if (stashed !== null) {return stashed;}- return readFromSearch(window.location.search);+ return attributionUtils.readAttributionFromSearch({+ search: window.location.search,+ });}-function readFromSearch(search: string): AcquisitionParams {- const params = new URLSearchParams(search);- return ACQUISITION_PARAM_KEYS.reduce<AcquisitionParams>((acc, key) => {- const value = params.get(key);- return value ? { ...acc, [key]: value } : acc;- }, {});+function clearAcquisitionParams(): void {+ tryCatchSync(() => localStorage.removeItem(ATTRIBUTION_STORAGE_KEY));}-function readStash(): AcquisitionParams | null {+function readStash(): AttributionParams | null {const { data } = tryCatchSync(() => {- const raw = sessionStorage.getItem(STORAGE_KEY);+ const raw = localStorage.getItem(ATTRIBUTION_STORAGE_KEY);if (raw === null) {return null;}const parsed: unknown = JSON.parse(raw);- if (!isRecord(parsed)) {+ if (!isRecord(parsed) || typeof parsed.capturedAt !== 'number') {+ return null;+ }+ if (Date.now() - parsed.capturedAt > ATTRIBUTION_STORAGE_TTL_MS) {return null;}- return ACQUISITION_PARAM_KEYS.reduce<AcquisitionParams>((acc, key) => {- const value = parsed[key];- return typeof value === 'string' && value.length > 0- ? { ...acc, [key]: value }- : acc;- }, {});+ if (!isRecord(parsed.params)) {+ return null;+ }+ const params = pickAttribution(parsed.params);+ return attributionUtils.isEmptyAttribution({ attribution: params })+ ? null+ : params;});return data;}+function pickAttribution(source: Record<string, unknown>): AttributionParams {+ return ATTRIBUTION_PARAM_KEYS.reduce<AttributionParams>((acc, key) => {+ const value = source[key];+ if (typeof value !== 'string' || value.trim().length === 0) {+ return acc;+ }+ return {+ ...acc,+ [key]: value.trim().slice(0, ATTRIBUTION_VALUE_MAX_LENGTH),+ };+ }, {});+}+function isRecord(value: unknown): value is Record<string, unknown> {return typeof value === 'object' && value !== null;}@@ -70,8 +85,10 @@ function isRecord(value: unknown): value is Record<string, unknown> {export const acquisitionUtils = {stashAcquisitionParams,getAcquisitionParams,+ clearAcquisitionParams,};-export type AcquisitionParams = Partial<- Record<(typeof ACQUISITION_PARAM_KEYS)[number], string>->;+type StoredAttribution = {+ params: AttributionParams;+ capturedAt: number;+};diff --git a/packages/web/src/lib/authentication-session.ts b/packages/web/src/lib/authentication-session.tsindex daaf706e2d6..5faa9d89ef1 100644--- a/packages/web/src/lib/authentication-session.ts+++ b/packages/web/src/lib/authentication-session.ts@@ -11,6 +11,8 @@ import { authenticationApi } from '@/api/authentication-api';import { queryClient } from '@/app/query-client';import { ApStorage } from './ap-browser-storage';+import { telemetryUtils } from './telemetry-utils';+const tokenKey = 'token';const projectIdKey = 'projectId';export const authenticationSession = {@@ -128,7 +130,11 @@ export const authenticationSession = {ApStorage.getInstance().removeItem(tokenKey);},logOut() {+ const hadSession = !isNil(this.getToken());this.clearSession();+ if (hadSession) {+ telemetryUtils.resetIdentity();+ }window.location.href = '/sign-in';},};diff --git a/packages/web/src/lib/telemetry-utils.ts b/packages/web/src/lib/telemetry-utils.tsnew file mode 100644index 00000000000..e8c6b5ce4d4--- /dev/null+++ b/packages/web/src/lib/telemetry-utils.ts@@ -0,0 +1,24 @@+import { tryCatchSync } from '@activepieces/core-utils';+import posthog from 'posthog-js';++import { acquisitionUtils } from './acquisition-utils';++function resetIdentity(): void {+ if (posthog.__loaded) {+ posthog.reset();+ }+ acquisitionUtils.clearAcquisitionParams();+}++function getSessionId(): string | null {+ if (!posthog.__loaded) {+ return null;+ }+ const { data } = tryCatchSync(() => posthog.get_session_id());+ return data !== null && data.length > 0 ? data : null;+}++export const telemetryUtils = {+ resetIdentity,+ getSessionId,+};diff --git a/packages/web/src/main.tsx b/packages/web/src/main.tsxindex 77aeafccfbb..dadb1c95358 100644--- a/packages/web/src/main.tsx+++ b/packages/web/src/main.tsx@@ -4,9 +4,12 @@ import * as ReactDOM from 'react-dom/client';import './i18n';import App from './app/app';+import { acquisitionUtils } from './lib/acquisition-utils';import { errorReporting } from './lib/error-reporting';import { reloadOnceForStaleChunk } from './lib/lazy-with-retry';+acquisitionUtils.stashAcquisitionParams();+window.addEventListener('vite:preloadError', (event) => {if (reloadOnceForStaleChunk('vite-preload')) {event.preventDefault();diff --git a/packages/web/test/lib/acquisition-utils.test.ts b/packages/web/test/lib/acquisition-utils.test.tsindex ec358b323bd..0ecf890dce8 100644--- a/packages/web/test/lib/acquisition-utils.test.ts+++ b/packages/web/test/lib/acquisition-utils.test.ts@@ -1,10 +1,12 @@+import {+ ATTRIBUTION_STORAGE_KEY,+ ATTRIBUTION_STORAGE_TTL_MS,+} from '@activepieces/shared';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { acquisitionUtils } from '@/lib/acquisition-utils';-const STORAGE_KEY = 'ap_acquisition_params';--function makeSessionStorage(): Storage {+function makeStorage(): Storage {const store = new Map<string, string>();return {getItem: (key: string) => store.get(key) ?? null,@@ -26,45 +28,96 @@ function stubLocation(search: string): void {vi.stubGlobal('window', { location: { search } });}+function readStoredParams(storage: Storage): unknown {+ const raw = storage.getItem(ATTRIBUTION_STORAGE_KEY);+ if (raw === null) {+ return null;+ }+ const parsed: unknown = JSON.parse(raw);+ if (typeof parsed !== 'object' || parsed === null || !('params' in parsed)) {+ return parsed;+ }+ return parsed.params;+}++function writeStash({+ storage,+ params,+ capturedAt,+}: {+ storage: Storage;+ params: unknown;+ capturedAt: number;+}): void {+ storage.setItem(+ ATTRIBUTION_STORAGE_KEY,+ JSON.stringify({ params, capturedAt }),+ );+}+describe('acquisitionUtils', () => {- let sessionStorage: Storage;+ let localStorage: Storage;beforeEach(() => {- sessionStorage = makeSessionStorage();- vi.stubGlobal('sessionStorage', sessionStorage);+ localStorage = makeStorage();+ vi.stubGlobal('localStorage', localStorage);});afterEach(() => {vi.unstubAllGlobals();+ vi.useRealTimers();});- it('stashes known params from the landing URL', () => {+ it('stashes every known attribution param from the landing URL', () => {stubLocation(- '?utm_source=google&utm_medium=cpc&gclid=g123&ap_cta=hero&irrelevant=x',+ '?utm_source=google&utm_medium=cpc&gclid=g123&ap_cta=hero&ap_landing=/pricing&ap_referrer=news&ap_sid=s1&irrelevant=x',);acquisitionUtils.stashAcquisitionParams();- expect(JSON.parse(sessionStorage.getItem(STORAGE_KEY)!)).toEqual({+ expect(readStoredParams(localStorage)).toEqual({utm_source: 'google',utm_medium: 'cpc',gclid: 'g123',ap_cta: 'hero',+ ap_landing: '/pricing',+ ap_referrer: 'news',+ ap_sid: 's1',+ });+ });++ it('records when the stash was captured', () => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2026-01-01T00:00:00Z'));+ stubLocation('?utm_source=google');+ acquisitionUtils.stashAcquisitionParams();+ expect(JSON.parse(localStorage.getItem(ATTRIBUTION_STORAGE_KEY)!)).toEqual({+ params: { utm_source: 'google' },+ capturedAt: Date.now(),});});it('does not stash when the URL has no acquisition params', () => {stubLocation('?foo=bar');acquisitionUtils.stashAcquisitionParams();- expect(sessionStorage.getItem(STORAGE_KEY)).toBeNull();+ expect(localStorage.getItem(ATTRIBUTION_STORAGE_KEY)).toBeNull();});- it('first touch wins: a later stash never overwrites', () => {+ it('first touch wins while the stash is unexpired', () => {stubLocation('?utm_source=google');acquisitionUtils.stashAcquisitionParams();stubLocation('?utm_source=facebook&fbclid=f1');acquisitionUtils.stashAcquisitionParams();- expect(JSON.parse(sessionStorage.getItem(STORAGE_KEY)!)).toEqual({- utm_source: 'google',+ expect(readStoredParams(localStorage)).toEqual({ utm_source: 'google' });+ });++ it('lets a new touch replace an expired stash', () => {+ writeStash({+ storage: localStorage,+ params: { utm_source: 'google' },+ capturedAt: Date.now() - ATTRIBUTION_STORAGE_TTL_MS - 1,});+ stubLocation('?utm_source=facebook');+ acquisitionUtils.stashAcquisitionParams();+ expect(readStoredParams(localStorage)).toEqual({ utm_source: 'facebook' });});it('getAcquisitionParams prefers the stash over the current URL', () => {@@ -77,6 +130,18 @@ describe('acquisitionUtils', () => {});});+ it('treats an expired stash as absent', () => {+ writeStash({+ storage: localStorage,+ params: { utm_source: 'google' },+ capturedAt: Date.now() - ATTRIBUTION_STORAGE_TTL_MS - 1,+ });+ stubLocation('?utm_source=bing');+ expect(acquisitionUtils.getAcquisitionParams()).toEqual({+ utm_source: 'bing',+ });+ });+it('falls back to the current URL when there is no stash', () => {stubLocation('?utm_campaign=spring&utm_term=flows');expect(acquisitionUtils.getAcquisitionParams()).toEqual({@@ -86,7 +151,18 @@ describe('acquisitionUtils', () => {});it('ignores a corrupt stash and falls back to the URL', () => {- sessionStorage.setItem(STORAGE_KEY, 'not-json{');+ localStorage.setItem(ATTRIBUTION_STORAGE_KEY, 'not-json{');+ stubLocation('?utm_source=bing');+ expect(acquisitionUtils.getAcquisitionParams()).toEqual({+ utm_source: 'bing',+ });+ });++ it('ignores a legacy stash without a capture time', () => {+ localStorage.setItem(+ ATTRIBUTION_STORAGE_KEY,+ JSON.stringify({ utm_source: 'legacy' }),+ );stubLocation('?utm_source=bing');expect(acquisitionUtils.getAcquisitionParams()).toEqual({utm_source: 'bing',@@ -94,32 +170,46 @@ describe('acquisitionUtils', () => {});it('filters unknown keys and non-string values out of the stash', () => {- sessionStorage.setItem(- STORAGE_KEY,- JSON.stringify({+ writeStash({+ storage: localStorage,+ params: {utm_source: 'x',evil: 'y',utm_medium: 42,fbclid: '',- }),- );+ },+ capturedAt: Date.now(),+ });stubLocation('');expect(acquisitionUtils.getAcquisitionParams()).toEqual({utm_source: 'x',});});- it('survives sessionStorage throwing (storage disabled)', () => {- vi.stubGlobal('sessionStorage', {+ it('clearAcquisitionParams removes the stash', () => {+ stubLocation('?utm_source=google');+ acquisitionUtils.stashAcquisitionParams();+ acquisitionUtils.clearAcquisitionParams();+ expect(localStorage.getItem(ATTRIBUTION_STORAGE_KEY)).toBeNull();+ stubLocation('');+ expect(acquisitionUtils.getAcquisitionParams()).toEqual({});+ });++ it('survives localStorage throwing (storage disabled)', () => {+ vi.stubGlobal('localStorage', {getItem: () => {throw new Error('denied');},setItem: () => {throw new Error('denied');},+ removeItem: () => {+ throw new Error('denied');+ },});stubLocation('?utm_source=google');expect(() => acquisitionUtils.stashAcquisitionParams()).not.toThrow();+ expect(() => acquisitionUtils.clearAcquisitionParams()).not.toThrow();expect(acquisitionUtils.getAcquisitionParams()).toEqual({utm_source: 'google',});