camoucore 0.1.2
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/LICENSE +26 -0
- package/THIRD_PARTY_NOTICES.md +64 -0
- package/dist/cpu_affinity.d.ts +49 -0
- package/dist/cpu_affinity.js +210 -0
- package/dist/data-files/fpgen-model.json +22 -0
- package/dist/data-files/geoip.yml +40 -0
- package/dist/data-files/territoryInfo.xml +2024 -0
- package/dist/data-files/warnings.yml +14 -0
- package/dist/data.d.ts +5 -0
- package/dist/data.js +22 -0
- package/dist/display.d.ts +18 -0
- package/dist/display.js +129 -0
- package/dist/download.d.ts +60 -0
- package/dist/download.js +233 -0
- package/dist/exceptions.d.ts +46 -0
- package/dist/exceptions.js +91 -0
- package/dist/geolocation.d.ts +82 -0
- package/dist/geolocation.js +355 -0
- package/dist/host.d.ts +9 -0
- package/dist/host.js +49 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/ip.d.ts +27 -0
- package/dist/ip.js +302 -0
- package/dist/locales.d.ts +89 -0
- package/dist/locales.js +343 -0
- package/dist/product.d.ts +27 -0
- package/dist/product.js +36 -0
- package/dist/virtdisplay.d.ts +74 -0
- package/dist/virtdisplay.js +310 -0
- package/dist/warnings.d.ts +32 -0
- package/dist/warnings.js +68 -0
- package/package.json +61 -0
package/dist/ip.js
ADDED
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Helpers to find the user's public IP address for geolocation.
|
|
3
|
+
*
|
|
4
|
+
* TypeScript twin of python/src/camoucore/ip.py. Python sends the lookup with
|
|
5
|
+
* `requests`; here it goes through node:https, tunnelled by hand through an
|
|
6
|
+
* HTTP(S) CONNECT or SOCKS5 proxy, so the package needs no HTTP client.
|
|
7
|
+
*/
|
|
8
|
+
import * as http from "node:http";
|
|
9
|
+
import * as https from "node:https";
|
|
10
|
+
import * as net from "node:net";
|
|
11
|
+
import * as tls from "node:tls";
|
|
12
|
+
import { InvalidIP, InvalidProxy } from "./exceptions.js";
|
|
13
|
+
/** urllib.parse.quote(value, safe=''): everything but unreserved characters. */
|
|
14
|
+
function quote(value) {
|
|
15
|
+
return encodeURIComponent(value).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
|
|
16
|
+
}
|
|
17
|
+
// biome-ignore lint/complexity/noStaticOnlyClass: these are the Python Proxy dataclass's methods; the data itself is ProxyConfig
|
|
18
|
+
export class ProxyHelper {
|
|
19
|
+
/** Parses the proxy server string. */
|
|
20
|
+
static parseServer(server) {
|
|
21
|
+
const proxyMatch = server.match(/^(?:(\w+):\/\/)?(.*?)(?::(\d+))?$/);
|
|
22
|
+
if (!proxyMatch) {
|
|
23
|
+
throw new InvalidProxy(`Invalid proxy server: ${server}`);
|
|
24
|
+
}
|
|
25
|
+
return { schema: proxyMatch[1], url: proxyMatch[2], port: proxyMatch[3] };
|
|
26
|
+
}
|
|
27
|
+
static asString(proxy) {
|
|
28
|
+
const { schema, url, port } = ProxyHelper.parseServer(proxy.server);
|
|
29
|
+
let result = `${schema || "http"}://`;
|
|
30
|
+
// Percent-encode the credentials: a raw `#`, `/`, `?` or `@` breaks the
|
|
31
|
+
// URL, and a raw `%XX` is decoded into a different password.
|
|
32
|
+
if (proxy.username) {
|
|
33
|
+
result += quote(proxy.username);
|
|
34
|
+
if (proxy.password) {
|
|
35
|
+
result += `:${quote(proxy.password)}`;
|
|
36
|
+
}
|
|
37
|
+
result += "@";
|
|
38
|
+
}
|
|
39
|
+
result += url;
|
|
40
|
+
if (port) {
|
|
41
|
+
result += `:${port}`;
|
|
42
|
+
}
|
|
43
|
+
return result;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
export function validIPv4(ip) {
|
|
47
|
+
return ip ? net.isIPv4(ip) : false;
|
|
48
|
+
}
|
|
49
|
+
export function validIPv6(ip) {
|
|
50
|
+
return ip ? net.isIPv6(ip) : false;
|
|
51
|
+
}
|
|
52
|
+
export function validateIP(ip) {
|
|
53
|
+
if (!validIPv4(ip) && !validIPv6(ip)) {
|
|
54
|
+
throw new InvalidIP(`Invalid IP address: ${ip}`);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
// Probing the exit IP through a proxy adds a hop and a TLS handshake behind it;
|
|
58
|
+
// 5 s is not enough for a proxy that routes the long way round, and every URL
|
|
59
|
+
// timing out fails the whole launch. Direct probes keep 5 s.
|
|
60
|
+
export const DIRECT_IP_TIMEOUT_MS = 5000;
|
|
61
|
+
export const PROXIED_IP_TIMEOUT_MS = 15000;
|
|
62
|
+
function once(timeoutMs, what, run) {
|
|
63
|
+
return new Promise((resolve, reject) => {
|
|
64
|
+
const timer = setTimeout(() => reject(new Error(`${what} timed out after ${timeoutMs} ms`)), timeoutMs);
|
|
65
|
+
run((v) => {
|
|
66
|
+
clearTimeout(timer);
|
|
67
|
+
resolve(v);
|
|
68
|
+
}, (e) => {
|
|
69
|
+
clearTimeout(timer);
|
|
70
|
+
reject(e);
|
|
71
|
+
});
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
/** A TCP stream to host:port through an HTTP(S) proxy's CONNECT. */
|
|
75
|
+
function connectTunnel(proxy, host, port, timeoutMs) {
|
|
76
|
+
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
|
+
const request = (proxy.protocol === "https:" ? https : http).request({
|
|
84
|
+
host: proxy.hostname.replace(/^\[(.*)\]$/, "$1"),
|
|
85
|
+
port: proxy.port || (proxy.protocol === "https:" ? 443 : 80),
|
|
86
|
+
method: "CONNECT",
|
|
87
|
+
path: `${host}:${port}`,
|
|
88
|
+
headers,
|
|
89
|
+
});
|
|
90
|
+
request.on("connect", (response, socket) => {
|
|
91
|
+
if (response.statusCode === 200)
|
|
92
|
+
resolve(socket);
|
|
93
|
+
else {
|
|
94
|
+
socket.destroy();
|
|
95
|
+
reject(new Error(`proxy refused CONNECT: ${response.statusCode} ${response.statusMessage}`));
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
request.on("error", reject);
|
|
99
|
+
request.end();
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
/** A TCP stream to host:port through a SOCKS5 proxy (RFC 1928, RFC 1929). */
|
|
103
|
+
function connectSocks5(proxy, host, port, timeoutMs) {
|
|
104
|
+
return once(timeoutMs, "SOCKS5 handshake", (resolve, reject) => {
|
|
105
|
+
const username = decodeURIComponent(proxy.username);
|
|
106
|
+
const password = decodeURIComponent(proxy.password);
|
|
107
|
+
const socket = net.connect({
|
|
108
|
+
host: proxy.hostname.replace(/^\[(.*)\]$/, "$1"),
|
|
109
|
+
port: Number(proxy.port || 1080),
|
|
110
|
+
});
|
|
111
|
+
let buffered = Buffer.alloc(0);
|
|
112
|
+
let step = "greeting";
|
|
113
|
+
const fail = (message) => {
|
|
114
|
+
socket.destroy();
|
|
115
|
+
reject(new Error(message));
|
|
116
|
+
};
|
|
117
|
+
const sendConnect = () => {
|
|
118
|
+
step = "connect";
|
|
119
|
+
const name = Buffer.from(host);
|
|
120
|
+
socket.write(Buffer.concat([
|
|
121
|
+
Buffer.from([5, 1, 0, 3, name.length]),
|
|
122
|
+
name,
|
|
123
|
+
Buffer.from([port >> 8, port & 0xff]),
|
|
124
|
+
]));
|
|
125
|
+
};
|
|
126
|
+
socket.on("error", reject);
|
|
127
|
+
socket.on("connect", () => {
|
|
128
|
+
socket.write(Buffer.from(username ? [5, 2, 0, 2] : [5, 1, 0]));
|
|
129
|
+
});
|
|
130
|
+
const onData = (chunk) => {
|
|
131
|
+
buffered = Buffer.concat([buffered, chunk]);
|
|
132
|
+
if (step === "greeting") {
|
|
133
|
+
if (buffered.length < 2)
|
|
134
|
+
return;
|
|
135
|
+
const method = buffered[1];
|
|
136
|
+
buffered = buffered.subarray(2);
|
|
137
|
+
if (method === 0)
|
|
138
|
+
sendConnect();
|
|
139
|
+
else if (method === 2 && username) {
|
|
140
|
+
step = "auth";
|
|
141
|
+
const user = Buffer.from(username);
|
|
142
|
+
const pass = Buffer.from(password);
|
|
143
|
+
socket.write(Buffer.concat([
|
|
144
|
+
Buffer.from([1, user.length]),
|
|
145
|
+
user,
|
|
146
|
+
Buffer.from([pass.length]),
|
|
147
|
+
pass,
|
|
148
|
+
]));
|
|
149
|
+
}
|
|
150
|
+
else
|
|
151
|
+
fail("SOCKS5 proxy offered no usable authentication method");
|
|
152
|
+
}
|
|
153
|
+
else if (step === "auth") {
|
|
154
|
+
if (buffered.length < 2)
|
|
155
|
+
return;
|
|
156
|
+
const status = buffered[1];
|
|
157
|
+
buffered = buffered.subarray(2);
|
|
158
|
+
if (status !== 0)
|
|
159
|
+
fail("SOCKS5 proxy rejected the credentials");
|
|
160
|
+
else
|
|
161
|
+
sendConnect();
|
|
162
|
+
}
|
|
163
|
+
else {
|
|
164
|
+
if (buffered.length < 5)
|
|
165
|
+
return;
|
|
166
|
+
if (buffered[1] !== 0) {
|
|
167
|
+
fail(`SOCKS5 proxy refused the connection (code ${buffered[1]})`);
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
const addr = buffered[3];
|
|
171
|
+
const length = addr === 1 ? 10 : addr === 4 ? 22 : addr === 3 ? 7 + buffered[4] : -1;
|
|
172
|
+
if (length < 0) {
|
|
173
|
+
fail("SOCKS5 proxy sent a malformed reply");
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
if (buffered.length < length)
|
|
177
|
+
return;
|
|
178
|
+
socket.off("data", onData);
|
|
179
|
+
const rest = buffered.subarray(length);
|
|
180
|
+
if (rest.length)
|
|
181
|
+
socket.unshift(rest);
|
|
182
|
+
resolve(socket);
|
|
183
|
+
}
|
|
184
|
+
};
|
|
185
|
+
socket.on("data", onData);
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
function proxySocket(proxy, host, port, timeoutMs) {
|
|
189
|
+
let url;
|
|
190
|
+
try {
|
|
191
|
+
url = new URL(proxy);
|
|
192
|
+
}
|
|
193
|
+
catch (error) {
|
|
194
|
+
throw new InvalidProxy(`Invalid proxy server: ${proxy}`, { cause: error });
|
|
195
|
+
}
|
|
196
|
+
switch (url.protocol) {
|
|
197
|
+
case "http:":
|
|
198
|
+
case "https:":
|
|
199
|
+
return connectTunnel(url, host, port, timeoutMs);
|
|
200
|
+
case "socks5:":
|
|
201
|
+
case "socks5h:":
|
|
202
|
+
return connectSocks5(url, host, port, timeoutMs);
|
|
203
|
+
default:
|
|
204
|
+
throw new InvalidProxy(`Unsupported proxy scheme for the public IP lookup: ${url.protocol}//. ` +
|
|
205
|
+
"Supported: http, https, socks5.");
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
/** GET an https URL's body, directly or through `proxy`; certificates are verified. */
|
|
209
|
+
async function httpsGetText(url, proxy) {
|
|
210
|
+
const timeoutMs = proxy ? PROXIED_IP_TIMEOUT_MS : DIRECT_IP_TIMEOUT_MS;
|
|
211
|
+
const target = new URL(url);
|
|
212
|
+
const port = Number(target.port || 443);
|
|
213
|
+
let socket;
|
|
214
|
+
if (proxy) {
|
|
215
|
+
const raw = await proxySocket(proxy, target.hostname, port, timeoutMs);
|
|
216
|
+
socket = tls.connect({ socket: raw, servername: target.hostname });
|
|
217
|
+
}
|
|
218
|
+
return once(timeoutMs, `GET ${url}`, (resolve, reject) => {
|
|
219
|
+
const request = https.get(url, {
|
|
220
|
+
agent: false,
|
|
221
|
+
headers: { Connection: "close" },
|
|
222
|
+
...(socket ? { createConnection: () => socket } : {}),
|
|
223
|
+
}, (response) => {
|
|
224
|
+
const chunks = [];
|
|
225
|
+
response.on("data", (chunk) => chunks.push(chunk));
|
|
226
|
+
response.on("error", reject);
|
|
227
|
+
response.on("end", () => {
|
|
228
|
+
const status = response.statusCode ?? 0;
|
|
229
|
+
if (status >= 400) {
|
|
230
|
+
// requests' raise_for_status()
|
|
231
|
+
reject(new Error(`${status} Error: ${response.statusMessage} for url: ${url}`));
|
|
232
|
+
}
|
|
233
|
+
else
|
|
234
|
+
resolve(Buffer.concat(chunks).toString("utf8"));
|
|
235
|
+
});
|
|
236
|
+
});
|
|
237
|
+
request.on("error", reject);
|
|
238
|
+
}).finally(() => socket?.destroy());
|
|
239
|
+
}
|
|
240
|
+
const PUBLIC_IP_URLS = [
|
|
241
|
+
// Prefers IPv4
|
|
242
|
+
"https://api.ipify.org",
|
|
243
|
+
"https://checkip.amazonaws.com",
|
|
244
|
+
"https://ipinfo.io/ip",
|
|
245
|
+
// IPv4 & IPv6
|
|
246
|
+
"https://icanhazip.com",
|
|
247
|
+
"https://ifconfig.co/ip",
|
|
248
|
+
"https://ipecho.net/plain",
|
|
249
|
+
];
|
|
250
|
+
// Python memoizes public_ip() with lru_cache; mirror that so repeated launches
|
|
251
|
+
// through the same proxy don't re-hit the API endpoints.
|
|
252
|
+
const publicIPCache = new Map();
|
|
253
|
+
/** Sends a request to a public IP api. */
|
|
254
|
+
export function publicIP(proxy) {
|
|
255
|
+
const key = proxy ?? "";
|
|
256
|
+
const cached = publicIPCache.get(key);
|
|
257
|
+
if (cached)
|
|
258
|
+
return cached;
|
|
259
|
+
const pending = resolvePublicIP(proxy).catch((error) => {
|
|
260
|
+
// Never cache a failure: the next launch should retry.
|
|
261
|
+
publicIPCache.delete(key);
|
|
262
|
+
throw error;
|
|
263
|
+
});
|
|
264
|
+
publicIPCache.set(key, pending);
|
|
265
|
+
return pending;
|
|
266
|
+
}
|
|
267
|
+
let publicIPv6Cache;
|
|
268
|
+
/**
|
|
269
|
+
* This host's public IPv6 address, or null when it has none it can reach the
|
|
270
|
+
* internet from. The hosts have AAAA records only, so an answer proves the route.
|
|
271
|
+
*/
|
|
272
|
+
export function publicIPv6() {
|
|
273
|
+
publicIPv6Cache ??= (async () => {
|
|
274
|
+
for (const url of ["https://api6.ipify.org", "https://v6.ident.me"]) {
|
|
275
|
+
try {
|
|
276
|
+
const ip = (await httpsGetText(url)).trim();
|
|
277
|
+
if (validIPv6(ip))
|
|
278
|
+
return ip;
|
|
279
|
+
}
|
|
280
|
+
catch { }
|
|
281
|
+
}
|
|
282
|
+
return null;
|
|
283
|
+
})();
|
|
284
|
+
return publicIPv6Cache;
|
|
285
|
+
}
|
|
286
|
+
async function resolvePublicIP(proxy) {
|
|
287
|
+
let endException;
|
|
288
|
+
for (const url of PUBLIC_IP_URLS) {
|
|
289
|
+
try {
|
|
290
|
+
const ip = (await httpsGetText(url, proxy)).trim();
|
|
291
|
+
validateIP(ip);
|
|
292
|
+
return ip;
|
|
293
|
+
}
|
|
294
|
+
catch (error) {
|
|
295
|
+
endException = error;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
const detail = endException instanceof Error ? endException.message : String(endException);
|
|
299
|
+
throw new InvalidIP(`Failed to get IP address: ${detail}`, {
|
|
300
|
+
cause: endException,
|
|
301
|
+
});
|
|
302
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Stores locale, region, and script information.
|
|
3
|
+
*/
|
|
4
|
+
export declare class Locale {
|
|
5
|
+
language: string;
|
|
6
|
+
region?: string | undefined;
|
|
7
|
+
script?: string | undefined;
|
|
8
|
+
constructor(language: string, region?: string | undefined, script?: string | undefined);
|
|
9
|
+
get asString(): string;
|
|
10
|
+
/**
|
|
11
|
+
* Converts the locale to an intl config object.
|
|
12
|
+
*/
|
|
13
|
+
asConfig(): Record<string, string>;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Stores geolocation information.
|
|
17
|
+
*/
|
|
18
|
+
export declare class Geolocation {
|
|
19
|
+
readonly locale: Locale;
|
|
20
|
+
readonly longitude: number;
|
|
21
|
+
readonly latitude: number;
|
|
22
|
+
readonly timezone: string;
|
|
23
|
+
readonly accuracy?: number | undefined;
|
|
24
|
+
constructor(locale: Locale, longitude: number, latitude: number, timezone: string, accuracy?: number | undefined);
|
|
25
|
+
/**
|
|
26
|
+
* Converts the geolocation to a config object.
|
|
27
|
+
*/
|
|
28
|
+
asConfig(): Record<string, any>;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Normalizes and validates a locale code.
|
|
32
|
+
*
|
|
33
|
+
* The script is the LANGUAGE's Suppress-Script ("Latn" for "en"), exactly as
|
|
34
|
+
* pythonlib does -- not the tag's explicit script subtag. Parity note: that
|
|
35
|
+
* makes "en-US" come out as en/Latn/US, and "zh-Hans-CN" as zh/(none)/CN.
|
|
36
|
+
*/
|
|
37
|
+
export declare function normalizeLocale(locale: string): Locale;
|
|
38
|
+
/**
|
|
39
|
+
* Handles a locale input, normalizing it if necessary.
|
|
40
|
+
*/
|
|
41
|
+
export declare function handleLocale(locale: string, ignoreRegion?: boolean): Promise<Locale>;
|
|
42
|
+
/**
|
|
43
|
+
* Handles a list of locales, writing them into the config.
|
|
44
|
+
*/
|
|
45
|
+
export declare function handleLocales(locales: string | string[], config: Record<string, any>): Promise<void>;
|
|
46
|
+
/**
|
|
47
|
+
* numpy's pairwise summation (np.sum over a 1-D float64 array), so the
|
|
48
|
+
* normalised probabilities are bit-identical to the Python selector's.
|
|
49
|
+
*/
|
|
50
|
+
export declare function pairwiseSum(values: readonly number[]): number;
|
|
51
|
+
/**
|
|
52
|
+
* Injection point for the selector's one random draw (tests pin it).
|
|
53
|
+
* `random()` plays numpy's RandomState.random_sample().
|
|
54
|
+
*/
|
|
55
|
+
export declare const localeDeps: {
|
|
56
|
+
random: () => number;
|
|
57
|
+
};
|
|
58
|
+
/**
|
|
59
|
+
* numpy.random.choice(items, p=probabilities): searchsorted(right) of one
|
|
60
|
+
* uniform draw in the renormalised CDF.
|
|
61
|
+
*/
|
|
62
|
+
export declare function weightedChoice<T>(items: readonly T[], p: readonly number[]): T;
|
|
63
|
+
/**
|
|
64
|
+
* Selects a random locale based on statistical data. Takes either a territory
|
|
65
|
+
* code or a language code, and generates a Locale.
|
|
66
|
+
*/
|
|
67
|
+
export declare class StatisticalLocaleSelector {
|
|
68
|
+
/**
|
|
69
|
+
* Calculates a random language based on the territory code, based on the
|
|
70
|
+
* probability that a person speaks the language in the territory.
|
|
71
|
+
*/
|
|
72
|
+
private loadTerritoryData;
|
|
73
|
+
/**
|
|
74
|
+
* Calculates a random region for a language based on the total speakers of
|
|
75
|
+
* the language in that region.
|
|
76
|
+
*/
|
|
77
|
+
private loadLanguageData;
|
|
78
|
+
/** Normalize probabilities. */
|
|
79
|
+
normalizeProbabilities(items: string[], freq: number[]): [string[], number[]];
|
|
80
|
+
/**
|
|
81
|
+
* Get a random locale based on the territory ISO code.
|
|
82
|
+
*/
|
|
83
|
+
fromRegion(region: string): Promise<Locale>;
|
|
84
|
+
/**
|
|
85
|
+
* Get a random locale based on the language.
|
|
86
|
+
*/
|
|
87
|
+
fromLanguage(language: string): Promise<Locale>;
|
|
88
|
+
}
|
|
89
|
+
export declare const SELECTOR: StatisticalLocaleSelector;
|