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.
@@ -0,0 +1,82 @@
1
+ import { Geolocation } from "./locales.js";
2
+ export declare const GEOIP_DIR: string;
3
+ export declare const MMDB_DIR: string;
4
+ export declare const GEOIP_CONFIG: string;
5
+ export interface GeoIPRepo {
6
+ name: string;
7
+ urls: Record<string, string | string[]>;
8
+ paths: Record<string, string>;
9
+ extract?: boolean;
10
+ deprecated?: boolean;
11
+ [key: string]: any;
12
+ }
13
+ /** A reader over an mmdb file: maxminddb.Reader's `get` and `metadata`. */
14
+ export interface MmdbReader {
15
+ get(ip: string): any;
16
+ metadata?: {
17
+ buildEpoch: Date;
18
+ };
19
+ close?(): void;
20
+ }
21
+ /**
22
+ * Whether the mmdb reader is available. Python gates this on the optional
23
+ * `maxminddb` import (`pip install camoucore[geoip]`); here it is the optional
24
+ * `maxmind` package.
25
+ */
26
+ export declare function allowGeoip(): boolean;
27
+ /**
28
+ * Injection points (tests replace them): opening an mmdb, and downloading.
29
+ */
30
+ export declare const geoipDeps: {
31
+ openDatabase(mmdbPath: string): Promise<MmdbReader>;
32
+ downloadMmdb: (source?: string) => Promise<void>;
33
+ };
34
+ /**
35
+ * Load GeoIP sources and the default source's name from geoip.yml.
36
+ */
37
+ export declare function loadGeoipRepos(): [GeoIPRepo[], string];
38
+ /**
39
+ * Get GeoIP config by name from geoip.yml. If omitted, uses the default.
40
+ */
41
+ export declare function getGeoipConfigByName(name?: string | null): GeoIPRepo;
42
+ /**
43
+ * Warn that a GeoIP source is deprecated and name the default to use instead.
44
+ */
45
+ export declare function warnIfDeprecated(config: GeoIPRepo): void;
46
+ /**
47
+ * Load the active GeoIP config from disk, falling back to the geoip.yml default.
48
+ *
49
+ * A saved deprecated source that the user did not pick explicitly (every
50
+ * cache written before the default changed) resolves to the default.
51
+ */
52
+ export declare function loadGeoipConfig(): GeoIPRepo;
53
+ /**
54
+ * Save the active GeoIP source name to disk. `explicit` records that the user
55
+ * chose it, so a later default change does not move them off it.
56
+ */
57
+ export declare function saveGeoipConfig(config: GeoIPRepo, explicit?: boolean): void;
58
+ /**
59
+ * Get the path to the mmdb file for the specified IP version.
60
+ */
61
+ export declare function getMmdbPath(ipVersion?: string, config?: GeoIPRepo): string;
62
+ /**
63
+ * Checks that the mmdb reader is available.
64
+ */
65
+ export declare function geoipAllowed(): void;
66
+ /**
67
+ * Downloads the GeoIP database(s) to geoip/mmdb/. A named `source` becomes
68
+ * the user's explicit choice unless `activate` is false.
69
+ */
70
+ export declare function downloadMmdb(source?: string, progressCallback?: (downloaded: number, total: number) => void, activate?: boolean): Promise<void>;
71
+ /**
72
+ * Check if the GeoIP database needs an update: its data was built over
73
+ * UPDATE_DAYS ago and it was last downloaded over RECHECK_DAYS ago.
74
+ *
75
+ * This reads the build date rather than the file's age, so a source that
76
+ * keeps serving an old build is noticed.
77
+ */
78
+ export declare function needsUpdate(config?: GeoIPRepo): Promise<boolean>;
79
+ /**
80
+ * Gets the geolocation for an IP address.
81
+ */
82
+ export declare function getGeolocation(ip: string, geoipDb?: string): Promise<Geolocation>;
@@ -0,0 +1,355 @@
1
+ /**
2
+ * Helpers to fetch geolocation, timezone, and locale data given an IP.
3
+ *
4
+ * TypeScript twin of python/src/camoucore/geolocation.py. The on-disk layout
5
+ * (geoip/mmdb/<name>-<ipver>.mmdb and geoip/config.yml under the camoucore
6
+ * cache dir) is the Python package's, so both launchers share one database.
7
+ */
8
+ import * as fs from "node:fs";
9
+ import { createRequire } from "node:module";
10
+ import * as path from "node:path";
11
+ import { parse as parseYaml, stringify as stringifyYaml } from "yaml";
12
+ import { loadDataFile } from "./data.js";
13
+ import { NotInstalledGeoIPExtra, UnknownIPLocation } from "./exceptions.js";
14
+ import { userCacheDir } from "./host.js";
15
+ import { validateIP } from "./ip.js";
16
+ import { Geolocation, SELECTOR } from "./locales.js";
17
+ import { loadWarnings, warn } from "./warnings.js";
18
+ export const GEOIP_DIR = path.join(userCacheDir("camoucore"), "geoip");
19
+ export const MMDB_DIR = path.join(GEOIP_DIR, "mmdb");
20
+ export const GEOIP_CONFIG = path.join(GEOIP_DIR, "config.yml");
21
+ /** A database whose data was built longer ago than this is refreshed. The
22
+ * default source publishes weekly, so a week and a day catches every release. */
23
+ const UPDATE_DAYS = 8;
24
+ /** ...but at most once a day, so a source that stops publishing costs one
25
+ * download a day rather than one per launch. */
26
+ const RECHECK_DAYS = 1;
27
+ /** A freshly downloaded build older than this means its source is frozen. */
28
+ const FROZEN_DAYS = 30;
29
+ const DAY_MS = 24 * 60 * 60 * 1000;
30
+ const require_ = createRequire(import.meta.url);
31
+ /**
32
+ * Whether the mmdb reader is available. Python gates this on the optional
33
+ * `maxminddb` import (`pip install camoucore[geoip]`); here it is the optional
34
+ * `maxmind` package.
35
+ */
36
+ export function allowGeoip() {
37
+ try {
38
+ require_.resolve("maxmind");
39
+ return true;
40
+ }
41
+ catch {
42
+ return false;
43
+ }
44
+ }
45
+ /**
46
+ * Injection points (tests replace them): opening an mmdb, and downloading.
47
+ */
48
+ export const geoipDeps = {
49
+ async openDatabase(mmdbPath) {
50
+ const { Reader } = await import("maxmind");
51
+ const buffer = fs.readFileSync(mmdbPath);
52
+ return new Reader(buffer);
53
+ },
54
+ downloadMmdb: (source) => downloadMmdb(source, undefined, source === undefined),
55
+ };
56
+ /**
57
+ * Resolve a dotted path in a nested object.
58
+ */
59
+ function findIn(data, key) {
60
+ for (const part of key.split(".")) {
61
+ if (typeof data !== "object" || data === null || Array.isArray(data)) {
62
+ return null;
63
+ }
64
+ data = data[part];
65
+ if (data === undefined || data === null) {
66
+ return null;
67
+ }
68
+ }
69
+ return data;
70
+ }
71
+ /**
72
+ * Load GeoIP sources and the default source's name from geoip.yml.
73
+ */
74
+ export function loadGeoipRepos() {
75
+ const data = loadDataFile("geoip.yml");
76
+ return [data.geoip, data.default];
77
+ }
78
+ /**
79
+ * Get GeoIP config by name from geoip.yml. If omitted, uses the default.
80
+ */
81
+ export function getGeoipConfigByName(name) {
82
+ const [repos, defaultName] = loadGeoipRepos();
83
+ const targetName = name || defaultName;
84
+ const validateRepo = (repo) => {
85
+ const raw = repo;
86
+ if (!("urls" in raw)) {
87
+ throw new Error(`GeoIP repo '${raw.name}' missing required urls`);
88
+ }
89
+ if (!("paths" in raw)) {
90
+ throw new Error(`GeoIP repo '${raw.name}' missing required paths`);
91
+ }
92
+ return repo;
93
+ };
94
+ for (const repo of repos) {
95
+ if ((repo.name ?? "").toLowerCase() === targetName.toLowerCase()) {
96
+ return validateRepo(repo);
97
+ }
98
+ }
99
+ if (name) {
100
+ const available = repos.map((r) => `'${r.name ?? "Unknown"}'`);
101
+ throw new Error(`GeoIP database '${name}' not found. Available: [${available.join(", ")}]`);
102
+ }
103
+ if (repos.length) {
104
+ return validateRepo(repos[0]);
105
+ }
106
+ throw new Error("No GeoIP repos configured in geoip.yml");
107
+ }
108
+ /**
109
+ * Warn that a GeoIP source is deprecated and name the default to use instead.
110
+ */
111
+ export function warnIfDeprecated(config) {
112
+ if (config.deprecated) {
113
+ const [, defaultName] = loadGeoipRepos();
114
+ warn(loadWarnings()
115
+ .geoip_deprecated.replace("{name}", config.name)
116
+ .replace("{default}", defaultName), "FutureWarning");
117
+ }
118
+ }
119
+ /**
120
+ * Load the active GeoIP config from disk, falling back to the geoip.yml default.
121
+ *
122
+ * A saved deprecated source that the user did not pick explicitly (every
123
+ * cache written before the default changed) resolves to the default.
124
+ */
125
+ export function loadGeoipConfig() {
126
+ if (fs.existsSync(GEOIP_CONFIG)) {
127
+ const saved = parseYaml(fs.readFileSync(GEOIP_CONFIG, "utf-8")) ?? {};
128
+ let config;
129
+ try {
130
+ config = getGeoipConfigByName(saved.name);
131
+ }
132
+ catch {
133
+ return saved;
134
+ }
135
+ if (config.deprecated && !saved.explicit) {
136
+ return getGeoipConfigByName(undefined);
137
+ }
138
+ return config;
139
+ }
140
+ return getGeoipConfigByName(undefined);
141
+ }
142
+ /**
143
+ * Save the active GeoIP source name to disk. `explicit` records that the user
144
+ * chose it, so a later default change does not move them off it.
145
+ */
146
+ export function saveGeoipConfig(config, explicit = false) {
147
+ fs.mkdirSync(GEOIP_DIR, { recursive: true });
148
+ const saved = { name: config.name };
149
+ if (explicit) {
150
+ saved.explicit = true;
151
+ }
152
+ fs.writeFileSync(GEOIP_CONFIG, stringifyYaml(saved));
153
+ }
154
+ /**
155
+ * Get the path to the mmdb file for the specified IP version.
156
+ */
157
+ export function getMmdbPath(ipVersion = "ipv4", config) {
158
+ const cfg = config ?? loadGeoipConfig();
159
+ const name = (cfg.name ?? "geolite2").toLowerCase();
160
+ const urls = cfg.urls ?? {};
161
+ if ("combined" in urls) {
162
+ return path.join(MMDB_DIR, `${name}-combined.mmdb`);
163
+ }
164
+ return path.join(MMDB_DIR, `${name}-${ipVersion}.mmdb`);
165
+ }
166
+ /**
167
+ * Checks that the mmdb reader is available.
168
+ */
169
+ export function geoipAllowed() {
170
+ if (!allowGeoip()) {
171
+ throw new NotInstalledGeoIPExtra("Please install the geoip extra to use this feature: npm install maxmind");
172
+ }
173
+ }
174
+ /**
175
+ * Downloads the GeoIP database(s) to geoip/mmdb/. A named `source` becomes
176
+ * the user's explicit choice unless `activate` is false.
177
+ */
178
+ export async function downloadMmdb(source, progressCallback, activate = true) {
179
+ geoipAllowed();
180
+ const { unzip, webdl } = await import("./download.js");
181
+ const config = source ? getGeoipConfigByName(source) : loadGeoipConfig();
182
+ const urls = config.urls;
183
+ const name = config.name.toLowerCase();
184
+ fs.mkdirSync(MMDB_DIR, { recursive: true });
185
+ const extract = config.extract ?? false;
186
+ const isCombined = "combined" in urls;
187
+ for (const [ipVer, rawList] of Object.entries(urls)) {
188
+ const suffix = isCombined ? "" : ` (${ipVer})`;
189
+ let dlDesc = `Downloading ${config.name}${suffix}`;
190
+ let exDesc = `Extracting ${config.name}${suffix}`;
191
+ const maxLen = Math.max(dlDesc.length, exDesc.length);
192
+ dlDesc = dlDesc.padEnd(maxLen);
193
+ exDesc = exDesc.padEnd(maxLen);
194
+ const mmdbPath = path.join(MMDB_DIR, `${name}-${ipVer}.mmdb`);
195
+ const urlList = typeof rawList === "string" ? [rawList] : rawList;
196
+ let lastError;
197
+ let done = false;
198
+ for (const url of urlList) {
199
+ // Unpack beside the database, not in os.tmpdir(): the rename below
200
+ // fails with EXDEV when /tmp is a different filesystem (tmpfs).
201
+ const tmpDir = fs.mkdtempSync(path.join(GEOIP_DIR, ".download-"));
202
+ try {
203
+ const buffer = await webdl(url, dlDesc, progressCallback === undefined, null, { progressCallback });
204
+ if (extract) {
205
+ unzip(buffer, tmpDir, exDesc, progressCallback === undefined);
206
+ const found = findFirstMmdb(tmpDir);
207
+ if (!found) {
208
+ throw new Error("No .mmdb file found in archive");
209
+ }
210
+ fs.renameSync(found, mmdbPath);
211
+ }
212
+ else {
213
+ fs.writeFileSync(mmdbPath, buffer);
214
+ }
215
+ // The mtime is when we last checked, which needsUpdate() throttles on
216
+ const now = new Date();
217
+ fs.utimesSync(mmdbPath, now, now);
218
+ done = true;
219
+ break;
220
+ }
221
+ catch (error) {
222
+ lastError = error;
223
+ }
224
+ finally {
225
+ fs.rmSync(tmpDir, { recursive: true, force: true });
226
+ }
227
+ }
228
+ if (!done) {
229
+ throw lastError ?? new Error(`Failed to download ${ipVer}`);
230
+ }
231
+ const age = await buildAgeDays(mmdbPath);
232
+ if (age !== null && age > FROZEN_DAYS) {
233
+ warn(loadWarnings()
234
+ .geoip_frozen.replace("{name}", config.name)
235
+ .replace("{days}", String(Math.trunc(age))), "RuntimeWarning");
236
+ }
237
+ }
238
+ removeDeprecatedDatabases(config);
239
+ if (activate) {
240
+ // A refresh of the active source keeps whether the user chose it
241
+ saveGeoipConfig(config, Boolean(source) || chosenExplicitly(config));
242
+ }
243
+ }
244
+ /** Whether the saved config names this source as the user's explicit choice. */
245
+ function chosenExplicitly(config) {
246
+ if (!fs.existsSync(GEOIP_CONFIG))
247
+ return false;
248
+ const saved = parseYaml(fs.readFileSync(GEOIP_CONFIG, "utf-8")) ?? {};
249
+ return Boolean(saved.explicit) && saved.name === config.name;
250
+ }
251
+ /** Delete downloaded databases of deprecated sources other than `keep`. */
252
+ function removeDeprecatedDatabases(keep) {
253
+ const [repos] = loadGeoipRepos();
254
+ if (!fs.existsSync(MMDB_DIR))
255
+ return;
256
+ for (const repo of repos) {
257
+ if (!repo.deprecated || repo.name === keep.name)
258
+ continue;
259
+ const prefix = `${repo.name.toLowerCase()}-`;
260
+ for (const file of fs.readdirSync(MMDB_DIR)) {
261
+ if (file.startsWith(prefix) && file.endsWith(".mmdb")) {
262
+ fs.rmSync(path.join(MMDB_DIR, file), { force: true });
263
+ }
264
+ }
265
+ }
266
+ }
267
+ /** Days since the database's data was built, from its metadata. */
268
+ async function buildAgeDays(mmdbPath) {
269
+ try {
270
+ const reader = await geoipDeps.openDatabase(mmdbPath);
271
+ try {
272
+ const built = reader.metadata?.buildEpoch;
273
+ return built ? (Date.now() - built.getTime()) / DAY_MS : null;
274
+ }
275
+ finally {
276
+ reader.close?.();
277
+ }
278
+ }
279
+ catch {
280
+ return null;
281
+ }
282
+ }
283
+ /** Path(tmpdir).rglob('*.mmdb')[0] */
284
+ function findFirstMmdb(dir) {
285
+ const entries = fs.readdirSync(dir, { withFileTypes: true, recursive: true });
286
+ for (const entry of entries) {
287
+ if (entry.isFile() && entry.name.endsWith(".mmdb")) {
288
+ return path.join(entry.parentPath, entry.name);
289
+ }
290
+ }
291
+ return null;
292
+ }
293
+ /**
294
+ * Check if the GeoIP database needs an update: its data was built over
295
+ * UPDATE_DAYS ago and it was last downloaded over RECHECK_DAYS ago.
296
+ *
297
+ * This reads the build date rather than the file's age, so a source that
298
+ * keeps serving an old build is noticed.
299
+ */
300
+ export async function needsUpdate(config) {
301
+ const cfg = config ?? loadGeoipConfig();
302
+ const ipv4Path = getMmdbPath("ipv4", cfg);
303
+ if (!fs.existsSync(ipv4Path)) {
304
+ return true;
305
+ }
306
+ const checkedDays = (Date.now() - fs.statSync(ipv4Path).mtimeMs) / DAY_MS;
307
+ if (checkedDays < RECHECK_DAYS) {
308
+ return false;
309
+ }
310
+ const buildDays = await buildAgeDays(ipv4Path);
311
+ return buildDays === null || buildDays > UPDATE_DAYS;
312
+ }
313
+ /** float(x) for a value read out of the database. */
314
+ function pyFloat(value) {
315
+ if (value === null || value === undefined) {
316
+ throw new TypeError("float() argument must be a string or a real number, not 'NoneType'");
317
+ }
318
+ const n = Number(value);
319
+ if (Number.isNaN(n)) {
320
+ throw new Error(`could not convert string to float: '${value}'`);
321
+ }
322
+ return n;
323
+ }
324
+ /**
325
+ * Gets the geolocation for an IP address.
326
+ */
327
+ export async function getGeolocation(ip, geoipDb) {
328
+ validateIP(ip);
329
+ const ipVersion = ip.includes(":") ? "ipv6" : "ipv4";
330
+ // A per-call geoipDb reads its own database without becoming the active one
331
+ const config = geoipDb ? getGeoipConfigByName(geoipDb) : loadGeoipConfig();
332
+ warnIfDeprecated(config);
333
+ const mmdbPath = getMmdbPath(ipVersion, config);
334
+ if (!fs.existsSync(mmdbPath) || (await needsUpdate(config))) {
335
+ await geoipDeps.downloadMmdb(geoipDb);
336
+ }
337
+ const paths = config.paths;
338
+ const reader = await geoipDeps.openDatabase(mmdbPath);
339
+ try {
340
+ const resp = reader.get(ip);
341
+ if (!resp) {
342
+ throw new UnknownIPLocation(`IP not found in database: ${ip}`);
343
+ }
344
+ const isoCode = findIn(resp, paths.iso_code);
345
+ const longitude = findIn(resp, paths.longitude);
346
+ const latitude = findIn(resp, paths.latitude);
347
+ const timezone = findIn(resp, paths.timezone);
348
+ const iso = String(isoCode ?? "None").toUpperCase();
349
+ const locale = await SELECTOR.fromRegion(iso);
350
+ return new Geolocation(locale, pyFloat(longitude), pyFloat(latitude), String(timezone ?? "None"));
351
+ }
352
+ finally {
353
+ reader.close?.();
354
+ }
355
+ }
package/dist/host.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ export declare const ARCH_MAP: Record<string, string>;
2
+ export declare const OS_MAP: Record<string, "mac" | "win" | "lin">;
3
+ export declare const OS_NAME: "mac" | "win" | "lin";
4
+ /**
5
+ * platformdirs' user_cache_dir(appName), reimplemented so the TS and Python
6
+ * launchers share one cache directory. Hardcoding ~/.cache would diverge on
7
+ * hosts that set XDG_CACHE_HOME, and on macOS/Windows entirely.
8
+ */
9
+ export declare function userCacheDir(appName: string): string;
package/dist/host.js ADDED
@@ -0,0 +1,49 @@
1
+ /**
2
+ * The host this process runs on, in the names release assets use.
3
+ *
4
+ * TypeScript twin of python/src/camoucore/host.py.
5
+ */
6
+ import * as os from "node:os";
7
+ import * as path from "node:path";
8
+ import { UnsupportedOS } from "./exceptions.js";
9
+ export const ARCH_MAP = {
10
+ x64: "x86_64",
11
+ amd64: "x86_64",
12
+ x86: "x86_64",
13
+ ia32: "i686",
14
+ i686: "i686",
15
+ i386: "i686",
16
+ arm64: "arm64",
17
+ aarch64: "arm64",
18
+ arm: "arm64",
19
+ };
20
+ export const OS_MAP = {
21
+ darwin: "mac",
22
+ linux: "lin",
23
+ win32: "win",
24
+ };
25
+ if (!(process.platform in OS_MAP)) {
26
+ throw new UnsupportedOS(`OS ${process.platform} is not supported`);
27
+ }
28
+ export const OS_NAME = OS_MAP[process.platform];
29
+ /**
30
+ * platformdirs' user_cache_dir(appName), reimplemented so the TS and Python
31
+ * launchers share one cache directory. Hardcoding ~/.cache would diverge on
32
+ * hosts that set XDG_CACHE_HOME, and on macOS/Windows entirely.
33
+ */
34
+ export function userCacheDir(appName) {
35
+ if (OS_NAME === "win") {
36
+ const localAppData = process.env.LOCALAPPDATA;
37
+ const base = localAppData && path.isAbsolute(localAppData)
38
+ ? localAppData
39
+ : path.join(os.homedir(), "AppData", "Local");
40
+ return path.join(base, appName, appName, "Cache");
41
+ }
42
+ if (OS_NAME === "mac") {
43
+ return path.join(os.homedir(), "Library", "Caches", appName);
44
+ }
45
+ // platformdirs: any non-blank XDG_CACHE_HOME is taken as-is.
46
+ const xdg = process.env.XDG_CACHE_HOME ?? "";
47
+ const base = xdg.trim() ? xdg : path.join(os.homedir(), ".cache");
48
+ return path.join(base, appName);
49
+ }
@@ -0,0 +1,2 @@
1
+ export { CHROMIUM, type Engine, FIREFOX, Product } from "./product.js";
2
+ export { VirtualDisplay } from "./virtdisplay.js";
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { CHROMIUM, FIREFOX, Product } from "./product.js";
2
+ export { VirtualDisplay } from "./virtdisplay.js";
package/dist/ip.d.ts ADDED
@@ -0,0 +1,27 @@
1
+ export interface ProxyConfig {
2
+ server: string;
3
+ username?: string;
4
+ password?: string;
5
+ bypass?: string;
6
+ }
7
+ export declare class ProxyHelper {
8
+ /** Parses the proxy server string. */
9
+ static parseServer(server: string): {
10
+ schema?: string;
11
+ url: string;
12
+ port?: string;
13
+ };
14
+ static asString(proxy: ProxyConfig): string;
15
+ }
16
+ export declare function validIPv4(ip: string | false): boolean;
17
+ export declare function validIPv6(ip: string | false): boolean;
18
+ export declare function validateIP(ip: string): void;
19
+ export declare const DIRECT_IP_TIMEOUT_MS = 5000;
20
+ export declare const PROXIED_IP_TIMEOUT_MS = 15000;
21
+ /** Sends a request to a public IP api. */
22
+ export declare function publicIP(proxy?: string): Promise<string>;
23
+ /**
24
+ * This host's public IPv6 address, or null when it has none it can reach the
25
+ * internet from. The hosts have AAAA records only, so an answer proves the route.
26
+ */
27
+ export declare function publicIPv6(): Promise<string | null>;