Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

feat(web): report marketplace utm_source on OAuth registration (#42193)

Coding On Starb769a3469b11
diff --git a/web/app/account/oauth/authorize/__tests__/page.spec.tsx b/web/app/account/oauth/authorize/__tests__/page.spec.tsx
index 31bba9a90e8..db5d2465f0d 100644
--- a/web/app/account/oauth/authorize/__tests__/page.spec.tsx
+++ b/web/app/account/oauth/authorize/__tests__/page.spec.tsx
@@ -165,6 +165,26 @@ describe('OAuthAuthorize', () => {
expect(screen.queryByRole('button', { name: /continue/i })).not.toBeInTheDocument()
})
+ it('still returns to marketplace after a new-user registration with utm_source', async () => {
+ mocks.searchParams = new URLSearchParams({
+ client_id: 'marketplace-client',
+ redirect_uri: 'https://api.marketplace.example.com/api/v1/auth/callback/dify',
+ response_type: 'code',
+ state: 'marketplace-state',
+ oauth_new_user: 'true',
+ utm_source: 'dify_marketplace',
+ })
+ mockProviderResponses({ autoAuthorize: true })
+
+ renderPage()
+
+ await waitFor(() =>
+ expect(globalThis.location.href).toBe(
+ 'https://api.marketplace.example.com/api/v1/auth/callback/dify?code=oauth-code&state=marketplace-state',
+ ),
+ )
+ })
+
it('keeps the consent flow when the app is not flagged with auto_authorize', async () => {
renderPage()
@@ -195,6 +215,28 @@ describe('OAuthAuthorize', () => {
expect(findRequest('/oauth/provider/authorize')).toBeUndefined()
})
+ it('keeps marketplace utm_source on the signin return URL', async () => {
+ mocks.profileLoggedIn = false
+ mocks.searchParams = new URLSearchParams({
+ client_id: 'marketplace-client',
+ redirect_uri: 'https://api.marketplace.example.com/api/v1/auth/callback/dify',
+ response_type: 'code',
+ state: 'marketplace-state',
+ utm_source: 'dify_marketplace',
+ })
+ mockProviderResponses({ autoAuthorize: true })
+
+ renderPage()
+
+ await waitFor(() =>
+ expect(mocks.replace).toHaveBeenCalledWith(
+ `/signin?redirect_url=${encodeURIComponent(
+ 'https://dify.test/account/oauth/authorize?client_id=marketplace-client&redirect_uri=https%3A%2F%2Fapi.marketplace.example.com%2Fapi%2Fv1%2Fauth%2Fcallback%2Fdify&response_type=code&state=marketplace-state&utm_source=dify_marketplace',
+ )}`,
+ ),
+ )
+ })
+
it('does not auto-authorize with incomplete OAuth parameters', async () => {
mocks.searchParams = new URLSearchParams({
client_id: 'marketplace-client',
diff --git a/web/app/account/oauth/authorize/layout.tsx b/web/app/account/oauth/authorize/layout.tsx
index be29514a35f..a2817995324 100644
--- a/web/app/account/oauth/authorize/layout.tsx
+++ b/web/app/account/oauth/authorize/layout.tsx
@@ -1,6 +1,7 @@
'use client'
import type { ReactNode } from 'react'
import { useSuspenseQuery } from '@tanstack/react-query'
+import { OAuthRegistrationAnalytics } from '@/app/components/oauth-registration-analytics'
import Header from '@/app/signin/_header'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
@@ -15,6 +16,7 @@ export default function OAuthAuthorizeLayout({ children }: Props) {
return (
<div className="flex min-h-screen w-full justify-center bg-background-default-burn p-6">
+ <OAuthRegistrationAnalytics />
<div className="flex w-full shrink-0 flex-col items-center rounded-2xl border border-effects-highlight bg-background-default-subtle">
<Header />
<div className="flex w-full grow flex-col items-center justify-center px-6 md:px-27">
diff --git a/web/app/account/oauth/authorize/use-silent-authorize.ts b/web/app/account/oauth/authorize/use-silent-authorize.ts
index 6db8355072b..c967cd7cfa4 100644
--- a/web/app/account/oauth/authorize/use-silent-authorize.ts
+++ b/web/app/account/oauth/authorize/use-silent-authorize.ts
@@ -1,6 +1,10 @@
import { toast } from '@langgenius/dify-ui/toast'
+import Cookies from 'js-cookie'
import { useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
+import { flushRegistrationSuccess } from '@/app/components/base/amplitude/registration-tracking'
+import { flushEvents } from '@/app/components/base/amplitude/utils'
+import { reportOAuthRegistrationIfNewUser } from '@/app/components/oauth-registration-attribution'
import { useRouter } from '@/next/navigation'
export function buildReturnUrl(pathname: string, search: string) {
@@ -65,8 +69,14 @@ export function useSilentAuthorize({
}
startedRef.current = true
+ const authorizeSearchParams = new URLSearchParams(searchParams.toString())
+ const persistedNewUser = reportOAuthRegistrationIfNewUser(authorizeSearchParams)
+ if (persistedNewUser) Cookies.remove('utm_info')
+
void authorize({ body: { client_id: clientId } })
- .then(({ code }) => {
+ .then(async ({ code }) => {
+ await flushRegistrationSuccess()
+ await flushEvents()
globalThis.location.href = buildOAuthCallbackUrl(redirectUri, code, state)
})
.catch((error: unknown) => {
diff --git a/web/app/components/__tests__/oauth-registration-analytics.spec.tsx b/web/app/components/__tests__/oauth-registration-analytics.spec.tsx
index 53d18f0d2b9..4826dc91acc 100644
--- a/web/app/components/__tests__/oauth-registration-analytics.spec.tsx
+++ b/web/app/components/__tests__/oauth-registration-analytics.spec.tsx
@@ -145,6 +145,38 @@ describe('OAuthRegistrationAnalytics', () => {
expect(window.location.search).toBe('?source=signin')
})
+ it('reads marketplace utm_source from the landing URL when the utm cookie is missing', async () => {
+ setSearchParams('oauth_new_user=true&utm_source=dify_marketplace&client_id=marketplace')
+
+ render(<OAuthRegistrationAnalytics />)
+
+ await waitFor(() => {
+ expect(mockRememberRegistrationSuccess).toHaveBeenCalledWith({
+ method: 'oauth',
+ utmInfo: { utm_source: 'dify_marketplace' },
+ })
+ })
+ expect(mockSendGAEvent).toHaveBeenCalledWith('user_registration_success_with_utm', {
+ method: 'oauth',
+ utm_source: 'dify_marketplace',
+ })
+ expect(window.location.search).toBe('?utm_source=dify_marketplace&client_id=marketplace')
+ })
+
+ it('lets the current URL overwrite a stale utm cookie so marketplace last-touch wins', async () => {
+ Cookies.set('utm_info', JSON.stringify({ utm_source: 'linkedin', slug: 'old-campaign' }))
+ setSearchParams('oauth_new_user=true&utm_source=dify_marketplace')
+
+ render(<OAuthRegistrationAnalytics />)
+
+ await waitFor(() => {
+ expect(mockRememberRegistrationSuccess).toHaveBeenCalledWith({
+ method: 'oauth',
+ utmInfo: { utm_source: 'dify_marketplace', slug: 'old-campaign' },
+ })
+ })
+ })
+
it('uses the base event and cleans up when the UTM cookie is malformed', async () => {
Cookies.set('utm_info', '{invalid-json')
setSearchParams('oauth_new_user=true')
diff --git a/web/app/components/oauth-registration-analytics.tsx b/web/app/components/oauth-registration-analytics.tsx
index e82adaf2923..82fc717e281 100644
--- a/web/app/components/oauth-registration-analytics.tsx
+++ b/web/app/components/oauth-registration-analytics.tsx
@@ -10,15 +10,11 @@ import {
hasSentOAuthRegistrationGA,
markOAuthRegistrationGASent,
} from './base/amplitude/registration-session-state'
+import { rememberRegistrationSuccess } from './base/amplitude/registration-tracking'
import {
- normalizeRegistrationAttribution,
- rememberRegistrationSuccess,
-} from './base/amplitude/registration-tracking'
-
-const OAUTH_NEW_USER_PARAM = 'oauth_new_user'
-
-const isRecord = (value: unknown): value is Record<string, unknown> =>
- Boolean(value) && typeof value === 'object' && !Array.isArray(value)
+ OAUTH_NEW_USER_PARAM,
+ readOAuthRegistrationAttribution,
+} from './oauth-registration-attribution'
const removeOAuthNewUserParam = () => {
const url = new URL(window.location.href)
@@ -33,7 +29,7 @@ export function OAuthRegistrationAnalytics() {
const gaHandledRef = useRef(false)
const amplitudeHandledRef = useRef(false)
const cleanedRef = useRef(false)
- const utmInfoRef = useRef<ReturnType<typeof normalizeRegistrationAttribution> | undefined>(
+ const utmInfoRef = useRef<ReturnType<typeof readOAuthRegistrationAttribution> | undefined>(
undefined,
)
@@ -54,17 +50,10 @@ export function OAuthRegistrationAnalytics() {
}
if (utmInfoRef.current === undefined) {
- let parsedUtmInfo: Record<string, unknown> | null = null
- const utmInfoStr = Cookies.get('utm_info')
- if (utmInfoStr) {
- try {
- const parsed: unknown = JSON.parse(utmInfoStr)
- if (isRecord(parsed)) parsedUtmInfo = parsed
- } catch (e) {
- console.error('Failed to parse utm_info cookie:', e)
- }
- }
- utmInfoRef.current = normalizeRegistrationAttribution(parsedUtmInfo)
+ utmInfoRef.current = readOAuthRegistrationAttribution({
+ cookieValue: Cookies.get('utm_info'),
+ searchParams,
+ })
}
const utmInfo = utmInfoRef.current
@@ -95,7 +84,7 @@ export function OAuthRegistrationAnalytics() {
Cookies.remove('utm_info')
removeOAuthNewUserParam()
}
- }, [analyticsConsent, oauthNewUserParam])
+ }, [analyticsConsent, oauthNewUserParam, searchParams])
return null
}
diff --git a/web/app/components/oauth-registration-attribution.ts b/web/app/components/oauth-registration-attribution.ts
new file mode 100644
index 00000000000..483363bfb1f
--- /dev/null
+++ b/web/app/components/oauth-registration-attribution.ts
@@ -0,0 +1,73 @@
+import Cookies from 'js-cookie'
+import { sendGAEvent } from '@/utils/gtag'
+import {
+ ATTRIBUTION_KEYS,
+ hasSentOAuthRegistrationGA,
+ markOAuthRegistrationGASent,
+} from './base/amplitude/registration-session-state'
+import {
+ normalizeRegistrationAttribution,
+ rememberRegistrationSuccess,
+} from './base/amplitude/registration-tracking'
+
+export const OAUTH_NEW_USER_PARAM = 'oauth_new_user'
+
+type SearchParamReader = {
+ get: (name: string) => string | null
+}
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ Boolean(value) && typeof value === 'object' && !Array.isArray(value)
+
+const readSearchParamAttribution = (searchParams: SearchParamReader) => {
+ const attribution: Record<string, string> = {}
+ ATTRIBUTION_KEYS.forEach((key) => {
+ const value = searchParams.get(key)?.trim()
+ if (value) attribution[key] = value
+ })
+ return attribution
+}
+
+const parseCookieUtmInfo = (raw: string | undefined) => {
+ if (!raw) return {} as Record<string, unknown>
+
+ try {
+ const parsed: unknown = JSON.parse(raw)
+ return isRecord(parsed) ? parsed : {}
+ } catch (e) {
+ console.error('Failed to parse utm_info cookie:', e)
+ return {} as Record<string, unknown>
+ }
+}
+
+export const readOAuthRegistrationAttribution = ({
+ cookieValue,
+ searchParams,
+}: {
+ cookieValue?: string
+ searchParams: SearchParamReader
+}) => {
+ const merged = {
+ ...parseCookieUtmInfo(cookieValue),
+ ...readSearchParamAttribution(searchParams),
+ }
+ return normalizeRegistrationAttribution(Object.keys(merged).length ? merged : null)
+}
+
+export const reportOAuthRegistrationIfNewUser = (searchParams: SearchParamReader) => {
+ if (searchParams.get(OAUTH_NEW_USER_PARAM) !== 'true') return false
+
+ const utmInfo = readOAuthRegistrationAttribution({
+ cookieValue: Cookies.get('utm_info'),
+ searchParams,
+ })
+ const eventName = utmInfo ? 'user_registration_success_with_utm' : 'user_registration_success'
+ if (!hasSentOAuthRegistrationGA()) {
+ sendGAEvent(eventName, {
+ method: 'oauth',
+ ...utmInfo,
+ })
+ markOAuthRegistrationGASent()
+ }
+ return rememberRegistrationSuccess({ method: 'oauth', utmInfo })
+}
diff --git a/web/app/signin/utils/__tests__/post-login-redirect.spec.ts b/web/app/signin/utils/__tests__/post-login-redirect.spec.ts
index e4671dc5c83..7215955edba 100644
--- a/web/app/signin/utils/__tests__/post-login-redirect.spec.ts
+++ b/web/app/signin/utils/__tests__/post-login-redirect.spec.ts
@@ -132,4 +132,15 @@ describe('post-login redirect utilities', () => {
href: '/account/oauth/authorize?client_id=marketplace-client&redirect_uri=https%3A%2F%2Fapi.marketplace.dify.ai%2Fapi%2Fv1%2Fauth%2Fcallback%2Fdify&state=oauth-state&response_type=code',
})
})
+
+ it('should preserve marketplace utm_source on the OAuth authorize return path', () => {
+ setPostLoginRedirect(
+ '/account/oauth/authorize?client_id=marketplace-client&redirect_uri=https%3A%2F%2Fapi.marketplace.dify.ai%2Fapi%2Fv1%2Fauth%2Fcallback%2Fdify&state=oauth-state&response_type=code&utm_source=dify_marketplace',
+ )
+
+ expect(resolvePostLoginRedirect()).toEqual({
+ kind: 'internal',
+ href: '/account/oauth/authorize?client_id=marketplace-client&redirect_uri=https%3A%2F%2Fapi.marketplace.dify.ai%2Fapi%2Fv1%2Fauth%2Fcallback%2Fdify&state=oauth-state&response_type=code&utm_source=dify_marketplace',
+ })
+ })
})
diff --git a/web/app/signin/utils/post-login-redirect.ts b/web/app/signin/utils/post-login-redirect.ts
index fc4ecaaca43..53d0e63b71d 100644
--- a/web/app/signin/utils/post-login-redirect.ts
+++ b/web/app/signin/utils/post-login-redirect.ts
@@ -13,6 +13,12 @@ const ALLOWED: Record<string, ReadonlySet<string>> = {
'response_type',
'scope',
'state',
+ 'utm_source',
+ 'utm_medium',
+ 'utm_campaign',
+ 'utm_content',
+ 'utm_term',
+ 'slug',
]),
}