-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathcheckIfRequestIsBlocked.ts
More file actions
86 lines (67 loc) · 2.3 KB
/
checkIfRequestIsBlocked.ts
File metadata and controls
86 lines (67 loc) · 2.3 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
/* eslint-disable max-lines-per-function */
import type { ServerResponse } from "http";
import { Agent } from "../../agent/Agent";
import { getContext } from "../../agent/Context";
import { escapeHTML } from "../../helpers/escapeHTML";
import { ipAllowedToAccessRoute } from "./ipAllowedToAccessRoute";
/**
* Inspects the IP address of the request:
* - Whether the IP address is blocked by an IP blocklist (e.g. Geo restrictions)
* - Whether the IP address is allowed to access the current route (e.g. Admin panel)
*/
export function checkIfRequestIsBlocked(
res: ServerResponse,
agent: Agent
): boolean {
if (res.headersSent) {
// The headers have already been sent, so we can't block the request
// This might happen if the server has multiple listeners
return false;
}
const context = getContext();
if (!context) {
return false;
}
if (!ipAllowedToAccessRoute(context, agent)) {
res.statusCode = 403;
res.setHeader("Content-Type", "text/plain");
let message = "Your IP address is not allowed to access this resource.";
if (context.remoteAddress) {
message += ` (Your IP: ${escapeHTML(context.remoteAddress)})`;
}
res.end(message);
return true;
}
const isBypassedIP =
context.remoteAddress &&
agent.getConfig().isBypassedIP(context.remoteAddress);
if (isBypassedIP) {
return false;
}
const result = context.remoteAddress
? agent.getConfig().isIPAddressBlocked(context.remoteAddress)
: ({ blocked: false } as const);
if (result.blocked) {
res.statusCode = 403;
res.setHeader("Content-Type", "text/plain");
let message = `Your IP address is blocked due to ${escapeHTML(result.reason)}.`;
if (context.remoteAddress) {
message += ` (Your IP: ${escapeHTML(context.remoteAddress)})`;
}
res.end(message);
return true;
}
const isUserAgentBlocked =
context.headers && typeof context.headers["user-agent"] === "string"
? agent.getConfig().isUserAgentBlocked(context.headers["user-agent"])
: ({ blocked: false } as const);
if (isUserAgentBlocked.blocked) {
res.statusCode = 403;
res.setHeader("Content-Type", "text/plain");
res.end(
"You are not allowed to access this resource because you have been identified as a bot."
);
return true;
}
return false;
}