umami/src/pages/api/send.ts

197 lines
4.7 KiB
TypeScript
Raw Normal View History

import ipaddr from 'ipaddr.js';
2024-03-01 23:20:04 +01:00
import { isbot } from 'isbot';
import { COLLECTION_TYPE, HOSTNAME_REGEX, IP_REGEX } from 'lib/constants';
import { secret, visitSalt, uuid } from 'lib/crypto';
2023-08-31 01:40:32 +02:00
import { getIpAddress } from 'lib/detect';
2023-08-20 07:23:15 +02:00
import { useCors, useSession, useValidate } from 'lib/middleware';
import { CollectionType, YupRequest } from 'lib/types';
2022-11-15 22:21:14 +01:00
import { NextApiRequest, NextApiResponse } from 'next';
import {
badRequest,
createToken,
forbidden,
methodNotAllowed,
ok,
safeDecodeURI,
send,
} from 'next-basics';
2023-08-20 07:23:15 +02:00
import { saveEvent, saveSessionData } from 'queries';
import * as yup from 'yup';
2022-11-15 22:21:14 +01:00
2023-03-30 20:18:57 +02:00
export interface CollectRequestBody {
payload: {
data: { [key: string]: any };
hostname: string;
ip: string;
2023-03-30 20:18:57 +02:00
language: string;
referrer: string;
screen: string;
title: string;
url: string;
website: string;
name: string;
};
type: CollectionType;
2023-03-30 20:18:57 +02:00
}
2022-11-15 22:21:14 +01:00
export interface NextApiRequestCollect extends NextApiRequest {
2023-03-30 20:18:57 +02:00
body: CollectRequestBody;
2022-11-15 22:21:14 +01:00
session: {
id: string;
websiteId: string;
visitId: string;
2023-05-16 05:41:12 +02:00
ownerId: string;
2022-11-15 22:21:14 +01:00
hostname: string;
browser: string;
os: string;
device: string;
screen: string;
language: string;
country: string;
subdivision1: string;
subdivision2: string;
city: string;
2024-03-26 01:49:13 +01:00
iat: number;
2022-11-15 22:21:14 +01:00
};
2023-03-30 20:18:57 +02:00
headers: { [key: string]: any };
2023-08-20 07:23:15 +02:00
yup: YupRequest;
2022-11-15 22:21:14 +01:00
}
2023-08-20 07:23:15 +02:00
const schema = {
POST: yup.object().shape({
payload: yup
.object()
.shape({
data: yup.object(),
hostname: yup.string().matches(HOSTNAME_REGEX).max(100),
ip: yup.string().matches(IP_REGEX),
2023-08-20 07:23:15 +02:00
language: yup.string().max(35),
2024-02-28 00:09:57 +01:00
referrer: yup.string(),
2023-08-20 07:23:15 +02:00
screen: yup.string().max(11),
2024-02-28 00:09:57 +01:00
title: yup.string(),
url: yup.string(),
2023-08-20 07:23:15 +02:00
website: yup.string().uuid().required(),
name: yup.string().max(50),
})
.required(),
type: yup
.string()
.matches(/event|identify/i)
.required(),
}),
};
2022-11-15 22:21:14 +01:00
export default async (req: NextApiRequestCollect, res: NextApiResponse) => {
await useCors(req, res);
2023-08-31 08:53:05 +02:00
if (req.method === 'POST') {
2023-11-12 05:45:09 +01:00
if (!process.env.DISABLE_BOT_CHECK && isbot(req.headers['user-agent'])) {
2023-08-31 08:53:05 +02:00
return ok(res);
}
2023-09-30 05:24:48 +02:00
await useValidate(schema, req, res);
2023-11-28 20:03:55 +01:00
if (hasBlockedIp(req)) {
2023-08-31 08:53:05 +02:00
return forbidden(res);
}
2023-11-28 20:03:55 +01:00
const { type, payload } = req.body;
const { url, referrer, name: eventName, data: eventData, title } = payload;
const pageTitle = safeDecodeURI(title);
2023-08-31 08:53:05 +02:00
await useSession(req, res);
const session = req.session;
// expire visitId after 30 minutes
session.visitId =
!!session.iat && Math.floor(new Date().getTime() / 1000) - session.iat > 1800
? uuid(session.id, visitSalt())
: session.visitId;
session.iat = Math.floor(new Date().getTime() / 1000);
2023-08-31 08:53:05 +02:00
if (type === COLLECTION_TYPE.event) {
// eslint-disable-next-line prefer-const
let [urlPath, urlQuery] = safeDecodeURI(url)?.split('?') || [];
let [referrerPath, referrerQuery] = safeDecodeURI(referrer)?.split('?') || [];
2024-03-26 06:51:10 +01:00
let referrerDomain = '';
2023-08-31 08:53:05 +02:00
if (!urlPath) {
urlPath = '/';
}
if (referrerPath?.startsWith('http')) {
const refUrl = new URL(referrer);
referrerPath = refUrl.pathname;
referrerQuery = refUrl.search.substring(1);
referrerDomain = refUrl.hostname.replace(/www\./, '');
}
if (process.env.REMOVE_TRAILING_SLASH) {
2024-03-12 04:56:36 +01:00
urlPath = urlPath.replace(/(.+)\/$/, '$1');
2023-08-31 08:53:05 +02:00
}
await saveEvent({
urlPath,
urlQuery,
referrerPath,
referrerQuery,
referrerDomain,
pageTitle,
eventName,
eventData,
...session,
sessionId: session.id,
visitId: session.visitId,
2023-08-31 08:53:05 +02:00
});
}
2023-08-31 08:53:05 +02:00
if (type === COLLECTION_TYPE.identify) {
if (!eventData) {
return badRequest(res, 'Data required.');
}
2024-01-14 11:21:39 +01:00
await saveSessionData({
websiteId: session.websiteId,
sessionId: session.id,
sessionData: eventData,
});
}
2023-08-31 08:53:05 +02:00
const token = createToken(session, secret());
2023-08-31 08:53:05 +02:00
return send(res, token);
}
2023-08-31 08:53:05 +02:00
return methodNotAllowed(res);
};
2023-11-28 20:03:55 +01:00
function hasBlockedIp(req: NextApiRequestCollect) {
const ignoreIps = process.env.IGNORE_IP;
2023-11-28 20:03:55 +01:00
if (ignoreIps) {
const ips = [];
if (ignoreIps) {
ips.push(...ignoreIps.split(',').map(n => n.trim()));
}
const clientIp = getIpAddress(req);
2023-06-15 08:48:11 +02:00
return ips.find(ip => {
if (ip === clientIp) return true;
// CIDR notation
if (ip.indexOf('/') > 0) {
const addr = ipaddr.parse(clientIp);
const range = ipaddr.parseCIDR(ip);
if (addr.kind() === range[0].kind() && addr.match(range)) return true;
}
});
2023-03-16 00:06:51 +01:00
}
2023-11-28 20:03:55 +01:00
return false;
}