-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
send.ts
177 lines (148 loc) · 4.26 KB
/
send.ts
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
import ipaddr from 'ipaddr.js';
import { isbot } from 'isbot';
import { COLLECTION_TYPE, HOSTNAME_REGEX, IP_REGEX } from 'lib/constants';
import { secret } from 'lib/crypto';
import { getIpAddress } from 'lib/detect';
import { useCors, useSession, useValidate } from 'lib/middleware';
import { CollectionType, YupRequest } from 'lib/types';
import { NextApiRequest, NextApiResponse } from 'next';
import { badRequest, createToken, forbidden, methodNotAllowed, ok, send } from 'next-basics';
import { saveEvent, saveSessionData } from 'queries';
import * as yup from 'yup';
export interface CollectRequestBody {
payload: {
data: { [key: string]: any };
hostname: string;
ip: string;
language: string;
referrer: string;
screen: string;
title: string;
url: string;
website: string;
name: string;
};
type: CollectionType;
}
export interface NextApiRequestCollect extends NextApiRequest {
body: CollectRequestBody;
session: {
id: string;
websiteId: string;
ownerId: string;
hostname: string;
browser: string;
os: string;
device: string;
screen: string;
language: string;
country: string;
subdivision1: string;
subdivision2: string;
city: string;
};
headers: { [key: string]: any };
yup: YupRequest;
}
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),
language: yup.string().max(35),
referrer: yup.string(),
screen: yup.string().max(11),
title: yup.string(),
url: yup.string(),
website: yup.string().uuid().required(),
name: yup.string().max(50),
})
.required(),
type: yup
.string()
.matches(/event|identify/i)
.required(),
}),
};
export default async (req: NextApiRequestCollect, res: NextApiResponse) => {
await useCors(req, res);
if (req.method === 'POST') {
if (!process.env.DISABLE_BOT_CHECK && isbot(req.headers['user-agent'])) {
return ok(res);
}
await useValidate(schema, req, res);
if (hasBlockedIp(req)) {
return forbidden(res);
}
const { type, payload } = req.body;
const { url, referrer, name: eventName, data: eventData, title: pageTitle } = payload;
await useSession(req, res);
const session = req.session;
if (type === COLLECTION_TYPE.event) {
// eslint-disable-next-line prefer-const
let [urlPath, urlQuery] = url?.split('?') || [];
let [referrerPath, referrerQuery] = referrer?.split('?') || [];
let referrerDomain;
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) {
urlPath = urlPath.replace(/.+\/$/, '');
}
await saveEvent({
urlPath,
urlQuery,
referrerPath,
referrerQuery,
referrerDomain,
pageTitle,
eventName,
eventData,
...session,
sessionId: session.id,
});
}
if (type === COLLECTION_TYPE.identify) {
if (!eventData) {
return badRequest(res, 'Data required.');
}
await saveSessionData({
websiteId: session.websiteId,
sessionId: session.id,
sessionData: eventData,
});
}
const token = createToken(session, secret());
return send(res, token);
}
return methodNotAllowed(res);
};
function hasBlockedIp(req: NextApiRequestCollect) {
const ignoreIps = process.env.IGNORE_IP;
if (ignoreIps) {
const ips = [];
if (ignoreIps) {
ips.push(...ignoreIps.split(',').map(n => n.trim()));
}
const clientIp = getIpAddress(req);
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;
}
});
}
return false;
}