-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy path_post.ts
More file actions
249 lines (221 loc) · 7.04 KB
/
Copy path_post.ts
File metadata and controls
249 lines (221 loc) · 7.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
import { AnalyticsEvent } from '@codebuff/common/constants/analytics-events'
import db from '@codebuff/internal/db'
import * as schema from '@codebuff/internal/db/schema'
import { eq } from 'drizzle-orm'
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { requireUserFromApiKey } from '../../_helpers'
import type { TrackEventFn } from '@codebuff/common/types/contracts/analytics'
import type { GetUserInfoFromApiKeyFn } from '@codebuff/common/types/contracts/database'
import type {
Logger,
LoggerWithContextFn,
} from '@codebuff/common/types/contracts/logger'
import type { NextRequest } from 'next/server'
// Rate limiting: max impressions per user per hour
const MAX_IMPRESSIONS_PER_HOUR = 60
// In-memory rate limiter (resets on server restart, which is acceptable for this use case)
const impressionRateLimiter = new Map<
string,
{ count: number; resetAt: number }
>()
/**
* Clean up expired entries from the rate limiter to prevent memory leaks.
* Called periodically during rate limit checks.
*/
function cleanupExpiredEntries(): void {
const now = Date.now()
for (const [userId, limit] of impressionRateLimiter) {
if (now >= limit.resetAt) {
impressionRateLimiter.delete(userId)
}
}
}
// Track last cleanup time to avoid cleaning up on every request
let lastCleanupTime = 0
const CLEANUP_INTERVAL_MS = 5 * 60 * 1000 // Clean up every 5 minutes
/**
* Check and update rate limit for a user.
* Returns true if the request is allowed, false if rate limited.
*/
function checkRateLimit(userId: string): boolean {
const now = Date.now()
const hourMs = 60 * 60 * 1000
// Periodically clean up expired entries to prevent memory leak
if (now - lastCleanupTime > CLEANUP_INTERVAL_MS) {
cleanupExpiredEntries()
lastCleanupTime = now
}
const userLimit = impressionRateLimiter.get(userId)
if (!userLimit || now >= userLimit.resetAt) {
// Reset or initialize the counter
impressionRateLimiter.set(userId, { count: 1, resetAt: now + hourMs })
return true
}
if (userLimit.count >= MAX_IMPRESSIONS_PER_HOUR) {
return false
}
userLimit.count++
return true
}
const bodySchema = z.object({
impUrl: z.url(),
mode: z.string().optional(),
})
export async function postAdImpression(params: {
req: NextRequest
getUserInfoFromApiKey: GetUserInfoFromApiKeyFn
logger: Logger
loggerWithContext: LoggerWithContextFn
trackEvent: TrackEventFn
fetch: typeof globalThis.fetch
}) {
const { req, getUserInfoFromApiKey, loggerWithContext, trackEvent, fetch } =
params
const baseLogger = params.logger
// Parse and validate request body
let impUrl: string
try {
const json = await req.json()
const parsed = bodySchema.safeParse(json)
if (!parsed.success) {
return NextResponse.json(
{ error: 'Invalid request body', details: parsed.error.format() },
{ status: 400 },
)
}
impUrl = parsed.data.impUrl
} catch {
return NextResponse.json(
{ error: 'Invalid JSON in request body' },
{ status: 400 },
)
}
const authed = await requireUserFromApiKey({
req,
getUserInfoFromApiKey,
logger: baseLogger,
loggerWithContext,
trackEvent,
authErrorEvent: AnalyticsEvent.USAGE_API_AUTH_ERROR,
})
if (!authed.ok) return authed.response
const { userId, logger } = authed.data
// Look up the ad from our database using the impUrl
// This ensures we use server-side trusted data, not client-provided data
const adRecord = await db.query.adImpression.findFirst({
where: eq(schema.adImpression.imp_url, impUrl),
})
if (!adRecord) {
logger.warn(
{ userId, impUrl },
'[ads] Ad impression not found in database - was it served through our API?',
)
return NextResponse.json(
{ success: false, error: 'Ad not found', creditsGranted: 0 },
{ status: 404 },
)
}
// Verify the ad belongs to this user
if (adRecord.user_id !== userId) {
logger.warn(
{ userId, adUserId: adRecord.user_id, impUrl },
'[ads] User attempting to claim impression for ad served to different user',
)
return NextResponse.json(
{ success: false, error: 'Ad not found', creditsGranted: 0 },
{ status: 404 },
)
}
// Check if impression was already fired (before rate limiting to not penalize duplicates)
if (adRecord.impression_fired_at) {
logger.debug(
{ userId, impUrl },
'[ads] Impression already recorded for this ad',
)
return NextResponse.json({
success: true,
creditsGranted: adRecord.credits_granted,
alreadyRecorded: true,
})
}
// Check rate limit (after duplicate check so duplicates don't consume quota)
if (!checkRateLimit(userId)) {
logger.warn(
{ userId, maxPerHour: MAX_IMPRESSIONS_PER_HOUR },
'[ads] Rate limited ad impression request',
)
return NextResponse.json(
{ success: false, error: 'Rate limited', creditsGranted: 0 },
{ status: 429 },
)
}
// Fire the primary impression pixel plus any provider-specific extra
// tracking pixels (Carbon returns these via the `pixel` field). ZeroClick
// impressions must be reported from the client device, so the CLI handles
// that directly and this endpoint only records our local state.
if (adRecord.provider !== 'zeroclick') {
const now = Math.floor(Date.now() / 1000).toString()
const extraPixels = (adRecord.extra_pixels ?? []).map((p) =>
p.replaceAll('[timestamp]', now),
)
const pixelUrls = [impUrl, ...extraPixels]
const requestUserAgent = req.headers.get('user-agent') ?? undefined
await Promise.all(
pixelUrls.map(async (pixelUrl) => {
try {
await fetch(pixelUrl, {
...(requestUserAgent
? { headers: { 'User-Agent': requestUserAgent } }
: {}),
})
} catch (error) {
logger.warn(
{
pixelUrl,
error:
error instanceof Error
? { name: error.name, message: error.message }
: error,
},
'[ads] Failed to fire impression pixel',
)
}
}),
)
logger.info(
{ userId, provider: adRecord.provider, pixelCount: pixelUrls.length },
'[ads] Fired impression pixels',
)
}
// No credits granted for ad impressions
const creditsGranted = 0
// Update the ad_impression record with impression details (for ALL modes)
try {
await db
.update(schema.adImpression)
.set({
impression_fired_at: new Date(),
credits_granted: 0,
grant_operation_id: null,
})
.where(eq(schema.adImpression.id, adRecord.id))
logger.info({ userId, impUrl }, '[ads] Updated ad impression record')
} catch (error) {
logger.error(
{
userId,
impUrl,
error:
error instanceof Error
? { name: error.name, message: error.message }
: error,
},
'[ads] Failed to update ad impression record',
)
}
return NextResponse.json({
success: true,
creditsGranted,
})
}