@astratra/web-search 1.1.0 → 1.2.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/README.fr.md +230 -14
- package/README.md +222 -14
- package/package.json +15 -8
- package/src/address.js +13 -8
- package/src/browser/cli.js +298 -0
- package/src/browser/client.js +251 -0
- package/src/browser/deploy.js +426 -0
- package/src/browser/egressProxy.js +234 -0
- package/src/browser/engine.js +631 -0
- package/src/browser/guard.js +92 -0
- package/src/browser/isolation.js +81 -0
- package/src/browser/pageScript.js +214 -0
- package/src/browser/robots.js +167 -0
- package/src/browser/service.js +237 -0
- package/src/browser/siteSearch.js +149 -0
- package/src/browser/webBotAuth.js +117 -0
- package/src/errors.js +9 -1
- package/src/format.js +42 -1
- package/src/index.d.ts +242 -12
- package/src/index.js +10 -1
- package/src/mcp.d.ts +5 -2
- package/src/mcp.js +10 -6
- package/src/mcpStdio.js +21 -16
- package/src/providers/gateway.js +6 -11
- package/src/tools.js +92 -16
- package/src/webSearch.js +234 -40
package/src/address.js
CHANGED
|
@@ -9,18 +9,23 @@
|
|
|
9
9
|
|
|
10
10
|
const net = require('net');
|
|
11
11
|
|
|
12
|
-
|
|
13
|
-
|
|
12
|
+
/* Les mêmes listes servent au pare-feu du navigateur (createBrowserFirewall). */
|
|
13
|
+
const BLOCKED_IPV4 = Object.freeze([
|
|
14
14
|
['0.0.0.0', 8], ['10.0.0.0', 8], ['100.64.0.0', 10], ['127.0.0.0', 8], ['169.254.0.0', 16],
|
|
15
15
|
['172.16.0.0', 12], ['192.0.0.0', 24], ['192.0.2.0', 24], ['192.88.99.0', 24], ['192.168.0.0', 16],
|
|
16
16
|
['198.18.0.0', 15], ['198.51.100.0', 24], ['203.0.113.0', 24], ['224.0.0.0', 4], ['240.0.0.0', 4]
|
|
17
|
-
])
|
|
18
|
-
|
|
19
|
-
const
|
|
20
|
-
for (const [prefix, bits] of [
|
|
17
|
+
]);
|
|
18
|
+
/* En IPv6, seul 2000::/3 (unicast global) est public, moins ces plages. */
|
|
19
|
+
const BLOCKED_IPV6 = Object.freeze([
|
|
21
20
|
['64:ff9b::', 96], ['64:ff9b:1::', 48], ['100::', 64], ['2001::', 23], ['2001:db8::', 32],
|
|
22
21
|
['2002::', 16], ['3fff::', 20], ['fc00::', 7], ['fe80::', 10], ['fec0::', 10], ['ff00::', 8]
|
|
23
|
-
])
|
|
22
|
+
]);
|
|
23
|
+
|
|
24
|
+
const blocked4 = new net.BlockList();
|
|
25
|
+
for (const [prefix, bits] of BLOCKED_IPV4) blocked4.addSubnet(prefix, bits, 'ipv4');
|
|
26
|
+
|
|
27
|
+
const blocked6 = new net.BlockList();
|
|
28
|
+
for (const [prefix, bits] of BLOCKED_IPV6) blocked6.addSubnet(prefix, bits, 'ipv6');
|
|
24
29
|
|
|
25
30
|
/** Les 8 groupes de 16 bits d'une adresse IPv6, ou null. */
|
|
26
31
|
function groupsOf(address) {
|
|
@@ -68,4 +73,4 @@ function isBlockedHostname(hostname) {
|
|
|
68
73
|
|| host.endsWith('.in-addr.arpa') || host.endsWith('.ip6.arpa');
|
|
69
74
|
}
|
|
70
75
|
|
|
71
|
-
module.exports = { isPublicAddress, isBlockedHostname };
|
|
76
|
+
module.exports = { isPublicAddress, isBlockedHostname, BLOCKED_IPV4, BLOCKED_IPV6 };
|
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* astratra-web-browser : le service navigateur du paquet @astratra/web-search.
|
|
4
|
+
*
|
|
5
|
+
* astratra-web-browser serve [--port 5008] [--proxy-port 5009] [--token-file F] [--max-contexts 2]
|
|
6
|
+
* [--queue-ms 10000] [--info-url U] [--signing-key-file F --signature-agent U]
|
|
7
|
+
* [--unsafe-no-firewall]
|
|
8
|
+
* astratra-web-browser setup --out DOSSIER --node /usr/bin/node --token-file /etc/astratra/browser-token
|
|
9
|
+
* [--user navigateur] [--clients-group astratra-browser] [--chromium CHEMIN]
|
|
10
|
+
* [--browsers-path P] [--dns 127.0.0.53] [--port 5008] [--proxy-port 5009]
|
|
11
|
+
* [--memory-max 2G] [--cpu-quota 200%]
|
|
12
|
+
* vérifie aussi la machine (Linux, systemd, nftables, AppArmor, Node, Chromium) et dit ce qui manque ;
|
|
13
|
+
* sans --dns, les résolveurs viennent de /etc/resolv.conf.
|
|
14
|
+
* astratra-web-browser token --out FICHIER [--group astratra-browser]
|
|
15
|
+
* avec --group : fichier en mode 640, lisible par ce groupe (les applications qui appellent le service).
|
|
16
|
+
* astratra-web-browser keygen --out CLE.pem [--directory annuaire.json]
|
|
17
|
+
*
|
|
18
|
+
* Chaque option de `serve` se lit aussi dans l'environnement (WEB_BROWSER_PORT,
|
|
19
|
+
* WEB_BROWSER_PROXY_PORT, WEB_BROWSER_TOKEN_FILE, WEB_BROWSER_MAX_CONTEXTS,
|
|
20
|
+
* WEB_BROWSER_QUEUE_MS, WEB_BROWSER_INFO_URL, WEB_BROWSER_SIGNING_KEY_FILE,
|
|
21
|
+
* WEB_BROWSER_SIGNATURE_AGENT).
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
const fs = require('fs');
|
|
25
|
+
const path = require('path');
|
|
26
|
+
const crypto = require('crypto');
|
|
27
|
+
const { parseArgs } = require('util');
|
|
28
|
+
|
|
29
|
+
const USAGE = `astratra-web-browser serve | setup | token | keygen (voir le README de @astratra/web-search)`;
|
|
30
|
+
|
|
31
|
+
function integer(value, name, min, max) {
|
|
32
|
+
if (value === undefined || value === '') return undefined;
|
|
33
|
+
const number = Number(value);
|
|
34
|
+
if (!Number.isInteger(number) || number < min || number > max) throw new Error(`${name}: ${min} to ${max}.`);
|
|
35
|
+
return number;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function writeSecret(file, content) {
|
|
39
|
+
const target = path.resolve(file);
|
|
40
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
41
|
+
/* wx : ne jamais écraser un secret existant. */
|
|
42
|
+
fs.writeFileSync(target, content, { mode: 0o600, flag: 'wx' });
|
|
43
|
+
return target;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function serve(values) {
|
|
47
|
+
if (typeof process.getuid === 'function' && process.getuid() === 0) {
|
|
48
|
+
throw new Error('refusing to run as root: start the service as its own system user (see astratra-web-browser setup).');
|
|
49
|
+
}
|
|
50
|
+
const env = process.env;
|
|
51
|
+
const unsafeNoFirewall = values['unsafe-no-firewall'] === true;
|
|
52
|
+
if (env.WEB_BROWSER_UNSAFE_NO_FIREWALL) throw new Error('--unsafe-no-firewall is a command-line flag only, never an environment variable.');
|
|
53
|
+
const tokenFile = values['token-file'] || env.WEB_BROWSER_TOKEN_FILE;
|
|
54
|
+
if (!tokenFile) throw new Error('a token file is required (--token-file or WEB_BROWSER_TOKEN_FILE).');
|
|
55
|
+
const { createBrowserEngine } = require('./engine');
|
|
56
|
+
const { createBrowserService } = require('./service');
|
|
57
|
+
const { signerFromFile } = require('./webBotAuth');
|
|
58
|
+
const signer = signerFromFile({
|
|
59
|
+
signingKeyFile: values['signing-key-file'] || env.WEB_BROWSER_SIGNING_KEY_FILE,
|
|
60
|
+
signatureAgent: values['signature-agent'] || env.WEB_BROWSER_SIGNATURE_AGENT
|
|
61
|
+
});
|
|
62
|
+
const engine = createBrowserEngine({
|
|
63
|
+
infoUrl: values['info-url'] || env.WEB_BROWSER_INFO_URL || undefined,
|
|
64
|
+
signer,
|
|
65
|
+
proxyPort: integer(values['proxy-port'] || env.WEB_BROWSER_PROXY_PORT, 'proxy port', 1, 65535) ?? 5009,
|
|
66
|
+
maxContexts: integer(values['max-contexts'] || env.WEB_BROWSER_MAX_CONTEXTS, 'max contexts', 1, 16),
|
|
67
|
+
queueMs: integer(values['queue-ms'] || env.WEB_BROWSER_QUEUE_MS, 'queue ms', 0, 120_000)
|
|
68
|
+
});
|
|
69
|
+
const service = createBrowserService({
|
|
70
|
+
engine,
|
|
71
|
+
tokenFile,
|
|
72
|
+
port: integer(values.port || env.WEB_BROWSER_PORT, 'port', 1, 65535) ?? 5008,
|
|
73
|
+
unsafeNoFirewall,
|
|
74
|
+
log: (event) => {
|
|
75
|
+
if (event.outcome !== 'ok') process.stdout.write(`${JSON.stringify({ at: new Date().toISOString(), ...event })}\n`);
|
|
76
|
+
}
|
|
77
|
+
});
|
|
78
|
+
let started;
|
|
79
|
+
try {
|
|
80
|
+
started = await service.start();
|
|
81
|
+
} catch (error) {
|
|
82
|
+
if (error.code === 'isolation_failed') {
|
|
83
|
+
process.stderr.write(`isolation_failed: ${JSON.stringify(error.isolation.probes)}\n`);
|
|
84
|
+
process.stderr.write('The browser can reach the internal network. Load the firewall rules (astratra-web-browser setup), or use --unsafe-no-firewall on a development machine only.\n');
|
|
85
|
+
}
|
|
86
|
+
throw error;
|
|
87
|
+
}
|
|
88
|
+
const health = await engine.health();
|
|
89
|
+
process.stdout.write(`astratra-web-browser ${health.version} listening on ${started.host}:${started.port}, Chromium ${health.chromium}, sandbox on, `
|
|
90
|
+
+ `${started.isolation.ok ? 'isolation ok' : 'ISOLATION FAILED (--unsafe-no-firewall: development only)'}\n`);
|
|
91
|
+
const stop = async () => {
|
|
92
|
+
await service.close().catch(() => {});
|
|
93
|
+
process.exit(0);
|
|
94
|
+
};
|
|
95
|
+
process.once('SIGTERM', stop);
|
|
96
|
+
process.once('SIGINT', stop);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function headlessShellIn(browsersPath) {
|
|
100
|
+
if (!browsersPath || !fs.existsSync(browsersPath)) return null;
|
|
101
|
+
for (const entry of fs.readdirSync(browsersPath).filter((name) => name.startsWith('chromium_headless_shell-')).sort().reverse()) {
|
|
102
|
+
const base = path.join(browsersPath, entry);
|
|
103
|
+
for (const sub of fs.readdirSync(base)) {
|
|
104
|
+
const candidate = path.join(base, sub, 'chrome-headless-shell');
|
|
105
|
+
if (fs.existsSync(candidate)) return candidate;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return null;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Les résolveurs DNS de la machine (lignes nameserver de resolv.conf). */
|
|
112
|
+
function resolversOf(text) {
|
|
113
|
+
return String(text || '').split('\n')
|
|
114
|
+
.map((line) => /^\s*nameserver\s+(\S+)/.exec(line)?.[1])
|
|
115
|
+
.filter((address) => address && require('net').isIP(address.replace(/%.*$/, '')))
|
|
116
|
+
.map((address) => address.replace(/%.*$/, ''));
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Vrai si une commande se trouve dans le PATH ou dans /usr/sbin, /sbin. */
|
|
120
|
+
function hasCommand(name, env = process.env, exists = fs.existsSync) {
|
|
121
|
+
const dirs = [...String(env.PATH || '').split(path.delimiter), '/usr/sbin', '/sbin', '/usr/bin', '/bin'].filter(Boolean);
|
|
122
|
+
return dirs.some((dir) => exists(path.join(dir, name)));
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Ce que la machine a, et ce qui manque pour le service.
|
|
127
|
+
* @param {object} [host] ce qui est lu sur la machine (remplaçable dans les tests).
|
|
128
|
+
* @returns {{ name: string, ok: boolean, detail: string, fix?: string }[]}
|
|
129
|
+
*/
|
|
130
|
+
function inspectBrowserHost(host = {}) {
|
|
131
|
+
const platform = host.platform || process.platform;
|
|
132
|
+
const exists = host.exists || fs.existsSync;
|
|
133
|
+
const read = host.read || ((file) => {
|
|
134
|
+
try {
|
|
135
|
+
return fs.readFileSync(file, 'utf8');
|
|
136
|
+
} catch (_error) {
|
|
137
|
+
return null;
|
|
138
|
+
}
|
|
139
|
+
});
|
|
140
|
+
const command = host.hasCommand || ((name) => hasCommand(name, process.env, exists));
|
|
141
|
+
const nodeVersion = host.nodeVersion || process.versions.node;
|
|
142
|
+
const checks = [];
|
|
143
|
+
const add = (name, ok, detail, fix) => checks.push({ name, ok, detail, ...(ok || !fix ? {} : { fix }) });
|
|
144
|
+
const linux = platform === 'linux';
|
|
145
|
+
add('linux', linux, linux ? 'Linux' : platform,
|
|
146
|
+
'The service, its firewall and its systemd unit need a Linux server. On macOS or Windows, use createLocalBrowser() for development.');
|
|
147
|
+
if (!linux) return checks;
|
|
148
|
+
add('systemd', exists('/run/systemd/system'), exists('/run/systemd/system') ? 'systemd is running' : 'no systemd',
|
|
149
|
+
'Without systemd, use createBrowserPm2App (fewer protections) and keep the firewall.');
|
|
150
|
+
add('nftables', command('nft'), command('nft') ? 'nft found' : 'nft not found', 'Install nftables (apt install nftables): the firewall is mandatory.');
|
|
151
|
+
const restricted = String(read('/proc/sys/kernel/apparmor_restrict_unprivileged_userns') || '').trim() === '1';
|
|
152
|
+
if (restricted) {
|
|
153
|
+
add('apparmor', Boolean(host.chromiumPath), host.chromiumPath ? `profile written for ${host.chromiumPath}` : 'user namespaces are restricted and Chromium was not found',
|
|
154
|
+
'Install Chromium first (PLAYWRIGHT_BROWSERS_PATH=… npx playwright install --with-deps chromium-headless-shell), then rerun setup with --browsers-path or --chromium.');
|
|
155
|
+
} else {
|
|
156
|
+
add('apparmor', true, 'user namespaces are not restricted (no AppArmor profile needed)');
|
|
157
|
+
}
|
|
158
|
+
const major = Number(String(nodeVersion).split('.')[0]);
|
|
159
|
+
add('node', major >= 22, `Node ${nodeVersion}`, 'Install Node 22 or later.');
|
|
160
|
+
add('chromium', Boolean(host.chromiumPath), host.chromiumPath || 'chrome-headless-shell not found',
|
|
161
|
+
'PLAYWRIGHT_BROWSERS_PATH=/opt/ms-playwright npx playwright install --with-deps chromium-headless-shell, then --browsers-path /opt/ms-playwright.');
|
|
162
|
+
const resolvers = host.resolvers || [];
|
|
163
|
+
add('dns', resolvers.length > 0, resolvers.length ? `resolvers ${resolvers.join(', ')}` : 'no resolver in /etc/resolv.conf', 'Pass --dns with the address of the resolver the server uses.');
|
|
164
|
+
return checks;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function setup(values) {
|
|
168
|
+
const { browserSetupFiles } = require('./deploy');
|
|
169
|
+
if (!values.out) throw new Error('--out <folder> is required.');
|
|
170
|
+
if (!values['token-file']) throw new Error('--token-file <path> is required (the file the service and the applications read).');
|
|
171
|
+
const browsersPath = values['browsers-path'] || process.env.PLAYWRIGHT_BROWSERS_PATH || undefined;
|
|
172
|
+
const chromiumPath = values.chromium || headlessShellIn(browsersPath) || undefined;
|
|
173
|
+
const given = values.dns ? String(values.dns).split(',').map((item) => item.trim()).filter(Boolean) : null;
|
|
174
|
+
const detected = resolversOf(fs.existsSync('/etc/resolv.conf') ? fs.readFileSync('/etc/resolv.conf', 'utf8') : '');
|
|
175
|
+
const dnsServers = given || (detected.length ? detected : undefined);
|
|
176
|
+
const checks = inspectBrowserHost({ chromiumPath, resolvers: dnsServers || [] });
|
|
177
|
+
process.stdout.write('Machine check:\n');
|
|
178
|
+
for (const check of checks) process.stdout.write(` ${check.ok ? 'ok ' : 'MISSING'} ${check.name}: ${check.detail}${check.fix ? `\n → ${check.fix}` : ''}\n`);
|
|
179
|
+
const files = browserSetupFiles({
|
|
180
|
+
node: values.node || process.execPath,
|
|
181
|
+
user: values.user || 'navigateur',
|
|
182
|
+
clientsGroup: values['clients-group'] || 'astratra-browser',
|
|
183
|
+
tokenFile: values['token-file'],
|
|
184
|
+
chromiumPath,
|
|
185
|
+
browsersPath,
|
|
186
|
+
dnsServers,
|
|
187
|
+
port: integer(values.port, 'port', 1, 65535),
|
|
188
|
+
proxyPort: integer(values['proxy-port'], 'proxy port', 1, 65535),
|
|
189
|
+
memoryMax: values['memory-max'],
|
|
190
|
+
cpuQuota: values['cpu-quota'],
|
|
191
|
+
infoUrl: values['info-url'],
|
|
192
|
+
...(values['signing-key-file'] ? { signingKeyFile: values['signing-key-file'], signatureAgent: values['signature-agent'] } : {})
|
|
193
|
+
});
|
|
194
|
+
const out = path.resolve(values.out);
|
|
195
|
+
fs.mkdirSync(out, { recursive: true });
|
|
196
|
+
for (const [name, content] of Object.entries(files)) fs.writeFileSync(path.join(out, name), content, { mode: 0o644 });
|
|
197
|
+
const missing = checks.filter((check) => !check.ok).length;
|
|
198
|
+
process.stdout.write(`Wrote ${Object.keys(files).join(', ')} to ${out}. Follow ${path.join(out, 'INSTALL.md')} (French: INSTALL.fr.md).\n`
|
|
199
|
+
+ (missing ? `${missing} item(s) above must be fixed before the service can start safely.\n` : ''));
|
|
200
|
+
return { checks, files: Object.keys(files) };
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** L'identifiant d'un groupe, par son nom ou son numéro. */
|
|
204
|
+
function groupId(group) {
|
|
205
|
+
if (/^\d+$/.test(String(group))) return Number(group);
|
|
206
|
+
if (!/^[a-z_][a-z0-9_-]*$/.test(String(group))) throw new Error(`--group: invalid group name ${String(group).slice(0, 40)}.`);
|
|
207
|
+
try {
|
|
208
|
+
const line = require('child_process').execFileSync('getent', ['group', group], { encoding: 'utf8' });
|
|
209
|
+
const gid = Number(line.split(':')[2]);
|
|
210
|
+
if (Number.isInteger(gid)) return gid;
|
|
211
|
+
} catch (_error) {
|
|
212
|
+
/* pas de getent : /etc/group */
|
|
213
|
+
}
|
|
214
|
+
const entry = (fs.existsSync('/etc/group') ? fs.readFileSync('/etc/group', 'utf8') : '').split('\n').find((line) => line.split(':')[0] === group);
|
|
215
|
+
const gid = entry ? Number(entry.split(':')[2]) : NaN;
|
|
216
|
+
if (!Number.isInteger(gid)) throw new Error(`--group: no group named ${group} (create it with groupadd --system ${group}).`);
|
|
217
|
+
return gid;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Le jeton du service : 32 octets tirés au hasard, jamais écrasé. Avec
|
|
222
|
+
* --group, le fichier est lisible par ce groupe (mode 640) : on y met les
|
|
223
|
+
* utilisateurs des applications qui appellent le service ; les autres
|
|
224
|
+
* programmes de la machine ne le lisent pas.
|
|
225
|
+
*/
|
|
226
|
+
function token(values) {
|
|
227
|
+
if (!values.out) throw new Error('--out <file> is required.');
|
|
228
|
+
const gid = values.group ? groupId(values.group) : null;
|
|
229
|
+
const target = writeSecret(values.out, `${crypto.randomBytes(32).toString('base64url')}\n`);
|
|
230
|
+
if (gid !== null) {
|
|
231
|
+
try {
|
|
232
|
+
fs.chownSync(target, -1, gid);
|
|
233
|
+
fs.chmodSync(target, 0o640);
|
|
234
|
+
} catch (error) {
|
|
235
|
+
fs.rmSync(target, { force: true });
|
|
236
|
+
throw new Error(`could not give the token to group ${values.group} (${error.code || 'error'}): run this command as root.`, { cause: error });
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
process.stdout.write(`Token written to ${target} (mode ${gid === null ? '600' : `640, group ${values.group}`}).\n`);
|
|
240
|
+
if (gid !== null && (fs.statSync(path.dirname(target)).mode & 0o011) === 0) {
|
|
241
|
+
process.stdout.write(`Warning: ${path.dirname(target)} is not traversable by the group: the applications cannot reach the token (chmod 755 ${path.dirname(target)}).\n`);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function keygen(values) {
|
|
246
|
+
const { createSigningKey, signatureDirectory, jwkThumbprint, SIGNATURE_DIRECTORY_PATH, SIGNATURE_DIRECTORY_TYPE } = require('./webBotAuth');
|
|
247
|
+
if (!values.out) throw new Error('--out <key.pem> is required.');
|
|
248
|
+
const { privateKeyPem, publicJwk } = createSigningKey();
|
|
249
|
+
const target = writeSecret(values.out, privateKeyPem);
|
|
250
|
+
const directory = `${JSON.stringify(signatureDirectory(publicJwk), null, 2)}\n`;
|
|
251
|
+
if (values.directory) fs.writeFileSync(path.resolve(values.directory), directory, { mode: 0o644 });
|
|
252
|
+
process.stdout.write(`Private key written to ${target} (mode 600), keyid ${jwkThumbprint(publicJwk)}.\n`
|
|
253
|
+
+ `Publish this directory at https://<your domain>${SIGNATURE_DIRECTORY_PATH} with content-type ${SIGNATURE_DIRECTORY_TYPE}:\n${directory}`);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
async function main(argv = process.argv.slice(2)) {
|
|
257
|
+
const [command, ...rest] = argv;
|
|
258
|
+
const { values } = parseArgs({
|
|
259
|
+
args: rest,
|
|
260
|
+
strict: true,
|
|
261
|
+
options: {
|
|
262
|
+
port: { type: 'string' },
|
|
263
|
+
'proxy-port': { type: 'string' },
|
|
264
|
+
'token-file': { type: 'string' },
|
|
265
|
+
'max-contexts': { type: 'string' },
|
|
266
|
+
'queue-ms': { type: 'string' },
|
|
267
|
+
'info-url': { type: 'string' },
|
|
268
|
+
'signing-key-file': { type: 'string' },
|
|
269
|
+
'signature-agent': { type: 'string' },
|
|
270
|
+
'unsafe-no-firewall': { type: 'boolean' },
|
|
271
|
+
out: { type: 'string' },
|
|
272
|
+
node: { type: 'string' },
|
|
273
|
+
user: { type: 'string' },
|
|
274
|
+
chromium: { type: 'string' },
|
|
275
|
+
'browsers-path': { type: 'string' },
|
|
276
|
+
dns: { type: 'string' },
|
|
277
|
+
'memory-max': { type: 'string' },
|
|
278
|
+
'cpu-quota': { type: 'string' },
|
|
279
|
+
directory: { type: 'string' },
|
|
280
|
+
group: { type: 'string' },
|
|
281
|
+
'clients-group': { type: 'string' }
|
|
282
|
+
}
|
|
283
|
+
});
|
|
284
|
+
if (command === 'serve' || command === undefined) return serve(values);
|
|
285
|
+
if (command === 'setup') return setup(values);
|
|
286
|
+
if (command === 'token') return token(values);
|
|
287
|
+
if (command === 'keygen') return keygen(values);
|
|
288
|
+
throw new Error(USAGE);
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
if (require.main === module) {
|
|
292
|
+
main().catch((error) => {
|
|
293
|
+
process.stderr.write(`astratra-web-browser: ${error.message}\n`);
|
|
294
|
+
process.exit(1);
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
module.exports = { main, headlessShellIn, inspectBrowserHost, resolversOf, setup, token };
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
/* global AbortController */
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Le client du navigateur intégré, et le même moteur dans le processus.
|
|
5
|
+
*
|
|
6
|
+
* `createBrowserClient({ baseUrl, token })` appelle le service
|
|
7
|
+
* `astratra-web-browser`, sans dépendance. Comme le client de
|
|
8
|
+
* `@astratra/models`, il ne lève jamais : chaque appel rend
|
|
9
|
+
* { ok: true, result } ou { ok: false, code, retryable, status?, message? }
|
|
10
|
+
* et `result.status` dit ce qu'est devenue la page (ok, robots_disallowed,
|
|
11
|
+
* blocked…). Délai par appel, nouvel essai sur panne réseau ou service
|
|
12
|
+
* occupé, disjoncteur : un service arrêté coûte un refus rapide, pas un délai
|
|
13
|
+
* par lecture.
|
|
14
|
+
*
|
|
15
|
+
* `createLocalBrowser(options)` : le moteur dans le processus (Playwright
|
|
16
|
+
* requis), pour le développement et les tests ; même interface.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
const fs = require('fs');
|
|
20
|
+
const { createBrowserEngine } = require('./engine');
|
|
21
|
+
|
|
22
|
+
const OUTAGES = new Set(['timeout', 'network_error', 'server_error', 'unavailable', 'bad_response', 'unauthorized', 'token_unavailable']);
|
|
23
|
+
const RETRYABLE = new Set(['network_error', 'busy', 'unavailable']);
|
|
24
|
+
|
|
25
|
+
/** Un disjoncteur : `failureThreshold` pannes de suite l'ouvrent `recoveryMs`, puis un seul essai passe. */
|
|
26
|
+
function createBreaker({ failureThreshold = 3, recoveryMs = 30_000, now = Date.now, onChange = () => {} } = {}) {
|
|
27
|
+
let state = 'closed';
|
|
28
|
+
let failures = 0;
|
|
29
|
+
let openedAt = 0;
|
|
30
|
+
let probing = false;
|
|
31
|
+
const move = (to) => {
|
|
32
|
+
if (state === to) return;
|
|
33
|
+
const from = state;
|
|
34
|
+
state = to;
|
|
35
|
+
try {
|
|
36
|
+
onChange({ from, to });
|
|
37
|
+
} catch (_error) {
|
|
38
|
+
/* un observateur ne casse rien */
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
return {
|
|
42
|
+
/** Vrai si un appel peut partir maintenant. */
|
|
43
|
+
allow() {
|
|
44
|
+
if (state === 'open') {
|
|
45
|
+
if (now() - openedAt < recoveryMs) return false;
|
|
46
|
+
move('half-open');
|
|
47
|
+
}
|
|
48
|
+
if (state === 'half-open') {
|
|
49
|
+
if (probing) return false;
|
|
50
|
+
probing = true;
|
|
51
|
+
}
|
|
52
|
+
return true;
|
|
53
|
+
},
|
|
54
|
+
success() {
|
|
55
|
+
failures = 0;
|
|
56
|
+
probing = false;
|
|
57
|
+
move('closed');
|
|
58
|
+
},
|
|
59
|
+
failure() {
|
|
60
|
+
probing = false;
|
|
61
|
+
if (state === 'half-open') {
|
|
62
|
+
openedAt = now();
|
|
63
|
+
move('open');
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
failures += 1;
|
|
67
|
+
if (failures >= failureThreshold) {
|
|
68
|
+
openedAt = now();
|
|
69
|
+
move('open');
|
|
70
|
+
}
|
|
71
|
+
},
|
|
72
|
+
/* Une réponse qui n'est pas une panne libère l'essai sans fermer ni ouvrir. */
|
|
73
|
+
neutral() {
|
|
74
|
+
probing = false;
|
|
75
|
+
if (state === 'half-open') move('closed');
|
|
76
|
+
},
|
|
77
|
+
status: () => ({ state, failures })
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function normaliseBaseUrl(value) {
|
|
82
|
+
const raw = value || 'http://127.0.0.1:5008';
|
|
83
|
+
let url;
|
|
84
|
+
try {
|
|
85
|
+
url = new URL(raw);
|
|
86
|
+
} catch (error) {
|
|
87
|
+
throw new TypeError('createBrowserClient: baseUrl must be an absolute http(s) URL.', { cause: error });
|
|
88
|
+
}
|
|
89
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') throw new TypeError('createBrowserClient: baseUrl must be an absolute http(s) URL.');
|
|
90
|
+
return raw.replace(/\/+$/, '');
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* @param {object} [options]
|
|
95
|
+
* @param {string} [options.baseUrl] Défaut http://127.0.0.1:5008.
|
|
96
|
+
* @param {string|Function} [options.token] le jeton, ou une fonction (async) qui le rend.
|
|
97
|
+
* @param {string} [options.tokenFile] ou un fichier, relu à chaque appel.
|
|
98
|
+
* @param {Function} [options.fetch] Défaut globalThis.fetch.
|
|
99
|
+
* @param {number} [options.timeoutMs] Défaut 30 s (le service s'arrête à 25 s).
|
|
100
|
+
* @param {{ attempts?: number, baseDelayMs?: number, maxDelayMs?: number }} [options.retry] Défaut 2 essais.
|
|
101
|
+
* @param {{ failureThreshold?: number, recoveryMs?: number }|false} [options.breaker]
|
|
102
|
+
* @param {Function} [options.onEvent] ({ type, … }) => void.
|
|
103
|
+
*/
|
|
104
|
+
function createBrowserClient(options = {}) {
|
|
105
|
+
const fetchImpl = options.fetch || globalThis.fetch;
|
|
106
|
+
if (typeof fetchImpl !== 'function') throw new TypeError('createBrowserClient: a fetch function is required.');
|
|
107
|
+
const baseUrl = normaliseBaseUrl(options.baseUrl);
|
|
108
|
+
const timeoutMs = options.timeoutMs ?? 30_000;
|
|
109
|
+
const attempts = Math.max(1, Math.floor(options.retry?.attempts ?? 2));
|
|
110
|
+
const baseDelayMs = options.retry?.baseDelayMs ?? 250;
|
|
111
|
+
const maxDelayMs = options.retry?.maxDelayMs ?? 1_500;
|
|
112
|
+
const sleep = options.sleep || ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
113
|
+
const random = options.random || Math.random;
|
|
114
|
+
const onEvent = typeof options.onEvent === 'function' ? options.onEvent : () => {};
|
|
115
|
+
const emit = (event) => {
|
|
116
|
+
try {
|
|
117
|
+
onEvent(event);
|
|
118
|
+
} catch (_error) {
|
|
119
|
+
/* un observateur ne casse rien */
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
const breaker = options.breaker === false ? null : createBreaker({ ...(options.breaker || {}), now: options.now, onChange: ({ from, to }) => emit({ type: 'breaker', from, to }) });
|
|
123
|
+
|
|
124
|
+
async function token() {
|
|
125
|
+
if (typeof options.token === 'function') return options.token();
|
|
126
|
+
if (typeof options.token === 'string') return options.token;
|
|
127
|
+
if (options.tokenFile) return (await fs.promises.readFile(options.tokenFile, 'utf8')).trim();
|
|
128
|
+
return null;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const refuse = (code, extra = {}) => ({ ok: false, code, retryable: RETRYABLE.has(code), ...extra });
|
|
132
|
+
|
|
133
|
+
async function exchange(method, path, body, signal) {
|
|
134
|
+
if (signal?.aborted) return refuse('aborted');
|
|
135
|
+
const controller = new AbortController();
|
|
136
|
+
let timedOut = false;
|
|
137
|
+
const timer = setTimeout(() => {
|
|
138
|
+
timedOut = true;
|
|
139
|
+
controller.abort();
|
|
140
|
+
}, timeoutMs);
|
|
141
|
+
const onAbort = () => controller.abort();
|
|
142
|
+
signal?.addEventListener?.('abort', onAbort, { once: true });
|
|
143
|
+
try {
|
|
144
|
+
let secret;
|
|
145
|
+
try {
|
|
146
|
+
secret = await token();
|
|
147
|
+
} catch (_error) {
|
|
148
|
+
return refuse('token_unavailable');
|
|
149
|
+
}
|
|
150
|
+
let response;
|
|
151
|
+
try {
|
|
152
|
+
response = await fetchImpl(`${baseUrl}${path}`, {
|
|
153
|
+
method,
|
|
154
|
+
headers: { accept: 'application/json', ...(body ? { 'content-type': 'application/json' } : {}), ...(secret ? { authorization: `Bearer ${secret}` } : {}) },
|
|
155
|
+
body: body ? JSON.stringify(body) : undefined,
|
|
156
|
+
signal: controller.signal
|
|
157
|
+
});
|
|
158
|
+
} catch (_error) {
|
|
159
|
+
if (timedOut) return refuse('timeout');
|
|
160
|
+
if (signal?.aborted) return refuse('aborted');
|
|
161
|
+
return refuse('network_error');
|
|
162
|
+
}
|
|
163
|
+
let data = null;
|
|
164
|
+
try {
|
|
165
|
+
data = await response.json();
|
|
166
|
+
} catch (_error) {
|
|
167
|
+
if (timedOut) return refuse('timeout');
|
|
168
|
+
if (signal?.aborted) return refuse('aborted');
|
|
169
|
+
return refuse('bad_response', { status: response.status });
|
|
170
|
+
}
|
|
171
|
+
if (response.status >= 200 && response.status < 300) {
|
|
172
|
+
if (!data || typeof data !== 'object') return refuse('bad_response', { status: response.status });
|
|
173
|
+
return { ok: true, result: data };
|
|
174
|
+
}
|
|
175
|
+
const code = typeof data?.error?.code === 'string' ? data.error.code : null;
|
|
176
|
+
const message = typeof data?.error?.message === 'string' ? data.error.message.slice(0, 200) : undefined;
|
|
177
|
+
const extra = { status: response.status, ...(message ? { message } : {}) };
|
|
178
|
+
if (response.status === 400) return refuse('invalid_input', extra);
|
|
179
|
+
if (response.status === 401 || response.status === 403) return refuse('unauthorized', extra);
|
|
180
|
+
if (response.status === 404 || response.status === 405) return refuse('not_found', extra);
|
|
181
|
+
if (response.status === 413 || response.status === 415) return refuse('invalid_input', extra);
|
|
182
|
+
if (response.status === 503) return refuse(code === 'busy' ? 'busy' : code === 'token_unavailable' ? 'token_unavailable' : 'unavailable', extra);
|
|
183
|
+
return refuse('server_error', extra);
|
|
184
|
+
} finally {
|
|
185
|
+
clearTimeout(timer);
|
|
186
|
+
signal?.removeEventListener?.('abort', onAbort);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
async function call(name, method, path, body, signal) {
|
|
191
|
+
if (breaker && !breaker.allow()) return refuse('circuit_open');
|
|
192
|
+
let last = null;
|
|
193
|
+
for (let attempt = 1; attempt <= attempts; attempt += 1) {
|
|
194
|
+
last = await exchange(method, path, body, signal);
|
|
195
|
+
if (last.ok || !last.retryable || attempt === attempts || signal?.aborted) break;
|
|
196
|
+
emit({ type: 'retry', endpoint: name, code: last.code, attempt });
|
|
197
|
+
await sleep(Math.min(maxDelayMs, baseDelayMs * 2 ** (attempt - 1)) * random());
|
|
198
|
+
}
|
|
199
|
+
if (breaker) {
|
|
200
|
+
if (last.ok) breaker.success();
|
|
201
|
+
else if (OUTAGES.has(last.code)) breaker.failure();
|
|
202
|
+
else breaker.neutral();
|
|
203
|
+
}
|
|
204
|
+
emit({ type: 'call', endpoint: name, ok: last.ok, ...(last.ok ? { status: last.result.status } : { code: last.code }) });
|
|
205
|
+
return last;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
return {
|
|
209
|
+
/** @param {{ url: string, screenshot?: boolean, waitFor?: string, allowDomains?: string[], blockDomains?: string[], lang?: string }} request */
|
|
210
|
+
open: (request, { signal } = {}) => call('open', 'POST', '/v1/open', request, signal),
|
|
211
|
+
/** @param {{ url: string, query: string, screenshot?: boolean, allowDomains?: string[], blockDomains?: string[], lang?: string }} request */
|
|
212
|
+
siteSearch: (request, { signal } = {}) => call('site-search', 'POST', '/v1/site-search', request, signal),
|
|
213
|
+
health: ({ signal } = {}) => call('health', 'GET', '/health', undefined, signal),
|
|
214
|
+
breakerStatus: () => breaker?.status() || null,
|
|
215
|
+
kind: 'service'
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Le moteur dans le processus, avec l'interface du client. Pour le
|
|
221
|
+
* développement et les tests : il n'a ni utilisateur à part, ni pare-feu, ni
|
|
222
|
+
* contrôle d'isolement. Il refuse donc de tourner quand NODE_ENV vaut
|
|
223
|
+
* `production`, sauf `allowInProduction: true` donné en connaissance de cause.
|
|
224
|
+
* @param {object} [options] les options de createBrowserEngine (ou `engine` déjà créé), et allowInProduction.
|
|
225
|
+
*/
|
|
226
|
+
function createLocalBrowser(options = {}) {
|
|
227
|
+
if (process.env.NODE_ENV === 'production' && options.allowInProduction !== true && !options.engine) {
|
|
228
|
+
throw new Error('createLocalBrowser runs Chromium inside your application, without a separate user, firewall or isolation check: '
|
|
229
|
+
+ 'it is meant for development. In production, run the astratra-web-browser service and use createBrowserClient '
|
|
230
|
+
+ '(see the README, "Integrated browser"). To run it anyway, pass { allowInProduction: true }.');
|
|
231
|
+
}
|
|
232
|
+
const engineOptions = { ...options };
|
|
233
|
+
delete engineOptions.allowInProduction;
|
|
234
|
+
const engine = options.engine || createBrowserEngine(engineOptions);
|
|
235
|
+
const wrap = (result) => {
|
|
236
|
+
if (result.status === 'busy') return { ok: false, code: 'busy', retryable: true };
|
|
237
|
+
if (result.status === 'invalid_input') return { ok: false, code: 'invalid_input', retryable: false, message: `${result.reason || 'request'} is invalid.` };
|
|
238
|
+
if (result.status === 'browser_unavailable') return { ok: false, code: 'unavailable', retryable: false, message: result.reason };
|
|
239
|
+
return { ok: true, result };
|
|
240
|
+
};
|
|
241
|
+
return {
|
|
242
|
+
open: async (request, { signal } = {}) => wrap(await engine.open(request, { signal })),
|
|
243
|
+
siteSearch: async (request, { signal } = {}) => wrap(await engine.siteSearch(request, { signal })),
|
|
244
|
+
health: async () => ({ ok: true, result: await engine.health() }),
|
|
245
|
+
start: () => engine.start(),
|
|
246
|
+
close: () => engine.close(),
|
|
247
|
+
kind: 'local'
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
module.exports = { createBrowserClient, createLocalBrowser };
|