Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

fix bot detection

Carl-Gerhard Lindesvärd94614f121739
diff --git a/apps/sdk-api/src/controllers/event.controller.ts b/apps/sdk-api/src/controllers/event.controller.ts
index 07437ac2c..9d2204090 100644
--- a/apps/sdk-api/src/controllers/event.controller.ts
+++ b/apps/sdk-api/src/controllers/event.controller.ts
@@ -1,5 +1,3 @@
-import { isBot } from '@/bots';
-import { logInfo } from '@/utils/logger';
import { getClientIp, parseIp } from '@/utils/parseIp';
import { getReferrerWithQuery, parseReferrer } from '@/utils/parseReferrer';
import { isUserAgentSet, parseUserAgent } from '@/utils/parseUserAgent';
@@ -9,7 +7,7 @@ import { v4 as uuid } from 'uuid';
import { generateDeviceId, getTime, toISOString } from '@mixan/common';
import type { IServiceCreateEventPayload } from '@mixan/db';
-import { createBotEvent, createEvent, getEvents, getSalts } from '@mixan/db';
+import { createEvent, getEvents, getSalts } from '@mixan/db';
import type { JobsOptions } from '@mixan/queue';
import { eventsQueue, findJobByPrefix } from '@mixan/queue';
import type { PostEventPayload } from '@mixan/sdk';
@@ -155,21 +153,6 @@ export async function postEvent(
return reply.status(200).send('');
}
- const bot = isBot(ua);
- if (bot) {
- request.log.info({ bot, ua }, 'bot detected 2');
- try {
- await createBotEvent({
- ...bot,
- projectId,
- createdAt: new Date(body.timestamp),
- });
- } catch (e) {
- request.log.error(e, 'bot detected 2 failed');
- }
- return reply.status(200).send('');
- }
-
const [geo, eventsJobs] = await Promise.all([
parseIp(ip),
eventsQueue.getJobs(['delayed']),
@@ -231,7 +214,6 @@ export async function postEvent(
profileId,
projectId,
deviceId,
- bot,
geo,
sessionStartEvent,
path,
diff --git a/apps/sdk-api/src/routes/event.router.ts b/apps/sdk-api/src/routes/event.router.ts
index 61e99a433..cb68fdcbd 100644
--- a/apps/sdk-api/src/routes/event.router.ts
+++ b/apps/sdk-api/src/routes/event.router.ts
@@ -1,27 +1,47 @@
-import { isBot as isGetBot } from '@/bots';
+import { isBot } from '@/bots';
import * as controller from '@/controllers/event.controller';
import { validateSdkRequest } from '@/utils/auth';
-import type { FastifyPluginCallback } from 'fastify';
+import type { FastifyPluginCallback, FastifyRequest } from 'fastify';
-const eventRouter: FastifyPluginCallback = (fastify, opts, done) => {
- fastify.addHook('preHandler', (req, reply, done) => {
- const isBot = req.headers['user-agent']
- ? isGetBot(req.headers['user-agent'])
- : false;
- if (isBot) {
- reply.log.warn({ ...req.headers, bot: isBot }, 'Bot detected');
- reply.status(202).send('OK');
- }
+import { createBotEvent } from '@mixan/db';
+import type { PostEventPayload } from '@mixan/sdk';
- validateSdkRequest(req.headers)
- .then((projectId) => {
+const eventRouter: FastifyPluginCallback = (fastify, opts, done) => {
+ fastify.addHook(
+ 'preHandler',
+ async (
+ req: FastifyRequest<{
+ Body: PostEventPayload;
+ }>,
+ reply
+ ) => {
+ try {
+ const projectId = await validateSdkRequest(req.headers);
req.projectId = projectId;
- done();
- })
- .catch((e) => {
+
+ const bot = req.headers['user-agent']
+ ? isBot(req.headers['user-agent'])
+ : null;
+
+ if (bot) {
+ const path = (req.body?.properties?.__path ||
+ req.body?.properties?.path) as string | undefined;
+ reply.log.warn({ ...req.headers, bot }, 'Bot detected (event)');
+ await createBotEvent({
+ ...bot,
+ projectId,
+ path: path ?? '',
+ createdAt: new Date(req.body?.timestamp),
+ });
+ reply.status(202).send('OK');
+ }
+ } catch (e) {
+ reply.log.warn(e, 'Érror');
reply.status(401).send();
- });
- });
+ return;
+ }
+ }
+ );
fastify.route({
method: 'POST',
diff --git a/apps/sdk-api/src/routes/profile.router.ts b/apps/sdk-api/src/routes/profile.router.ts
index 244458726..baa0de31b 100644
--- a/apps/sdk-api/src/routes/profile.router.ts
+++ b/apps/sdk-api/src/routes/profile.router.ts
@@ -1,17 +1,26 @@
+import { isBot } from '@/bots';
import * as controller from '@/controllers/profile.controller';
import { validateSdkRequest } from '@/utils/auth';
import type { FastifyPluginCallback } from 'fastify';
const eventRouter: FastifyPluginCallback = (fastify, opts, done) => {
- fastify.addHook('preHandler', (req, reply, done) => {
- validateSdkRequest(req.headers)
- .then((projectId) => {
- req.projectId = projectId;
- done();
- })
- .catch((e) => {
- reply.status(401).send();
- });
+ fastify.addHook('preHandler', async (req, reply) => {
+ try {
+ const projectId = await validateSdkRequest(req.headers);
+ req.projectId = projectId;
+
+ const bot = req.headers['user-agent']
+ ? isBot(req.headers['user-agent'])
+ : null;
+
+ if (bot) {
+ reply.log.warn({ ...req.headers, bot }, 'Bot detected (profile)');
+ reply.status(202).send('OK');
+ }
+ } catch (e) {
+ reply.status(401).send();
+ return;
+ }
});
fastify.route({