directus

Форк
0
/
agent-with-ip-validation.ts 
55 строк · 1.7 Кб
1
import type { Agent, ClientRequestArgs } from 'node:http';
2
import { isIP } from 'node:net';
3
import { isDeniedIp } from './is-denied-ip.js';
4

5
/**
6
 * 'createConnection' is missing in 'Agent' type, but assigned in actual implementation:
7
 * https://github.com/nodejs/node/blob/8a41d9b636be86350cd32847c3f89d327c4f6ff7/lib/_http_agent.js#L215
8
 */
9
export type _Agent = Agent & { createConnection: ClientRequestArgs['createConnection'] };
10

11
const deniedError = (domain: string) => new Error(`Requested domain "${domain}" resolves to a denied IP address`);
12

13
/** Extends a HTTP agent with IP validation */
14
export const agentWithIpValidation = (agent: Agent) => {
15
	const _agent = agent as _Agent;
16

17
	const { createConnection } = _agent;
18

19
	_agent.createConnection = function (options, oncreate) {
20
		const { host } = options;
21

22
		/*
23
		 * Unexpected, but according to the types 'host' might be undefined.
24
		 * In that case, the request is denied to be on the safe side,
25
		 * since the host cannot be verified.
26
		 */
27
		if (!host) {
28
			throw new Error('Request cannot be verified due to missing host');
29
		}
30

31
		/*
32
		 * At this point, host is only verified if it's already an IP address.
33
		 * Otherwise it will be verified on 'lookup' event.
34
		 */
35
		if (isIP(host) !== 0 && isDeniedIp(host)) throw deniedError(host);
36

37
		const socket = createConnection?.call(this, options, oncreate);
38

39
		// Unexpected, but in that case the request is denied to be on the safe side
40
		if (!socket) {
41
			throw new Error('Request cannot be verified due to lost socket');
42
		}
43

44
		// Emitted after resolving the host name but before connecting.
45
		socket.on('lookup', (error, address) => {
46
			if (error || !isDeniedIp(address)) return;
47

48
			return socket.destroy(deniedError(host));
49
		});
50

51
		return socket;
52
	};
53

54
	return agent;
55
};
56

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.