camoucore 0.1.2 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/data-files/antibot-rules.json +146 -0
- package/dist/data.js +1 -0
- package/dist/geolocation.d.ts +3 -2
- package/dist/geolocation.js +8 -9
- package/dist/host.d.ts +2 -0
- package/dist/host.js +16 -0
- package/dist/ip.d.ts +14 -0
- package/dist/ip.js +96 -26
- package/dist/passthrough.d.ts +16 -0
- package/dist/passthrough.js +50 -0
- package/dist/settings.d.ts +12 -0
- package/dist/settings.js +95 -0
- package/dist/telemetry.d.ts +128 -0
- package/dist/telemetry.js +425 -0
- package/package.json +1 -1
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
{
|
|
2
|
+
"_about": [
|
|
3
|
+
"How proxy telemetry recognises an anti-bot provider's answer, read by camoucore/telemetry.py and telemetry.ts.",
|
|
4
|
+
"A rule looks only at a response from the provider itself: one of its endpoints (url), or a response carrying the provider's own edge header (edge).",
|
|
5
|
+
"Every condition in a rule must hold; a provider's first matching rule decides. url is a regex searched in host + path (never the query); query tests named query parameters of that provider URL.",
|
|
6
|
+
"status is a list of codes or classes ('4xx'); headers and edge values are case-insensitive regexes; body is a case-insensitive regex, and is read only from provider endpoints and from a provider's error page (status 4xx or 5xx).",
|
|
7
|
+
"verdict: presence (the provider is on the page, no outcome yet), success, challenge, block. transient: a challenge that clears by itself (an interstitial) and counts only if nothing succeeds after it. opens false: the verdict only adds to an encounter something else showed.",
|
|
8
|
+
"unresolved: what an encounter with only presence counts as. 'unknown' for a provider whose verdict the browser never sees."
|
|
9
|
+
],
|
|
10
|
+
"version": 1,
|
|
11
|
+
"providers": {
|
|
12
|
+
"cloudflare": {
|
|
13
|
+
"edge": [{"name": "^cf-ray$"}],
|
|
14
|
+
"unresolved": "success",
|
|
15
|
+
"rules": [
|
|
16
|
+
{"document": true, "edge": true, "headers": {"cf-mitigated": "^challenge$"}, "verdict": "challenge", "transient": true},
|
|
17
|
+
{"document": true, "edge": true, "status": ["4xx"], "body": "error code: 10(06|07|08|20)|sorry, you have been blocked|cf-error-details", "verdict": "block"},
|
|
18
|
+
{"url": "^(?!challenges\\.cloudflare\\.com/)[^/]+/cdn-cgi/challenge-platform/", "verdict": "presence"},
|
|
19
|
+
{"document": true, "edge": true, "status": ["2xx"], "verdict": "success", "opens": false}
|
|
20
|
+
]
|
|
21
|
+
},
|
|
22
|
+
"turnstile": {
|
|
23
|
+
"unresolved": "unknown",
|
|
24
|
+
"rules": [
|
|
25
|
+
{"url": "^challenges\\.cloudflare\\.com/turnstile/", "verdict": "presence"}
|
|
26
|
+
]
|
|
27
|
+
},
|
|
28
|
+
"datadome": {
|
|
29
|
+
"edge": [{"name": "^x-datadome$"}, {"name": "^x-dd-b$"}],
|
|
30
|
+
"unresolved": "success",
|
|
31
|
+
"rules": [
|
|
32
|
+
{"url": "captcha-delivery\\.com/captcha/", "query": {"t": "^bv$"}, "verdict": "block"},
|
|
33
|
+
{"url": "captcha-delivery\\.com/captcha/", "verdict": "challenge"},
|
|
34
|
+
{"url": "captcha-delivery\\.com/interstitial/", "verdict": "challenge", "transient": true},
|
|
35
|
+
{"url": "^api-js\\.datadome\\.co/js/", "body": "\"status\"\\s*:\\s*200", "verdict": "success"},
|
|
36
|
+
{"url": "^(js|api-js)\\.datadome\\.co/", "verdict": "presence"},
|
|
37
|
+
{"document": true, "edge": true, "status": ["2xx"], "verdict": "success"},
|
|
38
|
+
{"document": true, "edge": true, "verdict": "presence"}
|
|
39
|
+
]
|
|
40
|
+
},
|
|
41
|
+
"akamai": {
|
|
42
|
+
"edge": [{"name": "^server$", "value": "^AkamaiGHost$"}, {"name": "^akamai-grn$"}],
|
|
43
|
+
"unresolved": "unknown",
|
|
44
|
+
"rules": [
|
|
45
|
+
{"document": true, "edge": true, "status": ["403"], "body": "access denied[\\s\\S]*reference\\s*#", "verdict": "block"},
|
|
46
|
+
{"url": "/_sec/cp_challenge/", "verdict": "challenge", "transient": true},
|
|
47
|
+
{"edge": true, "method": "POST", "headers": {"set-cookie": "(^|\\n|, ?)_abck=[^;]*~0~"}, "verdict": "success"},
|
|
48
|
+
{"document": true, "edge": true, "headers": {"set-cookie": "(^|\\n|, ?)_abck="}, "verdict": "presence"}
|
|
49
|
+
]
|
|
50
|
+
},
|
|
51
|
+
"perimeterx": {
|
|
52
|
+
"unresolved": "unknown",
|
|
53
|
+
"rules": [
|
|
54
|
+
{"url": "^captcha\\.(px-cdn|px-cloud)\\.net/|/captcha/captcha\\.js$", "verdict": "challenge"},
|
|
55
|
+
{"url": "^collector-[a-z0-9]+\\.(px-cloud|perimeterx)\\.net/|/api/v2/collector$", "body": "bake\\|_px3\\|", "verdict": "success"},
|
|
56
|
+
{"url": "(px-cloud|px-cdn|perimeterx)\\.net/|/api/v2/collector$", "verdict": "presence"}
|
|
57
|
+
]
|
|
58
|
+
},
|
|
59
|
+
"kasada": {
|
|
60
|
+
"edge": [{"name": "^x-kpsdk-"}],
|
|
61
|
+
"unresolved": "unknown",
|
|
62
|
+
"rules": [
|
|
63
|
+
{"document": true, "edge": true, "status": ["429"], "verdict": "challenge", "transient": true},
|
|
64
|
+
{"url": "/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/tl$", "status": ["2xx"], "verdict": "success"},
|
|
65
|
+
{"url": "/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/tl$", "status": ["4xx"], "verdict": "block"},
|
|
66
|
+
{"document": true, "edge": true, "status": ["4xx"], "verdict": "block"},
|
|
67
|
+
{"url": "/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/(ips\\.js|p\\.js|fp)$", "verdict": "presence"}
|
|
68
|
+
]
|
|
69
|
+
},
|
|
70
|
+
"imperva": {
|
|
71
|
+
"edge": [{"name": "^x-iinfo$"}, {"name": "^x-cdn$", "value": "imperva|incapsula"}],
|
|
72
|
+
"unresolved": "success",
|
|
73
|
+
"rules": [
|
|
74
|
+
{"document": true, "edge": true, "status": ["4xx", "5xx"], "body": "incapsula incident id|request unsuccessful", "verdict": "block"},
|
|
75
|
+
{"url": "/_Incapsula_Resource", "verdict": "challenge", "transient": true},
|
|
76
|
+
{"document": true, "edge": true, "status": ["2xx"], "verdict": "success"}
|
|
77
|
+
]
|
|
78
|
+
},
|
|
79
|
+
"awswaf": {
|
|
80
|
+
"edge": [{"name": "^x-amzn-waf-action$"}],
|
|
81
|
+
"unresolved": "success",
|
|
82
|
+
"rules": [
|
|
83
|
+
{"edge": true, "headers": {"x-amzn-waf-action": "^captcha$"}, "verdict": "challenge"},
|
|
84
|
+
{"edge": true, "headers": {"x-amzn-waf-action": "^challenge$"}, "verdict": "challenge", "transient": true},
|
|
85
|
+
{"url": "\\.token\\.awswaf\\.com/.*/verify$", "status": ["2xx"], "verdict": "success"},
|
|
86
|
+
{"url": "\\.awswaf\\.com/", "verdict": "presence"}
|
|
87
|
+
]
|
|
88
|
+
},
|
|
89
|
+
"hcaptcha": {
|
|
90
|
+
"unresolved": "unknown",
|
|
91
|
+
"rules": [
|
|
92
|
+
{"url": "^(api|api2|hcaptcha)\\.hcaptcha\\.com/getcaptcha/", "body": "\"generated_pass_UUID\"\\s*:\\s*\"[^\"]", "verdict": "success"},
|
|
93
|
+
{"url": "^(api|api2|hcaptcha)\\.hcaptcha\\.com/getcaptcha/", "body": "\"tasklist\"", "verdict": "challenge"},
|
|
94
|
+
{"url": "^(js|api|api2|hcaptcha|newassets)\\.hcaptcha\\.com/", "verdict": "presence"}
|
|
95
|
+
]
|
|
96
|
+
},
|
|
97
|
+
"recaptcha": {
|
|
98
|
+
"unresolved": "unknown",
|
|
99
|
+
"rules": [
|
|
100
|
+
{"url": "^(www\\.google\\.com|www\\.recaptcha\\.net|recaptcha\\.google\\.com)/recaptcha/(api2|enterprise)/payload$", "verdict": "challenge"},
|
|
101
|
+
{"url": "^(www\\.google\\.com|www\\.recaptcha\\.net|recaptcha\\.google\\.com)/recaptcha/(api2|enterprise)/reload$", "body": "\"nocaptcha\"", "verdict": "success"},
|
|
102
|
+
{"url": "^(www\\.google\\.com|www\\.gstatic\\.com|www\\.recaptcha\\.net|recaptcha\\.google\\.com)/recaptcha/", "verdict": "presence"}
|
|
103
|
+
]
|
|
104
|
+
},
|
|
105
|
+
"arkose": {
|
|
106
|
+
"unresolved": "unknown",
|
|
107
|
+
"rules": [
|
|
108
|
+
{"url": "(arkoselabs|funcaptcha)\\.com/fc/gt2/", "body": "\\|sup=1", "verdict": "success"},
|
|
109
|
+
{"url": "(arkoselabs|funcaptcha)\\.com/fc/gt2/", "body": "\"token\"", "verdict": "challenge"},
|
|
110
|
+
{"url": "(arkoselabs|funcaptcha)\\.com/", "verdict": "presence"}
|
|
111
|
+
]
|
|
112
|
+
},
|
|
113
|
+
"queueit": {
|
|
114
|
+
"unresolved": "unknown",
|
|
115
|
+
"rules": [
|
|
116
|
+
{"url": "queue-it\\.net/softblock", "verdict": "challenge"},
|
|
117
|
+
{"document": true, "url": "queue-it\\.net/", "status": ["4xx"], "verdict": "block"},
|
|
118
|
+
{"document": true, "url": "queue-it\\.net/", "status": ["2xx"], "verdict": "success"},
|
|
119
|
+
{"url": "queue-it\\.net/", "verdict": "presence"}
|
|
120
|
+
]
|
|
121
|
+
},
|
|
122
|
+
"shape": {
|
|
123
|
+
"unresolved": "unknown",
|
|
124
|
+
"rules": [
|
|
125
|
+
{"request_header_name": "^x-[a-z0-9]{8}-[abcdfz]$", "verdict": "presence"}
|
|
126
|
+
]
|
|
127
|
+
},
|
|
128
|
+
"threatmetrix": {
|
|
129
|
+
"unresolved": "unknown",
|
|
130
|
+
"rules": [
|
|
131
|
+
{"url": "(^|\\.)online-metrix\\.net/|/fp/(tags|check|clear)\\.js$", "verdict": "presence"}
|
|
132
|
+
]
|
|
133
|
+
},
|
|
134
|
+
"botguard": {
|
|
135
|
+
"unresolved": "unknown",
|
|
136
|
+
"rules": [
|
|
137
|
+
{"url": "^www\\.google\\.com/js/bg/", "verdict": "presence"}
|
|
138
|
+
]
|
|
139
|
+
}
|
|
140
|
+
},
|
|
141
|
+
"multi_label_suffixes": [
|
|
142
|
+
"co.uk", "org.uk", "ac.uk", "gov.uk", "com.au", "net.au", "org.au", "co.nz", "co.jp", "ne.jp", "or.jp",
|
|
143
|
+
"co.kr", "co.in", "net.in", "com.br", "com.ar", "com.mx", "com.cn", "net.cn", "com.hk", "com.tw", "com.sg",
|
|
144
|
+
"com.tr", "com.ua", "co.za", "co.il", "com.pl", "com.ru", "com.vn", "com.my", "co.id", "com.ph"
|
|
145
|
+
]
|
|
146
|
+
}
|
package/dist/data.js
CHANGED
package/dist/geolocation.d.ts
CHANGED
|
@@ -46,8 +46,9 @@ export declare function warnIfDeprecated(config: GeoIPRepo): void;
|
|
|
46
46
|
/**
|
|
47
47
|
* Load the active GeoIP config from disk, falling back to the geoip.yml default.
|
|
48
48
|
*
|
|
49
|
-
* A saved
|
|
50
|
-
* cache written before the default changed)
|
|
49
|
+
* A saved source the user did not pick explicitly resolves to the default
|
|
50
|
+
* when it is deprecated (every cache written before the default changed) or
|
|
51
|
+
* no longer in geoip.yml. One picked explicitly and gone throws.
|
|
51
52
|
*/
|
|
52
53
|
export declare function loadGeoipConfig(): GeoIPRepo;
|
|
53
54
|
/**
|
package/dist/geolocation.js
CHANGED
|
@@ -119,19 +119,18 @@ export function warnIfDeprecated(config) {
|
|
|
119
119
|
/**
|
|
120
120
|
* Load the active GeoIP config from disk, falling back to the geoip.yml default.
|
|
121
121
|
*
|
|
122
|
-
* A saved
|
|
123
|
-
* cache written before the default changed)
|
|
122
|
+
* A saved source the user did not pick explicitly resolves to the default
|
|
123
|
+
* when it is deprecated (every cache written before the default changed) or
|
|
124
|
+
* no longer in geoip.yml. One picked explicitly and gone throws.
|
|
124
125
|
*/
|
|
125
126
|
export function loadGeoipConfig() {
|
|
126
127
|
if (fs.existsSync(GEOIP_CONFIG)) {
|
|
127
128
|
const saved = parseYaml(fs.readFileSync(GEOIP_CONFIG, "utf-8")) ?? {};
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
return saved;
|
|
134
|
-
}
|
|
129
|
+
const known = loadGeoipRepos()[0].map((r) => (r.name ?? "").toLowerCase());
|
|
130
|
+
const name = saved.explicit || known.includes(String(saved.name ?? "").toLowerCase())
|
|
131
|
+
? saved.name
|
|
132
|
+
: undefined;
|
|
133
|
+
const config = getGeoipConfigByName(name);
|
|
135
134
|
if (config.deprecated && !saved.explicit) {
|
|
136
135
|
return getGeoipConfigByName(undefined);
|
|
137
136
|
}
|
package/dist/host.d.ts
CHANGED
|
@@ -7,3 +7,5 @@ export declare const OS_NAME: "mac" | "win" | "lin";
|
|
|
7
7
|
* hosts that set XDG_CACHE_HOME, and on macOS/Windows entirely.
|
|
8
8
|
*/
|
|
9
9
|
export declare function userCacheDir(appName: string): string;
|
|
10
|
+
/** platformdirs' user_config_dir(appName), so both launchers read one defaults file. */
|
|
11
|
+
export declare function userConfigDir(appName: string): string;
|
package/dist/host.js
CHANGED
|
@@ -47,3 +47,19 @@ export function userCacheDir(appName) {
|
|
|
47
47
|
const base = xdg.trim() ? xdg : path.join(os.homedir(), ".cache");
|
|
48
48
|
return path.join(base, appName);
|
|
49
49
|
}
|
|
50
|
+
/** platformdirs' user_config_dir(appName), so both launchers read one defaults file. */
|
|
51
|
+
export function userConfigDir(appName) {
|
|
52
|
+
if (OS_NAME === "win") {
|
|
53
|
+
const localAppData = process.env.LOCALAPPDATA;
|
|
54
|
+
const base = localAppData && path.isAbsolute(localAppData)
|
|
55
|
+
? localAppData
|
|
56
|
+
: path.join(os.homedir(), "AppData", "Local");
|
|
57
|
+
return path.join(base, appName, appName);
|
|
58
|
+
}
|
|
59
|
+
if (OS_NAME === "mac") {
|
|
60
|
+
return path.join(os.homedir(), "Library", "Application Support", appName);
|
|
61
|
+
}
|
|
62
|
+
const xdg = process.env.XDG_CONFIG_HOME ?? "";
|
|
63
|
+
const base = xdg.trim() ? xdg : path.join(os.homedir(), ".config");
|
|
64
|
+
return path.join(base, appName);
|
|
65
|
+
}
|
package/dist/ip.d.ts
CHANGED
|
@@ -18,6 +18,20 @@ export declare function validIPv6(ip: string | false): boolean;
|
|
|
18
18
|
export declare function validateIP(ip: string): void;
|
|
19
19
|
export declare const DIRECT_IP_TIMEOUT_MS = 5000;
|
|
20
20
|
export declare const PROXIED_IP_TIMEOUT_MS = 15000;
|
|
21
|
+
/** Where a proxy exits: its IP and that IP's timezone, country and position. */
|
|
22
|
+
export interface ExitGeo {
|
|
23
|
+
ip: string;
|
|
24
|
+
timezone: string;
|
|
25
|
+
country: string;
|
|
26
|
+
latitude: number;
|
|
27
|
+
longitude: number;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Where `proxy` exits, looked up through the proxy. Throws InvalidIP when the
|
|
31
|
+
* lookup fails: a context that silently kept the host's WebRTC IP and timezone
|
|
32
|
+
* behind a proxy would be a leak.
|
|
33
|
+
*/
|
|
34
|
+
export declare function proxyExitGeo(proxy: string): Promise<ExitGeo>;
|
|
21
35
|
/** Sends a request to a public IP api. */
|
|
22
36
|
export declare function publicIP(proxy?: string): Promise<string>;
|
|
23
37
|
/**
|
package/dist/ip.js
CHANGED
|
@@ -71,21 +71,30 @@ function once(timeoutMs, what, run) {
|
|
|
71
71
|
});
|
|
72
72
|
});
|
|
73
73
|
}
|
|
74
|
+
/** Where an HTTP(S) proxy listens. */
|
|
75
|
+
function proxyEndpoint(proxy) {
|
|
76
|
+
return {
|
|
77
|
+
host: proxy.hostname.replace(/^\[(.*)\]$/, "$1"),
|
|
78
|
+
port: proxy.port || (proxy.protocol === "https:" ? 443 : 80),
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
/** Basic auth for an HTTP(S) proxy, when its URL carries credentials. */
|
|
82
|
+
function proxyAuthorization(proxy) {
|
|
83
|
+
if (!proxy.username)
|
|
84
|
+
return {};
|
|
85
|
+
const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;
|
|
86
|
+
return {
|
|
87
|
+
"Proxy-Authorization": `Basic ${Buffer.from(auth).toString("base64")}`,
|
|
88
|
+
};
|
|
89
|
+
}
|
|
74
90
|
/** A TCP stream to host:port through an HTTP(S) proxy's CONNECT. */
|
|
75
91
|
function connectTunnel(proxy, host, port, timeoutMs) {
|
|
76
92
|
return once(timeoutMs, "proxy CONNECT", (resolve, reject) => {
|
|
77
|
-
const headers = { Host: `${host}:${port}` };
|
|
78
|
-
if (proxy.username) {
|
|
79
|
-
const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;
|
|
80
|
-
headers["Proxy-Authorization"] =
|
|
81
|
-
`Basic ${Buffer.from(auth).toString("base64")}`;
|
|
82
|
-
}
|
|
83
93
|
const request = (proxy.protocol === "https:" ? https : http).request({
|
|
84
|
-
|
|
85
|
-
port: proxy.port || (proxy.protocol === "https:" ? 443 : 80),
|
|
94
|
+
...proxyEndpoint(proxy),
|
|
86
95
|
method: "CONNECT",
|
|
87
96
|
path: `${host}:${port}`,
|
|
88
|
-
headers,
|
|
97
|
+
headers: { Host: `${host}:${port}`, ...proxyAuthorization(proxy) },
|
|
89
98
|
});
|
|
90
99
|
request.on("connect", (response, socket) => {
|
|
91
100
|
if (response.statusCode === 200)
|
|
@@ -185,14 +194,15 @@ function connectSocks5(proxy, host, port, timeoutMs) {
|
|
|
185
194
|
socket.on("data", onData);
|
|
186
195
|
});
|
|
187
196
|
}
|
|
188
|
-
function
|
|
189
|
-
let url;
|
|
197
|
+
function parseProxy(proxy) {
|
|
190
198
|
try {
|
|
191
|
-
|
|
199
|
+
return new URL(proxy);
|
|
192
200
|
}
|
|
193
201
|
catch (error) {
|
|
194
202
|
throw new InvalidProxy(`Invalid proxy server: ${proxy}`, { cause: error });
|
|
195
203
|
}
|
|
204
|
+
}
|
|
205
|
+
function proxySocket(url, host, port, timeoutMs) {
|
|
196
206
|
switch (url.protocol) {
|
|
197
207
|
case "http:":
|
|
198
208
|
case "https:":
|
|
@@ -205,22 +215,47 @@ function proxySocket(proxy, host, port, timeoutMs) {
|
|
|
205
215
|
"Supported: http, https, socks5.");
|
|
206
216
|
}
|
|
207
217
|
}
|
|
208
|
-
/**
|
|
209
|
-
|
|
218
|
+
/**
|
|
219
|
+
* GET a URL's body, directly or through `proxy`, as requests.get() sends it:
|
|
220
|
+
* https is tunnelled and its certificate verified; plain http goes to an
|
|
221
|
+
* HTTP(S) proxy in absolute form, and through a SOCKS5 tunnel otherwise.
|
|
222
|
+
*/
|
|
223
|
+
async function getText(url, proxy) {
|
|
210
224
|
const timeoutMs = proxy ? PROXIED_IP_TIMEOUT_MS : DIRECT_IP_TIMEOUT_MS;
|
|
211
225
|
const target = new URL(url);
|
|
212
|
-
const
|
|
226
|
+
const secure = target.protocol === "https:";
|
|
227
|
+
const options = {
|
|
228
|
+
agent: false,
|
|
229
|
+
headers: { Connection: "close" },
|
|
230
|
+
};
|
|
231
|
+
let client = secure ? https : http;
|
|
213
232
|
let socket;
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
233
|
+
const proxyUrl = proxy ? parseProxy(proxy) : undefined;
|
|
234
|
+
if (proxyUrl && !secure && proxyUrl.protocol.startsWith("http")) {
|
|
235
|
+
client = proxyUrl.protocol === "https:" ? https : http;
|
|
236
|
+
Object.assign(options, proxyEndpoint(proxyUrl), {
|
|
237
|
+
path: url,
|
|
238
|
+
headers: {
|
|
239
|
+
...options.headers,
|
|
240
|
+
Host: target.host,
|
|
241
|
+
...proxyAuthorization(proxyUrl),
|
|
242
|
+
},
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
else if (proxyUrl) {
|
|
246
|
+
const port = Number(target.port || (secure ? 443 : 80));
|
|
247
|
+
const raw = await proxySocket(proxyUrl, target.hostname, port, timeoutMs);
|
|
248
|
+
const stream = secure
|
|
249
|
+
? tls.connect({ socket: raw, servername: target.hostname })
|
|
250
|
+
: raw;
|
|
251
|
+
socket = stream;
|
|
252
|
+
// Node ignores createConnection when an agent is given, `false`
|
|
253
|
+
// included, and would connect to the target itself, around the proxy.
|
|
254
|
+
options.agent = undefined;
|
|
255
|
+
options.createConnection = () => stream;
|
|
217
256
|
}
|
|
218
257
|
return once(timeoutMs, `GET ${url}`, (resolve, reject) => {
|
|
219
|
-
const
|
|
220
|
-
agent: false,
|
|
221
|
-
headers: { Connection: "close" },
|
|
222
|
-
...(socket ? { createConnection: () => socket } : {}),
|
|
223
|
-
}, (response) => {
|
|
258
|
+
const onResponse = (response) => {
|
|
224
259
|
const chunks = [];
|
|
225
260
|
response.on("data", (chunk) => chunks.push(chunk));
|
|
226
261
|
response.on("error", reject);
|
|
@@ -233,10 +268,45 @@ async function httpsGetText(url, proxy) {
|
|
|
233
268
|
else
|
|
234
269
|
resolve(Buffer.concat(chunks).toString("utf8"));
|
|
235
270
|
});
|
|
236
|
-
}
|
|
271
|
+
};
|
|
272
|
+
const request = options.path
|
|
273
|
+
? client.get(options, onResponse)
|
|
274
|
+
: client.get(url, options, onResponse);
|
|
237
275
|
request.on("error", reject);
|
|
238
276
|
}).finally(() => socket?.destroy());
|
|
239
277
|
}
|
|
278
|
+
const PROXY_LOOKUP_FAILED = "Could not look up where the proxy exits. Pass webrtc_ip, timezoneId, " +
|
|
279
|
+
"locale and geolocation explicitly to skip the lookup";
|
|
280
|
+
/**
|
|
281
|
+
* Where `proxy` exits, looked up through the proxy. Throws InvalidIP when the
|
|
282
|
+
* lookup fails: a context that silently kept the host's WebRTC IP and timezone
|
|
283
|
+
* behind a proxy would be a leak.
|
|
284
|
+
*/
|
|
285
|
+
export async function proxyExitGeo(proxy) {
|
|
286
|
+
let data;
|
|
287
|
+
try {
|
|
288
|
+
data = JSON.parse(await getText("http://ip-api.com/json?fields=status,message,query,timezone,countryCode,lat,lon", proxy));
|
|
289
|
+
}
|
|
290
|
+
catch (error) {
|
|
291
|
+
throw new InvalidIP(`${PROXY_LOOKUP_FAILED}: ${error}`, { cause: error });
|
|
292
|
+
}
|
|
293
|
+
if (data.status !== "success" ||
|
|
294
|
+
!data.query ||
|
|
295
|
+
!data.timezone ||
|
|
296
|
+
!data.countryCode ||
|
|
297
|
+
data.lat == null ||
|
|
298
|
+
data.lon == null) {
|
|
299
|
+
throw new InvalidIP(`${PROXY_LOOKUP_FAILED}: ${data.message ?? JSON.stringify(data)}`);
|
|
300
|
+
}
|
|
301
|
+
validateIP(data.query);
|
|
302
|
+
return {
|
|
303
|
+
ip: data.query,
|
|
304
|
+
timezone: data.timezone,
|
|
305
|
+
country: data.countryCode,
|
|
306
|
+
latitude: data.lat,
|
|
307
|
+
longitude: data.lon,
|
|
308
|
+
};
|
|
309
|
+
}
|
|
240
310
|
const PUBLIC_IP_URLS = [
|
|
241
311
|
// Prefers IPv4
|
|
242
312
|
"https://api.ipify.org",
|
|
@@ -273,7 +343,7 @@ export function publicIPv6() {
|
|
|
273
343
|
publicIPv6Cache ??= (async () => {
|
|
274
344
|
for (const url of ["https://api6.ipify.org", "https://v6.ident.me"]) {
|
|
275
345
|
try {
|
|
276
|
-
const ip = (await
|
|
346
|
+
const ip = (await getText(url)).trim();
|
|
277
347
|
if (validIPv6(ip))
|
|
278
348
|
return ip;
|
|
279
349
|
}
|
|
@@ -287,7 +357,7 @@ async function resolvePublicIP(proxy) {
|
|
|
287
357
|
let endException;
|
|
288
358
|
for (const url of PUBLIC_IP_URLS) {
|
|
289
359
|
try {
|
|
290
|
-
const ip = (await
|
|
360
|
+
const ip = (await getText(url, proxy)).trim();
|
|
291
361
|
validateIP(ip);
|
|
292
362
|
return ip;
|
|
293
363
|
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Passthrough: launch the browser as this machine's own, with no fingerprint injected.
|
|
3
|
+
*
|
|
4
|
+
* TypeScript twin of python/src/camoucore/passthrough.py. A passthrough launch
|
|
5
|
+
* draws no identity and sends the browser no fingerprint config; behaviour
|
|
6
|
+
* options (proxy, humanize, block_images, addons, a virtual display) still apply.
|
|
7
|
+
*/
|
|
8
|
+
import type { Product } from "./product.js";
|
|
9
|
+
/** Launch options that set or constrain an injected fingerprint (snake_case, as the launchers take them). */
|
|
10
|
+
export declare const IDENTITY_OPTIONS: readonly ["config", "os", "fingerprint", "fingerprint_preset", "webgl_config", "cpu", "screen", "window", "fonts", "custom_fonts_only", "locale", "geoip", "canvas_noise", "pin_cpu_cores", "allow_os_mismatch", "ff_version", "chrome_version"];
|
|
11
|
+
/** The identity options set in `options`, in IDENTITY_OPTIONS order. */
|
|
12
|
+
export declare function passthroughConflicts(options: Record<string, unknown>): string[];
|
|
13
|
+
/** Throw naming every identity option set alongside passthrough: true. */
|
|
14
|
+
export declare function checkPassthrough(product: Product, options: Record<string, unknown>): void;
|
|
15
|
+
/** A proxied passthrough launch reports this machine's timezone and languages. */
|
|
16
|
+
export declare function warnPassthrough(product: Product, proxy: unknown, iKnowWhatImDoing?: boolean): void;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { LeakWarning } from "./warnings.js";
|
|
2
|
+
/** Launch options that set or constrain an injected fingerprint (snake_case, as the launchers take them). */
|
|
3
|
+
export const IDENTITY_OPTIONS = [
|
|
4
|
+
"config",
|
|
5
|
+
"os",
|
|
6
|
+
"fingerprint",
|
|
7
|
+
"fingerprint_preset",
|
|
8
|
+
"webgl_config",
|
|
9
|
+
"cpu",
|
|
10
|
+
"screen",
|
|
11
|
+
"window",
|
|
12
|
+
"fonts",
|
|
13
|
+
"custom_fonts_only",
|
|
14
|
+
"locale",
|
|
15
|
+
"geoip",
|
|
16
|
+
"canvas_noise",
|
|
17
|
+
"pin_cpu_cores",
|
|
18
|
+
"allow_os_mismatch",
|
|
19
|
+
"ff_version",
|
|
20
|
+
"chrome_version",
|
|
21
|
+
];
|
|
22
|
+
function isSet(value) {
|
|
23
|
+
if (value === undefined || value === null || value === false)
|
|
24
|
+
return false;
|
|
25
|
+
if (Array.isArray(value))
|
|
26
|
+
return value.length > 0;
|
|
27
|
+
if (typeof value === "object")
|
|
28
|
+
return Object.keys(value).length > 0;
|
|
29
|
+
return true;
|
|
30
|
+
}
|
|
31
|
+
/** The identity options set in `options`, in IDENTITY_OPTIONS order. */
|
|
32
|
+
export function passthroughConflicts(options) {
|
|
33
|
+
return IDENTITY_OPTIONS.filter((name) => isSet(options[name]));
|
|
34
|
+
}
|
|
35
|
+
/** Throw naming every identity option set alongside passthrough: true. */
|
|
36
|
+
export function checkPassthrough(product, options) {
|
|
37
|
+
const conflicts = passthroughConflicts(options);
|
|
38
|
+
if (conflicts.length) {
|
|
39
|
+
throw new Error(`passthrough=True launches ${product.title} with this machine's own fingerprint, so it ` +
|
|
40
|
+
`cannot be combined with options that inject one: ${conflicts.join(", ")}. ` +
|
|
41
|
+
"Remove them, or set passthrough=False.");
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/** A proxied passthrough launch reports this machine's timezone and languages. */
|
|
45
|
+
export function warnPassthrough(product, proxy, iKnowWhatImDoing) {
|
|
46
|
+
if (proxy) {
|
|
47
|
+
LeakWarning.warn(`passthrough=True with a proxy: ${product.title} reports this machine's timezone, ` +
|
|
48
|
+
"languages and locale, which can disagree with where the proxy exits.", iKnowWhatImDoing);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { Product } from "./product.js";
|
|
2
|
+
/** Where a user's own defaults live: `<NAME>_DEFAULTS`, or the user config directory. */
|
|
3
|
+
export declare function userDefaultsPath(product: Product): string;
|
|
4
|
+
/**
|
|
5
|
+
* The launch defaults: the packaged file's, overlaid with the user's own file
|
|
6
|
+
* when it exists. An unknown option or a wrong type in the user's file throws.
|
|
7
|
+
*/
|
|
8
|
+
export declare function loadDefaults(product: Product, packaged: string, userFile?: string): Record<string, unknown>;
|
|
9
|
+
/** `options` with each one the caller left unset (null or undefined) taken from `defaults`. */
|
|
10
|
+
export declare function applyDefaults<T extends Record<string, unknown>>(defaults: Record<string, unknown>, options: T): T;
|
|
11
|
+
/** Copy the packaged defaults file to the user's path unless one is there; return that path. */
|
|
12
|
+
export declare function writeUserDefaults(product: Product, packaged: string): string;
|
package/dist/settings.js
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A launcher's defaults file: the values every launch starts from.
|
|
3
|
+
*
|
|
4
|
+
* TypeScript twin of python/src/camoucore/settings.py. The packaged
|
|
5
|
+
* `<name>.defaults.json` documents each option as
|
|
6
|
+
* `{"default": ..., "about": "...", "examples": [...]}`; a user's file of the
|
|
7
|
+
* same shape, or the short form `{"telemetry": false}`, overrides it. A value
|
|
8
|
+
* a caller passes to the launch wins over both.
|
|
9
|
+
*/
|
|
10
|
+
import fs from "node:fs";
|
|
11
|
+
import os from "node:os";
|
|
12
|
+
import path from "node:path";
|
|
13
|
+
import { userConfigDir } from "./host.js";
|
|
14
|
+
/** Where a user's own defaults live: `<NAME>_DEFAULTS`, or the user config directory. */
|
|
15
|
+
export function userDefaultsPath(product) {
|
|
16
|
+
const override = product.getenv("DEFAULTS");
|
|
17
|
+
if (override)
|
|
18
|
+
return override.replace(/^~(?=$|[\\/])/, os.homedir());
|
|
19
|
+
return path.join(userConfigDir(product.name), "defaults.json");
|
|
20
|
+
}
|
|
21
|
+
function read(file) {
|
|
22
|
+
let data;
|
|
23
|
+
try {
|
|
24
|
+
data = JSON.parse(fs.readFileSync(file, "utf-8"));
|
|
25
|
+
}
|
|
26
|
+
catch (e) {
|
|
27
|
+
if (e instanceof SyntaxError)
|
|
28
|
+
throw new Error(`${file} is not valid JSON: ${e.message}`);
|
|
29
|
+
throw e;
|
|
30
|
+
}
|
|
31
|
+
if (!data || typeof data !== "object" || Array.isArray(data))
|
|
32
|
+
throw new Error(`${file} must hold a JSON object of option names`);
|
|
33
|
+
return data;
|
|
34
|
+
}
|
|
35
|
+
const skipped = (name) => name.startsWith("$") || name.startsWith("_");
|
|
36
|
+
const typeName = (v) => Array.isArray(v) ? "array" : v === null ? "null" : typeof v;
|
|
37
|
+
function documentedDefaults(file) {
|
|
38
|
+
const out = {};
|
|
39
|
+
for (const [name, entry] of Object.entries(read(file))) {
|
|
40
|
+
if (skipped(name))
|
|
41
|
+
continue;
|
|
42
|
+
const e = entry;
|
|
43
|
+
if (!e || typeof e !== "object" || !("default" in e) || !e.about)
|
|
44
|
+
throw new Error(`${file}: "${name}" needs a "default" and an "about"`);
|
|
45
|
+
out[name] = e.default;
|
|
46
|
+
}
|
|
47
|
+
return out;
|
|
48
|
+
}
|
|
49
|
+
function userValues(file, known) {
|
|
50
|
+
const out = {};
|
|
51
|
+
for (const [name, entry] of Object.entries(read(file))) {
|
|
52
|
+
if (skipped(name))
|
|
53
|
+
continue;
|
|
54
|
+
if (!(name in known))
|
|
55
|
+
throw new Error(`${file}: "${name}" is not an option of the defaults file (${Object.keys(known).join(", ")})`);
|
|
56
|
+
const value = entry && typeof entry === "object" && "default" in entry
|
|
57
|
+
? entry.default
|
|
58
|
+
: entry;
|
|
59
|
+
const expected = known[name];
|
|
60
|
+
if (expected !== null &&
|
|
61
|
+
value !== null &&
|
|
62
|
+
typeName(value) !== typeName(expected))
|
|
63
|
+
throw new Error(`${file}: "${name}" is ${typeName(value)}, but its default is ${typeName(expected)}`);
|
|
64
|
+
out[name] = value;
|
|
65
|
+
}
|
|
66
|
+
return out;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* The launch defaults: the packaged file's, overlaid with the user's own file
|
|
70
|
+
* when it exists. An unknown option or a wrong type in the user's file throws.
|
|
71
|
+
*/
|
|
72
|
+
export function loadDefaults(product, packaged, userFile) {
|
|
73
|
+
const defaults = documentedDefaults(packaged);
|
|
74
|
+
const file = userFile ?? userDefaultsPath(product);
|
|
75
|
+
if (fs.existsSync(file) && fs.statSync(file).isFile())
|
|
76
|
+
Object.assign(defaults, userValues(file, defaults));
|
|
77
|
+
return defaults;
|
|
78
|
+
}
|
|
79
|
+
/** `options` with each one the caller left unset (null or undefined) taken from `defaults`. */
|
|
80
|
+
export function applyDefaults(defaults, options) {
|
|
81
|
+
const out = { ...options };
|
|
82
|
+
for (const [name, value] of Object.entries(defaults))
|
|
83
|
+
if (out[name] === undefined || out[name] === null)
|
|
84
|
+
out[name] = value;
|
|
85
|
+
return out;
|
|
86
|
+
}
|
|
87
|
+
/** Copy the packaged defaults file to the user's path unless one is there; return that path. */
|
|
88
|
+
export function writeUserDefaults(product, packaged) {
|
|
89
|
+
const file = userDefaultsPath(product);
|
|
90
|
+
if (!fs.existsSync(file)) {
|
|
91
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
92
|
+
fs.copyFileSync(packaged, file);
|
|
93
|
+
}
|
|
94
|
+
return file;
|
|
95
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import type { Product } from "./product.js";
|
|
2
|
+
export declare const DEFAULT_ENDPOINT = "https://api.camoufox.com/v1/telemetry/antibot";
|
|
3
|
+
export declare const SCHEMA = 1;
|
|
4
|
+
export declare const OUTCOMES: readonly ["success", "challenge", "block", "unknown"];
|
|
5
|
+
export type Outcome = (typeof OUTCOMES)[number];
|
|
6
|
+
export type Counts = Record<string, Record<Outcome, number>>;
|
|
7
|
+
export declare const FLUSH_INTERVAL_MS = 600000;
|
|
8
|
+
export declare const SEND_TIMEOUT_MS = 3000;
|
|
9
|
+
export declare const BODY_LIMIT = 65536;
|
|
10
|
+
export declare const RULES_DATA: any;
|
|
11
|
+
/** Whether to report: the launch's setting, unless the environment turns it off. */
|
|
12
|
+
export declare function telemetryEnabled(product: Product, setting: boolean | null | undefined): boolean;
|
|
13
|
+
/** The domain a business registers: 'gate.example.co.uk' -> 'example.co.uk'. */
|
|
14
|
+
export declare function registrableDomain(host: string): string;
|
|
15
|
+
export type ProxySetting = null | undefined | string | {
|
|
16
|
+
server?: string;
|
|
17
|
+
[key: string]: unknown;
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* The proxy provider's registrable domain, and nothing else of the proxy:
|
|
21
|
+
* 'none' without one, 'ip-address' for a bare IP, 'self-hosted' for a
|
|
22
|
+
* loopback, private or tailnet host.
|
|
23
|
+
*/
|
|
24
|
+
export declare function proxyProvider(proxy: ProxySetting): string;
|
|
25
|
+
/** What a rule may look at: one response, reduced to the fields rules test. */
|
|
26
|
+
export interface ResponseView {
|
|
27
|
+
url: string;
|
|
28
|
+
method: string;
|
|
29
|
+
status: number;
|
|
30
|
+
/** Lower-case names. */
|
|
31
|
+
headers: Record<string, string>;
|
|
32
|
+
document: boolean;
|
|
33
|
+
requestHeaderNames?: Iterable<string>;
|
|
34
|
+
/** With set-cookie, fetched on demand. */
|
|
35
|
+
allHeaders?: Record<string, string>;
|
|
36
|
+
/** Fetched on demand. */
|
|
37
|
+
body?: string;
|
|
38
|
+
}
|
|
39
|
+
/** A rule's other conditions hold, and it needs these to decide. */
|
|
40
|
+
export interface Need {
|
|
41
|
+
need: true;
|
|
42
|
+
headers: boolean;
|
|
43
|
+
body: boolean;
|
|
44
|
+
}
|
|
45
|
+
/** provider, verdict, transient, opens */
|
|
46
|
+
export type Observation = [string, string, boolean, boolean];
|
|
47
|
+
interface CompiledRule {
|
|
48
|
+
verdict: string;
|
|
49
|
+
transient: boolean;
|
|
50
|
+
opens: boolean;
|
|
51
|
+
document: boolean;
|
|
52
|
+
edge: boolean;
|
|
53
|
+
method?: string;
|
|
54
|
+
status?: string[];
|
|
55
|
+
url?: RegExp;
|
|
56
|
+
query: [string, RegExp][];
|
|
57
|
+
headers: [string, RegExp][];
|
|
58
|
+
body?: RegExp;
|
|
59
|
+
requestHeaderName?: RegExp;
|
|
60
|
+
}
|
|
61
|
+
interface CompiledProvider {
|
|
62
|
+
edge: [RegExp, RegExp | null][];
|
|
63
|
+
rules: CompiledRule[];
|
|
64
|
+
unresolved: Outcome;
|
|
65
|
+
}
|
|
66
|
+
export declare class Rules {
|
|
67
|
+
readonly providers: Map<string, CompiledProvider>;
|
|
68
|
+
constructor(data?: any);
|
|
69
|
+
private static isEdge;
|
|
70
|
+
/** The observations this response makes, or what has to be fetched first. */
|
|
71
|
+
classify(view: ResponseView): Need | Observation[];
|
|
72
|
+
unresolved(provider: string): Outcome;
|
|
73
|
+
}
|
|
74
|
+
/** Encounters in progress and the outcome counts of finished ones. */
|
|
75
|
+
export declare class Tally {
|
|
76
|
+
readonly rules: Rules;
|
|
77
|
+
private counts;
|
|
78
|
+
private readonly open;
|
|
79
|
+
constructor(rules: Rules);
|
|
80
|
+
observe(page: unknown, site: string, observation: Observation): void;
|
|
81
|
+
/** A page's main frame now shows `site`: encounters on another site are over. */
|
|
82
|
+
navigated(page: unknown, site: string): void;
|
|
83
|
+
closePage(page: unknown): void;
|
|
84
|
+
closeAll(): void;
|
|
85
|
+
/** The finished counts, reset. */
|
|
86
|
+
take(): Counts;
|
|
87
|
+
private finish;
|
|
88
|
+
}
|
|
89
|
+
export type Sender = (url: string, payload: object) => Promise<void>;
|
|
90
|
+
export interface TelemetryOptions {
|
|
91
|
+
version: string;
|
|
92
|
+
browserVersion: string;
|
|
93
|
+
pro: boolean;
|
|
94
|
+
crossOs: boolean;
|
|
95
|
+
passthrough: boolean;
|
|
96
|
+
proxy: ProxySetting;
|
|
97
|
+
rules?: Rules;
|
|
98
|
+
send?: Sender;
|
|
99
|
+
/** 0 turns the periodic flush off. */
|
|
100
|
+
intervalMs?: number;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* One launch's reporter. A launcher creates it when telemetry is enabled,
|
|
104
|
+
* hands it each browser context with `watch`, and awaits `close` when the
|
|
105
|
+
* browser closes. Counts are sent every FLUSH_INTERVAL_MS and at close.
|
|
106
|
+
*/
|
|
107
|
+
export declare class Telemetry {
|
|
108
|
+
readonly endpoint: string;
|
|
109
|
+
readonly dimensions: Record<string, string | boolean>;
|
|
110
|
+
readonly rules: Rules;
|
|
111
|
+
readonly tally: Tally;
|
|
112
|
+
private readonly send;
|
|
113
|
+
private readonly timer?;
|
|
114
|
+
private closed;
|
|
115
|
+
private readonly onExit;
|
|
116
|
+
constructor(product: Product, options: TelemetryOptions);
|
|
117
|
+
payload(counts: Counts): object;
|
|
118
|
+
flush(): Promise<void>;
|
|
119
|
+
/** Count every open encounter and send what is left. Safe to call twice. */
|
|
120
|
+
close(): Promise<void>;
|
|
121
|
+
/** Listen to a Playwright BrowserContext. */
|
|
122
|
+
watch(context: any): void;
|
|
123
|
+
/** Count and send everything when the browser closes or disconnects. */
|
|
124
|
+
watchBrowser(browser: any): void;
|
|
125
|
+
private watchPage;
|
|
126
|
+
private onResponse;
|
|
127
|
+
}
|
|
128
|
+
export {};
|
|
@@ -0,0 +1,425 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Proxy telemetry: how often anti-bot providers let a launch through, challenge
|
|
3
|
+
* it or block it, counted per provider and reported with the proxy provider's
|
|
4
|
+
* domain.
|
|
5
|
+
*
|
|
6
|
+
* TypeScript twin of python/src/camoucore/telemetry.py, which documents what is
|
|
7
|
+
* collected and what never is. In short: outcome counts per anti-bot provider
|
|
8
|
+
* and the launch's dimensions (launcher, versions, Pro, cross-OS, passthrough,
|
|
9
|
+
* proxy provider domain). Never a URL, site, page content, cookie, header
|
|
10
|
+
* value, IP address, proxy credential, or any identifier of the user.
|
|
11
|
+
*
|
|
12
|
+
* Off with `telemetry: false`, `<NAME>_TELEMETRY=0`, or `DO_NOT_TRACK=1`.
|
|
13
|
+
*/
|
|
14
|
+
import * as net from "node:net";
|
|
15
|
+
import { loadDataFile } from "./data.js";
|
|
16
|
+
export const DEFAULT_ENDPOINT = "https://api.camoufox.com/v1/telemetry/antibot";
|
|
17
|
+
export const SCHEMA = 1;
|
|
18
|
+
export const OUTCOMES = ["success", "challenge", "block", "unknown"];
|
|
19
|
+
export const FLUSH_INTERVAL_MS = 600_000;
|
|
20
|
+
export const SEND_TIMEOUT_MS = 3_000;
|
|
21
|
+
export const BODY_LIMIT = 65536;
|
|
22
|
+
const OFF = new Set(["0", "false", "off", "no"]);
|
|
23
|
+
export const RULES_DATA = loadDataFile("antibot-rules.json");
|
|
24
|
+
/** Whether to report: the launch's setting, unless the environment turns it off. */
|
|
25
|
+
export function telemetryEnabled(product, setting) {
|
|
26
|
+
if (setting === false)
|
|
27
|
+
return false;
|
|
28
|
+
if (OFF.has((product.getenv("TELEMETRY") ?? "").trim().toLowerCase()))
|
|
29
|
+
return false;
|
|
30
|
+
const dnt = (process.env.DO_NOT_TRACK ?? "").trim().toLowerCase();
|
|
31
|
+
return !(dnt && !OFF.has(dnt));
|
|
32
|
+
}
|
|
33
|
+
// ---------------------------------------------------------------- domains
|
|
34
|
+
const SUFFIXES = new Set(RULES_DATA.multi_label_suffixes);
|
|
35
|
+
/** The domain a business registers: 'gate.example.co.uk' -> 'example.co.uk'. */
|
|
36
|
+
export function registrableDomain(host) {
|
|
37
|
+
const labels = host.toLowerCase().replace(/\.$/, "").split(".");
|
|
38
|
+
const keep = SUFFIXES.has(labels.slice(-2).join(".")) ? 3 : 2;
|
|
39
|
+
return labels.slice(-keep).join(".");
|
|
40
|
+
}
|
|
41
|
+
// Loopback, private, link-local, carrier-grade NAT (tailnets) and unique-local.
|
|
42
|
+
const SELF_HOSTED = new net.BlockList();
|
|
43
|
+
for (const [address, prefix] of [
|
|
44
|
+
["127.0.0.0", 8],
|
|
45
|
+
["10.0.0.0", 8],
|
|
46
|
+
["172.16.0.0", 12],
|
|
47
|
+
["192.168.0.0", 16],
|
|
48
|
+
["169.254.0.0", 16],
|
|
49
|
+
["100.64.0.0", 10],
|
|
50
|
+
])
|
|
51
|
+
SELF_HOSTED.addSubnet(address, prefix, "ipv4");
|
|
52
|
+
for (const [address, prefix] of [
|
|
53
|
+
["::1", 128],
|
|
54
|
+
["fc00::", 7],
|
|
55
|
+
["fe80::", 10],
|
|
56
|
+
])
|
|
57
|
+
SELF_HOSTED.addSubnet(address, prefix, "ipv6");
|
|
58
|
+
function proxyHost(proxy) {
|
|
59
|
+
let server = typeof proxy === "string" ? proxy : proxy?.server;
|
|
60
|
+
if (!server)
|
|
61
|
+
return null;
|
|
62
|
+
server = String(server).trim();
|
|
63
|
+
if (!server.includes("://"))
|
|
64
|
+
server = `http://${server}`;
|
|
65
|
+
try {
|
|
66
|
+
return new URL(server).hostname.replace(/^\[|\]$/g, "") || null;
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* The proxy provider's registrable domain, and nothing else of the proxy:
|
|
74
|
+
* 'none' without one, 'ip-address' for a bare IP, 'self-hosted' for a
|
|
75
|
+
* loopback, private or tailnet host.
|
|
76
|
+
*/
|
|
77
|
+
export function proxyProvider(proxy) {
|
|
78
|
+
const host = proxyHost(proxy);
|
|
79
|
+
if (!host)
|
|
80
|
+
return "none";
|
|
81
|
+
const family = net.isIP(host);
|
|
82
|
+
if (family)
|
|
83
|
+
return SELF_HOSTED.check(host, family === 4 ? "ipv4" : "ipv6")
|
|
84
|
+
? "self-hosted"
|
|
85
|
+
: "ip-address";
|
|
86
|
+
if (!host.includes(".") ||
|
|
87
|
+
/\.(local|internal|lan|ts\.net|localhost)$/i.test(host))
|
|
88
|
+
return "self-hosted";
|
|
89
|
+
return registrableDomain(host);
|
|
90
|
+
}
|
|
91
|
+
const rx = (pattern) => new RegExp(pattern, "i");
|
|
92
|
+
function statusOk(status, wanted) {
|
|
93
|
+
const s = String(status);
|
|
94
|
+
return wanted.some((w) => s === w || (w.endsWith("xx") && s[0] === w[0]));
|
|
95
|
+
}
|
|
96
|
+
function splitUrl(url) {
|
|
97
|
+
try {
|
|
98
|
+
const u = new URL(url);
|
|
99
|
+
const query = new Map();
|
|
100
|
+
for (const [k, v] of u.searchParams)
|
|
101
|
+
query.set(k, [...(query.get(k) ?? []), v]);
|
|
102
|
+
return { hostPath: u.hostname + u.pathname, query };
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
return { hostPath: "", query: new Map() };
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
export class Rules {
|
|
109
|
+
providers = new Map();
|
|
110
|
+
constructor(data = RULES_DATA) {
|
|
111
|
+
for (const [name, spec] of Object.entries(data.providers)) {
|
|
112
|
+
this.providers.set(name, {
|
|
113
|
+
edge: (spec.edge ?? []).map((e) => [
|
|
114
|
+
rx(e.name),
|
|
115
|
+
"value" in e ? rx(e.value) : null,
|
|
116
|
+
]),
|
|
117
|
+
unresolved: spec.unresolved,
|
|
118
|
+
rules: spec.rules.map((r) => ({
|
|
119
|
+
verdict: r.verdict,
|
|
120
|
+
transient: Boolean(r.transient),
|
|
121
|
+
opens: r.opens ?? true,
|
|
122
|
+
document: Boolean(r.document),
|
|
123
|
+
edge: Boolean(r.edge),
|
|
124
|
+
method: r.method,
|
|
125
|
+
status: r.status,
|
|
126
|
+
url: r.url ? rx(r.url) : undefined,
|
|
127
|
+
query: Object.entries(r.query ?? {}).map(([k, v]) => [
|
|
128
|
+
k,
|
|
129
|
+
rx(v),
|
|
130
|
+
]),
|
|
131
|
+
headers: Object.entries(r.headers ?? {}).map(([k, v]) => [
|
|
132
|
+
k,
|
|
133
|
+
rx(v),
|
|
134
|
+
]),
|
|
135
|
+
body: r.body ? rx(r.body) : undefined,
|
|
136
|
+
requestHeaderName: r.request_header_name
|
|
137
|
+
? rx(r.request_header_name)
|
|
138
|
+
: undefined,
|
|
139
|
+
})),
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
static isEdge(edge, headers) {
|
|
144
|
+
return edge.some(([name, value]) => Object.entries(headers).some(([k, v]) => name.test(k) && (value === null || value.test(v))));
|
|
145
|
+
}
|
|
146
|
+
/** The observations this response makes, or what has to be fetched first. */
|
|
147
|
+
classify(view) {
|
|
148
|
+
const { hostPath, query } = splitUrl(view.url);
|
|
149
|
+
const requestHeaderNames = [...(view.requestHeaderNames ?? [])];
|
|
150
|
+
const out = [];
|
|
151
|
+
let needHeaders = false;
|
|
152
|
+
let needBody = false;
|
|
153
|
+
for (const [name, provider] of this.providers) {
|
|
154
|
+
let isEdge = null;
|
|
155
|
+
for (const rule of provider.rules) {
|
|
156
|
+
if (rule.document && !view.document)
|
|
157
|
+
continue;
|
|
158
|
+
if (rule.method && rule.method !== view.method)
|
|
159
|
+
continue;
|
|
160
|
+
if (rule.url && !rule.url.test(hostPath))
|
|
161
|
+
continue;
|
|
162
|
+
if (rule.status && !statusOk(view.status, rule.status))
|
|
163
|
+
continue;
|
|
164
|
+
if (rule.edge) {
|
|
165
|
+
isEdge ??= Rules.isEdge(provider.edge, view.headers);
|
|
166
|
+
if (!isEdge)
|
|
167
|
+
continue;
|
|
168
|
+
}
|
|
169
|
+
if (rule.query.some(([k, p]) => !(query.get(k) ?? []).some((v) => p.test(v))))
|
|
170
|
+
continue;
|
|
171
|
+
if (rule.requestHeaderName &&
|
|
172
|
+
!requestHeaderNames.some((h) => rule.requestHeaderName?.test(h)))
|
|
173
|
+
continue;
|
|
174
|
+
if (rule.headers.length) {
|
|
175
|
+
if (rule.headers.some(([k]) => k === "set-cookie") &&
|
|
176
|
+
view.allHeaders === undefined) {
|
|
177
|
+
needHeaders = true;
|
|
178
|
+
break;
|
|
179
|
+
}
|
|
180
|
+
const headers = view.allHeaders ?? view.headers;
|
|
181
|
+
if (rule.headers.some(([k, p]) => !p.test(headers[k] ?? "")))
|
|
182
|
+
continue;
|
|
183
|
+
}
|
|
184
|
+
if (rule.body) {
|
|
185
|
+
if (view.body === undefined) {
|
|
186
|
+
needBody = true;
|
|
187
|
+
break;
|
|
188
|
+
}
|
|
189
|
+
if (!rule.body.test(view.body))
|
|
190
|
+
continue;
|
|
191
|
+
}
|
|
192
|
+
out.push([name, rule.verdict, rule.transient, rule.opens]);
|
|
193
|
+
break;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
if (needHeaders || needBody)
|
|
197
|
+
return { need: true, headers: needHeaders, body: needBody };
|
|
198
|
+
return out;
|
|
199
|
+
}
|
|
200
|
+
unresolved(provider) {
|
|
201
|
+
const p = this.providers.get(provider);
|
|
202
|
+
if (!p)
|
|
203
|
+
throw new Error(`unknown provider ${provider}`);
|
|
204
|
+
return p.unresolved;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
/** Encounters in progress and the outcome counts of finished ones. */
|
|
208
|
+
export class Tally {
|
|
209
|
+
rules;
|
|
210
|
+
counts = {};
|
|
211
|
+
open = new Map();
|
|
212
|
+
constructor(rules) {
|
|
213
|
+
this.rules = rules;
|
|
214
|
+
}
|
|
215
|
+
observe(page, site, observation) {
|
|
216
|
+
const [provider, verdict, transient, opens] = observation;
|
|
217
|
+
let encounters = this.open.get(page);
|
|
218
|
+
let enc = encounters?.get(provider);
|
|
219
|
+
if (enc && enc.site !== site) {
|
|
220
|
+
this.finish(page, provider);
|
|
221
|
+
enc = undefined;
|
|
222
|
+
}
|
|
223
|
+
if (!enc) {
|
|
224
|
+
if (!opens)
|
|
225
|
+
return;
|
|
226
|
+
enc = { site, blocked: false, challenged: false, last: null };
|
|
227
|
+
if (!encounters) {
|
|
228
|
+
encounters = new Map();
|
|
229
|
+
this.open.set(page, encounters);
|
|
230
|
+
}
|
|
231
|
+
encounters.set(provider, enc);
|
|
232
|
+
}
|
|
233
|
+
if (verdict === "block")
|
|
234
|
+
enc.blocked = true;
|
|
235
|
+
else if (verdict === "challenge" && !transient)
|
|
236
|
+
enc.challenged = true;
|
|
237
|
+
else if (verdict === "success" || verdict === "challenge")
|
|
238
|
+
enc.last = verdict;
|
|
239
|
+
}
|
|
240
|
+
/** A page's main frame now shows `site`: encounters on another site are over. */
|
|
241
|
+
navigated(page, site) {
|
|
242
|
+
for (const [provider, enc] of this.open.get(page) ?? [])
|
|
243
|
+
if (enc.site !== site)
|
|
244
|
+
this.finish(page, provider);
|
|
245
|
+
}
|
|
246
|
+
closePage(page) {
|
|
247
|
+
for (const provider of [...(this.open.get(page)?.keys() ?? [])])
|
|
248
|
+
this.finish(page, provider);
|
|
249
|
+
}
|
|
250
|
+
closeAll() {
|
|
251
|
+
for (const page of [...this.open.keys()])
|
|
252
|
+
this.closePage(page);
|
|
253
|
+
}
|
|
254
|
+
/** The finished counts, reset. */
|
|
255
|
+
take() {
|
|
256
|
+
const counts = this.counts;
|
|
257
|
+
this.counts = {};
|
|
258
|
+
return counts;
|
|
259
|
+
}
|
|
260
|
+
finish(page, provider) {
|
|
261
|
+
const encounters = this.open.get(page);
|
|
262
|
+
const enc = encounters?.get(provider);
|
|
263
|
+
if (!encounters || !enc)
|
|
264
|
+
return;
|
|
265
|
+
encounters.delete(provider);
|
|
266
|
+
if (!encounters.size)
|
|
267
|
+
this.open.delete(page);
|
|
268
|
+
let outcome;
|
|
269
|
+
if (enc.blocked)
|
|
270
|
+
outcome = "block";
|
|
271
|
+
else if (enc.challenged || enc.last === "challenge")
|
|
272
|
+
outcome = "challenge";
|
|
273
|
+
else if (enc.last === "success")
|
|
274
|
+
outcome = "success";
|
|
275
|
+
else
|
|
276
|
+
outcome = this.rules.unresolved(provider);
|
|
277
|
+
this.counts[provider] ??= {
|
|
278
|
+
success: 0,
|
|
279
|
+
challenge: 0,
|
|
280
|
+
block: 0,
|
|
281
|
+
unknown: 0,
|
|
282
|
+
};
|
|
283
|
+
this.counts[provider][outcome] += 1;
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
// ---------------------------------------------------------------- reporting
|
|
287
|
+
function siteOf(url) {
|
|
288
|
+
try {
|
|
289
|
+
const host = new URL(url).hostname;
|
|
290
|
+
return host ? registrableDomain(host) : "";
|
|
291
|
+
}
|
|
292
|
+
catch {
|
|
293
|
+
return "";
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
async function post(url, payload) {
|
|
297
|
+
try {
|
|
298
|
+
await fetch(url, {
|
|
299
|
+
method: "POST",
|
|
300
|
+
headers: { "Content-Type": "application/json" },
|
|
301
|
+
body: JSON.stringify(payload),
|
|
302
|
+
signal: AbortSignal.timeout(SEND_TIMEOUT_MS),
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
catch {
|
|
306
|
+
// Telemetry never affects a launch: an unreachable endpoint loses the report.
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
/**
|
|
310
|
+
* One launch's reporter. A launcher creates it when telemetry is enabled,
|
|
311
|
+
* hands it each browser context with `watch`, and awaits `close` when the
|
|
312
|
+
* browser closes. Counts are sent every FLUSH_INTERVAL_MS and at close.
|
|
313
|
+
*/
|
|
314
|
+
export class Telemetry {
|
|
315
|
+
endpoint;
|
|
316
|
+
dimensions;
|
|
317
|
+
rules;
|
|
318
|
+
tally;
|
|
319
|
+
send;
|
|
320
|
+
timer;
|
|
321
|
+
closed = false;
|
|
322
|
+
onExit = () => void this.close();
|
|
323
|
+
constructor(product, options) {
|
|
324
|
+
this.endpoint = product.getenv("TELEMETRY_URL") || DEFAULT_ENDPOINT;
|
|
325
|
+
this.dimensions = {
|
|
326
|
+
product: product.name,
|
|
327
|
+
version: options.version,
|
|
328
|
+
browser_version: options.browserVersion,
|
|
329
|
+
pro: Boolean(options.pro),
|
|
330
|
+
cross_os: Boolean(options.crossOs),
|
|
331
|
+
passthrough: Boolean(options.passthrough),
|
|
332
|
+
// The domain is all that is kept of the proxy.
|
|
333
|
+
proxy_provider: proxyProvider(options.proxy),
|
|
334
|
+
};
|
|
335
|
+
this.rules = options.rules ?? new Rules();
|
|
336
|
+
this.tally = new Tally(this.rules);
|
|
337
|
+
this.send = options.send ?? post;
|
|
338
|
+
const interval = options.intervalMs ?? FLUSH_INTERVAL_MS;
|
|
339
|
+
if (interval > 0) {
|
|
340
|
+
this.timer = setInterval(() => void this.flush(), interval);
|
|
341
|
+
this.timer.unref();
|
|
342
|
+
}
|
|
343
|
+
process.once("beforeExit", this.onExit);
|
|
344
|
+
}
|
|
345
|
+
payload(counts) {
|
|
346
|
+
return { schema: SCHEMA, ...this.dimensions, counts };
|
|
347
|
+
}
|
|
348
|
+
async flush() {
|
|
349
|
+
const counts = this.tally.take();
|
|
350
|
+
if (!Object.keys(counts).length)
|
|
351
|
+
return;
|
|
352
|
+
await this.send(this.endpoint, this.payload(counts));
|
|
353
|
+
}
|
|
354
|
+
/** Count every open encounter and send what is left. Safe to call twice. */
|
|
355
|
+
async close() {
|
|
356
|
+
if (this.closed)
|
|
357
|
+
return;
|
|
358
|
+
this.closed = true;
|
|
359
|
+
if (this.timer)
|
|
360
|
+
clearInterval(this.timer);
|
|
361
|
+
process.removeListener("beforeExit", this.onExit);
|
|
362
|
+
this.tally.closeAll();
|
|
363
|
+
await this.flush();
|
|
364
|
+
}
|
|
365
|
+
/** Listen to a Playwright BrowserContext. */
|
|
366
|
+
watch(context) {
|
|
367
|
+
context.on("response", (response) => void this.onResponse(response));
|
|
368
|
+
context.on("page", (page) => this.watchPage(page));
|
|
369
|
+
for (const page of context.pages())
|
|
370
|
+
this.watchPage(page);
|
|
371
|
+
context.on("close", () => {
|
|
372
|
+
for (const page of context.pages())
|
|
373
|
+
this.tally.closePage(page);
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
/** Count and send everything when the browser closes or disconnects. */
|
|
377
|
+
watchBrowser(browser) {
|
|
378
|
+
browser.on("disconnected", () => void this.close());
|
|
379
|
+
}
|
|
380
|
+
watchPage(page) {
|
|
381
|
+
const main = page.mainFrame();
|
|
382
|
+
page.on("framenavigated", (frame) => {
|
|
383
|
+
if (frame === main)
|
|
384
|
+
this.tally.navigated(page, siteOf(frame.url()));
|
|
385
|
+
});
|
|
386
|
+
page.on("close", () => this.tally.closePage(page));
|
|
387
|
+
}
|
|
388
|
+
async onResponse(response) {
|
|
389
|
+
try {
|
|
390
|
+
let page;
|
|
391
|
+
try {
|
|
392
|
+
page = response.frame().page();
|
|
393
|
+
}
|
|
394
|
+
catch {
|
|
395
|
+
return; // a service worker's response has no page
|
|
396
|
+
}
|
|
397
|
+
const request = response.request();
|
|
398
|
+
const site = siteOf(page.mainFrame().url());
|
|
399
|
+
const view = {
|
|
400
|
+
url: response.url(),
|
|
401
|
+
method: request.method(),
|
|
402
|
+
status: response.status(),
|
|
403
|
+
headers: response.headers(),
|
|
404
|
+
document: request.resourceType() === "document",
|
|
405
|
+
requestHeaderNames: Object.keys(request.headers()),
|
|
406
|
+
};
|
|
407
|
+
let result = this.rules.classify(view);
|
|
408
|
+
if ("need" in result) {
|
|
409
|
+
if (result.headers)
|
|
410
|
+
view.allHeaders = await response.allHeaders();
|
|
411
|
+
if (result.body)
|
|
412
|
+
view.body = (await response.body())
|
|
413
|
+
.subarray(0, BODY_LIMIT)
|
|
414
|
+
.toString("utf-8");
|
|
415
|
+
result = this.rules.classify(view);
|
|
416
|
+
}
|
|
417
|
+
if (Array.isArray(result))
|
|
418
|
+
for (const observation of result)
|
|
419
|
+
this.tally.observe(page, site, observation);
|
|
420
|
+
}
|
|
421
|
+
catch {
|
|
422
|
+
// Telemetry never affects a launch.
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
}
|