-
Notifications
You must be signed in to change notification settings - Fork 189
Expand file tree
/
Copy pathrequest-validation.ts
More file actions
319 lines (289 loc) · 7.69 KB
/
Copy pathrequest-validation.ts
File metadata and controls
319 lines (289 loc) · 7.69 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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
import {
getWebsiteByIdV2,
isValidIpFromSettings,
isValidOrigin,
isValidOriginFromSettings,
} from "@hooks/auth";
import { checkAutumnUsage } from "@lib/billing";
import { logBlockedTraffic } from "@lib/blocked-traffic";
import { runFork, send } from "@lib/producer";
import { basketErrors } from "@lib/structured-errors";
import { record } from "@lib/tracing";
import { extractIpFromRequest } from "@utils/ip-geo";
import { detectBot } from "@utils/user-agent";
import {
sanitizeString,
VALIDATION_LIMITS,
validatePayloadSize,
} from "@utils/validation";
import {
getClientAppAllowedOrigins,
isOriginInList,
} from "@databuddy/shared/utils/origins";
import { useLogger } from "evlog/elysia";
export interface ValidatedRequest {
clientId: string;
ip: string;
organizationId?: string;
ownerId?: string;
userAgent: string;
}
interface WebsiteSecuritySettings {
allowedIps?: string[];
allowedOrigins?: string[];
}
export function getWebsiteSecuritySettings(
settings: unknown
): WebsiteSecuritySettings | null {
if (!settings || typeof settings !== "object" || Array.isArray(settings)) {
return null;
}
const s = settings as Record<string, unknown>;
return {
allowedOrigins: Array.isArray(s.allowedOrigins)
? s.allowedOrigins.filter(
(item): item is string => typeof item === "string"
)
: undefined,
allowedIps: Array.isArray(s.allowedIps)
? s.allowedIps.filter((item): item is string => typeof item === "string")
: undefined,
};
}
/**
* Validate incoming request for analytics events.
* Throws basket ingest EvlogErrors on failure; returns `{ error: billing.response }` when quota is exceeded.
*/
export function validateRequest(
body: unknown,
query: unknown,
request: Request
): Promise<ValidatedRequest> {
return record("validateRequest", async () => {
const log = useLogger();
if (!validatePayloadSize(body, VALIDATION_LIMITS.PAYLOAD_MAX_SIZE)) {
logBlockedTraffic(
request,
body,
query,
"payload_too_large",
"Validation Error"
);
log.set({ validation: { failed: true, reason: "payload_too_large" } });
throw basketErrors.ingestPayloadTooLarge();
}
const queryRecord =
query && typeof query === "object" && !Array.isArray(query)
? (query as Record<string, unknown>)
: {};
let clientId = sanitizeString(
queryRecord.client_id,
VALIDATION_LIMITS.SHORT_STRING_MAX_LENGTH
);
if (!clientId) {
const headerClientId = request.headers.get("databuddy-client-id");
if (headerClientId) {
clientId = sanitizeString(
headerClientId,
VALIDATION_LIMITS.SHORT_STRING_MAX_LENGTH
);
}
}
if (!clientId) {
logBlockedTraffic(
request,
body,
query,
"missing_client_id",
"Validation Error"
);
log.set({ validation: { failed: true, reason: "missing_client_id" } });
throw basketErrors.ingestMissingClientId();
}
log.set({ clientId });
const website = await record("getWebsiteByIdV2", () =>
getWebsiteByIdV2(clientId)
);
if (!website || website.status !== "ACTIVE") {
logBlockedTraffic(
request,
body,
query,
"invalid_client_id",
"Validation Error",
undefined,
clientId
);
log.set({
validation: { failed: true, reason: "invalid_client_id" },
website: { status: website?.status || "not_found" },
});
throw basketErrors.ingestInvalidClientId();
}
log.set({ website: { domain: website.domain, status: website.status } });
if (website.ownerId) {
await checkAutumnUsage(website.ownerId, "events", {
website_domain: website.domain,
website_id: website.id,
website_name: website.name,
});
}
const origin = request.headers.get("origin");
const ip = extractIpFromRequest(request);
const clientAppAllowedOrigins = getClientAppAllowedOrigins();
const securitySettings = getWebsiteSecuritySettings(website.settings);
const allowedOrigins = securitySettings?.allowedOrigins;
const allowedIps = securitySettings?.allowedIps;
if (origin && isOriginInList(origin, clientAppAllowedOrigins)) {
log.set({ validation: { clientAppOriginAllowed: true, origin } });
} else if (origin && allowedOrigins && allowedOrigins.length > 0) {
if (
!(await record("isValidOriginFromSettings", () =>
isValidOriginFromSettings(origin, allowedOrigins)
))
) {
logBlockedTraffic(
request,
body,
query,
"origin_not_authorized",
"Security Check",
undefined,
clientId
);
log.set({
validation: { failed: true, reason: "origin_not_authorized", origin },
});
throw basketErrors.ingestOriginNotAuthorized();
}
} else if (
origin &&
!(await record("isValidOrigin", () =>
isValidOrigin(origin, website.domain)
))
) {
logBlockedTraffic(
request,
body,
query,
"origin_not_authorized",
"Security Check",
undefined,
clientId
);
log.set({
validation: { failed: true, reason: "origin_not_authorized", origin },
});
throw basketErrors.ingestOriginNotAuthorized();
}
if (
ip &&
allowedIps &&
allowedIps.length > 0 &&
!(await record("isValidIpFromSettings", () =>
isValidIpFromSettings(ip, allowedIps)
))
) {
logBlockedTraffic(
request,
body,
query,
"ip_not_authorized",
"Security Check",
undefined,
clientId
);
log.set({ validation: { failed: true, reason: "ip_not_authorized" } });
throw basketErrors.ingestIpNotAuthorized();
}
const userAgent =
sanitizeString(
request.headers.get("user-agent"),
VALIDATION_LIMITS.STRING_MAX_LENGTH
) || "";
return {
clientId,
userAgent,
ip,
ownerId: website.ownerId || undefined,
organizationId: website.organizationId || undefined,
};
});
}
/**
* Check if request is from a bot
* - ALLOW: Process normally (search engines, social media)
* - TRACK_ONLY: Log to ai_traffic_spans but don't count as pageview (AI crawlers)
* - BLOCK: Reject and log to blocked_traffic (scrapers, malicious bots)
*/
export function checkForBot(
request: Request,
body: unknown,
query: unknown,
clientId: string,
userAgent: string
): Promise<{ error?: Response } | undefined> {
return record("checkForBot", () => {
const log = useLogger();
const bodyRecord =
body && typeof body === "object" && !Array.isArray(body)
? (body as Record<string, unknown>)
: {};
const queryRecord =
query && typeof query === "object" && !Array.isArray(query)
? (query as Record<string, unknown>)
: {};
const botCheck = detectBot(userAgent, request);
if (!botCheck.isBot) {
return;
}
const { action, result } = botCheck;
log.set({
bot: { name: botCheck.botName, category: botCheck.category, action },
});
if (action === "allow") {
return;
}
if (action === "track_only") {
const path =
(typeof bodyRecord.path === "string" ? bodyRecord.path : undefined) ||
(typeof bodyRecord.url === "string" ? bodyRecord.url : undefined) ||
(typeof queryRecord.path === "string" ? queryRecord.path : undefined) ||
request.headers.get("referer") ||
"";
const referrer =
(typeof bodyRecord.referrer === "string"
? bodyRecord.referrer
: undefined) ||
request.headers.get("referer") ||
undefined;
runFork(
send("analytics-ai-traffic-spans", {
client_id: clientId,
timestamp: Date.now(),
bot_type: result?.category || "unknown",
bot_name: botCheck.botName || "unknown",
user_agent: userAgent,
path,
referrer,
action: "tracked",
})
);
return {
error: new Response(null, { status: 204 }),
};
}
logBlockedTraffic(
request,
body,
query,
botCheck.reason || "unknown_bot",
botCheck.category || "Bot Detection",
botCheck.botName,
clientId
);
return {
error: new Response(null, { status: 204 }),
};
});
}