|
| 1 | +import { createHash } from 'node:crypto' |
| 2 | + |
| 3 | +import { IS_PROD } from '@codebuff/common/env' |
| 4 | +import { extractClientIp } from '@codebuff/common/util/rate-limit' |
| 5 | +import type { Logger } from '@codebuff/common/types/contracts/logger' |
| 6 | +import type { |
| 7 | + RedditFirstPromptCapiEventName, |
| 8 | + RedditRetentionCapiEventName, |
| 9 | +} from '@codebuff/common/util/reddit-capi-events' |
| 10 | + |
| 11 | +export type { RedditFirstPromptCapiEventName, RedditRetentionCapiEventName } |
| 12 | + |
| 13 | +/** Reddit Ads pixel ID (public, also used for CAPI endpoint). */ |
| 14 | +export const REDDIT_PIXEL_ID = 'a2_j6o59svbxzzn' |
| 15 | + |
| 16 | +const REDDIT_CAPI_ENDPOINT = `https://ads-api.reddit.com/api/v3/pixels/${REDDIT_PIXEL_ID}/conversion_events` |
| 17 | + |
| 18 | +export type RedditActionSource = 'WEBSITE' | 'APP' | 'PHYSICAL_STORE' | 'OTHER' |
| 19 | + |
| 20 | +export type RedditCapiUser = { |
| 21 | + email?: string | null |
| 22 | + externalId?: string | null |
| 23 | + ipAddress?: string | null |
| 24 | + userAgent?: string | null |
| 25 | + clickId?: string | null |
| 26 | + uuid?: string | null |
| 27 | +} |
| 28 | + |
| 29 | +export type RedditCapiCustomEvent = |
| 30 | + | RedditFirstPromptCapiEventName |
| 31 | + | RedditRetentionCapiEventName |
| 32 | + |
| 33 | +function sha256(value: string): string { |
| 34 | + return createHash('sha256').update(value).digest('hex') |
| 35 | +} |
| 36 | + |
| 37 | +function normalizeEmail(email: string): string { |
| 38 | + return email.trim().toLowerCase() |
| 39 | +} |
| 40 | + |
| 41 | +function buildUserPayload(user: RedditCapiUser) { |
| 42 | + const payload: Record<string, string> = {} |
| 43 | + |
| 44 | + if (user.email) { |
| 45 | + payload.email = sha256(normalizeEmail(user.email)) |
| 46 | + } |
| 47 | + if (user.externalId) { |
| 48 | + payload.external_id = sha256(user.externalId.trim()) |
| 49 | + } |
| 50 | + if (user.ipAddress) { |
| 51 | + payload.ip_address = user.ipAddress |
| 52 | + } |
| 53 | + if (user.userAgent) { |
| 54 | + payload.user_agent = user.userAgent |
| 55 | + } |
| 56 | + if (user.clickId) { |
| 57 | + payload.click_id = user.clickId |
| 58 | + } |
| 59 | + if (user.uuid) { |
| 60 | + payload.uuid = user.uuid |
| 61 | + } |
| 62 | + |
| 63 | + return Object.keys(payload).length > 0 ? payload : undefined |
| 64 | +} |
| 65 | + |
| 66 | +export type SendRedditCustomConversionParams = { |
| 67 | + /** Conversion access token from Reddit Events Manager (env-provided; no-op when unset). */ |
| 68 | + accessToken: string | undefined |
| 69 | + customEventName: RedditCapiCustomEvent |
| 70 | + conversionId: string |
| 71 | + actionSource: RedditActionSource |
| 72 | + eventSourceUrl?: string |
| 73 | + user: RedditCapiUser |
| 74 | + fetchImpl?: typeof fetch |
| 75 | + logger?: Logger |
| 76 | +} |
| 77 | + |
| 78 | +/** Fire-and-forget Reddit Conversions API custom event. Never throws. */ |
| 79 | +export async function sendRedditCustomConversion( |
| 80 | + params: SendRedditCustomConversionParams, |
| 81 | +): Promise<void> { |
| 82 | + if (!IS_PROD || !params.accessToken) { |
| 83 | + return |
| 84 | + } |
| 85 | + |
| 86 | + const fetchImpl = params.fetchImpl ?? fetch |
| 87 | + const eventAt = Date.now() |
| 88 | + const user = buildUserPayload(params.user) |
| 89 | + |
| 90 | + const body = { |
| 91 | + data: { |
| 92 | + events: [ |
| 93 | + { |
| 94 | + event_at: eventAt, |
| 95 | + action_source: params.actionSource, |
| 96 | + ...(params.eventSourceUrl |
| 97 | + ? { event_source_url: params.eventSourceUrl } |
| 98 | + : {}), |
| 99 | + type: { |
| 100 | + tracking_type: 'CUSTOM', |
| 101 | + custom_event_name: params.customEventName, |
| 102 | + }, |
| 103 | + ...(params.user.clickId ? { click_id: params.user.clickId } : {}), |
| 104 | + metadata: { |
| 105 | + conversion_id: params.conversionId, |
| 106 | + }, |
| 107 | + ...(user ? { user } : {}), |
| 108 | + }, |
| 109 | + ], |
| 110 | + partner: 'FREEBUFF', |
| 111 | + partner_version: '1.0.0', |
| 112 | + }, |
| 113 | + } |
| 114 | + |
| 115 | + try { |
| 116 | + const response = await fetchImpl(REDDIT_CAPI_ENDPOINT, { |
| 117 | + method: 'POST', |
| 118 | + headers: { |
| 119 | + Authorization: `Bearer ${params.accessToken}`, |
| 120 | + 'Content-Type': 'application/json', |
| 121 | + 'User-Agent': 'freebuff/1.0 (reddit-capi)', |
| 122 | + }, |
| 123 | + body: JSON.stringify(body), |
| 124 | + signal: AbortSignal.timeout(3_000), |
| 125 | + }) |
| 126 | + if (!response.ok) { |
| 127 | + params.logger?.warn( |
| 128 | + { |
| 129 | + status: response.status, |
| 130 | + responseBody: (await response.text().catch(() => '')).slice(0, 500), |
| 131 | + customEventName: params.customEventName, |
| 132 | + conversionId: params.conversionId, |
| 133 | + }, |
| 134 | + 'Reddit CAPI rejected conversion event', |
| 135 | + ) |
| 136 | + } |
| 137 | + } catch (error) { |
| 138 | + // Best-effort ad attribution; never block product flows. |
| 139 | + params.logger?.warn( |
| 140 | + { |
| 141 | + error, |
| 142 | + customEventName: params.customEventName, |
| 143 | + conversionId: params.conversionId, |
| 144 | + }, |
| 145 | + 'Reddit CAPI conversion request failed', |
| 146 | + ) |
| 147 | + } |
| 148 | +} |
| 149 | + |
| 150 | +export function redditConversionId( |
| 151 | + event: RedditCapiCustomEvent, |
| 152 | + userId: string, |
| 153 | + suffix?: string, |
| 154 | +): string { |
| 155 | + return [event.toLowerCase(), userId, suffix ?? String(Date.now())].join('_') |
| 156 | +} |
| 157 | + |
| 158 | +/** |
| 159 | + * Identity fields shared by every server-side Reddit conversion call, built |
| 160 | + * from the incoming request's headers. Surface-specific attribution (click id, |
| 161 | + * uuid) is layered on by callers that have it. |
| 162 | + */ |
| 163 | +export function redditUserFromRequestHeaders(params: { |
| 164 | + userId: string |
| 165 | + email?: string | null |
| 166 | + headers: { get(name: string): string | null } |
| 167 | +}): RedditCapiUser { |
| 168 | + const ip = extractClientIp(params.headers) |
| 169 | + return { |
| 170 | + email: params.email, |
| 171 | + externalId: params.userId, |
| 172 | + ipAddress: ip === 'unknown' ? undefined : ip, |
| 173 | + userAgent: params.headers.get('user-agent')?.trim() || undefined, |
| 174 | + } |
| 175 | +} |
0 commit comments